From e15bd7c9f96e61c74fbca8182a4c43603cc8bf51 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 16:18:25 -0500 Subject: [PATCH 01/32] feat(grpc-data): A3 IProjectedConditionAccess / IProjectedConditionSink contracts --- .../IProjectedConditionAccess.cs | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedConditionAccess.cs diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedConditionAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedConditionAccess.cs new file mode 100644 index 000000000..41613492d --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedConditionAccess.cs @@ -0,0 +1,77 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; + +/// +/// A3 (plan §5.2/§5.5): one current placement of an imported condition on this consumer — realm-consistent: the +/// placement address lives in the realm of 's export, and the folder it hangs under is a +/// projected node of that same mapping. +/// +/// The RemoteNamespaceMapping whose root item listed the placement. +/// The mapping's (and the placement's) realm. +/// The origin placement address (a listing view; never a cross-realm id). +/// +/// The LOCAL subject (slash-joined local scope segments) of the projected folder the placement sits under: the +/// mapping anchor's own subject when the placement's parent is the remote root. The node manager wires that folder +/// when (and only while) it is materialised (N7). +/// +/// The placement address relative to the mapping's remote root (display only). +public sealed record ImportedConditionPlacement(string MappingId, DataRealm Realm, DataView Placement, string FolderLocalSubject, + string RelativePath); + +/// +/// A3: one imported condition as the consumer's condition runtime hands it to the node manager — identity +/// (, ), its current placements (primary first) and +/// the origin record to mirror. The node manager mints the NodeId from the identity only (N4). +/// +/// The deployed DataConnection the condition was imported over. +/// The origin record (already version-gated by the runtime). +/// The condition's static facts (type, name, source kind); the latest one the stream carried. +/// Every current placement on this node, the PRIMARY one first (§5.2: deployed config only). +/// The primary placement's display path (§5.2). +public sealed record ImportedConditionUpdate(string ConnectionId, DataConditionState State, DataConditionInfo? Info, + IReadOnlyList Placements, string SourceName); + +/// +/// A3 (§5.3/§5.5): what the consumer's condition runtime tells the node manager. Every call is bounded per Lock hold by +/// the implementation; none blocks on the network. +/// +public interface IProjectedConditionSink +{ + /// Materialises new conditions and applies records through the shared #656 delta gate. + void ApplyConditions(IReadOnlyList updates); + + /// Removes conditions (an origin removed record, or a complete re-snapshot that no longer lists them). + void RemoveConditions(string connectionId, IReadOnlyCollection conditionKeys); + + /// The connection is gone past its stale timeout: Quality = BadNoCommunication, one event each. + void MarkConnectionStale(string connectionId); + + /// Sends RefreshRequiredEventType to every item that may see a condition of the connection. + void RequireRefresh(string connectionId); +} + +/// +/// A3 (§5.4/§5.5): the consumer's condition access — the per-caller visibility gate and per-connection demand. SDK-free +/// apart from the identity type, like . +/// +public interface IProjectedConditionAccess +{ + /// + /// The §5.4 gate: whether passes the mapping gate for CreateMonitoredItems + /// () on ANY current placement mapping. Evaluated regardless of + /// Security:Acl:Enabled. Null caller ⇒ false. + /// + bool CanSee(RoleCarryingUserIdentity? caller, IReadOnlyList placements); + + /// A generation that moves whenever anything the gate reads may have changed (verdict caches key on it). + long AuthorityGeneration { get; } + + /// + /// An admitted local event item that could see imported conditions (Server object or a projected notifier). The + /// first one opens condition demand for every connection the caller could see; disposing the last starts the linger. + /// Null when no connection carries conditions (nothing to open). + /// + IDisposable? AcquireEventDemand(RoleCarryingUserIdentity? caller); +} From a75ea95e25f1a15367d1bc31e42e696d51e000a3 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 16:19:24 -0500 Subject: [PATCH 02/32] =?UTF-8?q?refactor(opcua):=20share=20condition=20no?= =?UTF-8?q?de=20factory=20+=20state-apply/delta=20gate=20(A3=20=C2=A75.3?= =?UTF-8?q?=20prerequisites)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ApplicationAlarmConditions.cs | 8 +- .../OtOpcUaNodeManager.cs | 313 ++++++++++-------- 2 files changed, 174 insertions(+), 147 deletions(-) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ApplicationAlarmConditions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ApplicationAlarmConditions.cs index 287d4248f..0718ed40c 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ApplicationAlarmConditions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ApplicationAlarmConditions.cs @@ -5,7 +5,7 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; /// Preserves the application's repeat-method contract at the SDK's supported validation seam. internal static class ApplicationAlarmConditions { - internal static AlarmConditionState Create(string type, NodeState parent) => type switch + internal static AlarmConditionState Create(string type, NodeState? parent) => type switch { "OffNormalAlarm" => new OffNormal(parent), "DiscreteAlarm" => new Discrete(parent), @@ -34,7 +34,7 @@ internal static class ApplicationAlarmConditions } } - private sealed class OffNormal(NodeState parent) : OffNormalAlarmState(parent) + private sealed class OffNormal(NodeState? parent) : OffNormalAlarmState(parent!) { protected override ServiceResult ProcessBeforeAcknowledge(ISystemContext context, ByteString id, LocalizedText comment) => CurrentTrunkRepeat(base.ProcessBeforeAcknowledge(context, id, comment), this, context, id, comment, true); @@ -43,7 +43,7 @@ internal static class ApplicationAlarmConditions protected override ConditionState CreateBranchInstance() => new OffNormal(this); } - private sealed class Discrete(NodeState parent) : DiscreteAlarmState(parent) + private sealed class Discrete(NodeState? parent) : DiscreteAlarmState(parent!) { protected override ServiceResult ProcessBeforeAcknowledge(ISystemContext context, ByteString id, LocalizedText comment) => CurrentTrunkRepeat(base.ProcessBeforeAcknowledge(context, id, comment), this, context, id, comment, true); @@ -52,7 +52,7 @@ internal static class ApplicationAlarmConditions protected override ConditionState CreateBranchInstance() => new Discrete(this); } - private sealed class Alarm(NodeState parent) : AlarmConditionState(parent) + private sealed class Alarm(NodeState? parent) : AlarmConditionState(parent!) { protected override ServiceResult ProcessBeforeAcknowledge(ISystemContext context, ByteString id, LocalizedText comment) => CurrentTrunkRepeat(base.ProcessBeforeAcknowledge(context, id, comment), this, context, id, comment, true); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index 2d1fceb3c..1d9f36dd1 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -1361,63 +1361,11 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage // NEVER passed through this method, so a last-written cache would be stale and // wrongly report a delta. By the time the engine re-projects that ack here, the node already // holds the acked state → no delta → suppress. - var current = ReadConditionDelta(condition); - var incoming = ToConditionDelta(state, condition); - bool fire = ShouldFireConditionEvent(current, incoming); - - // EnabledState / AckedState / ActiveState are mandatory children — always present after - // Create. Confirm + Shelving are optional Part 9 children: T14's real-server finding is - // that Create auto-builds them for our subtypes, but a base AlarmConditionState (or a - // future SDK that builds a leaner child set) may leave them null. Null-guard each optional - // child so projecting Confirmed/Shelving onto a node that lacks the sub-state machine is a - // no-op rather than an NRE. - condition.SetEnableState(SystemContext, state.Enabled); - condition.SetActiveState(SystemContext, state.Active); - condition.SetAcknowledgedState(SystemContext, state.Acknowledged); - if (condition.ConfirmedState is not null) - { - condition.SetConfirmedState(SystemContext, state.Confirmed); - } // A1 review nit: the absolute timed-shelve expiry rides the condition-state record (A2 projects it). if (state.Shelving == AlarmShelvingKind.Timed && state.UnshelveAtUtc is { } unshelveAt) _conditionUnshelveAt[key] = unshelveAt; else _conditionUnshelveAt.Remove(key); - if (condition.ShelvingState is not null) - { - // SetShelvingState(shelved, oneShot, shelvingTime): map our 3-way kind onto the SDK's - // (shelved, oneShot) flag pair. Timed shelving's expiry is owned by the engine; the time - // passed here is the engine's remaining time, so the node's UnshelveTime counts down to the - // real expiry (a 0 here reads as MaxTimeShelved, ~24.8 days). The SDK timer it - // arms does nothing (OnTimedUnshelve is a no-op): the engine's own expiry re-projects. - condition.SetShelvingState( - SystemContext, - shelved: state.Shelving != AlarmShelvingKind.Unshelved, - oneShot: state.Shelving == AlarmShelvingKind.OneShot, - shelvingTime: state.Shelving == AlarmShelvingKind.Timed ? RemainingShelveMs(state.UnshelveAtUtc, UtcNow) : 0); - } - condition.SetSeverity(SystemContext, ToPart9Severity(state.Severity)); - condition.Message!.Value = new LocalizedText(state.Message); - // #839: a classifying native source's Part 9 ConditionClass. Null leaves the node's class as it is - // (BaseConditionClass from materialise, or what an earlier event set). Not in the delta-gate: a class - // rides along with the transition that set it and never fires an event on its own. - if (state.ConditionClass is { } conditionClass) ApplyConditionClass(condition, conditionClass); - - // Project the source-data quality. A Good→Bad bucket change is a genuine condition - // change (it's in the delta-gate above), so it fires a Part 9 event carrying the new Quality; - // it never touches Active/Acked/Retain (annotation only). Quality is an optional Part 9 child — - // null-guard it like Confirmed/Shelving in case a leaner SDK child set omits it. - if (condition.Quality is not null) - { - condition.Quality.Value = new StatusCode(state.StatusCode); - if (condition.Quality.SourceTimestamp is not null) condition.Quality.SourceTimestamp.Value = sourceTimestampUtc; - } - - // Part 9: retain the condition while it is active OR unacknowledged so a client's - // ConditionRefresh replays it. The event firing below also depends on this Retain being - // correct (a non-retained inactive+acked condition still fires its transition event, but - // won't be replayed on a later ConditionRefresh). - condition.Retain!.Value = state.Active || !state.Acknowledged; - condition.Time!.Value = sourceTimestampUtc; - condition.ReceiveTime!.Value = sourceTimestampUtc; + // A3 (§5.3): the state-apply + #656 delta gate is shared with imported conditions (ApplyConditionState). + bool fire = ApplyConditionState(condition, state, sourceTimestampUtc); // T20 — fire a real Part 9 condition event ONLY when this projection is a genuine state // change (the delta-gate decided above, against the node's pre-projection state). A @@ -1447,6 +1395,71 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage } } + /// + /// Projects onto and decides, against the node's state BEFORE the + /// projection, whether it is a genuine transition (the T20 / #656 delta gate). Shared by + /// and the A3 imported-condition registry so both use exactly one gate. Caller holds Lock. + /// + /// when the projection is a genuine change that must be reported as one event. + private bool ApplyConditionState(AlarmConditionState condition, AlarmConditionSnapshot state, DateTime sourceTimestampUtc) + { + var current = ReadConditionDelta(condition); + var incoming = ToConditionDelta(state, condition); + bool fire = ShouldFireConditionEvent(current, incoming); + + // EnabledState / AckedState / ActiveState are mandatory children — always present after + // Create. Confirm + Shelving are optional Part 9 children: T14's real-server finding is + // that Create auto-builds them for our subtypes, but a base AlarmConditionState (or a + // future SDK that builds a leaner child set) may leave them null. Null-guard each optional + // child so projecting Confirmed/Shelving onto a node that lacks the sub-state machine is a + // no-op rather than an NRE. + condition.SetEnableState(SystemContext, state.Enabled); + condition.SetActiveState(SystemContext, state.Active); + condition.SetAcknowledgedState(SystemContext, state.Acknowledged); + if (condition.ConfirmedState is not null) + { + condition.SetConfirmedState(SystemContext, state.Confirmed); + } + if (condition.ShelvingState is not null) + { + // SetShelvingState(shelved, oneShot, shelvingTime): map our 3-way kind onto the SDK's + // (shelved, oneShot) flag pair. Timed shelving's expiry is owned by the engine; the time + // passed here is the engine's remaining time, so the node's UnshelveTime counts down to the + // real expiry (a 0 here reads as MaxTimeShelved, ~24.8 days). The SDK timer it + // arms does nothing (OnTimedUnshelve is a no-op): the engine's own expiry re-projects. + condition.SetShelvingState( + SystemContext, + shelved: state.Shelving != AlarmShelvingKind.Unshelved, + oneShot: state.Shelving == AlarmShelvingKind.OneShot, + shelvingTime: state.Shelving == AlarmShelvingKind.Timed ? RemainingShelveMs(state.UnshelveAtUtc, UtcNow) : 0); + } + condition.SetSeverity(SystemContext, ToPart9Severity(state.Severity)); + condition.Message!.Value = new LocalizedText(state.Message); + // #839: a classifying native source's Part 9 ConditionClass. Null leaves the node's class as it is + // (BaseConditionClass from materialise, or what an earlier event set). Not in the delta-gate: a class + // rides along with the transition that set it and never fires an event on its own. + if (state.ConditionClass is { } conditionClass) ApplyConditionClass(condition, conditionClass); + + // Project the source-data quality. A Good→Bad bucket change is a genuine condition + // change (it's in the delta-gate above), so it fires a Part 9 event carrying the new Quality; + // it never touches Active/Acked/Retain (annotation only). Quality is an optional Part 9 child — + // null-guard it like Confirmed/Shelving in case a leaner SDK child set omits it. + if (condition.Quality is not null) + { + condition.Quality.Value = new StatusCode(state.StatusCode); + if (condition.Quality.SourceTimestamp is not null) condition.Quality.SourceTimestamp.Value = sourceTimestampUtc; + } + + // Part 9: retain the condition while it is active OR unacknowledged so a client's + // ConditionRefresh replays it. The event firing below also depends on this Retain being + // correct (a non-retained inactive+acked condition still fires its transition event, but + // won't be replayed on a later ConditionRefresh). + condition.Retain!.Value = state.Active || !state.Acknowledged; + condition.Time!.Value = sourceTimestampUtc; + condition.ReceiveTime!.Value = sourceTimestampUtc; + return fire; + } + /// /// The Part 9 class type id + browse name of an (lmxopcua#839). /// @@ -2402,6 +2415,106 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage return AlarmShelvingKind.Unshelved; } + /// + /// Builds one Part 9 condition node — type, the optional children added before Create(), child ids + /// (), and the initial field values. Shared by and the A3 + /// imported-condition registry (one helper, so an imported condition has exactly a local one's shape). Caller holds + /// Lock; the caller wires handlers and parents/registers the node. + /// + private AlarmConditionState CreateConditionNode(string alarmType, NodeState? parent, NodeId nodeId, string displayName, + string sourceName, int severity, bool isNative) + { + AlarmConditionState alarm = CreateAlarmConditionOfType(alarmType, parent); + // SDK 2.0 creates optional confirmation nodes only when requested explicitly. + // Both are part of the application's existing Part 9 method/state contract. + alarm.ConfirmedState = new TwoStateVariableState(alarm); + alarm.Confirm = new AddCommentMethodState(alarm); + alarm.ShelvingState = new ShelvedStateMachineState(alarm); + alarm.MaxTimeShelved = new PropertyState.Implementation(alarm); + alarm.SymbolicName = displayName; + // Create builds the full mandatory Part 9 child set (EnabledState, AckedState, + // ActiveState, the Acknowledge/Confirm/AddComment/Enable/Disable methods, ...) from the + // type's embedded definition; we do not hand-build them. + alarm.Create( + SystemContext, + nodeId, + new QualifiedName(displayName, nodeId.NamespaceIndex), + new LocalizedText(displayName), + assignNodeIds: true); + // Create initializes the embedded definition and resets ReferenceTypeId in SDK 2.0.1. + // Restore the application's parent ownership before AddChild: hierarchical folder browses + // must expose the alarm as a HasComponent object, as they did before the SDK upgrade. + alarm.ReferenceTypeId = ReferenceTypeIds.HasComponent; + + // Main-branch id MUST be a concrete (null) NodeId before any Set* call: SetEnableState -> + // UpdateRetainState -> GetRetainState -> IsBranch() dereferences BranchId.Value, which + // Create leaves as a null reference and would NRE. NodeId.Null marks "the main branch". + // (Real-server finding from the T14 integration test — not obvious from the SDK notes.) + if (alarm.BranchId is not null) alarm.BranchId.Value = NodeId.Null; + + // The mandatory BaseEventType identity fields. Create() builds these three children from + // the type's embedded definition but leaves them UNSET (the init string declares them mandatory + // with NO default), and nothing downstream fills them in: the auto-filling + // BaseEventState.Initialize(context, source, severity, message) overload is only used for + // transient events, and ReportEvent / InstanceStateSnapshot copy the children verbatim. Unset + // here ⇒ null on the wire on EVERY condition event, so a client cannot attribute the alarm. + // SourceNode — the condition's OWN NodeId (== ConditionId): the condition IS the source. An + // alarm-bearing raw tag materialises ONLY this condition, with no sibling value + // variable (see AddressSpaceApplier's alarm branch), so there is no other node. + // SourceName — the same identifying id string (RawPath native / ScriptedAlarmId scripted). + // Deliberately the UNIQUE id, NOT the leaf: the leaf collides across devices and + // is already carried by ConditionName below. See docs/AlarmTracking.md. + alarm.EventType!.Value = alarm.TypeDefinitionId; + alarm.SourceNode!.Value = alarm.NodeId; // Create() assigned this above; do not rebuild it + alarm.SourceName!.Value = sourceName; + + // The mandatory ConditionType classification fields, unset by Create() for the same reason as + // the fields above (mandatory, no default, nothing downstream synthesises them) ⇒ NodeId.Null + empty + // text on the wire, which buckets every alarm as unclassified in a Part 9 HMI. + // BaseConditionClassType is Part 9's "no class modelled" value and is the honest report: we hold no + // classification at this seam. Deliberately NOT ProcessConditionClassType (the SDK sample's pick) — it + // would assert a classification we cannot back, and would be actively wrong for a Galaxy alarm whose + // upstream category is Safety/Diagnostics. Per-alarm classification arrives at RUNTIME instead: a + // classifying native driver states AlarmEventArgs.ConditionClass on its transitions (#839, Heidenhain), + // which WriteAlarmCondition applies over this default — the deploy-time seam still holds none. + if (alarm.ConditionClassId is not null) alarm.ConditionClassId.Value = ObjectTypeIds.BaseConditionClassType; + if (alarm.ConditionClassName is not null) alarm.ConditionClassName.Value = new LocalizedText("BaseConditionClass"); + + // ConditionType.Quality (the quality of the condition's source data). Create() leaves it + // UNSET, and default(StatusCode) == StatusCodes.Good (0x0), so an unassigned Quality reports Good + // unconditionally — a wrong VALUE (not a null), which hides a comms-lost source. A NATIVE condition + // has no data yet at materialise (its driver hasn't confirmed connectivity), so it starts + // BadWaitingForInitialData — the same "no driver data yet" convention value variables use — and is + // driven Good by the driver-connectivity path (DriverHostActor → ProjectQuality) once Connected. A + // SCRIPTED condition is script-computed and always live in v1, so it starts Good. Quality is a pure + // annotation: it NEVER alters Active/Acked/Retain (a comms-lost active alarm must stay active). + if (alarm.Quality is not null) + { + alarm.Quality.Value = isNative ? StatusCodes.BadWaitingForInitialData : StatusCodes.Good; + if (alarm.Quality.SourceTimestamp is not null) alarm.Quality.SourceTimestamp.Value = UtcNow; + } + + // Initial state via the SDK setters (T14: basic state only, NO event firing). + alarm.SetEnableState(SystemContext, true); + alarm.SetActiveState(SystemContext, false); + alarm.SetAcknowledgedState(SystemContext, true); + // A native condition is never Unconfirmed: it has no confirm workflow — Confirm is + // refused and Acknowledge re-asserts Confirmed — so start it Confirmed, the value NativeAlarmProjector + // supplies on every transition, rather than the SDK's default false until the first projection. + if (isNative && alarm.ConfirmedState is not null) alarm.SetConfirmedState(SystemContext, true); + alarm.SetSeverity(SystemContext, ToPart9Severity(severity)); + // Create() leaves MaxTimeShelved at 0, and the SDK's + // TimedShelve handler rejects any ShelvingTime above it — so every client TimedShelve failed with + // BadShelvingTimeOutOfRange. The bound becomes the longest shelve the SDK's own shelving timer can + // represent (int.MaxValue ms ≈ 24.8 days, the same ceiling SetShelvingState already saturated a 0 to). + if (alarm.MaxTimeShelved is { } maxTimeShelved && maxTimeShelved.Value <= 0) + maxTimeShelved.Value = int.MaxValue; + alarm.Retain!.Value = false; // inactive + acked ⇒ nothing to retain yet + alarm.Message!.Value = new LocalizedText(displayName); + if (alarm.ConditionName is not null) alarm.ConditionName.Value = displayName; + return alarm; + } + /// /// Materialise a real OPC UA Part 9 node under its equipment /// folder so clients can browse it as a proper condition (and subscribe to its events). The node @@ -2488,94 +2601,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage var parent = ResolveParentFolder(equipmentNodeId, realm); - AlarmConditionState alarm = CreateAlarmConditionOfType(alarmType, parent); - // SDK 2.0 creates optional confirmation nodes only when requested explicitly. - // Both are part of the application's existing Part 9 method/state contract. - alarm.ConfirmedState = new TwoStateVariableState(alarm); - alarm.Confirm = new AddCommentMethodState(alarm); - alarm.ShelvingState = new ShelvedStateMachineState(alarm); - alarm.MaxTimeShelved = new PropertyState.Implementation(alarm); - alarm.SymbolicName = displayName; - // Create builds the full mandatory Part 9 child set (EnabledState, AckedState, - // ActiveState, the Acknowledge/Confirm/AddComment/Enable/Disable methods, ...) from the - // type's embedded definition; we do not hand-build them. - alarm.Create( - SystemContext, - new NodeId(alarmNodeId, ns), - new QualifiedName(displayName, ns), - new LocalizedText(displayName), - assignNodeIds: true); - // Create initializes the embedded definition and resets ReferenceTypeId in SDK 2.0.1. - // Restore the application's parent ownership before AddChild: hierarchical folder browses - // must expose the alarm as a HasComponent object, as they did before the SDK upgrade. - alarm.ReferenceTypeId = ReferenceTypeIds.HasComponent; - - // Main-branch id MUST be a concrete (null) NodeId before any Set* call: SetEnableState -> - // UpdateRetainState -> GetRetainState -> IsBranch() dereferences BranchId.Value, which - // Create leaves as a null reference and would NRE. NodeId.Null marks "the main branch". - // (Real-server finding from the T14 integration test — not obvious from the SDK notes.) - if (alarm.BranchId is not null) alarm.BranchId.Value = NodeId.Null; - - // The mandatory BaseEventType identity fields. Create() builds these three children from - // the type's embedded definition but leaves them UNSET (the init string declares them mandatory - // with NO default), and nothing downstream fills them in: the auto-filling - // BaseEventState.Initialize(context, source, severity, message) overload is only used for - // transient events, and ReportEvent / InstanceStateSnapshot copy the children verbatim. Unset - // here ⇒ null on the wire on EVERY condition event, so a client cannot attribute the alarm. - // SourceNode — the condition's OWN NodeId (== ConditionId): the condition IS the source. An - // alarm-bearing raw tag materialises ONLY this condition, with no sibling value - // variable (see AddressSpaceApplier's alarm branch), so there is no other node. - // SourceName — the same identifying id string (RawPath native / ScriptedAlarmId scripted). - // Deliberately the UNIQUE id, NOT the leaf: the leaf collides across devices and - // is already carried by ConditionName below. See docs/AlarmTracking.md. - alarm.EventType!.Value = alarm.TypeDefinitionId; - alarm.SourceNode!.Value = alarm.NodeId; // Create() assigned this above; do not rebuild it - alarm.SourceName!.Value = alarmNodeId; - - // The mandatory ConditionType classification fields, unset by Create() for the same reason as - // the fields above (mandatory, no default, nothing downstream synthesises them) ⇒ NodeId.Null + empty - // text on the wire, which buckets every alarm as unclassified in a Part 9 HMI. - // BaseConditionClassType is Part 9's "no class modelled" value and is the honest report: we hold no - // classification at this seam. Deliberately NOT ProcessConditionClassType (the SDK sample's pick) — it - // would assert a classification we cannot back, and would be actively wrong for a Galaxy alarm whose - // upstream category is Safety/Diagnostics. Per-alarm classification arrives at RUNTIME instead: a - // classifying native driver states AlarmEventArgs.ConditionClass on its transitions (#839, Heidenhain), - // which WriteAlarmCondition applies over this default — the deploy-time seam still holds none. - if (alarm.ConditionClassId is not null) alarm.ConditionClassId.Value = ObjectTypeIds.BaseConditionClassType; - if (alarm.ConditionClassName is not null) alarm.ConditionClassName.Value = new LocalizedText("BaseConditionClass"); - - // ConditionType.Quality (the quality of the condition's source data). Create() leaves it - // UNSET, and default(StatusCode) == StatusCodes.Good (0x0), so an unassigned Quality reports Good - // unconditionally — a wrong VALUE (not a null), which hides a comms-lost source. A NATIVE condition - // has no data yet at materialise (its driver hasn't confirmed connectivity), so it starts - // BadWaitingForInitialData — the same "no driver data yet" convention value variables use — and is - // driven Good by the driver-connectivity path (DriverHostActor → ProjectQuality) once Connected. A - // SCRIPTED condition is script-computed and always live in v1, so it starts Good. Quality is a pure - // annotation: it NEVER alters Active/Acked/Retain (a comms-lost active alarm must stay active). - if (alarm.Quality is not null) - { - alarm.Quality.Value = isNative ? StatusCodes.BadWaitingForInitialData : StatusCodes.Good; - if (alarm.Quality.SourceTimestamp is not null) alarm.Quality.SourceTimestamp.Value = UtcNow; - } - - // Initial state via the SDK setters (T14: basic state only, NO event firing). - alarm.SetEnableState(SystemContext, true); - alarm.SetActiveState(SystemContext, false); - alarm.SetAcknowledgedState(SystemContext, true); - // A native condition is never Unconfirmed: it has no confirm workflow — Confirm is - // refused and Acknowledge re-asserts Confirmed — so start it Confirmed, the value NativeAlarmProjector - // supplies on every transition, rather than the SDK's default false until the first projection. - if (isNative && alarm.ConfirmedState is not null) alarm.SetConfirmedState(SystemContext, true); - alarm.SetSeverity(SystemContext, ToPart9Severity(severity)); - // Create() leaves MaxTimeShelved at 0, and the SDK's - // TimedShelve handler rejects any ShelvingTime above it — so every client TimedShelve failed with - // BadShelvingTimeOutOfRange. The bound becomes the longest shelve the SDK's own shelving timer can - // represent (int.MaxValue ms ≈ 24.8 days, the same ceiling SetShelvingState already saturated a 0 to). - if (alarm.MaxTimeShelved is { } maxTimeShelved && maxTimeShelved.Value <= 0) - maxTimeShelved.Value = int.MaxValue; - alarm.Retain!.Value = false; // inactive + acked ⇒ nothing to retain yet - alarm.Message!.Value = new LocalizedText(displayName); - if (alarm.ConditionName is not null) alarm.ConditionName.Value = displayName; + // A3 (§5.3): field/child-id assignment is shared with imported conditions (CreateConditionNode). + AlarmConditionState alarm = CreateConditionNode(alarmType, parent, new NodeId(alarmNodeId, ns), displayName, alarmNodeId, severity, isNative); // T18 — inbound Part 9 method handlers. Create() materialised the Acknowledge/Confirm/ // AddComment/Shelve/Unshelve method nodes and the condition types wired their built-in OnCall @@ -4067,7 +4094,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage /// Map our domain AlarmType string to the matching SDK condition subtype. Script /// alarms have no OPC limit/setpoint values, so limit-style types fall back to the base /// (see remarks). - private static AlarmConditionState CreateAlarmConditionOfType(string alarmType, NodeState parent) => + private static AlarmConditionState CreateAlarmConditionOfType(string alarmType, NodeState? parent) => ApplicationAlarmConditions.Create(alarmType, parent); /// From 1ff18caa794ea041bdac9d0b43611b8096cfebf2 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 16:25:17 -0500 Subject: [PATCH 03/32] =?UTF-8?q?feat(opcua):=20A3=20ProjectedConditionReg?= =?UTF-8?q?istry=20=E2=80=94=20mapped/conditions=20namespace,=20lazy=20sym?= =?UTF-8?q?metric=20notifier=20wiring,=20gated=20marked=20delivery,=20publ?= =?UTF-8?q?ish-time=20re-gating,=20refresh=20replay?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../OtOpcUaNodeManager.cs | 69 ++- .../OtOpcUaSdkServer.cs | 21 +- .../ProjectedConditionRegistry.cs | 581 ++++++++++++++++++ .../ProjectedEventDelivery.cs | 78 ++- .../Security/DataPlaneAuthorizer.cs | 20 + .../WarmStandby.cs | 38 +- 6 files changed, 788 insertions(+), 19 deletions(-) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index 1d9f36dd1..c1271a36a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -120,8 +120,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage /// SECOND ([1]); maps a realm /// to its index. Which realm a node belongs to travels with each sink call as an /// — the namespace is never parsed back out of the id string. + // A3 (§5.2 N4): the imported-condition namespace is registered FIFTH ([4]). It has no realm — every classifier dispatches + // IsImportedConditionId BEFORE RealmOf (which folds every index other than 0/2 into Uns). private static readonly string[] RegisteredNamespaceUris = { V3NodeIds.RawNamespaceUri, V3NodeIds.UnsNamespaceUri, - ProjectedDataIds.RawNamespaceUri, ProjectedDataIds.UnsNamespaceUri }; + ProjectedDataIds.RawNamespaceUri, ProjectedDataIds.UnsNamespaceUri, Core.Abstractions.DataConnections.ImportedConditionIds.NamespaceUri }; /// Transitional alias kept so the pre-v3 single-namespace integration tests /// (SubscriptionSurvivalTests) still resolve a namespace index. It points at @@ -286,6 +288,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage /// ones this manager mints into). /// The resolved SDK node id. /// The realm the node belongs to. + /// ⚠️ A3: an imported-condition id () has NO realm and must be dispatched before + /// this is asked; every classifier does (the authorizer intercepts the namespace before using the realm it is handed). private AddressSpaceRealm RealmOf(NodeId nodeId) => nodeId.NamespaceIndex == NamespaceIndexes[0] || nodeId.NamespaceIndex == NamespaceIndexes[2] ? AddressSpaceRealm.Raw : AddressSpaceRealm.Uns; @@ -821,6 +825,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage value.UnsSubjectResolver = ResolveUnsAclSubject; value.MappedSubjectResolver = _mappedSubjectResolver; value.MappedNamespacePredicate = _projectedDataAccess is null ? null : IsProjectedDescendant; + value.ImportedConditionClassifier = ClassifyImportedCondition; // A3: before RealmOf, always } _authorizer = value; } @@ -1931,6 +1936,12 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage /// private void QueueToItem(IEventMonitoredItem item, IFilterTarget e) { + if (ImportedOf(e) is { } imported) + { + QueueImportedToItem(item, e, imported); + return; + } + if (e is ConditionEventSnapshot snapshot) { if (snapshot.DeliveryCache.Queue(Server, item, e, UseProjectedEventDelivery)) Interlocked.Increment(ref _projectedDeliveries); @@ -2030,7 +2041,11 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage // legitimate notifier of it, and its visibility scopes — is resolved ONCE per hop, not per item (it is what // IsNotifierEventVisibleTo resolves for an item attached here). Only the grant check and the SDK's role check // remain per item. - var enforced = AclEnforced; + // A3 (§5.4): an imported condition reaches a projected folder's items only while the registry wires it there, and + // each item passes the mapping gate — ACLs on or off. + var imported = ImportedOf(e); + if (imported is not null && !_importedConditions.IsWiredTo(imported, monitored.Node)) return; + var enforced = AclEnforced && imported is null; List? scopes = null; if (enforced) { @@ -2053,6 +2068,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage if (IsAuditEvent(e) && !IsAuditDeliverableTo(item)) continue; if (!RoleAllows(item, e)) continue; if (scopes is not null && !IsConditionVisibleTo(item, scopes, visibleByIdentity!)) continue; + if (imported is not null && !ImportedVisibleTo(item, imported)) continue; QueueConditionEventToItem(item, e, deferred, DeferredFolderDeliveryProbe); } catch (Exception ex) @@ -2075,7 +2091,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage /// Whether is the instance the address space currently holds for its NodeId. private bool IsLiveCondition(NodeState condition) => - _alarmConditions.TryGetValue(MapKey(condition.NodeId), out var live) && ReferenceEquals(live, condition); + IsImportedConditionId(condition.NodeId) + ? _importedConditions.IsLive(condition) + : _alarmConditions.TryGetValue(MapKey(condition.NodeId), out var live) && ReferenceEquals(live, condition); /// Adjusts the deferred depth and logs episode entry/exit. Under the gate. private void CountDeferred(int delta, AlarmConditionState condition) @@ -4318,6 +4336,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage parent.AddChild(folder); AddPredefinedNode(SystemContext, folder); _projectedAnchors[id] = (definition, folder); _projectedNodeCharges.Add(id, charge); _projectedNodeBytes += charge; + OnProjectedFolderMaterialised(folder, definition.MappingId, definition.LocalSubject); // A3 N7 nodeId = id; return true; } } @@ -4346,12 +4365,14 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage { if (_projectedVariables.Remove(id, out var child)) { + OnProjectedFolderRemoving(id); // A3 N7: a removed mapping unwires even a pinned folder if (_projectedDefinitions.Remove(id, out var definition)) RetireProjectedCharge(id, definition.Lifetime); RemoveProjectedSample(id); TombstoneMonitoredNode(id, UtcNow); child.Node.Parent?.RemoveChild(child.Node); PredefinedNodes?.Remove(id); } } + OnProjectedFolderRemoving(nodeId); _projectedAnchors.TryRemove(nodeId, out _); _projectedRootLeaves.TryRemove(nodeId, out _); RetireProjectedCharge(nodeId, anchor.Definition.Lifetime); @@ -4439,9 +4460,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage if (_projectedVariables.Count + _projectedAnchors.Count - _projectedRootLeaves.Count + Volatile.Read(ref _retiredProjectedNodes) < _maxProjectedNodes && bytes <= _maxProjectedNodeBytes - _projectedNodeBytes - Volatile.Read(ref _retiredProjectedBytes) - _projectedSampleBytes) return true; foreach (var pair in _projectedDefinitions.ToArray()) { - if (_projectedRootLeaves.ContainsKey(pair.Key) || pair.Value.AuthorityIsCurrent() || + if (_projectedRootLeaves.ContainsKey(pair.Key) || pair.Value.AuthorityIsCurrent() || IsPinnedEventFolder(pair.Key) || _projectedVariables.Values.Any(child => child.Parent == pair.Key) || !pair.Value.Lifetime.TryRetire()) continue; if (!_projectedVariables.Remove(pair.Key, out var entry)) continue; + OnProjectedFolderRemoving(pair.Key); _projectedDefinitions.Remove(pair.Key); RemoveProjectedSample(pair.Key); RemoveCommittedProjectedDefinition(pair.Key); if (_projectedNodeCharges.Remove(pair.Key, out var oldBytes)) _projectedNodeBytes -= oldBytes; @@ -4450,9 +4472,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage } foreach (var pair in _projectedAnchors.ToArray()) { - if (pair.Value.Definition.AuthorityIsCurrent() || + if (pair.Value.Definition.AuthorityIsCurrent() || IsPinnedEventFolder(pair.Key) || _projectedVariables.Values.Any(node => node.Parent == pair.Key) || !pair.Value.Definition.Lifetime.TryRetire()) continue; if (!_projectedAnchors.TryRemove(pair.Key, out var anchor)) continue; + OnProjectedFolderRemoving(pair.Key); if (_projectedRootLeaves.TryRemove(pair.Key, out _)) { _projectedVariables.Remove(pair.Key); _projectedDefinitions.Remove(pair.Key); RemoveProjectedSample(pair.Key); @@ -4826,6 +4849,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage foreach (var id in added) { if (!_projectedVariables.Remove(id, out var entry)) continue; + OnProjectedFolderRemoving(id); RemoveProjectedSample(id); _projectedDefinitions.Remove(id); if (_projectedNodeCharges.Remove(id, out var charge)) _projectedNodeBytes -= charge; @@ -4936,7 +4960,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage lock (Lock) { if (_disposing || _projectedRootLeaves.ContainsKey(nodeId) || !_projectedDefinitions.TryGetValue(nodeId, out var current) || !ReferenceEquals(current, expected) || + IsPinnedEventFolder(nodeId) || // A3 N7: a folder holding an admitted event item is not retired _projectedVariables.Values.Any(child => child.Parent == nodeId) || !_projectedVariables.Remove(nodeId, out var entry)) return false; + OnProjectedFolderRemoving(nodeId); _projectedDefinitions.Remove(nodeId); RemoveProjectedSample(nodeId); RetireProjectedCharge(nodeId, current.Lifetime); TombstoneMonitoredNode(nodeId, UtcNow); entry.Node.Parent?.RemoveChild(entry.Node); PredefinedNodes?.Remove(nodeId); @@ -5003,6 +5029,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage _projectedVariables.Add(candidate, (definition.Parent, definition.ProjectionGeneration, definition.Metadata, node, definition.AuthorityIsCurrent)); _projectedDefinitions.Add(candidate, definition); _projectedNodeCharges.Add(candidate, charge); _projectedNodeBytes += charge; + if (node is FolderState projectedFolder && definition.Metadata.View.MappingId is { } folderMapping) + OnProjectedFolderMaterialised(projectedFolder, folderMapping, definition.Metadata.View.Subject); // A3 N7 if (!stage) CommitProjectedDefinition(candidate, definition); nodeId = candidate; return true; } @@ -6046,6 +6074,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage private bool Permits(RoleCarryingUserIdentity? identity, OpcUaOperation operation, NodeId nodeId) { if (!OwnsNamespace(nodeId)) return true; + // A3 (§5.2): the imported-condition namespace has no realm — classified BEFORE RealmOf, ACLs on or off. + if (IsImportedConditionId(nodeId)) return AuthorizeImportedCondition(identity, operation, nodeId); var realm = RealmOf(nodeId); if (_projectedAnchors.TryGetValue(nodeId, out var anchor) && operation == OpcUaOperation.Browse) { @@ -6525,7 +6555,16 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage // // Only creation is gated. Refusing an UNSUBSCRIBE would strand the item on a node the session can // no longer reach — the client could never detach it, and the server would keep delivering. - if (SecurityFilteringActive && !unsubscribe + // A3 (§5.4): an event item on a projected notifier (a folder wired for imported conditions) is admitted through the + // verified path — Browse on the folder at subscribe time, the mapping gate per event at delivery and again at + // publish — instead of the mapped blanket deny that still applies to data items. + var projectedNotifier = !unsubscribe && IsHandleInNamespace(sourceId) is { } candidate && IsProjectedEventNotifier(candidate.NodeId) + ? candidate.NodeId : (NodeId?)null; + if (projectedNotifier is { } notifierId) + { + if (!Permits(IdentityOf(context), OpcUaOperation.Browse, notifierId)) return StatusCodes.BadUserAccessDenied; + } + else if (SecurityFilteringActive && !unsubscribe && IsHandleInNamespace(sourceId) is { } source && !Permits(IdentityOf(context), OpcUaOperation.CreateMonitoredItems, source.NodeId)) { @@ -6557,11 +6596,13 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage } } + TrackImportedDemand(monitoredItem, unsubscribe: true); return base.SubscribeToEvents(context, sourceId, subscriptionId, monitoredItem, unsubscribe); } var result = base.SubscribeToEvents(context, sourceId, subscriptionId, monitoredItem, unsubscribe); TrackLiveEventItem(sourceId, monitoredItem); + if (projectedNotifier is not null && ServiceResult.IsGood(result)) TrackImportedDemand(monitoredItem, unsubscribe: false); return result; } @@ -7089,6 +7130,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage ReconcileAllEventsMonitoring(); } + // A3 (§5.5): a Server-object event item could see imported conditions — it opens (or releases) per-connection demand. + // Off Lock: the access never blocks, but it is not ours to call under Lock. + TrackImportedDemand(monitoredItem, unsubscribe); + return ServiceResult.Good; } @@ -7257,10 +7302,12 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage // through its OLD equipment folder (#808). if (!IsLiveCondition(node)) return; + // A3 (§5.4): an imported condition is gated per item by the mapping gate, ACLs on or off. + var imported = _importedConditions.Find(node); List? scopes; try { - scopes = AclEnforced ? ConditionVisibilityScopes(node) : null; + scopes = imported is null && AclEnforced ? ConditionVisibilityScopes(node) : null; } catch (Exception ex) { @@ -7279,6 +7326,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage { if (e is AuditEventState && !IsAuditDeliverableTo(item)) continue; if (scopes is not null && !IsConditionVisibleTo(item, scopes, visibleByIdentity!)) continue; + if (imported is not null && !ImportedVisibleTo(item, imported)) continue; if (!RoleAllows(item, e)) continue; if (reportingSession is { IsNull: false } reportingId && item.Session?.Id is { } own @@ -7875,6 +7923,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage if (direct.Count > 0) RefreshDirectItems(systemContext, direct, enforced); if (serverItems.Count > 0) RefreshServerObjectItems(systemContext, serverItems, enforced); + // A3 (§5.4): imported conditions are replayed through the gated, marked path, ACLs on or off. + ReplayImportedConditions(serverItems, direct); return ServiceResult.Good; } finally @@ -7980,7 +8030,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage foreach (var (e, _, scopes) in replay) { // #855 review 3: never replay a condition a deploy removed or replaced since the walk collected it. - if (ConditionOf(e) is AlarmConditionState walked && !IsLiveCondition(walked)) continue; + if (ConditionOf(e) is AlarmConditionState walked && (IsImportedConditionId(walked.NodeId) || !IsLiveCondition(walked))) continue; if (scopes is not null && !IsConditionVisibleTo(item, scopes)) continue; if (ServiceResult.IsBad(ValidateEventRolePermissions(item, e))) continue; item.QueueEvent(e); @@ -8265,7 +8315,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage foreach (var e in events) { // #855 review 3: never replay a condition a deploy removed or replaced since the walk collected it. - if (ConditionOf(e) is AlarmConditionState walked && !IsLiveCondition(walked)) continue; + if (ConditionOf(e) is AlarmConditionState walked && (IsImportedConditionId(walked.NodeId) || !IsLiveCondition(walked))) continue; if (!IsDirectRefreshEventAllowed(item, e, enforced)) continue; item.QueueEvent(e); } @@ -8374,6 +8424,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage foreach (var target in live) { if (target is not BaseInstanceState instance) continue; + if (IsImportedConditionId(instance.NodeId)) continue; // A3: replayed through the marked path only // A condition materialised since the verdicts were taken is decided here (rare). if (!allowed.Contains((item, instance))) { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaSdkServer.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaSdkServer.cs index d8bf1cd39..e7a72a311 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaSdkServer.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaSdkServer.cs @@ -743,7 +743,7 @@ public sealed class OtOpcUaSdkServer : StandardServer var response = await base.PublishAsync(secureChannelContext, requestHeader, subscriptionAcknowledgements, requestLifetime) .ConfigureAwait(false); if (response?.NotificationMessage is { } projectedMessage) - response.NotificationMessage = ProjectedNotificationRewriter.Project(projectedMessage, republish: false); + response.NotificationMessage = ProjectedNotificationRewriter.Project(projectedMessage, republish: false, ImportedGateFor(requestHeader)); if (_standby.Delivery is not { } record || response?.NotificationMessage is not { } message) return response!; if (message.NotificationData.Count > 0) @@ -765,12 +765,29 @@ public sealed class OtOpcUaSdkServer : StandardServer var response = await base.RepublishAsync(secureChannelContext, requestHeader, subscriptionId, retransmitSequenceNumber, requestLifetime).ConfigureAwait(false); if (response?.NotificationMessage is { } projectedMessage) - response.NotificationMessage = ProjectedNotificationRewriter.Project(projectedMessage, republish: true); + response.NotificationMessage = ProjectedNotificationRewriter.Project(projectedMessage, republish: true, ImportedGateFor(requestHeader)); if (_standby.Delivery is { } record && response?.NotificationMessage is { NotificationData.Count: > 0 } message) response.NotificationMessage = Decide(record, subscriptionId, message); return response!; } + /// + /// A3 (§5.4): the publishing session's gate for UNMARKED imported-condition event lists (a select-clause modify rebuilt + /// them). Null when no imported condition exists (v1 path, nothing to judge). + /// + private Func? ImportedGateFor(RequestHeader? requestHeader) + { + if (NodeManager is not { HasImportedConditions: true } nm) return null; + object? identity = null; + try + { + if (requestHeader?.AuthenticationToken is { IsNull: false } token) + identity = ServerInternal?.SessionManager?.GetSession(token)?.EffectiveIdentity; + } + catch (Exception) { identity = null; } + return list => nm.ReevaluateImportedEvent(list, identity); + } + /// The recorded (or, first time, current) decision for one delivery, applied to the SDK's fresh clone. private NotificationMessage Decide(FirstDeliveryRecord record, uint subscriptionId, NotificationMessage message) { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs new file mode 100644 index 000000000..56d13ddce --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs @@ -0,0 +1,581 @@ +using System.Collections.Concurrent; +using Microsoft.Extensions.Logging; +using Opc.Ua; +using Opc.Ua.Server; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; +using ReferenceEqualityComparer = System.Collections.Generic.ReferenceEqualityComparer; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; + +/// +/// A3 (plan §5.3): one imported condition — its node, identity (connection, condition_key), current placements and the +/// projected folders it is wired into right now. Mutated only under the node manager's Lock. +/// +internal sealed class ImportedCondition(AlarmConditionState alarm, string connectionId, string conditionKey) +{ + public AlarmConditionState Alarm { get; } = alarm; + public string ConnectionId { get; } = connectionId; + public string ConditionKey { get; } = conditionKey; + public IReadOnlyList Placements { get; set; } = []; + public HashSet Folders { get; } = new(ReferenceEqualityComparer.Instance); + /// The last origin record applied (state known), re-applied with another Quality on staleness. + public AlarmConditionSnapshot? Last { get; set; } + public DataActivationMarker? Activation { get; set; } + /// N6: consumer-minted EventIds of this condition's recent events → the activation marker each described. + public LinkedList<(ByteString EventId, DataActivationMarker? Activation)> RecentEvents { get; } = new(); + /// Bumped on every placement change (verdict caches key on it). + public long PlacementVersion { get; set; } + /// Native (driver-fed) at the origin: Confirm / shelve / enable have no upstream path. + public bool IsNative { get; init; } +} + +/// +/// A3: what a consumer-minted EventId of an imported condition resolves to — the seam remote condition methods (A3b, §5.6) +/// dispatch through: the connection, the origin's opaque key, the PRIMARY placement (the address the origin resolves), and +/// the activation marker of the event the client saw. +/// +public sealed record ImportedConditionBinding(string ConnectionId, string ConditionKey, ImportedConditionPlacement Primary, + IReadOnlyList Placements, DataActivationMarker? Activation, bool IsNative); + +/// +/// A3 (plan §5.3, N7): the consumer's imported-condition registry, keyed by FULL NodeId in the +/// https://zb.com/otopcua/mapped/conditions namespace. Imported conditions never enter the realm-keyed maps +/// (_alarmConditions and friends). Mutated only under the node manager's Lock; and +/// are lock-free reads. +/// +internal sealed class ProjectedConditionRegistry +{ + /// Recent EventIds kept per condition for N6 re-binding. + internal const int RecentEventIds = 32; + + private readonly ConcurrentDictionary _byNode = new(); + private readonly ConcurrentDictionary _byInstance = new(ReferenceEqualityComparer.Instance); + /// (mapping, folder local subject) → conditions placed there (wired or waiting for the folder to materialise). + internal readonly Dictionary<(string Mapping, string Subject), HashSet> ByFolderKey = new(); + /// Projected folder node → conditions wired into it. + internal readonly Dictionary> WiredByFolder = new(); + private readonly object _verdictGate = new(); + private readonly Dictionary<(object Identity, NodeId Condition), (long Generation, long PlacementVersion, bool Allowed)> _verdicts = new(); + + public int Count => _byNode.Count; + public IEnumerable All => _byNode.Values; + public bool IsLive(NodeState node) => node is AlarmConditionState alarm && _byInstance.ContainsKey(alarm); + public ImportedCondition? Find(NodeState? node) => + node is AlarmConditionState alarm && _byInstance.TryGetValue(alarm, out var c) ? c : null; + public ImportedCondition? Find(NodeId id) => _byNode.TryGetValue(id, out var c) ? c : null; + public bool IsWiredTo(ImportedCondition condition, NodeState notifier) => + notifier is FolderState folder && condition.Folders.Contains(folder) && _byInstance.ContainsKey(condition.Alarm); + + public void Add(ImportedCondition condition) + { + _byNode[condition.Alarm.NodeId] = condition; + _byInstance[condition.Alarm] = condition; + } + + public void Remove(ImportedCondition condition) + { + _byNode.TryRemove(condition.Alarm.NodeId, out _); + _byInstance.TryRemove(condition.Alarm, out _); + foreach (var key in condition.Placements.Select(FolderKey).Distinct()) + if (ByFolderKey.TryGetValue(key, out var set) && set.Remove(condition.Alarm.NodeId) && set.Count == 0) ByFolderKey.Remove(key); + lock (_verdictGate) + foreach (var stale in _verdicts.Keys.Where(k => k.Condition == condition.Alarm.NodeId).ToList()) _verdicts.Remove(stale); + } + + public static (string, string) FolderKey(ImportedConditionPlacement p) => (p.MappingId, p.FolderLocalSubject); + + /// The §5.4 verdict, cached per (identity, condition, authority generation, placement version). + public bool Verdict(object identity, ImportedCondition condition, long generation, Func compute) + { + var key = (identity, condition.Alarm.NodeId); + lock (_verdictGate) + { + if (_verdicts.TryGetValue(key, out var cached) && cached.Generation == generation && cached.PlacementVersion == condition.PlacementVersion) + return cached.Allowed; + } + var allowed = compute(); + lock (_verdictGate) + { + if (_verdicts.Count >= 65_536) _verdicts.Clear(); // bounded: a flood of identities only costs recomputation + _verdicts[key] = (generation, condition.PlacementVersion, allowed); + } + return allowed; + } +} + +public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink +{ + /// Most imported updates applied per Lock hold (bounded Lock holds, A1 lessons). + internal const int ImportedApplyChunk = 128; + + private readonly ProjectedConditionRegistry _importedConditions = new(); + private readonly ConcurrentDictionary _importedEventDemand = new(); + private long _importedEventsReported, _importedRefreshRequired; + + /// A3: the consumer's condition gate + demand (null on a node with no data connections). + public IProjectedConditionAccess? ProjectedConditionAccess { get; set; } + + /// Whether any imported condition is materialised (the publish rewriter's fast exit). + internal bool HasImportedConditions => _importedConditions.Count > 0; + + /// Imported conditions currently materialised (test/diagnostic observation). + internal int ImportedConditionCount => _importedConditions.Count; + + /// Imported condition events reported (one per genuine origin transition). + internal long ImportedEventsReported => Interlocked.Read(ref _importedEventsReported); + + /// RefreshRequired events queued for imported conditions. + internal long ImportedRefreshRequiredQueued => Interlocked.Read(ref _importedRefreshRequired); + + /// + /// A3 (§5.2 N4): whether is in the imported-condition namespace. Every NodeId classifier + /// (authorizer, read, history, call) asks this BEFORE , which would fold it into Uns. + /// + internal bool IsImportedConditionId(NodeId nodeId) => + NamespaceIndexes.Count > 4 && nodeId.NamespaceIndex == NamespaceIndexes[4]; + + /// The imported-condition NodeId for (connection, condition_key) — never the mapping or placement (N4). + internal NodeId ImportedConditionNodeId(string connectionId, string conditionKey) => + new(ImportedConditionIds.Identifier(connectionId, conditionKey), NamespaceIndexes[4]); + + /// The imported condition an event is about (its snapshot handle, or an audit's SourceNode), or null. + private ImportedCondition? ImportedOf(IFilterTarget e) + { + if (_importedConditions.Count == 0) return null; + var node = ConditionOf(e); + if (_importedConditions.Find(node) is { } c) return c; + return node is BaseEventState { SourceNode.Value: { IsNull: false } source } && IsImportedConditionId(source) + ? _importedConditions.Find(source) + : null; + } + + /// + /// A3 (§5.4): the mapping gate (CreateMonitoredItems on ANY current placement mapping) for an item's identity, + /// REGARDLESS of Security:Acl:Enabled. No access wired / no role-carrying identity ⇒ false. + /// + private bool ImportedVisibleTo(IEventMonitoredItem item, ImportedCondition condition) => + ImportedVisibleTo(item.EffectiveIdentity, condition); + + private bool ImportedVisibleTo(object? identity, ImportedCondition condition) + { + if (ProjectedConditionAccess is not { } access || identity is not RoleCarryingUserIdentity caller) return false; + var generation = access.AuthorityGeneration; + var placements = condition.Placements; + return _importedConditions.Verdict(caller, condition, generation, () => access.CanSee(caller, placements)); + } + + /// The marker a queued imported event carries: re-checked at every Publish and Republish (§5.4). + private ProjectedEventMarker ImportedMarker(IEventMonitoredItem item, ImportedCondition condition) + { + var identity = item.EffectiveIdentity; + var generation = ProjectedConditionAccess?.AuthorityGeneration ?? 0; + return new ProjectedEventMarker(identity, condition.Alarm.NodeId, generation, + () => _importedConditions.IsLive(condition.Alarm) && ImportedVisibleTo(identity, condition)); + } + + /// Imported-condition events always take the marked path, whatever says. + private void QueueImportedToItem(IEventMonitoredItem item, IFilterTarget e, ImportedCondition condition) + { + var cache = e is ConditionEventSnapshot snapshot ? snapshot.DeliveryCache : new EventDeliveryCache(); + if (cache.QueueMarked(Server, item, e, i => ImportedMarker(i, condition))) Interlocked.Increment(ref _projectedDeliveries); + } + + /// + /// §5.4: the publish-time gate for an UNMARKED list (a select-clause modify rebuilt it). Null when the list is not an + /// imported-condition event; otherwise the gate re-evaluated for the publishing session. + /// + internal bool? ReevaluateImportedEvent(EventFieldList list, object? identity) + { + if (list.Handle is not InstanceStateSnapshot { Handle: ConditionState condition } || !IsImportedConditionId(condition.NodeId)) + return null; + return _importedConditions.Find(condition.NodeId) is { } live && ReferenceEquals(live.Alarm, condition) + && ImportedVisibleTo(identity, live); + } + + /// + /// A3 (§5.4): the authorizer's classifier for an imported-condition id (or a child of one): Browse / Read / + /// CreateMonitoredItems are allowed when the caller passes the mapping gate on any placement; everything else + /// (Call — A3b, HistoryRead, writes) is refused here. + /// + internal bool AuthorizeImportedCondition(RoleCarryingUserIdentity? identity, OpcUaOperation operation, NodeId nodeId) + { + if (operation is not (OpcUaOperation.Browse or OpcUaOperation.Read or OpcUaOperation.CreateMonitoredItems)) return false; + if (!nodeId.TryGetValue(out string identifier) + || !ImportedConditionIds.TryParse(identifier, out var conditionIdentifier, out _, out _, out _)) return false; + var condition = _importedConditions.Find(new NodeId(conditionIdentifier, nodeId.NamespaceIndex)); + return condition is not null && ImportedVisibleTo(identity, condition); + } + + /// + /// A3b seam (§5.6, N6): resolves an imported condition NodeId and a consumer-minted EventId to its connection, origin + /// key, primary placement and the activation marker the event described. False for an unknown condition or EventId. + /// + public bool TryResolveImportedEvent(NodeId conditionId, ByteString eventId, out ImportedConditionBinding? binding) + { + binding = null; + lock (Lock) + { + if (_importedConditions.Find(conditionId) is not { Placements.Count: > 0 } c) return false; + foreach (var (id, activation) in c.RecentEvents) + { + if (id != eventId) continue; + binding = new(c.ConnectionId, c.ConditionKey, c.Placements[0], c.Placements, activation, c.IsNative); + return true; + } + return false; + } + } + + // --------------------------------------------------------------------------------------------------------------------- + // IProjectedConditionSink + // --------------------------------------------------------------------------------------------------------------------- + + /// + public void ApplyConditions(IReadOnlyList updates) + { + ArgumentNullException.ThrowIfNull(updates); + EnsureAddressSpaceCreated(); + for (var start = 0; start < updates.Count; start += ImportedApplyChunk) + { + lock (Lock) + { + if (_disposing) return; + var index = ProjectedFolderIndex(); + for (var i = start; i < Math.Min(updates.Count, start + ImportedApplyChunk); i++) + { + try { ApplyImported(updates[i], index); } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or ServiceResultException) + { + _logger.LogWarning(ex, "OtOpcUaNodeManager: imported condition update refused (connection {Connection})", + updates[i].ConnectionId); + } + } + } + } + } + + /// + public void RemoveConditions(string connectionId, IReadOnlyCollection conditionKeys) + { + var keys = conditionKeys.ToArray(); + for (var start = 0; start < keys.Length; start += ImportedApplyChunk) + { + lock (Lock) + { + foreach (var key in keys.Skip(start).Take(ImportedApplyChunk)) + { + if (!ImportedConditionIds.IsWellFormedConditionKey(key)) continue; + if (_importedConditions.Find(ImportedConditionNodeId(connectionId, key)) is { } c) RemoveImported(c); + } + } + } + } + + /// + public void MarkConnectionStale(string connectionId) + { + List targets; + lock (Lock) targets = _importedConditions.All.Where(c => string.Equals(c.ConnectionId, connectionId, StringComparison.OrdinalIgnoreCase)).ToList(); + for (var start = 0; start < targets.Count; start += ImportedApplyChunk) + { + lock (Lock) + { + foreach (var c in targets.Skip(start).Take(ImportedApplyChunk)) + { + if (!_importedConditions.IsLive(c.Alarm)) continue; + var stale = (c.Last ?? CurrentSnapshot(c.Alarm)) with { StatusCode = StatusCodes.BadNoCommunication.Code }; + if (ApplyConditionState(c.Alarm, stale, UtcNow)) ReportImported(c, UtcNow); + } + } + } + } + + /// + public void RequireRefresh(string connectionId) + { + List<(IEventMonitoredItem Item, bool Allowed)> targets = []; + lock (Lock) + { + var conditions = _importedConditions.All.Where(c => string.Equals(c.ConnectionId, connectionId, StringComparison.OrdinalIgnoreCase)).ToList(); + if (conditions.Count == 0) return; + var items = new HashSet(_allEventsItems.Keys, ReferenceEqualityComparer.Instance); + foreach (var folder in conditions.SelectMany(c => c.Folders).Distinct()) + if (MonitoredNodes.TryGetValue(folder.NodeId, out var monitored) && monitored.EventMonitoredItems is { } attached) + foreach (var item in attached.Values) if (item is not null) items.Add(item); + foreach (var item in items) targets.Add((item, conditions.Any(c => ImportedVisibleTo(item, c)))); + } + foreach (var (item, allowed) in targets) + { + if (!allowed) continue; + var e = new RefreshRequiredEventState(null); + e.Initialize(SystemContext, null, EventSeverity.Low, new LocalizedText("RefreshRequired")); + e.SetChildValue(SystemContext, BrowseNames.SourceNode, ObjectIds.Server, false); + e.SetChildValue(SystemContext, BrowseNames.SourceName, "Server", false); + item.QueueEvent(e); + Interlocked.Increment(ref _importedRefreshRequired); + } + } + + // --------------------------------------------------------------------------------------------------------------------- + // Materialise / apply / remove (under Lock) + // --------------------------------------------------------------------------------------------------------------------- + + private void ApplyImported(ImportedConditionUpdate update, Dictionary<(string, string), FolderState> folders) + { + var state = update.State; + if (update.Placements.Count == 0) throw new ArgumentException("An imported condition needs a placement.", nameof(update)); + var id = ImportedConditionNodeId(update.ConnectionId, state.ConditionKey); + if (state.Removed) + { + if (_importedConditions.Find(id) is { } gone) RemoveImported(gone); + return; + } + + var condition = _importedConditions.Find(id); + if (condition is null) + { + var info = update.Info; + var name = string.IsNullOrWhiteSpace(info?.ConditionName) ? state.ConditionKey : info!.ConditionName; + var native = info?.SourceKind == DataConditionSourceKind.Native; + var type = info?.ConditionType is { } t && t.Contains("OffNormalAlarm", StringComparison.Ordinal) ? "OffNormalAlarm" + : info?.ConditionType is { } d && d.Contains("DiscreteAlarm", StringComparison.Ordinal) ? "DiscreteAlarm" : "AlarmCondition"; + var alarm = CreateConditionNode(type, null, id, name, update.SourceName, (int)Math.Clamp(state.Severity, 1u, 1000u), native); + // A3a: no local apply of a remote method. Remote dispatch (claim / base.Call / await) is A3b (§5.6); until then + // every Part 9 method on an imported condition is refused before the SDK touches its state. + alarm.OnAcknowledge = (_, _, _, _) => new ServiceResult(StatusCodes.BadNotSupported); + alarm.OnConfirm = (_, _, _, _) => new ServiceResult(StatusCodes.BadNotSupported); + alarm.OnAddComment = (_, _, _, _) => new ServiceResult(StatusCodes.BadNotSupported); + alarm.OnShelve = (_, _, _, _, _) => new ServiceResult(StatusCodes.BadNotSupported); + alarm.OnTimedUnshelve = (_, _) => ServiceResult.Good; + alarm.OnEnableDisable = (_, _, _) => new ServiceResult(StatusCodes.BadNotSupported); + alarm.OnReportEvent = OnConditionReportEvent; + AddPredefinedNode(SystemContext, alarm); + condition = new ImportedCondition(alarm, update.ConnectionId, state.ConditionKey) { IsNative = native }; + if (!state.StateKnown && alarm.Quality is not null) + { + // §5.1 T2: unknown at first sight ⇒ Uncertain, never "known inactive". + alarm.Quality.Value = StatusCodes.UncertainInitialValue; + } + _importedConditions.Add(condition); + } + + UpdatePlacements(condition, update.Placements, folders); + if (condition.Alarm.SourceName is { } sourceName) sourceName.Value = update.SourceName; // display only; rides the next event + + // §5.1 T2: a record with state_known = false never changes the consumer's last state. + if (!state.StateKnown) return; + var snapshot = new AlarmConditionSnapshot(state.Active, state.Acknowledged, state.Confirmed, state.Enabled, + Enum.IsDefined(typeof(AlarmShelvingKind), state.Shelving) ? (AlarmShelvingKind)state.Shelving : AlarmShelvingKind.Unshelved, + (ushort)Math.Clamp(state.Severity, 1u, 1000u), state.Message ?? "", state.Quality, + state.UnshelveAtUtc?.UtcDateTime, + Enum.IsDefined(typeof(AlarmConditionClass), state.ConditionClass) ? (AlarmConditionClass)state.ConditionClass : null); + var ts = state.TimeUtc?.UtcDateTime ?? UtcNow; + if (condition.Alarm.Comment is { } comment && state.Comment is not null) comment.Value = new LocalizedText(state.Comment); + if (condition.Alarm.ClientUserId is { } user && state.ClientUserId is not null) user.Value = state.ClientUserId; + condition.Activation = state.Activation; + condition.Last = snapshot; + if (ApplyConditionState(condition.Alarm, snapshot, ts)) ReportImported(condition, ts); + } + + /// Reports one imported event (stamping a consumer-minted EventId, N6) through the shared reporter. + private void ReportImported(ImportedCondition condition, DateTime ts) + { + ReportConditionEvent(condition.Alarm, ts); + Interlocked.Increment(ref _importedEventsReported); + if (condition.Alarm.EventId?.Value is { } eventId) + { + condition.RecentEvents.AddFirst((eventId, condition.Activation)); + while (condition.RecentEvents.Count > ProjectedConditionRegistry.RecentEventIds) condition.RecentEvents.RemoveLast(); + } + } + + private void RemoveImported(ImportedCondition condition) + { + foreach (var folder in condition.Folders.ToList()) UnwireImportedFolder(condition, folder); + _importedConditions.Remove(condition); + TombstoneMonitoredSubtree(condition.Alarm, UtcNow); + ForgetPredefinedSubtree(condition.Alarm); + } + + /// A snapshot of a node's current state (staleness before any known record arrived). + private static AlarmConditionSnapshot CurrentSnapshot(AlarmConditionState alarm) => new( + alarm.ActiveState?.Id?.Value == true, alarm.AckedState?.Id?.Value != false, alarm.ConfirmedState?.Id?.Value != false, + alarm.EnabledState?.Id?.Value != false, AlarmShelvingKind.Unshelved, (ushort)Math.Clamp((int)(alarm.Severity?.Value ?? 1), 1, 1000), + alarm.Message?.Value.Text ?? "", alarm.Quality?.Value.Code ?? StatusCodes.Good.Code); + + // --------------------------------------------------------------------------------------------------------------------- + // Notifier wiring (N7): lazy, symmetric + // --------------------------------------------------------------------------------------------------------------------- + + /// (mapping, local subject) → materialised projected folder (anchors included). One scan per apply batch. + private Dictionary<(string, string), FolderState> ProjectedFolderIndex() + { + var index = new Dictionary<(string, string), FolderState>(); + if (_importedConditions.ByFolderKey.Count == 0 && _projectedVariables.Count + _projectedAnchors.Count == 0) return index; + foreach (var anchor in _projectedAnchors.Values) + if (anchor.Node is FolderState folder) index.TryAdd((anchor.Definition.MappingId, anchor.Definition.LocalSubject), folder); + foreach (var entry in _projectedVariables.Values) + if (entry.Node is FolderState folder && entry.Metadata.View.MappingId is { } mapping) + index.TryAdd((mapping, entry.Metadata.View.Subject), folder); + return index; + } + + private void UpdatePlacements(ImportedCondition condition, IReadOnlyList placements, + Dictionary<(string, string), FolderState> folders) + { + var before = condition.Placements.Select(ProjectedConditionRegistry.FolderKey).ToHashSet(); + var after = placements.Select(ProjectedConditionRegistry.FolderKey).ToHashSet(); + if (!condition.Placements.SequenceEqual(placements)) condition.PlacementVersion++; + condition.Placements = placements; + foreach (var key in before.Except(after)) + if (_importedConditions.ByFolderKey.TryGetValue(key, out var set) && set.Remove(condition.Alarm.NodeId) && set.Count == 0) + _importedConditions.ByFolderKey.Remove(key); + foreach (var key in after) + { + if (!_importedConditions.ByFolderKey.TryGetValue(key, out var set)) _importedConditions.ByFolderKey[key] = set = []; + set.Add(condition.Alarm.NodeId); + } + var desired = new HashSet(ReferenceEqualityComparer.Instance); + foreach (var key in after) if (folders.TryGetValue(key, out var f)) desired.Add(f); + foreach (var folder in condition.Folders.Where(f => !desired.Contains(f)).ToList()) UnwireImportedFolder(condition, folder); + foreach (var folder in desired) WireImportedFolder(condition, folder); + } + + private void WireImportedFolder(ImportedCondition condition, FolderState folder) + { + if (!condition.Folders.Add(folder)) return; + condition.Alarm.AddNotifier(SystemContext, NodeId.Null, isInverse: true, folder); + folder.AddNotifier(SystemContext, NodeId.Null, isInverse: false, condition.Alarm); + if (!_importedConditions.WiredByFolder.TryGetValue(folder.NodeId, out var wired)) + { + _importedConditions.WiredByFolder[folder.NodeId] = wired = []; + // Projected folders are created with EventNotifier = None (NM projected page sink); promoted only while wired. + folder.EventNotifier = (byte)(folder.EventNotifier | EventNotifiers.SubscribeToEvents); + AddRootNotifier(folder); + folder.ClearChangeMasks(SystemContext, includeChildren: false); + } + wired.Add(condition.Alarm.NodeId); + condition.PlacementVersion++; + } + + private void UnwireImportedFolder(ImportedCondition condition, FolderState folder) + { + if (!condition.Folders.Remove(folder)) return; + condition.Alarm.RemoveNotifier(SystemContext, folder, bidirectional: true); + condition.PlacementVersion++; + if (_importedConditions.WiredByFolder.TryGetValue(folder.NodeId, out var wired) && wired.Remove(condition.Alarm.NodeId) && wired.Count == 0) + { + _importedConditions.WiredByFolder.Remove(folder.NodeId); + RemoveRootNotifier(folder); + folder.EventNotifier = (byte)(folder.EventNotifier & ~EventNotifiers.SubscribeToEvents); + folder.ClearChangeMasks(SystemContext, includeChildren: false); + } + } + + /// A projected folder (or anchor) materialised: wire every imported condition placed there (N7). Under Lock. + private void OnProjectedFolderMaterialised(FolderState folder, string mappingId, string localSubject) + { + if (_importedConditions.Count == 0 || !_importedConditions.ByFolderKey.TryGetValue((mappingId, localSubject), out var set)) return; + foreach (var id in set.ToList()) + if (_importedConditions.Find(id) is { } c) WireImportedFolder(c, folder); + } + + /// A projected folder is being removed: unwire it symmetrically first (N7). Under Lock. + private void OnProjectedFolderRemoving(NodeId folderId) + { + if (!_importedConditions.WiredByFolder.TryGetValue(folderId, out var wired)) return; + foreach (var id in wired.ToList()) + { + if (_importedConditions.Find(id) is not { } c) continue; + var folder = c.Folders.FirstOrDefault(f => f.NodeId == folderId); + if (folder is not null) UnwireImportedFolder(c, folder); + } + } + + /// + /// N7: a projected folder holding an admitted event item is pinned — capacity eviction and page removal skip it (a + /// mapping removal still removes it, unwiring first). Under Lock. + /// + private bool IsPinnedEventFolder(NodeId nodeId) => + _importedConditions.WiredByFolder.ContainsKey(nodeId) + && MonitoredNodes.TryGetValue(nodeId, out var monitored) && monitored.EventMonitoredItems is { Count: > 0 }; + + /// A projected folder currently wired as a notifier of an imported condition (event items there are admitted, §5.4). + private bool IsProjectedEventNotifier(NodeId nodeId) + { + if (_importedConditions.Count == 0) return false; + lock (Lock) return _importedConditions.WiredByFolder.ContainsKey(nodeId); + } + + /// + /// The authorizer's pre-realm classifier (§5.2): null for any id outside the imported-condition namespace, otherwise + /// the imported verdict. + /// + internal bool? ClassifyImportedCondition(RoleCarryingUserIdentity? identity, OpcUaOperation operation, NodeId nodeId) => + IsImportedConditionId(nodeId) ? AuthorizeImportedCondition(identity, operation, nodeId) : null; + + /// Test observation: whether a projected folder is currently wired as a notifier of some imported condition. + internal bool IsImportedNotifierWired(NodeId folderId) + { + lock (Lock) return _importedConditions.WiredByFolder.ContainsKey(folderId); + } + + /// Test observation: the imported condition node for (connection, key), or null. + internal AlarmConditionState? FindImportedCondition(string connectionId, string conditionKey) => + _importedConditions.Find(ImportedConditionNodeId(connectionId, conditionKey))?.Alarm; + + // --------------------------------------------------------------------------------------------------------------------- + // Demand + ConditionRefresh + // --------------------------------------------------------------------------------------------------------------------- + + /// An admitted event item (Server object or projected notifier) opens condition demand; its removal releases it. + private void TrackImportedDemand(IEventMonitoredItem item, bool unsubscribe) + { + if (unsubscribe) + { + if (_importedEventDemand.TryRemove(item, out var lease)) lease.Dispose(); + return; + } + if (ProjectedConditionAccess is not { } access || _importedEventDemand.ContainsKey(item)) return; + IDisposable? acquired; + try { acquired = access.AcquireEventDemand(item.EffectiveIdentity as RoleCarryingUserIdentity); } + catch (Exception ex) { _logger.LogWarning(ex, "OtOpcUaNodeManager: imported condition demand failed"); return; } + if (acquired is not null && !_importedEventDemand.TryAdd(item, acquired)) acquired.Dispose(); + } + + /// + /// ConditionRefresh for imported conditions: every retained one the item may see, through the marked path. Server-object + /// items see all; a direct item only those wired to its notifier. One Lock hold (consistent with synchronous events). + /// + private void ReplayImportedConditions(List serverItems, List directItems) + { + if (_importedConditions.Count == 0) return; + lock (Lock) + { + var retained = _importedConditions.All.Where(c => c.Alarm.Retain?.Value == true).ToList(); + if (retained.Count == 0) return; + var snapshots = new Dictionary(ReferenceEqualityComparer.Instance); + InstanceStateSnapshot SnapshotOf(ImportedCondition c) + { + if (snapshots.TryGetValue(c, out var s)) return s; + s = new InstanceStateSnapshot(); + s.Initialize(SystemContext, c.Alarm); + return snapshots[c] = s; + } + foreach (var item in serverItems) + foreach (var c in retained) + if (ImportedVisibleTo(item, c) && !ServiceResult.IsBad(ValidateEventRolePermissions(item, c.Alarm))) + new EventDeliveryCache().QueueMarked(Server, item, SnapshotOf(c), i => ImportedMarker(i, c)); + foreach (var item in directItems) + { + if (!MonitoredItems.ContainsKey(item.Id) || (item.ManagerHandle as NodeHandle)?.Node is not FolderState notifier) continue; + foreach (var c in retained) + if (c.Folders.Contains(notifier) && ImportedVisibleTo(item, c) && !ServiceResult.IsBad(ValidateEventRolePermissions(item, c.Alarm))) + new EventDeliveryCache().QueueMarked(Server, item, SnapshotOf(c), i => ImportedMarker(i, c)); + } + } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedEventDelivery.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedEventDelivery.cs index 0f1aa859d..17cacc98a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedEventDelivery.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedEventDelivery.cs @@ -101,6 +101,24 @@ internal sealed class EventDeliveryCache return false; } + /// + /// A3 (§5.4): queues an imported-condition event ALWAYS through the projected path with a + /// marker, whatever the node manager's UseProjectedEventDelivery switch + /// says. An item of a shape the projected path cannot serve gets nothing (fail closed, counted) — never the SDK's + /// unmarked QueueEvent(IFilterTarget). + /// + /// True when queued (or decided not to queue exactly as the SDK would). + public bool QueueMarked(IServerInternal server, IEventMonitoredItem item, IFilterTarget e, Func marker) + { + if (item.GetType() == typeof(SdkMonitoredItem) + && e is InstanceStateSnapshot { Handle: ConditionState condition } + && condition.SupportsFilteredRetain?.Value != true + && ProjectedEventDelivery.TryQueue(server, (SdkMonitoredItem)item, e, this, marker)) + return true; + Interlocked.Increment(ref ProjectedEventFieldList.s_unservable); + return false; + } + /// Marks the item as queued for this report; false when it already was (the SDK's duplicate check). internal bool TryMarkQueued(IEventMonitoredItem item) { @@ -216,7 +234,8 @@ internal static class ProjectedEventDelivery /// The SDK's QueueEvent(instance, bypassFilter: false) for one condition snapshot, with the projection taken /// from . Returns false (nothing done) when the item is not in a shape this reproduces. /// - internal static bool TryQueue(IServerInternal server, SdkMonitoredItem item, IFilterTarget e, EventDeliveryCache cache) + internal static bool TryQueue(IServerInternal server, SdkMonitoredItem item, IFilterTarget e, EventDeliveryCache cache, + Func? marker = null) { if (!Available || (item.MonitoredItemType & 2) == 0) return false; @@ -237,12 +256,20 @@ internal static class ProjectedEventDelivery if (!projection.Passes || handler.SetQueueOverflowIfFull()) return true; Interlocked.Increment(ref s_projectedQueued); - item.QueueEvent(new EventFieldList - { - ClientHandle = item.ClientHandle, - Handle = e, - EventFields = projection.Fields, // shared, read-only (see Projection) - }); + // A3 (§5.4): an imported condition's list carries its publish-time re-check (ProjectedNotificationRewriter). + item.QueueEvent(marker is null + ? new EventFieldList + { + ClientHandle = item.ClientHandle, + Handle = e, + EventFields = projection.Fields, // shared, read-only (see Projection) + } + : new ProjectedEventFieldList(marker(item)) + { + ClientHandle = item.ClientHandle, + Handle = e, + EventFields = projection.Fields, + }); return true; } } @@ -412,3 +439,40 @@ internal static class ProjectedEventDelivery return property.GetMethod.CreateDelegate>(); } } + +/// +/// A3 (§5.4): the captured authority of one queued imported-condition event — the caller, the condition, the authority +/// generation it was admitted under and a re-check, like ProjectedNotificationMarker for data. +/// +internal sealed record ProjectedEventMarker(object? Identity, NodeId ConditionId, long Generation, Func Recheck) +{ + /// Re-evaluates the gate; any failure denies. + public bool Permits() + { + try { return Recheck(); } + catch { return false; } + } +} + +/// +/// A3 (§5.4): an carrying its . The SDK never clones a +/// queued list on its way to the wire (SDK 2.0.1: QueueEvent(EventFieldList) enqueues the instance, +/// Publish dequeues it, ConstructMessage places it, Republish returns the stored message), so +/// ProjectedNotificationRewriter sees this instance on every Publish and Republish and drops it when the re-check +/// fails. +/// +internal sealed class ProjectedEventFieldList(ProjectedEventMarker marker) : EventFieldList +{ + internal static long s_unservable, s_droppedOnPublish, s_droppedUnmarked, s_keptUnmarked; + + public ProjectedEventMarker Marker { get; } = marker; + + /// Imported events an item could not receive through the marked path (fail closed). + internal static long Unservable => Interlocked.Read(ref s_unservable); + /// Marked events dropped at Publish/Republish because the re-check failed. + internal static long DroppedOnPublish => Interlocked.Read(ref s_droppedOnPublish); + /// Unmarked imported events (rebuilt by a select-clause modify) dropped because the gate denied. + internal static long DroppedUnmarked => Interlocked.Read(ref s_droppedUnmarked); + /// Unmarked imported events kept after the gate re-evaluated them for the publishing session. + internal static long KeptUnmarked => Interlocked.Read(ref s_keptUnmarked); +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs index f3bfdce2a..663f5b457 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs @@ -141,6 +141,12 @@ public sealed class DataPlaneAuthorizer /// Live catalog classification owned by the node manager, consulted before either local path resolver. public Func? MappedSubjectResolver { get; set; } + /// + /// A3: the node manager's imported-condition classifier — null for an id outside the imported-condition namespace, + /// otherwise the verdict (Browse/Read/CreateMonitoredItems via the condition's mapping gate; anything else refused). + /// + public Func? ImportedConditionClassifier { get; set; } + /// Optional actual-namespace filter for projected subject classification. public Func? MappedNamespacePredicate { get; set; } @@ -162,6 +168,20 @@ public sealed class DataPlaneAuthorizer public bool TryAuthorizeMapped(RoleCarryingUserIdentity? identity, OpcUaOperation operation, NodeId nodeId, AddressSpaceRealm realm, out ServiceResult? veto) { + // A3 (§5.2 N4): the imported-condition namespace has NO realm; it is classified before anything reads `realm` (which a + // caller computed with the node manager's RealmOf, folding it into Uns). Every entry point (Authorize, AuthorizeIfRequired, + // IsAllowedCached, TryAuthorizeMapped) reaches this first, ACLs on or off. + if (ImportedConditionClassifier is { } imported) + { + bool? verdict; + try { verdict = imported(identity, operation, nodeId); } + catch (Exception ex) + { + _log.LogWarning(ex, "Imported condition classification failed"); + verdict = false; + } + if (verdict is { } decided) { veto = decided ? null : DeniedResult; return true; } + } var resolver = MappedSubjectResolver; if (MappedNamespacePredicate is { } predicate && !predicate(nodeId)) { veto = null; return false; } if (resolver is null) { veto = null; return false; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/WarmStandby.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/WarmStandby.cs index 38fcb2eb2..68786bb82 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/WarmStandby.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/WarmStandby.cs @@ -916,12 +916,48 @@ internal sealed class ProjectedLossMarker(uint clientHandle, ProjectedMonitoredI /// Rechecks captured projected notification authority for every delivery and retransmission. internal static class ProjectedNotificationRewriter { - public static NotificationMessage Project(NotificationMessage message, bool republish) + public static NotificationMessage Project(NotificationMessage message, bool republish) => Project(message, republish, null); + + /// The message about to be sent (Publish) or re-sent (Republish). + /// Whether this is a Republish. + /// + /// A3 (§5.4): for an UNMARKED event list whose Handle is an imported-condition snapshot (a select-clause + /// ModifyMonitoredItems rebuilt it through GetEventFields), re-evaluates the gate for the publishing + /// session: true keeps it, false drops it; null = not an imported condition (kept, v1 behaviour). + /// + public static NotificationMessage Project(NotificationMessage message, bool republish, Func? importedGate) { var changed = false; var payloads = new List(message.NotificationData.Count); foreach (var payload in message.NotificationData) { + if (payload.TryGetValue(out var events) && events is not null) + { + var kept = new List(events.Events.Count); + foreach (var list in events.Events) + { + if (list is ProjectedEventFieldList marked) + { + if (marked.Marker.Permits()) kept.Add(list); + else Interlocked.Increment(ref ProjectedEventFieldList.s_droppedOnPublish); + continue; + } + bool? verdict; + try { verdict = importedGate?.Invoke(list); } + catch { verdict = false; } + if (verdict == false) { Interlocked.Increment(ref ProjectedEventFieldList.s_droppedUnmarked); continue; } + if (verdict == true) Interlocked.Increment(ref ProjectedEventFieldList.s_keptUnmarked); + kept.Add(list); + } + if (kept.Count == events.Events.Count) payloads.Add(payload); + else + { + changed = true; + // Events have no Bad-value form: a denied event is dropped; an emptied list leaves the payload out. + if (kept.Count > 0) payloads.Add(new ExtensionObject(new EventNotificationList { Events = kept })); + } + continue; + } if (!payload.TryGetValue(out var change) || change is null) { payloads.Add(payload); continue; } var items = new List(change.MonitoredItems.Count); From 4f6e26dd4ecbad78c8ea029d442d4adab4e7f127 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 16:28:45 -0500 Subject: [PATCH 04/32] =?UTF-8?q?feat(grpc-data):=20A3=20ProjectedConditio?= =?UTF-8?q?nAccess=20=E2=80=94=20per-connection=20demand,=20snapshot=20bar?= =?UTF-8?q?rier,=20condition=20budget,=20version=20rule,=20re-snapshot=20l?= =?UTF-8?q?ifetime,=20mapping=20gate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ProjectedConditionAccess.cs | 624 ++++++++++++++++++ 1 file changed, 624 insertions(+) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs new file mode 100644 index 000000000..8d2ed3ce0 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs @@ -0,0 +1,624 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using ZB.MOM.WW.OtOpcUa.Commons.Observability; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// A3: the deployed mapping placements the condition runtime reads (an adapter over ). +public interface IProjectedConditionMappings +{ + /// The currently published placements (copies; read on change only). + IReadOnlyList Current { get; } + + /// Raised after the published placement set changes. + event Action? Changed; +} + +/// The production adapter over . +public sealed class DeployedConditionMappings : IProjectedConditionMappings +{ + private readonly ProjectedMappingDeploymentRuntime _runtime; + private volatile IReadOnlyList _current; + + public DeployedConditionMappings(ProjectedMappingDeploymentRuntime runtime) + { + _runtime = runtime ?? throw new ArgumentNullException(nameof(runtime)); + _current = runtime.Active; + runtime.Changed += placements => { _current = placements; Changed?.Invoke(); }; + } + + public IReadOnlyList Current => _current; + public event Action? Changed; +} + +/// A3 host limits (§5.5 "Budget"). +/// How long a connection's condition items stay open after the last event item goes (default 30 s). +/// Per consumer node (default 122,500 = 2,500 × 49). +/// Per consumer node (default 400 MiB; provisional until L2). +/// Pause before re-opening an ended condition stream. +public sealed record ProjectedConditionOptions(TimeSpan Linger, int MaxImportedConditionNodes, long MaxImportedConditionBytes, + TimeSpan ReconnectDelay) +{ + /// Counted, not estimated (plan §5.5 table): the worst case per condition. + public const int NodesPerCondition = 49; + /// Measured retained managed size per condition (≈ 157 KiB, SDK 2.0.1). + public const long BytesPerCondition = 160_997; + + public static ProjectedConditionOptions Default { get; } = + new(TimeSpan.FromSeconds(30), 122_500, 400L * 1024 * 1024, TimeSpan.FromSeconds(1)); +} + +/// Why a condition-bearing mapping is not contributing conditions. +public enum ProjectedConditionMappingStatus { Pending, Snapshotting, Complete, Unavailable, ConditionCapacity } + +/// +/// A3 (plan §5.4, §5.5): the consumer's condition runtime. +/// +/// Gate (): the mapping gate for CreateMonitoredItems on ANY current placement +/// mapping — the mapping's Subscribe + AlarmSubscribe bits and a local Subscribe grant on the placement folder's local +/// scope — regardless of Security:Acl:Enabled. +/// Demand: the first admitted event item opens, per condition-bearing connection, ONE stream with one +/// root-scoped condition item per enabled condition-bearing mapping (under the connection's service principal); +/// they close together after the last item goes plus . +/// Barrier + budget: total > MaxConditions ⇒ that mapping is +/// and its item removed before anything is +/// materialised; host caps reject the mappings that would cross them, in deployed order; conditions are materialised +/// only after every mapping completed its snapshot (or timed out ⇒ Unavailable). +/// Versions: per key and epoch; a removed record and a snapshot begin bypass the gate; a removal is +/// applied unconditionally and forgets the key's version. +/// Lifetime: a stream end is "re-snapshot", never "conditions removed"; only a COMPLETE re-snapshot that +/// no longer lists a key removes it. Past ConditionStaleTimeoutMilliseconds without a stream the conditions go +/// BadNoCommunication (one event each) — never "known inactive" (§5.1 T2). +/// +/// +public sealed class ProjectedConditionAccess : IProjectedConditionAccess, IDisposable +{ + private readonly IProjectedConditionMappings _mappings; + private readonly IGrpcDataAdapterConnectionSource _connections; + private readonly DataOperationPolicy _policy; + private readonly Func _sink; + private readonly TimeProvider _clock; + private readonly ProjectedConditionOptions _options; + private readonly ILogger _log; + private readonly object _gate = new(); + private readonly Dictionary _runners = new(StringComparer.OrdinalIgnoreCase); + private int _demand; + private long _mappingVersion = 1; + private ITimer? _linger; + private bool _disposed; + + public ProjectedConditionAccess(IProjectedConditionMappings mappings, IGrpcDataAdapterConnectionSource connections, + DataOperationPolicy policy, Func sink, TimeProvider clock, ProjectedConditionOptions? options = null, + ILogger? logger = null) + { + _mappings = mappings ?? throw new ArgumentNullException(nameof(mappings)); + _connections = connections ?? throw new ArgumentNullException(nameof(connections)); + _policy = policy ?? throw new ArgumentNullException(nameof(policy)); + _sink = sink ?? throw new ArgumentNullException(nameof(sink)); + _clock = clock ?? throw new ArgumentNullException(nameof(clock)); + _options = options ?? ProjectedConditionOptions.Default; + _log = logger ?? NullLogger.Instance; + _mappings.Changed += OnMappingsChanged; + } + + /// Whether a mapping is condition-bearing: enabled, Subscribe + AlarmSubscribe granted. + public static bool IsConditionBearing(RemoteNamespaceMapping mapping) => + mapping.Enabled && (mapping.AllowedOperations & (DataOperations.Subscribe | DataOperations.AlarmSubscribe)) + == (DataOperations.Subscribe | DataOperations.AlarmSubscribe); + + /// + public long AuthorityGeneration => unchecked((Interlocked.Read(ref _mappingVersion) << 32) ^ _policy.AuthorityEpoch); + + /// + public bool CanSee(RoleCarryingUserIdentity? caller, IReadOnlyList placements) + { + if (caller is null || string.IsNullOrWhiteSpace(caller.Principal) || placements.Count == 0) return false; + var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc); + var current = _mappings.Current; + foreach (var placement in placements) + { + var mapping = current.FirstOrDefault(x => string.Equals(x.Mapping.RemoteNamespaceMappingId, placement.MappingId, StringComparison.OrdinalIgnoreCase)); + if (mapping is null || !mapping.Authority.IsActive || !IsConditionBearing(mapping.Mapping) || mapping.Mapping.Realm != placement.Realm) + continue; + if (!TryFolderScope(mapping, placement.FolderLocalSubject, out var scope)) continue; + try + { + if (_policy.AuthorizeLocal(identity, OpcUaOperation.CreateMonitoredItems, scope)) return true; + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { } + } + return false; + } + + /// The local scope of a placement's folder: the mapping's local scope plus the folder's path below the anchor. + internal static bool TryFolderScope(ProjectedMappingPlacement mapping, string folderLocalSubject, out NodeScope scope) + { + scope = mapping.Scope; + var anchor = string.Join('/', mapping.Scope.Segments); + if (string.Equals(folderLocalSubject, anchor, StringComparison.Ordinal)) return true; + if (!folderLocalSubject.StartsWith(anchor + "/", StringComparison.Ordinal)) return false; + var below = folderLocalSubject[(anchor.Length + 1)..].Split('/'); + if (below.Any(string.IsNullOrEmpty)) return false; + scope = mapping.Scope with { Segments = Array.AsReadOnly(mapping.Scope.Segments.Concat(below).ToArray()) }; + return true; + } + + /// + public IDisposable? AcquireEventDemand(RoleCarryingUserIdentity? caller) + { + lock (_gate) + { + if (_disposed) return null; + _demand++; + _linger?.Dispose(); _linger = null; + ReconcileRunners(); + } + return new DemandLease(this); + } + + private void ReleaseDemand() + { + lock (_gate) + { + if (_disposed || --_demand > 0) return; + _linger?.Dispose(); + _linger = _clock.CreateTimer(_ => OnLingerExpired(), null, _options.Linger, Timeout.InfiniteTimeSpan); + } + } + + private void OnLingerExpired() + { + List stopped; + lock (_gate) + { + if (_disposed || _demand > 0) return; + stopped = _runners.Values.ToList(); + _runners.Clear(); + } + foreach (var runner in stopped) runner.Stop(removeConditions: true); + } + + private void OnMappingsChanged() + { + Interlocked.Increment(ref _mappingVersion); + lock (_gate) + { + if (_disposed) return; + ReconcileRunners(); + } + } + + /// Starts a runner per condition-bearing connection while demand exists; restarts one whose mapping set changed. Under _gate. + private void ReconcileRunners() + { + if (_demand <= 0) return; + var byConnection = _mappings.Current.Where(x => x.Authority.IsActive && IsConditionBearing(x.Mapping)) + .GroupBy(x => x.Mapping.DataConnectionId, StringComparer.OrdinalIgnoreCase) + .ToDictionary(x => x.Key, x => OrderMappings(x).ToArray(), StringComparer.OrdinalIgnoreCase); + foreach (var id in _runners.Keys.Where(id => !byConnection.ContainsKey(id)).ToList()) + { + _runners.Remove(id, out var gone); + gone!.Stop(removeConditions: true); + } + foreach (var (id, mappings) in byConnection) + { + var signature = Signature(mappings); + if (_runners.TryGetValue(id, out var running)) + { + if (running.Signature == signature) continue; + // A changed mapping set: a new stream with a complete snapshot. ConditionIds never change (N4); placements, + // notifiers and SourceName follow the new set at its barrier. + running.Stop(removeConditions: false); + } + var runner = new ConnectionRunner(this, id, mappings, signature, running?.TakeMaterialised()); + _runners[id] = runner; + runner.Start(); + } + } + + /// §5.2: Raw mappings before UNS, then mapping id ordinal (deployed configuration only). + internal static IEnumerable OrderMappings(IEnumerable mappings) => + mappings.OrderBy(x => x.Mapping.Realm == DataRealm.Raw ? 0 : 1) + .ThenBy(x => x.Mapping.RemoteNamespaceMappingId, StringComparer.Ordinal); + + private static string Signature(IEnumerable mappings) => + string.Join('|', mappings.Select(x => $"{x.Mapping.RemoteNamespaceMappingId}:{x.Mapping.Revision}:{x.Mapping.MaxConditions}:{x.Anchor.Subject}")); + + /// Test/diagnostic observation: a connection's mapping statuses (null when no runner). + public IReadOnlyDictionary? MappingStatuses(string connectionId) + { + lock (_gate) return _runners.TryGetValue(connectionId, out var runner) ? runner.Statuses : null; + } + + /// Test observation: whether a connection has an open runner. + public bool IsRunning(string connectionId) + { + lock (_gate) return _runners.ContainsKey(connectionId); + } + + /// Test observation: snapshot barriers a connection completed. + public int BarriersCompleted(string connectionId) + { + lock (_gate) return _runners.TryGetValue(connectionId, out var runner) ? runner.Barriers : 0; + } + + public void Dispose() + { + List runners; + lock (_gate) + { + if (_disposed) return; + _disposed = true; + _linger?.Dispose(); + runners = _runners.Values.ToList(); + _runners.Clear(); + } + _mappings.Changed -= OnMappingsChanged; + foreach (var runner in runners) runner.Stop(removeConditions: false); + } + + private sealed class DemandLease(ProjectedConditionAccess owner) : IDisposable + { + private int _disposed; + public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) owner.ReleaseDemand(); } + } + + // ----------------------------------------------------------------------------------------------------------------- + // One connection: one stream, one root item per condition-bearing mapping + // ----------------------------------------------------------------------------------------------------------------- + + private sealed class MappingState(ProjectedMappingPlacement placement) + { + public ProjectedMappingPlacement Placement { get; } = placement; + public string MappingId => Placement.Mapping.RemoteNamespaceMappingId; + public DataView Root { get; } = new(placement.Anchor.Address, placement.Mapping.Realm, null, 0, placement.Anchor.Address.Identifier); + public string? RootSubject { get; set; } + public ulong? Handle { get; set; } + public ProjectedConditionMappingStatus Status { get; set; } = ProjectedConditionMappingStatus.Pending; + public int Total { get; set; } + /// The mapping's current records by key (the complete snapshot, then deltas). + public Dictionary Records { get; } = new(StringComparer.Ordinal); + public Dictionary Infos { get; } = new(StringComparer.Ordinal); + public Dictionary Versions { get; } = new(StringComparer.Ordinal); + public bool Contributes => Status == ProjectedConditionMappingStatus.Complete; + } + + private sealed class ConnectionRunner + { + private readonly ProjectedConditionAccess _owner; + private readonly string _connectionId; + private readonly ProjectedMappingPlacement[] _mappings; + private readonly CancellationTokenSource _stop = new(); + private readonly object _statusGate = new(); + private Task _loop = Task.CompletedTask; + private MappingState[] _states = []; + /// Keys currently materialised at the sink (owned by the loop; handed over on a restart). + private HashSet _materialised; + private ITimer? _stale; + private int _barriers; + + public ConnectionRunner(ProjectedConditionAccess owner, string connectionId, ProjectedMappingPlacement[] mappings, string signature, + HashSet? materialised) + { + _owner = owner; _connectionId = connectionId; _mappings = mappings; Signature = signature; + _materialised = materialised ?? new HashSet(StringComparer.Ordinal); + } + + public string Signature { get; } + public int Barriers => Volatile.Read(ref _barriers); + + public IReadOnlyDictionary Statuses + { + get { lock (_statusGate) return _states.ToDictionary(x => x.MappingId, x => x.Status, StringComparer.OrdinalIgnoreCase); } + } + + public void Start() => _loop = Task.Run(() => RunAsync(_stop.Token)); + + public HashSet TakeMaterialised() + { + var taken = _materialised; + _materialised = new HashSet(StringComparer.Ordinal); + return taken; + } + + public void Stop(bool removeConditions) + { + _stop.Cancel(); + _stale?.Dispose(); + if (!removeConditions) return; + _ = _loop.ContinueWith(_ => + { + var keys = _materialised.ToArray(); + if (keys.Length > 0 && _owner._sink() is { } sink) sink.RemoveConditions(_connectionId, keys); + _materialised.Clear(); + }, TaskScheduler.Default); + } + + private async Task RunAsync(CancellationToken ct) + { + var epoch = 0L; + while (!ct.IsCancellationRequested) + { + epoch++; + try { await RunStreamAsync(epoch, ct).ConfigureAwait(false); } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; } + catch (Exception ex) + { + _owner._log.LogInformation(ex, "Imported conditions: stream for connection {Connection} ended; re-snapshotting", _connectionId); + } + // §5.5 lifetime rule: a stream end is "re-snapshot", never "conditions removed". Arm staleness instead. + ArmStale(); + OtOpcUaTelemetry.DataConnConditionResyncs.Add(1); + try { await Task.Delay(_owner._options.ReconnectDelay, _owner._clock, ct).ConfigureAwait(false); } + catch (OperationCanceledException) { return; } + } + } + + private void ArmStale() + { + if (_stale is not null || _materialised.Count == 0) return; + var timeout = TimeSpan.FromMilliseconds(Math.Max(1, _mappings.Min(x => x.Mapping.ConditionStaleTimeoutMilliseconds))); + _stale = _owner._clock.CreateTimer(_ => + { + if (!_stop.IsCancellationRequested) _owner._sink()?.MarkConnectionStale(_connectionId); + }, null, timeout, Timeout.InfiniteTimeSpan); + } + + private void DisarmStale() + { + _stale?.Dispose(); + _stale = null; + } + + private async Task RunStreamAsync(long epoch, CancellationToken ct) + { + var states = _mappings.Select(x => new MappingState(x)).ToArray(); + lock (_statusGate) _states = states; + await using var lease = await _owner._connections.AcquireAsync(_connectionId, ct).ConfigureAwait(false) + ?? throw new InvalidOperationException("Connection unavailable."); + using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, lease.CancellationToken); + var token = linked.Token; + var connection = lease.Connection; + // The remote root's origin subject: placement addresses are made relative to it (SourceName, folder subject). + try + { + var budget = new DataBudget(TimeSpan.FromSeconds(10), Math.Max(1, states.Length), 1024 * 1024); + var metadata = await connection.GetMetadataAsync(new MetadataRequest(states.Select(x => x.Root).ToArray(), budget), token) + .ConfigureAwait(false); + for (var i = 0; i < states.Length && i < metadata.Count; i++) + if (metadata[i] is { Status: DataItemStatus.Good, Value: { } root }) states[i].RootSubject = root.View.Subject; + } + catch (Exception ex) when (ex is not OperationCanceledException) { } + + await using var subscription = await connection.SubscribeAsync(token).ConfigureAwait(false); + var subscriptionId = "conditions-" + Guid.NewGuid().ToString("N"); + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); + var items = states.Select(x => new DataSubscriptionItem(x.MappingId, x.Root, settings, new DataConditionScope(IncludeInfo: true))).ToArray(); + await subscription.SendAsync(new OpenSubscription(subscriptionId, epoch, "open", TimeSpan.FromSeconds(30), items, false, + TimeSpan.FromMinutes(60), new DataBudget(TimeSpan.FromSeconds(30), 1000, 4 * 1024 * 1024)), token).ConfigureAwait(false); + + var snapshotTimeout = TimeSpan.FromMilliseconds(Math.Max(1, states.Max(x => x.Placement.Mapping.ConditionSnapshotTimeoutMilliseconds))); + var barrierPassed = false; + _timedOut = false; + var timeout = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var barrierTimer = _owner._clock.CreateTimer(_ => + { + // ConditionSnapshotTimeoutMilliseconds: the incomplete mappings are Unavailable and the rest proceed. + lock (_statusGate) + foreach (var s in states.Where(s => s.Status is ProjectedConditionMappingStatus.Pending or ProjectedConditionMappingStatus.Snapshotting)) + s.Status = ProjectedConditionMappingStatus.Unavailable; + _timedOut = true; + timeout.TrySetResult(); + }, null, snapshotTimeout, Timeout.InfiniteTimeSpan); + + await using var frames = subscription.ReadAllAsync(token).GetAsyncEnumerator(token); + Task? next = null; + while (true) + { + next ??= frames.MoveNextAsync().AsTask(); + if (!barrierPassed && !timeout.Task.IsCompleted + && await Task.WhenAny(next, timeout.Task).ConfigureAwait(false) != next) + { + barrierPassed = TryPassBarrier(states); + continue; + } + if (!barrierPassed && timeout.Task.IsCompleted && !next.IsCompleted) + { + barrierPassed = TryPassBarrier(states); + if (!barrierPassed) { await next.ConfigureAwait(false); } + else continue; + } + if (!await next.ConfigureAwait(false)) return; + next = null; + var changed = await ProcessAsync(frames.Current, states, subscription, subscriptionId, epoch, token).ConfigureAwait(false); + if (!barrierPassed) { barrierPassed = TryPassBarrier(states); continue; } + if (changed.Count > 0) Publish(states, changed); + } + } + + private bool TryPassBarrier(MappingState[] states) + { + lock (_statusGate) + if (states.Any(x => x.Status is ProjectedConditionMappingStatus.Pending or ProjectedConditionMappingStatus.Snapshotting)) return false; + Interlocked.Increment(ref _barriers); + DisarmStale(); + PassBarrier(states); + if (_timedOut) _owner._sink()?.RequireRefresh(_connectionId); // an incomplete (re)snapshot + return true; + } + + private async Task> ProcessAsync(DataSubscriptionFrame frame, MappingState[] states, IDataSubscription subscription, + string subscriptionId, long epoch, CancellationToken token) + { + var changed = new HashSet(StringComparer.Ordinal); + switch (frame) + { + case DataSubscriptionAck ack: + foreach (var itemAck in ack.Items) + { + var state = states.FirstOrDefault(x => x.MappingId == itemAck.ClientItemId); + if (state is null) continue; + lock (_statusGate) + { + if (itemAck.Status == DataItemStatus.Good && itemAck.Handle is { } handle) state.Handle = handle.Handle; + else if (state.Status != ProjectedConditionMappingStatus.ConditionCapacity) state.Status = ProjectedConditionMappingStatus.Unavailable; + } + } + break; + case DataSubscriptionConditions conditions: + var mapping = states.FirstOrDefault(x => x.Handle == conditions.Handle.Handle); + if (mapping is null || mapping.Status is ProjectedConditionMappingStatus.Unavailable or ProjectedConditionMappingStatus.ConditionCapacity) break; + if (conditions.IsSnapshot && conditions.Total is { } total) + { + if (!Admit(mapping, total, states)) + { + // §5.5: the over-limit item is REMOVED (it costs an item slot and the origin's re-listing). + await subscription.SendAsync(new RemoveSubscriptionItems(subscriptionId, epoch, "remove-" + mapping.MappingId, + TimeSpan.FromSeconds(30), [conditions.Handle]), token).ConfigureAwait(false); + foreach (var key in mapping.Records.Keys) changed.Add(key); + mapping.Records.Clear(); + break; + } + // A snapshot begin bypasses the version gate: it resets every key. + foreach (var key in mapping.Records.Keys) changed.Add(key); + mapping.Records.Clear(); mapping.Versions.Clear(); + lock (_statusGate) mapping.Status = ProjectedConditionMappingStatus.Snapshotting; + } + foreach (var record in conditions.Items) + { + if (!ImportedConditionIds.IsWellFormedConditionKey(record.ConditionKey)) continue; + if (record.Info is { } info) mapping.Infos[record.ConditionKey] = info; + if (record.Removed) + { + // A removal is applied unconditionally and forgets the key's version. + mapping.Records.Remove(record.ConditionKey); + mapping.Versions.Remove(record.ConditionKey); + changed.Add(record.ConditionKey); + continue; + } + if (mapping.Versions.TryGetValue(record.ConditionKey, out var last) && record.Version <= last) continue; + mapping.Versions[record.ConditionKey] = record.Version; + mapping.Records[record.ConditionKey] = record; + changed.Add(record.ConditionKey); + } + if (conditions.SnapshotComplete) + lock (_statusGate) mapping.Status = ProjectedConditionMappingStatus.Complete; + break; + } + return changed; + } + + private volatile bool _timedOut; + + /// §5.5 admission at snapshot begin: the mapping limit, then the host caps (deployed order). + private bool Admit(MappingState mapping, int total, MappingState[] states) + { + mapping.Total = total; + if (total > mapping.Placement.Mapping.MaxConditions) + { + lock (_statusGate) mapping.Status = ProjectedConditionMappingStatus.ConditionCapacity; + OtOpcUaTelemetry.DataConnConditionCapacityRejections.Add(1); + _owner._log.LogWarning("Imported conditions: mapping {Mapping} lists {Total} conditions, over its MaxConditions {Max} — Unavailable(ConditionCapacity)", + mapping.MappingId, total, mapping.Placement.Mapping.MaxConditions); + return false; + } + // Host caps: conditions are charged once per key; before materialising, `total` is the bound. Mappings earlier in + // deployed order are charged first. + long charged = 0; + foreach (var other in states) + { + if (ReferenceEquals(other, mapping)) break; + if (other.Status is ProjectedConditionMappingStatus.Snapshotting or ProjectedConditionMappingStatus.Complete) charged += other.Total; + } + var after = charged + total; + if (after * ProjectedConditionOptions.NodesPerCondition > _owner._options.MaxImportedConditionNodes + || after * ProjectedConditionOptions.BytesPerCondition > _owner._options.MaxImportedConditionBytes) + { + lock (_statusGate) mapping.Status = ProjectedConditionMappingStatus.ConditionCapacity; + OtOpcUaTelemetry.DataConnConditionCapacityRejections.Add(1); + _owner._log.LogWarning("Imported conditions: mapping {Mapping} ({Total}) would cross the host condition caps — Unavailable(ConditionCapacity)", + mapping.MappingId, total); + return false; + } + if (after * ProjectedConditionOptions.NodesPerCondition > _owner._options.MaxImportedConditionNodes * 8L / 10) + _owner._log.LogWarning("Imported conditions: host condition budget above 80% ({Count} conditions)", after); + return true; + } + + /// The barrier: materialise the union; a key the previous materialisation held but this complete set lacks is removed. + private void PassBarrier(MappingState[] states) + { + var keys = states.Where(x => x.Contributes).SelectMany(x => x.Records.Keys).ToHashSet(StringComparer.Ordinal); + var gone = _materialised.Where(k => !keys.Contains(k)).ToArray(); + // Only a key no complete mapping lists is removed; a key of a mapping that did not complete is kept (unknown ≠ gone). + var incomplete = states.Any(x => !x.Contributes && x.Status != ProjectedConditionMappingStatus.ConditionCapacity); + if (gone.Length > 0 && !incomplete && _owner._sink() is { } sink) + { + sink.RemoveConditions(_connectionId, gone); + foreach (var key in gone) _materialised.Remove(key); + } + Publish(states, keys); + } + + private void Publish(MappingState[] states, IEnumerable keys) + { + if (_owner._sink() is not { } sink) return; + var updates = new List(); + var removals = new List(); + foreach (var key in keys) + { + var update = Merge(states, key); + if (update is null) + { + if (_materialised.Remove(key)) removals.Add(key); + continue; + } + updates.Add(update); + _materialised.Add(key); + } + if (removals.Count > 0) sink.RemoveConditions(_connectionId, removals); + if (updates.Count > 0) sink.ApplyConditions(updates); + } + + /// One key across the connection's complete mappings: placements (primary first), latest record, SourceName. + private ImportedConditionUpdate? Merge(MappingState[] states, string key) + { + DataConditionState? latest = null; + DataConditionInfo? info = null; + var placements = new List<(int Order, ImportedConditionPlacement Placement)>(); + for (var i = 0; i < states.Length; i++) + { + var state = states[i]; + if (!state.Contributes || !state.Records.TryGetValue(key, out var record)) continue; + if (latest is null || record.Version > latest.Version) latest = record; + if (state.Infos.TryGetValue(key, out var stateInfo)) info ??= stateInfo; + if (!state.Infos.TryGetValue(key, out var placementInfo)) continue; + foreach (var view in placementInfo.Placements.Where(p => p.Realm == state.Placement.Mapping.Realm) + .OrderBy(p => p.Address.Identifier, StringComparer.Ordinal)) + placements.Add((i, ToPlacement(state, view))); + } + if (latest is null || placements.Count == 0) return null; + var ordered = placements.OrderBy(x => x.Order).Select(x => x.Placement).ToArray(); + var primary = ordered[0]; + var anchor = states[placements.Min(x => x.Order)].Placement.Anchor.Subject; + return new ImportedConditionUpdate(_connectionId, latest, info, ordered, anchor + "/" + primary.RelativePath); + } + + private static ImportedConditionPlacement ToPlacement(MappingState state, DataView view) + { + var relative = view.Subject; + if (state.RootSubject is { Length: > 0 } root && relative.StartsWith(root + "/", StringComparison.Ordinal)) + relative = relative[(root.Length + 1)..]; + var cut = relative.LastIndexOf('/'); + var anchor = state.Placement.Anchor.Subject; + var folder = cut < 0 ? anchor : anchor + "/" + relative[..cut]; + return new ImportedConditionPlacement(state.MappingId, state.Placement.Mapping.Realm, view, folder, relative); + } + } +} From 8d6c94a3b35e9124384fb416fe2450c6beccfcda Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 16:30:03 -0500 Subject: [PATCH 05/32] feat(host): wire A3 ProjectedConditionAccess (DI, node-manager sink, host condition caps) --- .../Configuration/DataConnectionOptions.cs | 4 ++++ .../Configuration/DataConnectionRegistration.cs | 11 +++++++++++ .../OpcUa/OtOpcUaServerHostedService.cs | 9 ++++++++- .../DataConnections/ProjectedConditionAccess.cs | 7 +++++-- 4 files changed, 28 insertions(+), 3 deletions(-) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs index f9653992b..3dedbbd93 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs @@ -19,6 +19,10 @@ public sealed class DataConnectionOptions public int MaxStreamsPerPrincipal { get; set; } = 8; public int MaxMonitoredItems { get; set; } = 10_000; public long MaxTransportBytes { get; set; } = 64 * 1024 * 1024; + /// A3 (§5.5): imported-condition node budget per consumer node (2,500 × 49 worst-case nodes per condition). + public int MaxImportedConditionNodes { get; set; } = 122_500; + /// A3 (§5.5): imported-condition memory budget per consumer node (≈ 2,500 × 157 KiB; provisional until L2). + public long MaxImportedConditionBytes { get; set; } = 400L * 1024 * 1024; public long MaxPendingBytes { get; set; } = 1024 * 1024; public TimeSpan MaxSessionLifetime { get; set; } = TimeSpan.FromHours(1); /// A2b: remote condition-method operations the origin remembers at once for duplicate protection (all principals). diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs index ec6ebe806..9953a7bb2 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs @@ -143,6 +143,17 @@ public static class DataConnectionRegistration ? bytes : null, sp.GetRequiredService(), sp.GetRequiredService())); services.AddSingleton(sp => sp.GetRequiredService()); + // A3: imported conditions (§5.3–§5.5) — the gate, per-connection demand and the stream runtime. The node manager is + // bound as its sink by OtOpcUaServerHostedService once the server is up. + services.AddSingleton(sp => new ProjectedConditionAccess( + new DeployedConditionMappings(sp.GetRequiredService()), + sp.GetRequiredService(), sp.GetRequiredService(), null, + sp.GetRequiredService(), ProjectedConditionOptions.Default with + { + MaxImportedConditionNodes = options.MaxImportedConditionNodes, + MaxImportedConditionBytes = options.MaxImportedConditionBytes, + })); + services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(sp => new ConfiguredProjectionDiscovery( sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs index 3809da6b7..614744bd3 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs @@ -61,6 +61,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl private readonly IProjectedBrowseAccess? _projectedBrowseAccess; private readonly IProjectedDataAccess? _projectedDataAccess; private readonly IProjectedHistoryAccess? _projectedHistoryAccess; + private readonly IProjectedConditionAccess? _projectedConditionAccess; // A1 (plan §5.1): the condition-state hub the node manager's delta callback feeds. Invisible until A2. private readonly IConditionStateSink? _conditionStateSink; private readonly IFederatedProjectionCatalog? _projectedCatalog; @@ -170,8 +171,10 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl IProjectedDataAccess? projectedDataAccess = null, IFederatedProjectionCatalog? projectedCatalog = null, IProjectedHistoryAccess? projectedHistoryAccess = null, - IConditionStateSink? conditionStateSink = null) + IConditionStateSink? conditionStateSink = null, + IProjectedConditionAccess? projectedConditionAccess = null) { + _projectedConditionAccess = projectedConditionAccess; _projectedHistoryAccess = projectedHistoryAccess; _conditionStateSink = conditionStateSink; _dataConnectionOptions = configuration.GetSection(DataConnectionOptions.SectionName).Get() ?? new(); @@ -273,6 +276,10 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl _server.NodeManager.ProjectedBrowseClock = _time; _server.NodeManager.ProjectedDataAccess = _projectedDataAccess; _server.NodeManager.ProjectedHistoryAccess = _projectedHistoryAccess; + // A3: imported conditions — the gate/demand into the node manager, the node manager as the runtime's sink. + _server.NodeManager.ProjectedConditionAccess = _projectedConditionAccess; + if (_projectedConditionAccess is ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ProjectedConditionAccess conditions) + conditions.Sink = _server.NodeManager; _server.NodeManager.ConditionStateSink = _conditionStateSink; if (_projectedCatalog is { } projectedCatalog) _server.NodeManager.MappedSubjectResolver = (realm, identifier) => diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs index 8d2ed3ce0..182bbca6d 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs @@ -94,19 +94,22 @@ public sealed class ProjectedConditionAccess : IProjectedConditionAccess, IDispo private bool _disposed; public ProjectedConditionAccess(IProjectedConditionMappings mappings, IGrpcDataAdapterConnectionSource connections, - DataOperationPolicy policy, Func sink, TimeProvider clock, ProjectedConditionOptions? options = null, + DataOperationPolicy policy, Func? sink, TimeProvider clock, ProjectedConditionOptions? options = null, ILogger? logger = null) { _mappings = mappings ?? throw new ArgumentNullException(nameof(mappings)); _connections = connections ?? throw new ArgumentNullException(nameof(connections)); _policy = policy ?? throw new ArgumentNullException(nameof(policy)); - _sink = sink ?? throw new ArgumentNullException(nameof(sink)); + _sink = sink ?? (() => Sink); _clock = clock ?? throw new ArgumentNullException(nameof(clock)); _options = options ?? ProjectedConditionOptions.Default; _log = logger ?? NullLogger.Instance; _mappings.Changed += OnMappingsChanged; } + /// The node manager the host binds once the server is up (used when no sink delegate was supplied). + public IProjectedConditionSink? Sink { get; set; } + /// Whether a mapping is condition-bearing: enabled, Subscribe + AlarmSubscribe granted. public static bool IsConditionBearing(RemoteNamespaceMapping mapping) => mapping.Enabled && (mapping.AllowedOperations & (DataOperations.Subscribe | DataOperations.AlarmSubscribe)) From de381157cfd7bd75bb71b87a0c92ff4295e59a2f Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 16:35:01 -0500 Subject: [PATCH 06/32] test(grpc-data): A3a over-the-wire imported-condition events (exactly-once, identity, A3-SEC, child Read, N4, N7, resync, T2) + OwnsNamespace covers mapped/conditions --- .../OtOpcUaNodeManager.cs | 11 +- .../ProjectedConditionRegistry.cs | 12 + .../ImportedConditionEventWireTests.cs | 380 ++++++++++++++++++ 3 files changed, 399 insertions(+), 4 deletions(-) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionEventWireTests.cs diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index c1271a36a..973446e88 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -6051,7 +6051,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage private bool OwnsNamespace(NodeId? nodeId) => nodeId is { } id && (id.NamespaceIndex == NamespaceIndexes[0] || id.NamespaceIndex == NamespaceIndexes[1] || - id.NamespaceIndex == NamespaceIndexes[2] || id.NamespaceIndex == NamespaceIndexes[3]); + id.NamespaceIndex == NamespaceIndexes[2] || id.NamespaceIndex == NamespaceIndexes[3] || + // A3: the imported-condition namespace is ours too — without it a condition's children keep their type ids and + // every Permits() would pass an imported id as "not ours to gate". + (NamespaceIndexes.Count > 4 && id.NamespaceIndex == NamespaceIndexes[4])); /// Pulls the ACL identity off an SDK operation context. /// The SDK context carrying the session identity. @@ -6556,13 +6559,13 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage // Only creation is gated. Refusing an UNSUBSCRIBE would strand the item on a node the session can // no longer reach — the client could never detach it, and the server would keep delivering. // A3 (§5.4): an event item on a projected notifier (a folder wired for imported conditions) is admitted through the - // verified path — Browse on the folder at subscribe time, the mapping gate per event at delivery and again at - // publish — instead of the mapped blanket deny that still applies to data items. + // verified path — the mapping gate of some condition wired there at subscribe time, per event at delivery and again + // at publish — instead of the mapped blanket deny that still applies to data items. var projectedNotifier = !unsubscribe && IsHandleInNamespace(sourceId) is { } candidate && IsProjectedEventNotifier(candidate.NodeId) ? candidate.NodeId : (NodeId?)null; if (projectedNotifier is { } notifierId) { - if (!Permits(IdentityOf(context), OpcUaOperation.Browse, notifierId)) return StatusCodes.BadUserAccessDenied; + if (!ImportedNotifierAdmits(IdentityOf(context), notifierId)) return StatusCodes.BadUserAccessDenied; } else if (SecurityFilteringActive && !unsubscribe && IsHandleInNamespace(sourceId) is { } source diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs index 56d13ddce..31236feca 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs @@ -510,6 +510,18 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink lock (Lock) return _importedConditions.WiredByFolder.ContainsKey(nodeId); } + /// §5.4 admission of an event item on a projected notifier: the caller sees at least one condition wired there. + private bool ImportedNotifierAdmits(RoleCarryingUserIdentity? identity, NodeId notifierId) + { + List wired; + lock (Lock) + { + if (!_importedConditions.WiredByFolder.TryGetValue(notifierId, out var ids)) return false; + wired = ids.Select(_importedConditions.Find).OfType().ToList(); + } + return wired.Any(c => ImportedVisibleTo(identity, c)); + } + /// /// The authorizer's pre-realm classifier (§5.2): null for any id outside the imported-condition namespace, otherwise /// the imported verdict. diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionEventWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionEventWireTests.cs new file mode 100644 index 000000000..e53f52577 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionEventWireTests.cs @@ -0,0 +1,380 @@ +using System.Security.Cryptography; +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; +using SdkMonitoredItem = Opc.Ua.Client.MonitoredItem; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests; + +/// +/// A3a over the wire (plan §5.2–§5.5): imported conditions materialised by the consumer's registry in the +/// mapped/conditions namespace reach a projected placement folder and the Server object (i=2253) as exactly +/// one event per origin transition, carry the §5.2 identity fields, are gated by the mapping gate with ACLs OFF (A3-SEC), +/// keep their ConditionId when placements change (N4), wire/unwire notifiers lazily and symmetrically (N7), and never +/// tell a client "known inactive" on staleness (T2). Every absence assertion follows a must-arrive sentinel. +/// +[Trait("Feature", "GrpcData"), Trait("Phase", "A3")] +public sealed class ImportedConditionEventWireTests +{ + private const string Connection = "conn-a"; + private const string MappingA = "map-a"; + private const string MappingB = "map-b"; + private const string Granted = ServerEventRig.KeyPrincipal; + private static readonly string Key1 = KeyOf("cond-1"); + private static readonly string Key2 = KeyOf("cond-2"); + + // Select clauses: EventId, SourceNode, SourceName, Message, Severity, ConditionName, ActiveState/Id, AckedState/Id, + // Quality, ConditionId (ConditionType NodeId attribute), EventType. + private const int EventIdF = 0, SourceNodeF = 1, SourceNameF = 2, MessageF = 3, SeverityF = 4, ConditionNameF = 5, + ActiveF = 6, AckedF = 7, QualityF = 8, ConditionIdF = 9, EventTypeF = 10; + + [Fact] + public async Task Exactly_one_event_per_origin_transition_at_both_placement_folders_and_the_Server_object_with_identity_fields() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3-once", encrypted: false, ct); + var f = Fixture.Install(rig, Granted); + using var session = await rig.ConnectAsync(anonymous: false, ct); + f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements())); + var events = new Events(); + var subscription = await SubscribeAsync(session, events, ct); + var server = AddItem(subscription, ObjectIds.Server); + var device = AddItem(subscription, f.DeviceFolder); + var anchor = AddItem(subscription, f.Anchor); + await subscription.ApplyChangesAsync(ct); + new[] { server, device, anchor }.ShouldAllBe(i => StatusCode.IsGood(i.Status.Error == null ? StatusCodes.Good : i.Status.Error.StatusCode)); + + f.Apply(Update(Key1, version: 4, active: true, acked: true, f.TwoPlacements(), message: "acked")); + f.Apply(Update(Key1, version: 5, active: false, acked: true, f.TwoPlacements(), message: "sentinel")); + await Events.WaitUntilAsync(() => events.Of(server).Any(e => Message(e) == "sentinel") && events.Of(device).Any(e => Message(e) == "sentinel") + && events.Of(anchor).Any(e => Message(e) == "sentinel")); + + foreach (var item in new[] { server, device, anchor }) + { + events.Of(item).Count(e => Message(e) == "acked").ShouldBe(1, $"exactly one event per transition at {item.StartNodeId}"); + events.Of(item).Count(e => Message(e) == "sentinel").ShouldBe(1); + } + + // §5.2 identity: ConditionId = SourceNode = the opaque (connection, key) id in mapped/conditions; SourceName = the + // primary placement's local display path; Severity verbatim; ConditionName from the origin. + var e0 = events.Of(server).First(e => Message(e) == "acked"); + var expectedId = new NodeId(ImportedConditionIds.Identifier(Connection, Key1), + (ushort)session.NamespaceUris.GetIndex(ImportedConditionIds.NamespaceUri)); + e0[SourceNodeF].GetNodeId().ShouldBe(expectedId); + e0[ConditionIdF].GetNodeId().ShouldBe(expectedId); + e0[SourceNameF].GetString().ShouldBe("Plant/remote-a/dev1/HR200"); + e0[SeverityF].GetUInt16().ShouldBe((ushort)777); + e0[ConditionNameF].GetString().ShouldBe("HR200"); + e0[AckedF].GetBoolean().ShouldBeTrue(); + e0[ActiveF].GetBoolean().ShouldBeTrue(); + rig.Nm.ImportedConditionCount.ShouldBe(1); + } + + [Fact] + public async Task A3_SEC_with_ACLs_off_a_session_without_the_mapping_grant_receives_nothing_at_i2253_on_a_folder_or_on_refresh() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3-sec", encrypted: false, ct); + var f = Fixture.Install(rig, Granted); // the anonymous principal holds no grant; ACL enforcement is OFF in this rig + f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements())); + using var allowed = await rig.ConnectAsync(anonymous: false, ct); + using var denied = await rig.ConnectAsync(anonymous: true, ct); + var allowedEvents = new Events(); + var deniedEvents = new Events(); + var allowedSub = await SubscribeAsync(allowed, allowedEvents, ct); + var deniedSub = await SubscribeAsync(denied, deniedEvents, ct); + var allowedServer = AddItem(allowedSub, ObjectIds.Server); + var deniedServer = AddItem(deniedSub, ObjectIds.Server); + var deniedFolder = AddItem(deniedSub, f.DeviceFolder); + await allowedSub.ApplyChangesAsync(ct); + await deniedSub.ApplyChangesAsync(ct); + deniedFolder.Status.Error?.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code, + "a projected notifier admits only a caller who sees a condition wired there"); + + await allowedSub.ConditionRefreshAsync(ct); + await deniedSub.ConditionRefreshAsync(ct); + f.Apply(Update(Key1, version: 4, active: true, acked: true, f.TwoPlacements(), message: "sentinel")); + await Events.WaitUntilAsync(() => allowedEvents.Of(allowedServer).Any(e => Message(e) == "sentinel")); + // Positive control: the granted session got the refresh replay AND the transition. + allowedEvents.Of(allowedServer).Count(e => e[AckedF].TryGetValue(out bool _)).ShouldBe(2); + // Must-arrive sentinel on the denied session's own subscription (a non-condition event every session receives): + // RefreshStart/End of its own refresh arrived, so its queue was published after the transition. + await Events.WaitUntilAsync(() => deniedEvents.Of(deniedServer).Any(e => e[EventTypeF].GetNodeId() == ObjectTypeIds.RefreshEndEventType)); + deniedEvents.Of(deniedServer).Count(e => e[AckedF].TryGetValue(out bool _)).ShouldBe(0, "no imported condition event, live or refreshed"); + + // Revocation reaches a queued event at publish time: the marker re-checks the gate. + f.Access.Allowed.Clear(); + Interlocked.Increment(ref f.Access.Generation); // a revocation moves the authority generation (verdict caches key on it) + f.Apply(Update(Key1, version: 5, active: false, acked: true, f.TwoPlacements(), message: "after-revoke")); + await Task.Delay(500, ct); + allowedEvents.Of(allowedServer).Count(e => Message(e) == "after-revoke").ShouldBe(0); + } + + [Fact] + public async Task A_condition_child_Read_is_authorized_through_the_condition_and_methods_are_refused_unapplied() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3-child", encrypted: false, ct); + var f = Fixture.Install(rig, Granted); + f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements())); + using var allowed = await rig.ConnectAsync(anonymous: false, ct); + using var denied = await rig.ConnectAsync(anonymous: true, ct); + var ns = (ushort)allowed.NamespaceUris.GetIndex(ImportedConditionIds.NamespaceUri); + var id = ImportedConditionIds.Identifier(Connection, Key1); + var child = new NodeId(ImportedConditionIds.ChildIdentifier(id, "ActiveState/Id"), ns); + + rig.Nm.FindImportedCondition(Connection, Key1)!.ActiveState!.Id!.NodeId.ShouldBe(child, "children are instance-scoped (#629) in mapped/conditions"); + var good = await allowed.ReadValueAsync(child, ct); + StatusCode.IsGood(good.StatusCode).ShouldBeTrue(); + good.WrappedValue.GetBoolean().ShouldBeTrue(); + var refused = await Should.ThrowAsync(() => denied.ReadValueAsync(child, ct)); + refused.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code); + + // A3a: no local apply of a remote method — the condition stays unacknowledged (A3b dispatches to the origin). + var eventId = rig.Nm.FindImportedCondition(Connection, Key1)!.EventId!.Value; + await Should.ThrowAsync(() => allowed.CallAsync(new NodeId(id, ns), MethodIds.AcknowledgeableConditionType_Acknowledge, + ct, eventId, new LocalizedText("x"))); + rig.Nm.FindImportedCondition(Connection, Key1)!.AckedState!.Id!.Value.ShouldBeFalse(); + } + + [Fact] + public async Task Disabling_the_primary_placement_mapping_moves_only_notifiers_and_SourceName_and_a_later_mapping_changes_no_NodeId() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3-n4", encrypted: false, ct); + var f = Fixture.Install(rig, Granted); + f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements())); + var before = rig.Nm.FindImportedCondition(Connection, Key1)!; + var id = before.NodeId; + rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeTrue(); + + // The primary (dev1, map-a) disappears; only the mapping-B anchor placement remains. + f.Apply(Update(Key1, version: 4, active: true, acked: true, [f.BPlacement()], message: "moved")); + var after = rig.Nm.FindImportedCondition(Connection, Key1)!; + after.NodeId.ShouldBe(id, "ConditionId is keyed on (connection, condition_key) only"); + ReferenceEquals(after, before).ShouldBeTrue("the same condition instance"); + rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeFalse("the old placement folder is unwired symmetrically"); + rig.Nm.IsImportedNotifierWired(f.AnchorB).ShouldBeTrue(); + after.SourceName!.Value.ShouldBe("Plant/remote-b/HR200"); + + // A second mapping opened later (adds placements back): no NodeId changes. + f.Apply(Update(Key1, version: 5, active: true, acked: true, [.. f.TwoPlacements(), f.BPlacement()], message: "added")); + rig.Nm.FindImportedCondition(Connection, Key1)!.NodeId.ShouldBe(id); + rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeTrue(); + } + + [Fact] + public async Task A_retired_placement_folder_is_unwired_and_a_folder_holding_an_event_item_is_not_retired() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3-n7", encrypted: false, ct); + var f = Fixture.Install(rig, Granted); + f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements())); + using var session = await rig.ConnectAsync(anonymous: false, ct); + var events = new Events(); + var subscription = await SubscribeAsync(session, events, ct); + var item = AddItem(subscription, f.DeviceFolder); + await subscription.ApplyChangesAsync(ct); + + var sink = (IProjectedNamespacePageSink)rig.Nm; + sink.TryRemove(f.DeviceFolder, f.DeviceDefinition).ShouldBeFalse("pinned by the admitted event item"); + rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeTrue(); + + subscription.RemoveItem(item); + await subscription.ApplyChangesAsync(ct); + sink.TryRemove(f.DeviceFolder, f.DeviceDefinition).ShouldBeTrue(); + rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeFalse("retirement unwires the notifier"); + } + + [Fact] + public async Task A_resync_of_unchanged_state_reports_nothing_and_the_next_real_transition_arrives_exactly_once() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3-resync", encrypted: false, ct); + var f = Fixture.Install(rig, Granted); + f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements())); + using var session = await rig.ConnectAsync(anonymous: false, ct); + var events = new Events(); + var subscription = await SubscribeAsync(session, events, ct); + var server = AddItem(subscription, ObjectIds.Server); + await subscription.ApplyChangesAsync(ct); + var reported = rig.Nm.ImportedEventsReported; + + // A re-snapshot after a stream end re-states the same state under new versions (a new epoch): the shared delta gate + // suppresses it. + f.Apply(Update(Key1, version: 10, active: true, acked: false, f.TwoPlacements())); + f.Apply(Update(Key1, version: 11, active: true, acked: false, f.TwoPlacements())); + rig.Nm.ImportedEventsReported.ShouldBe(reported); + // Positive control: a real transition after it must arrive, once. + f.Apply(Update(Key1, version: 12, active: true, acked: true, f.TwoPlacements(), message: "real")); + await Events.WaitUntilAsync(() => events.Of(server).Any(e => Message(e) == "real")); + events.Of(server).Count(e => e[AckedF].TryGetValue(out bool _)).ShouldBe(1); + } + + [Fact] + public async Task Staleness_is_BadNoCommunication_once_per_condition_and_never_known_inactive_and_unknown_records_change_nothing() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3-stale", encrypted: false, ct); + var f = Fixture.Install(rig, Granted); + f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements())); + f.Apply(Update(Key2, version: 3, active: false, acked: true, f.TwoPlacements(), known: false)); + using var session = await rig.ConnectAsync(anonymous: false, ct); + var events = new Events(); + var subscription = await SubscribeAsync(session, events, ct); + var server = AddItem(subscription, ObjectIds.Server); + await subscription.ApplyChangesAsync(ct); + + // T2: a state-unknown record never states "inactive" — the never-known condition is Uncertain, not Good. + rig.Nm.FindImportedCondition(Connection, Key2)!.Quality!.Value.Code.ShouldBe(StatusCodes.UncertainInitialValue.Code); + f.Apply(Update(Key1, version: 4, active: false, acked: true, f.TwoPlacements(), known: false)); + rig.Nm.FindImportedCondition(Connection, Key1)!.ActiveState!.Id!.Value.ShouldBeTrue("an unknown record never changes the last state"); + + rig.Nm.MarkConnectionStale(Connection); + rig.Nm.MarkConnectionStale(Connection); // idempotent: the delta gate reports the Quality change once + f.Apply(Update(Key1, version: 5, active: true, acked: true, f.TwoPlacements(), message: "sentinel")); + await Events.WaitUntilAsync(() => events.Of(server).Any(e => Message(e) == "sentinel")); + var stale = events.Of(server).Where(e => e[QualityF].TryGetValue(out StatusCode q) && q.Code == StatusCodes.BadNoCommunication.Code).ToList(); + stale.Count.ShouldBe(2, "one BadNoCommunication event per condition"); + stale.ShouldContain(e => e[ActiveF].GetBoolean(), "the active condition stays active while stale"); + } + + // --------------------------------------------------------------------------------------------------------------------- + + private static string KeyOf(string seed) => + Convert.ToBase64String(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(seed))).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + + private static ImportedConditionUpdate Update(string key, long version, bool active, bool acked, + IReadOnlyList placements, string message = "HR200 high", bool known = true) + { + var info = new DataConditionInfo("http://opcfoundation.org/UA/:AlarmConditionType", "HR200", DataConditionSourceKind.Native, + placements.Select(p => p.Placement).ToArray(), (uint)DataConditionMethodSets.Native); + var state = new DataConditionState(key, version, false, known, info, active, acked, true, true, 0, 777, message, + StatusCodes.Good.Code, null, 0, DateTimeOffset.UtcNow, active || !acked, new DataActivationMarker("inc", 1)); + var sourceName = (placements[0].MappingId == MappingA ? "Plant/remote-a/" : "Plant/remote-b/") + placements[0].RelativePath; + return new ImportedConditionUpdate(Connection, state, info, placements, sourceName); + } + + private static string? Message(ArrayOf e) => e[MessageF].GetLocalizedText().Text; + + private static async Task SubscribeAsync(ISession session, Events events, CancellationToken ct) + { + var subscription = new Subscription(session.DefaultSubscription) { PublishingInterval = 100 }; + subscription.FastEventCallback = events.OnEvents; + session.AddSubscription(subscription); + await subscription.CreateAsync(ct); + return subscription; + } + + private static SdkMonitoredItem AddItem(Subscription subscription, NodeId source) + { + var filter = new EventFilter(); + filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.EventId)); + filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.SourceNode)); + filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.SourceName)); + filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.Message)); + filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.Severity)); + filter.AddSelectClause(ObjectTypeIds.ConditionType, QualifiedName.From(BrowseNames.ConditionName)); + filter.SelectClauses += new SimpleAttributeOperand(ObjectTypeIds.AlarmConditionType, + [QualifiedName.From(BrowseNames.ActiveState), QualifiedName.From(BrowseNames.Id)]); + filter.SelectClauses += new SimpleAttributeOperand(ObjectTypeIds.AcknowledgeableConditionType, + [QualifiedName.From(BrowseNames.AckedState), QualifiedName.From(BrowseNames.Id)]); + filter.AddSelectClause(ObjectTypeIds.ConditionType, QualifiedName.From(BrowseNames.Quality)); + filter.SelectClauses += new SimpleAttributeOperand { TypeDefinitionId = ObjectTypeIds.ConditionType, AttributeId = Attributes.NodeId }; + filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.EventType)); + var item = new SdkMonitoredItem(subscription.DefaultItem) + { + StartNodeId = source, AttributeId = Attributes.EventNotifier, Filter = filter, QueueSize = 1000, SamplingInterval = 0, + }; + subscription.AddItem(item); + return item; + } + + private sealed class Events + { + private readonly object _gate = new(); + private readonly List<(uint Handle, ArrayOf Fields)> _events = []; + + public void OnEvents(Subscription subscription, EventNotificationList notification, ArrayOf stringTable) + { + lock (_gate) foreach (var e in notification.Events) _events.Add((e.ClientHandle, e.EventFields)); + } + + public IReadOnlyList> Of(SdkMonitoredItem item) + { + lock (_gate) return _events.Where(e => e.Handle == item.ClientHandle).Select(e => e.Fields).ToList(); + } + + public static Task WaitUntilAsync(Func condition) => RecordedEvents.WaitUntilAsync(condition); + } + + /// The fake §5.4 gate: a principal set (ACL enforcement stays OFF in the rig). + internal sealed class FakeConditionAccess : IProjectedConditionAccess + { + public HashSet Allowed { get; } = new(StringComparer.Ordinal); + public int Demands; + public long Generation = 1; + public bool CanSee(RoleCarryingUserIdentity? caller, IReadOnlyList placements) => + caller is not null && Allowed.Contains(caller.Principal); + public long AuthorityGeneration => Interlocked.Read(ref Generation); + public IDisposable? AcquireEventDemand(RoleCarryingUserIdentity? caller) + { + Interlocked.Increment(ref Demands); + return null; + } + } + + /// A local parent, two mapping anchors (map-a, map-b) and one projected device folder under map-a. + private sealed class Fixture + { + public required ServerEventRig Rig { get; init; } + public required FakeConditionAccess Access { get; init; } + public required NodeId Anchor { get; init; } + public required NodeId AnchorB { get; init; } + public required NodeId DeviceFolder { get; init; } + public required ProjectedVariableDefinition DeviceDefinition { get; init; } + + public static Fixture Install(ServerEventRig rig, string grantedPrincipal) + { + var nm = rig.Nm; + nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); + var parent = nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; + var rootA = new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant"); + var rootB = new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Other"); + nm.TryEnsureProjectedAnchor(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(MappingA, rootA), parent, + "remote-a", "Plant/remote-a", MappingA, 1, () => true), out var anchor).ShouldBeTrue(); + nm.TryEnsureProjectedAnchor(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(MappingB, rootB), parent, + "remote-b", "Plant/remote-b", MappingB, 1, () => true), out var anchorB).ShouldBeTrue(); + var devAddress = new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant/dev1"); + var metadata = new DataMetadata(new DataView(devAddress, DataRealm.Raw, MappingA, 1, "Plant/remote-a/dev1"), "dev1", "Folder", + DataValueKind.Null, -1, [], false, DataOperations.Browse, 1, null, null, false); + var definition = new ProjectedVariableDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(MappingA, devAddress), anchor!.Value, + metadata, 1, () => true); + nm.TryEnsureProjectedVariable(definition, out var device).ShouldBeTrue(); + var access = new FakeConditionAccess(); + access.Allowed.Add(grantedPrincipal); + nm.ProjectedConditionAccess = access; + return new Fixture { Rig = rig, Access = access, Anchor = anchor.Value, AnchorB = anchorB!.Value, DeviceFolder = device!.Value, + DeviceDefinition = definition }; + } + + /// Primary: the raw tag under dev1 (map-a); second: the same condition listed directly under the map-a root. + public IReadOnlyList TwoPlacements() => + [ + new(MappingA, DataRealm.Raw, View("Plant/dev1/HR200"), "Plant/remote-a/dev1", "dev1/HR200"), + new(MappingA, DataRealm.Raw, View("Plant/HR200"), "Plant/remote-a", "HR200"), + ]; + + public ImportedConditionPlacement BPlacement() => + new(MappingB, DataRealm.Raw, View("Other/HR200"), "Plant/remote-b", "HR200"); + + private static DataView View(string path) => + new(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", path), DataRealm.Raw, null, 0, path); + + public void Apply(ImportedConditionUpdate update) => Rig.Nm.ApplyConditions([update]); + } +} From 4b74ac9cc2356f13d3a9badcead6e4ebe83dc52c Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 16:38:57 -0500 Subject: [PATCH 07/32] test(grpc-data): A3a ProjectedConditionAccess runtime tests (capacity, barrier, host caps, 2000 conditions, version rule, lifetime, timeout, primary placement, gate, linger) --- .../GrpcDataProjectedConditionAccessTests.cs | 383 ++++++++++++++++++ 1 file changed, 383 insertions(+) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs new file mode 100644 index 000000000..817ede9ec --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs @@ -0,0 +1,383 @@ +using System.Security.Cryptography; +using System.Threading.Channels; +using Microsoft.Extensions.Logging.Abstractions; +using Opc.Ua; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using BrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest; +using ReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest; +using ReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// A3a (plan §5.4, §5.5): the consumer condition runtime over a scripted origin stream — the per-mapping capacity +/// decision before anything is materialised (and the item removed), the snapshot barrier, the host caps, 2,000 conditions +/// without MaxProjectionNodes, the version rule (removal bypasses it and forgets the version), the lifetime rule (a +/// stream end re-snapshots and never removes; only a complete re-snapshot does), staleness, the mapping gate with a real +/// , primary placement from deployed config, and demand with linger. +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "A3")] +public sealed class GrpcDataProjectedConditionAccessTests +{ + private const string Connection = "conn-a"; + + [Fact] + public async Task A_total_over_MaxConditions_is_ConditionCapacity_and_its_item_removed_before_materialising_other_mappings_unaffected() + { + await using var f = new Fixture(("map-a", DataRealm.Raw, 2), ("map-b", DataRealm.Raw, 10)); + using var demand = f.Access.AcquireEventDemand(null); + var stream = await f.NextStreamAsync(); + stream.Ack(); + stream.Begin("map-a", total: 3); + await f.WaitAsync(() => stream.Removed.Count == 1); + stream.Removed.Single().ShouldBe(stream.HandleOf("map-a"), "the over-limit item is removed, not held open"); + f.Sink.Applied.ShouldBeEmpty("nothing is materialised before the barrier"); + stream.Begin("map-b", total: 2); + stream.Records("map-b", Record(Key("x"), 3), Record(Key("y"), 3)); + f.Sink.Applied.ShouldBeEmpty(); + stream.Complete("map-b"); + await f.WaitAsync(() => f.Sink.Applied.Count == 2); + f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity); + f.Access.MappingStatuses(Connection)!["map-b"].ShouldBe(ProjectedConditionMappingStatus.Complete); + f.Sink.Applied.ShouldAllBe(u => u.Placements.All(p => p.MappingId == "map-b")); + } + + [Fact] + public async Task Two_thousand_conditions_in_one_mapping_materialise_without_MaxProjectionNodes_and_the_host_cap_rejects_before_materialising() + { + await using var f = new Fixture(("map-a", DataRealm.Raw, 5000)); + f.Mappings.Current[0].Mapping.MaxProjectionNodes = 10; + using var demand = f.Access.AcquireEventDemand(null); + var stream = await f.NextStreamAsync(); + stream.Ack(); + stream.Begin("map-a", total: 2000); + stream.Records("map-a", Enumerable.Range(0, 2000).Select(i => Record(Key("k" + i), 3)).ToArray()); + stream.Complete("map-a"); + await f.WaitAsync(() => f.Sink.Applied.Count == 2000); + f.Sink.Applied.Select(u => u.State.ConditionKey).Distinct().Count().ShouldBe(2000); + f.Mappings.Current[0].Mapping.MaxProjectionNodes.ShouldBe(10, "conditions have their own budget"); + + // Host cap: 1,999 conditions' worth of nodes ⇒ the 2,000-condition mapping is rejected at begin. + await using var capped = new Fixture(new ProjectedConditionOptions(TimeSpan.FromMilliseconds(200), 1999 * 49, long.MaxValue, + TimeSpan.FromMilliseconds(50)), ("map-a", DataRealm.Raw, 5000)); + using var cappedDemand = capped.Access.AcquireEventDemand(null); + var cappedStream = await capped.NextStreamAsync(); + cappedStream.Ack(); + cappedStream.Begin("map-a", total: 2000); + await capped.WaitAsync(() => cappedStream.Removed.Count == 1); + capped.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity); + capped.Sink.Applied.ShouldBeEmpty(); + } + + [Fact] + public async Task Versions_gate_per_key_but_a_removal_bypasses_the_gate_and_forgets_the_version() + { + await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); + using var demand = f.Access.AcquireEventDemand(null); + var stream = await f.NextStreamAsync(); + stream.Ack(); + stream.Begin("map-a", total: 1); + stream.Records("map-a", Record(Key("x"), 5)); + stream.Complete("map-a"); + await f.WaitAsync(() => f.Sink.Applied.Count == 1); + stream.Records("map-a", Record(Key("x"), 4, message: "stale")); // older ⇒ dropped + stream.Records("map-a", Record(Key("x"), 5, removed: true)); // removal at the hub watermark (= an applied version) + await f.WaitAsync(() => f.Sink.Removed.Count == 1); + f.Sink.Applied.ShouldNotContain(u => u.State.Message == "stale"); + stream.Records("map-a", Record(Key("x"), 3, message: "re-added")); // the version was forgotten + await f.WaitAsync(() => f.Sink.Applied.Any(u => u.State.Message == "re-added")); + } + + [Fact] + public async Task A_stream_end_re_snapshots_without_removing_and_only_a_complete_re_snapshot_removes_staleness_in_between() + { + await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); + using var demand = f.Access.AcquireEventDemand(null); + var first = await f.NextStreamAsync(); + first.Ack(); + first.Begin("map-a", total: 2); + first.Records("map-a", Record(Key("x"), 3), Record(Key("y"), 3)); + first.Complete("map-a"); + await f.WaitAsync(() => f.Sink.Applied.Count == 2); + + first.End(); // an origin deploy ends the stream (A2 S1) + var second = await f.NextStreamAsync(); + await f.WaitAsync(() => f.Sink.Stale.Count >= 1); // stale timeout (100 ms) passes before the new snapshot completes + f.Sink.Removed.ShouldBeEmpty("a stream end is never 'conditions removed'"); + second.Ack(); + second.Begin("map-a", total: 1); + second.Records("map-a", Record(Key("x"), 9)); + f.Sink.Removed.ShouldBeEmpty("an incomplete snapshot removes nothing"); + second.Complete("map-a"); + await f.WaitAsync(() => f.Sink.Removed.Count == 1); + f.Sink.Removed.Single().ShouldBe(Key("y")); + f.Access.BarriersCompleted(Connection).ShouldBe(2, "one barrier per stream: the first snapshot and the re-snapshot"); + } + + [Fact] + public async Task A_mapping_whose_snapshot_times_out_is_Unavailable_the_rest_proceed_and_RefreshRequired_follows() + { + await using var f = new Fixture(("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); + f.Mappings.Current[0].Mapping.ConditionSnapshotTimeoutMilliseconds = 300; + f.Mappings.Current[1].Mapping.ConditionSnapshotTimeoutMilliseconds = 300; + using var demand = f.Access.AcquireEventDemand(null); + var stream = await f.NextStreamAsync(); + stream.Ack(); + stream.Begin("map-b", total: 1); + stream.Records("map-b", Record(Key("x"), 3)); + stream.Complete("map-b"); + await f.WaitAsync(() => f.Sink.Applied.Count == 1); + f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable); + f.Sink.RefreshRequired.ShouldBe(1); + } + + [Fact] + public async Task The_primary_placement_comes_from_deployed_config_Raw_first_then_mapping_id_and_SourceName_follows_it() + { + await using var f = new Fixture(("map-u", DataRealm.Uns, 10), ("map-z", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); + using var demand = f.Access.AcquireEventDemand(null); + var stream = await f.NextStreamAsync(); + stream.Ack(); + // Stream order deliberately the reverse of the deployed order. + foreach (var mapping in new[] { "map-u", "map-z", "map-b" }) + { + stream.Begin(mapping, total: 1); + stream.Records(mapping, Record(Key("x"), 3, placement: mapping == "map-u" ? f.UnsPlacement : f.RawPlacement)); + stream.Complete(mapping); + } + await f.WaitAsync(() => f.Sink.Applied.Count == 1); + var update = f.Sink.Applied.Single(); + update.Placements.Select(p => p.MappingId).ShouldBe(["map-b", "map-z", "map-u"]); + update.SourceName.ShouldBe("Plant/map-b/dev1/HR200", "the primary mapping's branch path + the address below the remote root"); + update.Placements[0].FolderLocalSubject.ShouldBe("Plant/map-b/dev1"); + } + + [Fact] + public async Task The_gate_is_the_mapping_Subscribe_grant_on_the_placement_folder_and_needs_the_condition_bits() + { + await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); + var placement = new ImportedConditionPlacement("map-a", DataRealm.Raw, f.RawPlacement, "Plant/map-a/dev1", "dev1/HR200"); + f.Grant(NodePermissions.Browse | NodePermissions.Subscribe); + f.Access.CanSee(f.Identity("reader"), [placement]).ShouldBeTrue(); + f.Access.CanSee(f.Identity("someone-else"), [placement]).ShouldBeFalse(); + f.Access.CanSee(null, [placement]).ShouldBeFalse(); + f.Grant(NodePermissions.Browse); + f.Access.CanSee(f.Identity("reader"), [placement]).ShouldBeFalse("Subscribe is the visibility permission (not AlarmRead)"); + f.Grant(NodePermissions.Browse | NodePermissions.Subscribe); + f.Mappings.Current[0].Mapping.AllowedOperations = DataOperations.Browse | DataOperations.Subscribe; + f.Access.CanSee(f.Identity("reader"), [placement]).ShouldBeFalse("a mapping without AlarmSubscribe carries no conditions"); + } + + [Fact] + public async Task Demand_opens_the_stream_and_the_linger_closes_it_and_removes_what_it_materialised() + { + await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); + f.Access.IsRunning(Connection).ShouldBeFalse(); + var demand = f.Access.AcquireEventDemand(null)!; + var stream = await f.NextStreamAsync(); + stream.Ack(); + stream.Begin("map-a", total: 1); + stream.Records("map-a", Record(Key("x"), 3)); + stream.Complete("map-a"); + await f.WaitAsync(() => f.Sink.Applied.Count == 1); + demand.Dispose(); + f.Access.IsRunning(Connection).ShouldBeTrue("the linger keeps it open"); + await f.WaitAsync(() => !f.Access.IsRunning(Connection) && f.Sink.Removed.Count == 1); + } + + // --------------------------------------------------------------------------------------------------------------------- + + internal static string Key(string seed) => + Convert.ToBase64String(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(seed))).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + + private static DataConditionState Record(string key, long version, bool removed = false, string message = "high", DataView? placement = null) + { + var info = removed ? null : new DataConditionInfo("AlarmConditionType", "HR200", DataConditionSourceKind.Native, + [placement ?? Fixture.DefaultRawPlacement], 3); + return new DataConditionState(key, version, removed, !removed, info, true, false, true, true, 0, 500, message, 0, null, 0, + DateTimeOffset.UtcNow, true, new DataActivationMarker("inc", 1)); + } + + private sealed class Fixture : IAsyncDisposable + { + internal static readonly DataView DefaultRawPlacement = + new(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant/dev1/HR200"), DataRealm.Raw, null, 0, "Plant/dev1/HR200"); + public DataView RawPlacement => DefaultRawPlacement; + public DataView UnsPlacement { get; } = + new(new DataAddress("origin", "https://zb.com/otopcua/uns", "string", "Area/Line/Filler/HR200"), DataRealm.Uns, null, 0, "Area/Line/Filler/HR200"); + private readonly DataPlaneAuthorityState _state = new(); + private readonly ApiKey _key = new() { ApiKeyId = "key-a", Name = "key-a", Principal = "reader", SecretHash = "hash", Enabled = true, + ExpiresUtc = DateTime.UtcNow.AddHours(1) }; + public FakeMappings Mappings { get; } + public FakeSink Sink { get; } = new(); + public FakeConnections Connections { get; } = new(); + public ProjectedConditionAccess Access { get; } + + public Fixture(params (string Id, DataRealm Realm, int MaxConditions)[] mappings) + : this(new ProjectedConditionOptions(TimeSpan.FromMilliseconds(200), 122_500, long.MaxValue, TimeSpan.FromMilliseconds(50)), mappings) { } + + public Fixture(ProjectedConditionOptions options, params (string Id, DataRealm Realm, int MaxConditions)[] mappings) + { + Grant(NodePermissions.Browse | NodePermissions.Subscribe); + Mappings = new FakeMappings(mappings.Select(m => Placement(m.Id, m.Realm, m.MaxConditions)).ToList()); + var policy = new DataOperationPolicy(_state, new TriePermissionEvaluator(_state.Tries, TimeProvider.System), TimeProvider.System); + Access = new ProjectedConditionAccess(Mappings, Connections, policy, () => Sink, TimeProvider.System, options, NullLogger.Instance); + } + + public void Grant(NodePermissions permissions) => + _state.Apply("c1", "rev-" + (int)permissions, [_key], + [new NodeAcl { NodeAclId = "acl", ClusterId = "c1", Principal = "reader", ScopeKind = NodeAclScopeKind.RawFolder, + ScopeId = "folder", PermissionFlags = permissions }], + new Dictionary> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant"])] }); + + public RoleCarryingUserIdentity Identity(string principal) => new(new UserNameIdentityToken { UserName = "apikey" }, [], principal, + _key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(_key), DateTimeOffset.UtcNow.AddMinutes(5)); + + private static ProjectedMappingPlacement Placement(string id, DataRealm realm, int maxConditions) + { + var mapping = new RemoteNamespaceMapping + { + RemoteNamespaceMappingId = id, DataConnectionId = Connection, Enabled = true, Realm = realm, RemoteRealm = realm, + AllowedOperations = DataOperations.Browse | DataOperations.Subscribe | DataOperations.AlarmSubscribe, MaxConditions = maxConditions, + ConditionStaleTimeoutMilliseconds = 100, ConditionSnapshotTimeoutMilliseconds = 30_000, BranchName = id, + RemoteNamespaceUri = realm == DataRealm.Raw ? "https://zb.com/otopcua/raw" : "https://zb.com/otopcua/uns", + RemoteIdentifierKind = "string", RemoteIdentifier = realm == DataRealm.Raw ? "Plant" : "Area", + }; + var segments = new[] { "Plant", id }; + var anchor = new DataView(new DataAddress("origin", mapping.RemoteNamespaceUri, "string", mapping.RemoteIdentifier), realm, id, 1, + string.Join('/', segments)); + var scope = new NodeScope { ClusterId = "c1", Kind = realm == DataRealm.Raw ? NodeHierarchyKind.Raw : NodeHierarchyKind.Uns, Segments = segments }; + return new ProjectedMappingPlacement(mapping, anchor, anchor, scope, ["local-parent"], new ActiveAuthority()); + } + + public async Task NextStreamAsync() => await Connections.Streams.Reader.ReadAsync(TestContext.Current.CancellationToken); + + public async Task WaitAsync(Func condition) + { + var deadline = DateTime.UtcNow.AddSeconds(10); + while (!condition()) + { + if (DateTime.UtcNow > deadline) condition().ShouldBeTrue("condition not met within 10 s"); + await Task.Delay(20, TestContext.Current.CancellationToken); + } + } + + public ValueTask DisposeAsync() { Access.Dispose(); return ValueTask.CompletedTask; } + } + + private sealed class ActiveAuthority : IDataMappedCatalogAuthority + { + public long CatalogEpoch => 1; + public long AuthorityEpoch => 1; + public bool IsActive => true; + } + + internal sealed class FakeMappings(List current) : IProjectedConditionMappings + { + public IReadOnlyList Current { get; } = current; + public event Action? Changed; + public void Raise() => Changed?.Invoke(); + } + + internal sealed class FakeSink : IProjectedConditionSink + { + private readonly object _gate = new(); + private readonly List _applied = []; + private readonly List _removed = []; + private readonly List _stale = []; + private int _refresh; + public IReadOnlyList Applied { get { lock (_gate) return _applied.ToList(); } } + public IReadOnlyList Removed { get { lock (_gate) return _removed.ToList(); } } + public IReadOnlyList Stale { get { lock (_gate) return _stale.ToList(); } } + public int RefreshRequired => Volatile.Read(ref _refresh); + public void ApplyConditions(IReadOnlyList updates) { lock (_gate) _applied.AddRange(updates); } + public void RemoveConditions(string connectionId, IReadOnlyCollection conditionKeys) { lock (_gate) _removed.AddRange(conditionKeys); } + public void MarkConnectionStale(string connectionId) { lock (_gate) _stale.Add(connectionId); } + public void RequireRefresh(string connectionId) => Interlocked.Increment(ref _refresh); + } + + internal sealed class FakeConnections : IGrpcDataAdapterConnectionSource + { + public Channel Streams { get; } = Channel.CreateUnbounded(); + public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken) => + ValueTask.FromResult(new Lease(new FakeConnection(this))); + + private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease + { + public IDataConnection Connection => connection; + public CancellationToken CancellationToken => CancellationToken.None; + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + } + + private sealed class FakeConnection(FakeConnections owner) : IDataConnection + { + public DataTarget Target { get; } = new(DataTargetMode.Cluster, "origin", null); + public TimeProvider Clock => TimeProvider.System; + public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => + Task.FromResult>>(request.Views.Select(v => new DataItemResult("0", DataItemStatus.Good, + new DataMetadata(v with { Subject = v.Address.Identifier }, v.Address.Identifier, "Folder", DataValueKind.Null, -1, [], false, + DataOperations.Browse, 1, null, null, false), null)).ToArray()); + public Task> ReadAsync(ReadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task SubscribeAsync(CancellationToken cancellationToken) + { + var stream = new FakeStream(); + owner.Streams.Writer.TryWrite(stream); + return Task.FromResult(stream); + } + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + + internal sealed class FakeStream : IDataSubscription + { + private readonly Channel _frames = Channel.CreateUnbounded(); + private readonly TaskCompletionSource _open = new(TaskCreationOptions.RunContinuationsAsynchronously); + private long _sequence; + public List Removed { get; } = []; + + public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken) + { + if (command is OpenSubscription open) _open.TrySetResult(open); + if (command is RemoveSubscriptionItems remove) lock (Removed) Removed.AddRange(remove.Items); + return Task.CompletedTask; + } + + public IAsyncEnumerable ReadAllAsync(CancellationToken cancellationToken) => _frames.Reader.ReadAllAsync(cancellationToken); + public ValueTask DisposeAsync() { _frames.Writer.TryComplete(); return ValueTask.CompletedTask; } + + private OpenSubscription Open => _open.Task.Wait(TimeSpan.FromSeconds(10)) ? _open.Task.Result : throw new TimeoutException("no open"); + + public DataItemHandle HandleOf(string mapping) + { + var index = Open.Items.Select((x, i) => (x, i)).Single(x => x.x.ClientItemId == mapping).i; + return new DataItemHandle(Open.SubscriptionId, Open.StreamEpoch, (ulong)(index + 1), 1); + } + + public void Ack() => _frames.Writer.TryWrite(new DataSubscriptionAck(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, "open", + Open.Items.Select(x => new DataSubscriptionItemAck(x.ClientItemId, DataItemStatus.Good, HandleOf(x.ClientItemId), x.Settings, null)).ToArray())); + + public void Begin(string mapping, int total) => Frame(mapping, true, total, [], false); + public void Records(string mapping, params DataConditionState[] records) + { + foreach (var chunk in records.Chunk(128)) Frame(mapping, false, null, chunk, false); + } + public void Complete(string mapping) => Frame(mapping, true, null, [], true); + public void End() => _frames.Writer.TryComplete(); + + private void Frame(string mapping, bool snapshot, int? total, IReadOnlyList items, bool complete) => + _frames.Writer.TryWrite(new DataSubscriptionConditions(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, HandleOf(mapping), snapshot, + total, items, complete)); + } +} From 855f72566087185f6650ae72517489409abbff76 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 16:40:43 -0500 Subject: [PATCH 08/32] test(grpc-data): A3a classifier guard across authorizer entry points + publish-time event rewriter --- .../ImportedConditionClassifierTests.cs | 166 ++++++++++++++++++ 1 file changed, 166 insertions(+) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs new file mode 100644 index 000000000..1fbe9484b --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs @@ -0,0 +1,166 @@ +using System.Security.Cryptography; +using Microsoft.Extensions.Logging.Abstractions; +using Opc.Ua; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections; + +/// +/// A3a (plan §5.2 N4, §5.4): an imported-condition id is classified BEFORE RealmOf on every authorizer entry point +/// (read, history, call, subscribe), whatever realm the caller computed; and the publish-time rewriter drops a marked +/// imported event whose re-check fails, and re-gates an unmarked one for the publishing session. +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "A3")] +public sealed class ImportedConditionClassifierTests : IAsyncDisposable +{ + private readonly string _pki = Path.Combine(Path.GetTempPath(), $"otopcua-imported-classifier-{Guid.NewGuid():N}"); + private OpcUaApplicationHost? _host; + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void A_condition_namespace_id_is_never_decided_by_the_realm_walk_on_any_authorizer_entry_point(bool aclEnabled) + { + var f = new Fixture(aclEnabled); // a Cluster-wide grant: the Raw/Uns walk would ALLOW everything + var conditionId = new NodeId("c1.anything", 9); + var calls = new List<(OpcUaOperation, NodeId)>(); + f.Gate.ImportedConditionClassifier = (_, op, id) => + { + if (id.NamespaceIndex != 9) return null; + calls.Add((op, id)); + return false; + }; + foreach (var realm in new[] { AddressSpaceRealm.Raw, AddressSpaceRealm.Uns }) + { + foreach (var op in new[] { OpcUaOperation.Read, OpcUaOperation.Browse, OpcUaOperation.HistoryRead, OpcUaOperation.Call, + OpcUaOperation.CreateMonitoredItems, OpcUaOperation.AlarmAcknowledge }) + { + f.Gate.Authorize(f.Identity, op, conditionId, realm).ShouldNotBeNull($"Authorize {op} {realm}"); + f.Gate.AuthorizeIfRequired(f.Identity, op, conditionId, realm).ShouldNotBeNull($"AuthorizeIfRequired {op} {realm}"); + f.Gate.IsAllowedCached(f.Identity, op, conditionId, realm).ShouldBeFalse($"IsAllowedCached {op} {realm}"); + f.Gate.TryAuthorizeMapped(f.Identity, op, conditionId, realm, out var veto).ShouldBeTrue(); + veto.ShouldNotBeNull(); + } + } + calls.Count.ShouldBe(2 * 6 * 4, "every entry point asked the condition classifier, never the realm"); + + // Positive control: the same identity on an ordinary Raw id is decided by the grant walk (allowed). + f.Gate.Authorize(f.Identity, OpcUaOperation.Read, new NodeId("Plant/x", 2), AddressSpaceRealm.Raw).ShouldBeNull(); + } + + [Fact] + public async Task The_node_manager_classifier_allows_Read_and_Subscribe_through_the_condition_and_refuses_history_and_calls() + { + var nm = await BootAsync(); + var f = new Fixture(aclEnabled: true); + nm.Authorizer = f.Gate; + var access = new Access(); + nm.ProjectedConditionAccess = access; + var key = Convert.ToBase64String(SHA256.HashData("k"u8.ToArray())).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + var view = new DataView(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant/dev1/HR"), DataRealm.Raw, null, 0, "Plant/dev1/HR"); + var placement = new ImportedConditionPlacement("map-a", DataRealm.Raw, view, "Plant/remote-a/dev1", "dev1/HR"); + var state = new DataConditionState(key, 1, false, true, new DataConditionInfo("AlarmConditionType", "HR", DataConditionSourceKind.Native, + [view], 3), true, false, true, true, 0, 500, "m", 0, null, 0, DateTimeOffset.UtcNow, true, new DataActivationMarker("i", 1)); + nm.ApplyConditions([new ImportedConditionUpdate("conn-a", state, state.Info, [placement], "Plant/remote-a/dev1/HR")]); + var alarm = nm.FindImportedCondition("conn-a", key).ShouldNotBeNull(); + nm.IsImportedConditionId(alarm.NodeId).ShouldBeTrue(); + var child = alarm.ActiveState!.Id!.NodeId; + nm.IsImportedConditionId(child).ShouldBeTrue("children live in the condition's namespace (#629)"); + + foreach (var realm in new[] { AddressSpaceRealm.Raw, AddressSpaceRealm.Uns }) + { + access.Visible = true; + f.Gate.Authorize(f.Identity, OpcUaOperation.Read, child, realm).ShouldBeNull(); + f.Gate.Authorize(f.Identity, OpcUaOperation.CreateMonitoredItems, alarm.NodeId, realm).ShouldBeNull(); + f.Gate.Authorize(f.Identity, OpcUaOperation.HistoryRead, alarm.NodeId, realm).ShouldNotBeNull("no imported condition history"); + f.Gate.Authorize(f.Identity, OpcUaOperation.Call, alarm.NodeId, realm).ShouldNotBeNull("remote methods are A3b"); + f.Gate.Authorize(f.Identity, OpcUaOperation.AlarmAcknowledge, alarm.NodeId, realm).ShouldNotBeNull(); + access.Visible = false; + access.Generation++; + f.Gate.Authorize(f.Identity, OpcUaOperation.Read, child, realm).ShouldNotBeNull("not visible ⇒ denied despite the Cluster grant"); + } + } + + [Fact] + public void The_rewriter_drops_a_failed_marked_event_and_regates_an_unmarked_imported_one() + { + var keep = new ProjectedEventFieldList(new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => true)) { ClientHandle = 1 }; + var drop = new ProjectedEventFieldList(new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => false)) { ClientHandle = 2 }; + var unmarkedDenied = new EventFieldList { ClientHandle = 3 }; + var unmarkedOther = new EventFieldList { ClientHandle = 4 }; + var throwing = new ProjectedEventFieldList(new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => throw new InvalidOperationException())) { ClientHandle = 5 }; + var message = new NotificationMessage + { + SequenceNumber = 7, + NotificationData = [new ExtensionObject(new EventNotificationList { Events = [keep, drop, unmarkedDenied, unmarkedOther, throwing] })], + }; + var projected = ProjectedNotificationRewriter.Project(message, republish: false, list => list.ClientHandle == 3 ? false : null); + var events = projected.NotificationData[0].TryGetValue(out var list) ? list! : throw new InvalidOperationException(); + projected.NotificationData.Count.ShouldBe(1); + events.Events.ToArray()!.Select(e => e.ClientHandle).ShouldBe([1u, 4u]); + + // Every denied event emptied ⇒ the payload is left out entirely (events have no Bad-value form). + var allDenied = new NotificationMessage { SequenceNumber = 8, + NotificationData = [new ExtensionObject(new EventNotificationList { Events = [drop] })] }; + ProjectedNotificationRewriter.Project(allDenied, republish: true, null).NotificationData.Count.ShouldBe(0); + // No imported gate and no marker: v1 messages pass through as the same instance. + var plain = new NotificationMessage { SequenceNumber = 9, NotificationData = [new ExtensionObject(new EventNotificationList { Events = [unmarkedOther] })] }; + ReferenceEquals(ProjectedNotificationRewriter.Project(plain, republish: false, null), plain).ShouldBeTrue(); + } + + private async Task BootAsync() + { + var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions + { + ApplicationName = "ImportedClassifier", ApplicationUri = $"urn:ImportedClassifier:{Guid.NewGuid():N}", + OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = _pki, + }, NullLogger.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken); + _host = started.Host; + return started.Server.NodeManager!; + } + + public async ValueTask DisposeAsync() + { + if (_host is not null) await _host.DisposeAsync(); + if (Directory.Exists(_pki)) + try { Directory.Delete(_pki, recursive: true); } catch (IOException) { } + } + + private sealed class Access : IProjectedConditionAccess + { + public bool Visible { get; set; } + public long Generation { get; set; } = 1; + public bool CanSee(RoleCarryingUserIdentity? caller, IReadOnlyList placements) => caller is not null && Visible; + public long AuthorityGeneration => Generation; + public IDisposable? AcquireEventDemand(RoleCarryingUserIdentity? caller) => null; + } + + private sealed class Fixture + { + private readonly DataPlaneAuthorityState _state = new(); + private readonly ApiKey _key = new() { ApiKeyId = "key-a", Name = "key-a", Principal = "reader", SecretHash = "hash", Enabled = true, + ExpiresUtc = DateTime.UtcNow.AddHours(1) }; + public DataPlaneAuthorizer Gate { get; } + + public Fixture(bool aclEnabled) + { + _state.Apply("c1", "rev", [_key], + [new NodeAcl { NodeAclId = "acl", ClusterId = "c1", Principal = "reader", ScopeKind = NodeAclScopeKind.Cluster, + PermissionFlags = (NodePermissions)~0 }], + new Dictionary>()); + Gate = new DataPlaneAuthorizer(_state, new TriePermissionEvaluator(_state.Tries, TimeProvider.System), aclEnabled, + NullLogger.Instance, TimeProvider.System); + } + + public RoleCarryingUserIdentity Identity => new(new UserNameIdentityToken { UserName = "apikey" }, [], "reader", _key.ApiKeyId, + DataCallerIdentity.CredentialVersionFor(_key), DateTimeOffset.UtcNow.AddMinutes(5)); + } +} From bdc29ac25a79b7305fc763db87c472a820de1922 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 16:42:13 -0500 Subject: [PATCH 09/32] =?UTF-8?q?test(grpc-data):=20A3=20extends=20the=20r?= =?UTF-8?q?ecorded-v1-client=20gate=20=E2=80=94=20fake=20origin=20emits=20?= =?UTF-8?q?begin/total,=20info=20record,=20snapshot=5Fcomplete,=20removed?= =?UTF-8?q?=20delta?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../GrpcDataV1CompatibilityTests.cs | 42 ++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1CompatibilityTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1CompatibilityTests.cs index 0c5adf646..0b24ef423 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1CompatibilityTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1CompatibilityTests.cs @@ -115,6 +115,32 @@ public sealed class GrpcDataV1CompatibilityTests else cases.ShouldNotContain(W.SubscriptionFrame.FrameOneofCase.ConditionStates); } + /// + /// A3: the fake origin now emits what the consumer registry consumes (begin with total, an info-carrying record, + /// snapshot_complete, a removed delta). A header-less caller — even one whose item carries a condition + /// scope — still gets the golden v1 bytes; the negotiated stream carries all three condition frames. + /// + [Fact] + [Trait("Phase", "A3")] + public async Task A3_consumer_condition_shapes_reach_only_a_negotiated_stream_and_v1_bytes_are_unchanged() + { + var open = W.SubscriptionCommand.Parser.ParseFrom(Convert.FromHexString(GrpcDataV1Goldens.Requests["Subscribe"])); + open.Open.Items[0].ConditionScope = new W.ConditionScope { IncludeInfo = true }; + (await V1CompatibilityHarness.DriveAsync("Subscribe", new Metadata(), request: open.ToByteArray())) + .ShouldBe(GrpcDataV1Goldens.Responses["Subscribe"]); + (await V1CompatibilityHarness.DriveAsync("Subscribe", new Metadata(), request: Convert.FromHexString(GrpcDataV1Goldens.Requests["Subscribe"]))) + .ShouldBe(GrpcDataV1Goldens.Responses["Subscribe"]); + var negotiated = (await V1CompatibilityHarness.DriveAsync("Subscribe", new Metadata { { "x-otopcua-data-features", "conditions" } }, + request: open.ToByteArray())).Split('|').Select(f => W.SubscriptionFrame.Parser.ParseFrom(Convert.FromHexString(f))) + .Where(f => f.FrameCase == W.SubscriptionFrame.FrameOneofCase.ConditionStates) + .Select(ZB.MOM.WW.OtOpcUa.Commons.DataConnections.DataConditionProtoMapper.DecodeFrame).ToArray(); + negotiated.Length.ShouldBe(3); + negotiated[0].Total.ShouldBe(1); + negotiated[1].SnapshotComplete.ShouldBeTrue(); + negotiated[1].Items.Single().Info!.Placements.Single().Address.Identifier.ShouldBe("Plant/dev1/HR200"); + negotiated[2].Items.Single().Removed.ShouldBeTrue(); + } + [Fact] public async Task H2_a_history_capable_origin_shows_history_shapes_only_with_the_header() { @@ -432,7 +458,21 @@ internal static class V1CompatibilityHarness [new(0, 3)], 1, 1, "done"), token); // A2a new-shape data: a condition-scoped item gets a snapshot-begin condition frame (arm 9). if (open.Items[0].ConditionScope is not null) - await Emit(sink, new DataSubscriptionConditions(open.SubscriptionId, open.StreamEpoch, 5, handle, true, 0, [], true), token); + { + // A3 new-shape data (what the consumer registry consumes): begin with `total`, a record with info and a + // placement, snapshot_complete, then a delta `removed` record at the hub watermark. + await Emit(sink, new DataSubscriptionConditions(open.SubscriptionId, open.StreamEpoch, 5, handle, true, 1, [], false), token); + var placement = new DataView(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant/dev1/HR200"), + DataRealm.Raw, null, 0, "Plant/dev1/HR200"); + var key = new string('A', 43); + await Emit(sink, new DataSubscriptionConditions(open.SubscriptionId, open.StreamEpoch, 6, handle, true, null, + [new DataConditionState(key, 3, false, true, new DataConditionInfo("AlarmConditionType", "HR200", + DataConditionSourceKind.Native, [placement], 3), true, false, true, true, 0, 777, "high", 0, null, 0, + Source, true, new DataActivationMarker("inc", 1))], true), token); + await Emit(sink, new DataSubscriptionConditions(open.SubscriptionId, open.StreamEpoch, 7, handle, false, null, + [new DataConditionState(key, 3, true, false, null, false, false, false, false, 0, 0, "", 0, null, 0, null, false, null)], + false), token); + } } private static async Task Emit(IDataSubscriptionDeliverySink sink, DataSubscriptionFrame frame, CancellationToken token) { From 762b0fa15dc994ad354efa3a63260c8831661fbe Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 16:43:22 -0500 Subject: [PATCH 10/32] test(grpc-data): A3 unit-phase manifest entry --- scripts/validation/grpc-data/unit-phases.json | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/scripts/validation/grpc-data/unit-phases.json b/scripts/validation/grpc-data/unit-phases.json index a7f7f9d5c..e1e2681dc 100644 --- a/scripts/validation/grpc-data/unit-phases.json +++ b/scripts/validation/grpc-data/unit-phases.json @@ -1148,5 +1148,38 @@ ], "existing_classes": [] } + ], + "A3": [ + { + "project": "tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=A3)|FullyQualifiedName~.GrpcDataConditionStreamTests.|FullyQualifiedName~.GrpcDataConditionMethodClientTests.", + "new_classes": [ + "GrpcDataProjectedConditionAccessTests" + ], + "existing_classes": [ + "GrpcDataConditionStreamTests", + "GrpcDataConditionMethodClientTests" + ] + }, + { + "project": "tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=A3)|FullyQualifiedName~.ConditionMethodNodeManagerTests.|FullyQualifiedName~.ProjectedHistoryReadTests.", + "new_classes": [ + "ImportedConditionClassifierTests" + ], + "existing_classes": [ + "ConditionMethodNodeManagerTests", + "ProjectedHistoryReadTests" + ] + }, + { + "project": "tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/ZB.MOM.WW.OtOpcUa.Host.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=A3)|FullyQualifiedName~.GrpcDataV1CompatibilityTests.|FullyQualifiedName~.GrpcDataV1RealOriginCompatibilityTests.", + "new_classes": [], + "existing_classes": [ + "GrpcDataV1CompatibilityTests", + "GrpcDataV1RealOriginCompatibilityTests" + ] + } ] } From b5ab6e7cde5de50880bd0c76261fa43eadfed729 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 17:00:02 -0500 Subject: [PATCH 11/32] =?UTF-8?q?docs(grpc-data):=20A3a=20evidence=20?= =?UTF-8?q?=E2=80=94=20progress,=20implementation,=20tests,=20mutation=20r?= =?UTF-8?q?ecord,=20deviations,=20gates?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/plans/evidence/grpc-data-ext/A3.md | 163 ++++++++++++++++++++++++ 1 file changed, 163 insertions(+) create mode 100644 docs/plans/evidence/grpc-data-ext/A3.md diff --git a/docs/plans/evidence/grpc-data-ext/A3.md b/docs/plans/evidence/grpc-data-ext/A3.md new file mode 100644 index 000000000..dcef51e2e --- /dev/null +++ b/docs/plans/evidence/grpc-data-ext/A3.md @@ -0,0 +1,163 @@ +# A3 evidence — PART 1 (A3a): consumer condition registry, visibility and event delivery + +Phase A3 (first half) of `docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md`, 2026-11-24, branch +`a3-consumer` (from master `83c7e586`). A3b (§5.6 remote methods: `ICallAsyncNodeManager`, claim / `base.Call` / await, +lock-freedom, `BadEventIdUnknown`, native Confirm) is a separate agent's work on top of this. + +## Progress log + +1. Contracts (`e15bd7c9`): `OpcUaServer/IProjectedConditionAccess.cs` — `IProjectedConditionAccess` (gate, generation, + demand), `IProjectedConditionSink` (apply / remove / stale / RefreshRequired), `ImportedConditionPlacement`, + `ImportedConditionUpdate`. SDK-free except the identity type (as `IProjectedHistoryAccess`). +2. Shared helpers (`a75ea95e`, §5.3 "one refactored helper"): `CreateConditionNode` (type, optional children before + `Create()`, child ids via `New`, initial fields) is now the body of `MaterialiseAlarmCondition` AND the imported factory; + `ApplyConditionState` (state projection + the T20/#656 delta gate) is now the body of `WriteAlarmCondition` AND the + imported apply. `ApplicationAlarmConditions.Create` accepts a null parent (an imported condition has no folder parent). +3. Registry (`1ff18caa`): `OpcUaServer/ProjectedConditionRegistry.cs` (registry class + NM partial implementing + `IProjectedConditionSink`). +4. Runtime (`4f6e26dd`): `Runtime/DataConnections/ProjectedConditionAccess.cs`. +5. Host wiring (`8d6c94a3`): DI singleton + `IProjectedConditionAccess`; `OtOpcUaServerHostedService` sets + `NodeManager.ProjectedConditionAccess` and binds the node manager as the runtime's sink; host caps + `DataConnections:MaxImportedConditionNodes` (122,500) / `MaxImportedConditionBytes` (400 MiB). +6. Tests (`de381157`, `4b74ac9c`, `855f7256`, `bdc29ac2`) and the `A3` manifest entry (`762b0fa1`). + +## What is implemented (A3a) + +- **Namespace + classification (§5.2 N4).** `https://zb.com/otopcua/mapped/conditions` is the node manager's FIFTH + registered namespace. `IsImportedConditionId` is asked before `RealmOf` by `Permits` (read / browse / subscribe) and by + `DataPlaneAuthorizer.TryAuthorizeMapped`, which every authorizer entry point (`Authorize`, `AuthorizeIfRequired`, + `IsAllowedCached`, the alarm-command gate, history) reaches first — so the realm a caller computed with `RealmOf` (which + folds the index into Uns) is never consulted. Imported ids: Browse / Read / CreateMonitoredItems via the condition's + mapping gate; HistoryRead, writes, Call and the alarm operations refused (Call = A3b). ⚠️ **Defect found while testing:** + `OwnsNamespace` listed only indexes 0–3, so condition children kept their ns=0 TYPE ids AND `Permits` treated an + imported id as "not ours to gate" (ungated Read). Fixed; pinned by the child-Read wire test. +- **Registry (§5.3).** Keyed by full NodeId (`c1.` + base64url JSON{ConnectionId, ConditionKey}); never `_alarmConditions` / + `_eventNotifierSources` / `_nativeAlarmNodeIds`. Conditions are parentless predefined nodes with instance-scoped children + (#629). SourceNode = ConditionId = the imported id; SourceName = primary placement path; Severity verbatim (1..1000); + ConditionName / Message / Comment / ClientUserId / ConditionClass / Quality from the record. All Part 9 methods on an + imported condition answer `BadNotSupported` before the SDK touches state (no local apply; A3b replaces this). +- **Notifier wiring (N7).** Lazy and symmetric: a placement's folder (projected folder or mapping anchor, matched on + `(mappingId, local subject)`) is wired when it is materialised — at apply time, or later from `TryEnsureProjectedVariable` + / `TryEnsureProjectedAnchor` — with `AddNotifier` both ways + `EventNotifier |= SubscribeToEvents` + `AddRootNotifier`; + unwired (`RemoveNotifier(bidirectional)`, root notifier removed, `SubscribeToEvents` cleared when the last condition + leaves) at every projected removal site (anchor removal, capacity eviction, page removal, page rollback). A folder holding + an admitted event item is **pinned**: eviction and page removal skip it; a mapping (anchor) removal still removes it, + unwiring first. The Server object is always the delivery point (`OnConditionReportEvent`). +- **Delivery + gate (§5.4).** Delivery reuses the node manager's report walk (`ReportConditionEvent` → condition's + `OnReportEvent` → Server-object items; inverse notifiers → wired folder items), so exactly-once, the #838 deferral queue + and the #854 cuts apply unchanged. The imported branch: the mapping gate per item **regardless of `AclEnforced`** + (Server object, folder hop, refresh), cached per (identity, condition, authority generation, placement version); the + folder hop also requires the folder to be currently wired. `RaiseConditionRecord` is a no-op for imported conditions + (they are not in `_alarmConditions`), so an imported condition never re-enters the origin hub. +- **`ProjectedEventFieldList : EventFieldList` + rewriter (§5.4).** Imported events ALWAYS take the marked projected path + (`EventDeliveryCache.QueueMarked`), whatever `UseProjectedEventDelivery` says; an item the projected path cannot serve + gets nothing (fail closed, counted). The marker carries identity, condition id, generation and a re-check (live condition + ∧ gate). `ProjectedNotificationRewriter.Project` now also walks `EventNotificationList`: a marked list whose re-check + fails is dropped (counted); an UNMARKED list whose `Handle` is an imported-condition snapshot (a select-clause modify + rebuilt it) is re-gated for the publishing session (identity from the Publish/Republish request header's session) and + dropped only on deny (counted); anything else passes as before (v1 messages return the same instance). +- **Event items on projected notifiers.** Admitted (instead of the mapped blanket deny, which still applies to data items) + when the caller passes the gate of at least one condition wired at that folder; delivery and publish re-check per event. +- **Demand / barrier / budget (§5.5)** in `ProjectedConditionAccess`: the first admitted Server-object or projected-notifier + event item opens, per condition-bearing connection (mapping enabled ∧ Subscribe ∧ AlarmSubscribe), ONE stream under the + connection's service principal with one root-scoped item per mapping (Raw first, then mapping id ordinal); all close + together after the last item plus a 30 s linger (and the linger removes what they materialised). Snapshot begin + `total > MaxConditions` ⇒ `ConditionCapacity`, the item is REMOVED (`RemoveSubscriptionItems`), counted + (`otopcua.dataconn.conditions.capacity_rejections`); host caps (`total × 49` nodes, `total × 160,997` bytes) reject the + mappings that would cross them, in deployed order; 80% warning. Nothing is materialised until every mapping completed or + `ConditionSnapshotTimeoutMilliseconds` expired (incomplete ⇒ `Unavailable`, the rest proceed, then `RefreshRequired`). + Conditions never consume `MaxProjectionNodes`. +- **Version rule (A2 N2).** Per key per epoch; `removed` and snapshot begin bypass; a removal is applied unconditionally and + forgets the key's version. +- **Lifetime rule (A2 S1).** A stream end is re-snapshot, never removal; staleness after `ConditionStaleTimeoutMilliseconds` + ⇒ `MarkConnectionStale` (Quality `BadNoCommunication` through the shared delta gate: one event each, Active/Acked + unchanged). Only a COMPLETE re-snapshot that no longer lists a key removes it (an incomplete mapping removes nothing). + T2: a `state_known = false` record never changes state; a never-known condition is `UncertainInitialValue`. +- **Primary placement / SourceName (§5.2).** From deployed config only: Raw mappings before UNS, mapping id ordinal, + placement address ordinal. SourceName = `/` (root + subject learned once per stream with `GetMetadataAsync`). ConditionId depends on (connection, key) only (N4): disabling + the primary mapping moves notifiers and SourceName, nothing else. +- **EventId re-binding seam (N6) for A3b.** `ReportImported` records each consumer-minted EventId with the activation marker + it described (32 per condition); `OtOpcUaNodeManager.TryResolveImportedEvent(conditionId, eventId, out + ImportedConditionBinding)` returns connection, condition_key, primary placement, all placements, activation marker, + native flag — everything §5.6 dispatch needs. +- **RefreshRequired.** `IProjectedConditionSink.RequireRefresh` queues `RefreshRequiredEventType` to every Server-object and + wired-folder item that may see a condition of the connection. +- **ConditionRefresh.** Imported conditions are excluded from the local replay paths (plain + cut, Server object + direct) + and replayed once by `ReplayImportedConditions` through the gated marked path, ACLs on or off. +- **§5.7.** No `alerts` publication / no consumer alarm history (imported conditions are not in `_alarmConditions`, the + condition-state sink never sees them, they are not fed to `NativeAlarmProjector`), no local shelving timers + (`OnTimedUnshelve` no-op, shelve refused). + +## Tests + +| Project | Class | What | +|---|---|---| +| OI | `ImportedConditionEventWireTests` (7, Phase=A3) | real SDK server + real client sessions: exactly one event per transition at a projected device folder, the mapping anchor (second placement) and `i=2253`, after a sentinel; §5.2 identity fields (SourceNode = ConditionId = `c1.` id in mapped/conditions, SourceName, Severity 777 verbatim, ConditionName); **A3-SEC** with ACLs off (no grant ⇒ folder item refused, zero events live and on ConditionRefresh, positive control + RefreshEnd sentinel; a revocation drops a queued event at publish); child Read authorized through the condition (granted Good / ungranted `BadUserAccessDenied`), Acknowledge refused and unapplied; disabling the primary mapping keeps the ConditionId and the instance (notifiers + SourceName move), a later mapping changes no NodeId; folder with an event item not retired, retirement unwires; resync of unchanged state reports nothing, then a must-arrive transition exactly once; staleness = one `BadNoCommunication` event per condition, still Active, unknown records change nothing, never-known = Uncertain | +| Runtime | `GrpcDataProjectedConditionAccessTests` (8, Phase=A3) | scripted origin stream: `total > MaxConditions` ⇒ `ConditionCapacity` + item removed before anything materialises, other mapping unaffected; 2,000 conditions with `MaxProjectionNodes = 10`; host node cap rejects at begin; version gate, removal bypass + forgotten version; stream end ⇒ no removal, staleness, complete re-snapshot removes only the missing key, incomplete removes nothing; snapshot timeout ⇒ Unavailable + RefreshRequired; primary placement Raw-first/ordinal independent of stream order + SourceName + folder subject; the gate with a REAL `DataOperationPolicy` (Subscribe grant on the folder scope; not AlarmRead; mapping needs AlarmSubscribe); demand opens, linger closes and removes | +| OpcUaServer | `ImportedConditionClassifierTests` (4, Phase=A3) | **guard test**: a condition-namespace id fed to `Authorize` / `AuthorizeIfRequired` / `IsAllowedCached` / `TryAuthorizeMapped` × {Raw, Uns} × {Read, Browse, HistoryRead, Call, CreateMonitoredItems, AlarmAcknowledge}, ACL on and off, under a Cluster-wide grant — the classifier is asked every time (48), never the realm walk; positive control on a Raw id; the node manager's classifier: Read/Subscribe through the condition, HistoryRead/Call/Ack refused, invisible ⇒ denied despite the Cluster grant; rewriter drops failed / throwing markers, re-gates unmarked, empties payloads, passes v1 messages through as the same instance | +| Host | `GrpcDataV1CompatibilityTests.A3_consumer_condition_shapes_…` (Phase=A3) | recorded-v1-client gate: the fake origin now also emits begin+`total`, an info/placement record + `snapshot_complete`, a `removed` delta; header-less (scoped or not) still the golden bytes; negotiated decodes all three. `git diff master -- '*Goldens.cs'` empty | + +**Mutation record (A3-SEC, OI).** Removing only the Server-object delivery gate leaves A3-SEC green: the publish-time +marker re-check drops the event (the second layer works). Removing the delivery gate AND making the marker re-check +`true` turns it red (`deniedEvents … Count` 1). Both layers are real; no single-layer test isolates the delivery gate. + +## Deviations / decisions (no questions asked; reasoning recorded) + +1. **Delivery reuses the node manager's report walk** instead of a separate fan-out: imported conditions are not in the + realm-keyed maps (as the plan requires), but `ReportConditionEvent`/`DeliverConditionEventAsync`/`OnConditionReportEvent`/ + `DeliverToNotifierItems`/`QueueToItem` gained an imported branch. This keeps exactly-once, #838/#854/#855 semantics + without a second implementation. +2. **Demand is global, not "per connection the caller could see"**: the first admitted event item opens every + condition-bearing connection. The per-event gate still decides visibility; the cost is opening streams a caller might not + see. Simpler and fail-safe; A4 diagnostics can reconsider. +3. **Folder event-item admission** uses the imported gate of a condition wired at that folder (not the folder's mapped + Browse proof). A folder is a notifier only while a condition is wired there (N7), so a folder-only client cannot open + demand by itself — a Server-object item (or an already-wired folder) is needed. Recorded for A4. +4. **RefreshRequired** is sent on an INCOMPLETE barrier (snapshot timeout); "a ConditionRefresh before the barrier ⇒ + RefreshRequired when it completes" is not tracked separately (the timeout path covers incomplete resyncs). An UNMARKED + list dropped by the rewriter is counted but the item does NOT get a RefreshRequired (the rewriter has no item handle) — + follow-up for A3b/A4. +5. **Verdict cache** keys on `AuthorityGeneration` = (mapping-set version ≪ 32) ⊕ the policy's authority epoch, plus the + condition's placement version; the policy's own decision cache sits under it. Bounded (65,536 entries, then cleared). +6. **Removal of an imported condition emits no event** (no NodeDeleted model change for the condition namespace); clients + key on ConditionId and see it no longer refreshed. The linger close removes materialised conditions (no stale state left + when no one watches). +7. **Root-leaf replacement** of a mapping anchor (`TryApplyRootLeaf`) does not unwire an imported condition wired at that + anchor (a root-leaf mapping is a variable root; conditions there have a folder parent elsewhere). Edge case, recorded. +8. **ConditionRefresh replay of imported conditions** runs under one `Lock` hold (consistent with the synchronous events it + races); at the host cap (2,500 conditions) × items this is the longest hold A3a adds — L2/L3 live measurements should + include it. Apply is chunked at 128 updates per hold; the folder index is one scan of projected nodes per apply batch. +9. **Primary endpoint** for condition items (A2 N7: a Secondary advertises but refuses) is left to the connection source's + existing endpoint selection; a Secondary answers the item `Unavailable`, the mapping is `Unavailable` and retried on the + next stream. A3b/A4 should prefer the Primary explicitly. +10. **A3 OI tests** run outside the unit-phase runner (it accepts unit projects only), as for H1/H3. + +## Gates + +| Gate | Result | +|---|---| +| `dotnet build ZB.MOM.WW.OtOpcUa.slnx --no-incremental` | 0 warnings, 0 errors | +| `run-unit-phase.py A3` (Runtime + OpcUaServer + Host) | passed (`20261124T214213…`) | +| `run-unit-phase.py A2` | passed | +| `run-unit-phase.py A1`, `X0` | passed, passed | +| Host.Tests DataConnections (both v1 gates) | 207 passed | +| OI `ImportedConditionEventWireTests` | 7 passed | +| OpcUaServer.Tests full (`Category!=E2E&Category!=LiveIntegration`) | 1455 passed, 1 skipped | +| Runtime.Tests full (same filter) | 2030 passed, 3 skipped (no #920 rerun needed) | +| OI `Feature=GrpcData` + ConditionMethodEvent / NativeAlarmEventIdentityFieldDelivery / FolderConditionRefresh / ConditionRefreshDeferral | 116 passed | +| `git diff master -- '*Goldens.cs'` | empty | + +Live rig: not run for A3a (no consumer-side condition demand exists until a client subscribes, and A3b + the exit gate +own the live leg); the unit + OI wire tests above use a real SDK server and real client sessions. + +## Left for A3b + +- §5.6: `ICallAsyncNodeManager` on the node manager (claim / `base.Call` / await, never under `Lock`), dispatch through + `TryResolveImportedEvent` → `IDataConditionMethodService` on the connection, no local apply before the origin record, + unknown EventId ⇒ `BadEventIdUnknown` unsent, native Confirm ⇒ `BadNotSupported` unsent, lock-freedom (L3), binding the + mapping's `ConditionMethodTimeoutMilliseconds`. Today every Part 9 method on an imported condition is refused + (`BadNotSupported` handlers; the classifier also refuses `Call` / alarm operations). +- RefreshRequired to an item whose UNMARKED list the rewriter dropped (deviation 4); explicit Primary endpoint for + condition items (deviation 9); the mapping-change runner hand-over (an old runner's in-flight batch can still reach the + sink until its cancellation is observed — bounded by one frame). From c1be5725b9bbc9540edbe427eb5b7c606503db04 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 17:11:05 -0500 Subject: [PATCH 12/32] =?UTF-8?q?feat(grpc-data):=20A3b=20ICallAsyncNodeMa?= =?UTF-8?q?nager=20=E2=80=94=20claim=20imported-condition=20calls,=20base.?= =?UTF-8?q?Call=20unchanged=20for=20the=20rest,=20lock-free=20remote=20dis?= =?UTF-8?q?patch,=20EventId=20registry=20gate=20+=20N6=20re-binding?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ImportedConditionMethods.cs | 351 ++++++++++++++++++ .../ProjectedConditionRegistry.cs | 47 ++- 2 files changed, 387 insertions(+), 11 deletions(-) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ImportedConditionMethods.cs diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ImportedConditionMethods.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ImportedConditionMethods.cs new file mode 100644 index 000000000..21476a2a8 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ImportedConditionMethods.cs @@ -0,0 +1,351 @@ +using System.Collections.Concurrent; +using System.Diagnostics; +using Microsoft.Extensions.Logging; +using Opc.Ua; +using Opc.Ua.Server; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; + +/// +/// A3b (plan §5.6 step 2): where an authorized remote condition method goes — the placement the origin resolves (one the +/// caller passed the mapping gate on, primary order first) and that mapping's ConditionMethodTimeoutMilliseconds. +/// +/// The placement to dispatch through. +/// The mapping's method ceiling (default 5 s). +public sealed record ImportedConditionMethodRoute(ImportedConditionPlacement Placement, TimeSpan Timeout); + +/// +/// A3b (plan §5.6 step 4): one remote condition method the consumer's node manager hands to its condition runtime. Never +/// carries the local caller's credentials: the origin sees the connection's service principal; is +/// audit text only. +/// +/// The connection the condition was imported over. +/// The origin's opaque key (diagnostics only; the origin resolves ). +/// The placement to address the origin with. +/// Exactly one method. +/// The marker of the latest applied record (T3). +/// The Part 9 comment, or null. +/// A fresh id per dispatched call (the origin joins duplicates of it, never retried here). +/// min(request deadline, the mapping's method ceiling) minus what was already spent. +/// The local caller's principal, for the origin's audit log. +public sealed record ImportedConditionMethodCall(string ConnectionId, string ConditionKey, ImportedConditionPlacement Placement, + DataConditionMethods Method, DataActivationMarker ExpectedActivation, string? Comment, string OperationId, TimeSpan RemainingBudget, + string? OnBehalfOf); + +/// +/// A3b (plan §5.6): the consumer condition runtime's method port. SDK-free apart from the identity type. +/// +public interface IProjectedConditionMethods +{ + /// + /// The per-caller gate (re-evaluated for every local caller — the stream itself runs under the connection's service + /// principal): the caller's AlarmAcknowledge (Acknowledge, AddComment) or AlarmConfirm (Confirm) grant on + /// the placement's folder scope, on a current, condition-bearing mapping that itself grants the method's bit, with a + /// usable key (#563). Regardless of Security:Acl:Enabled. Null = denied. + /// + ImportedConditionMethodRoute? AuthorizeMethod(RoleCarryingUserIdentity? caller, IReadOnlyList placements, + DataConditionMethods method); + + /// One remote call. Answers, never throws for a remote failure; never retried. + Task CallAsync(ImportedConditionMethodCall call, CancellationToken cancellationToken); +} + +/// +/// A3b (plan §5.6 step 1): the Call service's interception point for imported conditions. The SDK's +/// AsyncNodeManagerAdapter forwards CallAsync to a wrapped manager only when it implements +/// ; otherwise it runs the synchronous Call, which takes Lock per request. +/// +public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager +{ + /// Most remote condition methods in flight on this node (§5.6: bounds upstream load, not threads). + internal const int DefaultImportedMethodConcurrency = 8; + + /// How long past the call's own budget the node manager waits for the port before answering BadTimeout. + internal static readonly TimeSpan ImportedMethodGrace = TimeSpan.FromMilliseconds(250); + + private readonly SemaphoreSlim _importedMethodSlots = new(DefaultImportedMethodConcurrency, DefaultImportedMethodConcurrency); + private readonly ConcurrentDictionary> _importedMethodsInFlight = new(StringComparer.Ordinal); + private long _importedMethodsDispatched, _importedMethodsJoined, _importedMethodsRefused; + + /// A3b: the consumer's remote condition method port (null ⇒ every imported method is BadNotSupported). + public IProjectedConditionMethods? ProjectedConditionMethods { get; set; } + + /// Remote condition methods handed to the port (test/diagnostic observation). + internal long ImportedMethodsDispatched => Interlocked.Read(ref _importedMethodsDispatched); + + /// Calls that joined an identical call already in flight instead of dispatching again. + internal long ImportedMethodsJoined => Interlocked.Read(ref _importedMethodsJoined); + + /// Imported-condition calls refused locally (nothing sent). + internal long ImportedMethodsRefused => Interlocked.Read(ref _importedMethodsRefused); + + /// + /// §5.6 step 1: (a) claim every unprocessed request whose ObjectId is in mapped/conditions — a namespace-index + /// test, no lock; (b) the unchanged synchronous base.Call for everything else (it skips claimed requests), run + /// and completed before any remote await; (c) the claimed calls concurrently, bounded by the per-node semaphore. + /// No Lock is held by this method at any point. + /// + public override async ValueTask CallAsync(OperationContext context, ArrayOf methodsToCall, + IList results, IList errors, CancellationToken cancellationToken = default) + { + List? claimed = null; + for (var i = 0; i < methodsToCall.Count; i++) + { + var request = methodsToCall[i]; + if (request is null || request.Processed || !IsImportedConditionId(request.ObjectId)) continue; + request.Processed = true; + (claimed ??= []).Add(i); + } + + base.Call(context, methodsToCall, results, errors); + if (claimed is null) return; + + var caller = context.UserIdentity as RoleCarryingUserIdentity; + var deadline = context.OperationDeadline; + using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, context.CancellationToken); + var calls = new Task[claimed.Count]; + for (var k = 0; k < claimed.Count; k++) + { + results[claimed[k]] = new CallMethodResult(); + calls[k] = CallImportedAsync(caller, methodsToCall[claimed[k]], deadline, linked.Token); + } + var outcomes = await Task.WhenAll(calls).ConfigureAwait(false); + for (var k = 0; k < claimed.Count; k++) errors[claimed[k]] = outcomes[k]; + } + + /// + /// §5.6 steps 2–5 for one claimed request. Every refusal returns before anything is sent; nothing here changes local + /// condition state — the origin applies, reports and streams, and the record's arrival changes the node (§5.3). + /// + private async Task CallImportedAsync(RoleCarryingUserIdentity? caller, CallMethodRequest request, DateTime deadline, + CancellationToken cancellationToken) + { + var started = Stopwatch.GetTimestamp(); + try + { + if (!request.ObjectId.TryGetValue(out string objectIdentifier) + || !ImportedConditionIds.TryParse(objectIdentifier, out var conditionIdentifier, out _, out _, out _) + || _importedConditions.Find(new NodeId(conditionIdentifier, request.ObjectId.NamespaceIndex)) is not { } condition) + return Refuse(StatusCodes.BadNodeIdUnknown); + var method = ImportedMethodOf(request.MethodId, conditionIdentifier); + if (method == DataConditionMethods.None) return Refuse(StatusCodes.BadNotSupported); // shelve, enable/disable, … + if (ProjectedConditionMethods is not { } port) return Refuse(StatusCodes.BadNotSupported); + + // Step 2 local checks (no I/O, no Lock). The mapping gate first: an unauthorized caller learns nothing else. + var placements = condition.Placements; + var route = port.AuthorizeMethod(caller, placements, method); + if (route is null || caller is null) return Refuse(StatusCodes.BadUserAccessDenied); + if (method == DataConditionMethods.Confirm && condition.IsNative) return Refuse(StatusCodes.BadNotSupported); + if (condition.SupportedMethods is { } supported && (supported & (uint)method) == 0) return Refuse(StatusCodes.BadNotSupported); + if (_standby.RefusesMutations) { Interlocked.Increment(ref _importedMethodsRefused); return WarmStandbyState.StandbyRefusal($"call {DataConditionMethodSets.Part9Name(method)}"); } + if (!TryReadMethodArguments(request.InputArguments, out var eventId, out var comment, out var argumentError)) + return Refuse(argumentError); + + // EventId: minted by this consumer for this condition under the SAME marker as the latest applied record (N6/T3). + DataActivationMarker? expected = null; + lock (condition.MethodGate) + { + foreach (var (id, activation) in condition.RecentEvents) + { + if (id != eventId) continue; + if (activation is not null && activation == condition.Activation) expected = activation; + break; + } + } + if (expected is null) return Refuse(StatusCodes.BadEventIdUnknown); + + // An identical call already in flight (same caller, condition, EventId, method, comment) joins it: one dispatch. + var key = string.Join('\n', caller.Principal, condition.Alarm.NodeId.ToString(), Convert.ToHexString(eventId.Span), + ((uint)method).ToString(System.Globalization.CultureInfo.InvariantCulture), comment ?? "\u0001"); + var mine = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var existing = _importedMethodsInFlight.GetOrAdd(key, mine.Task); + if (!ReferenceEquals(existing, mine.Task)) + { + Interlocked.Increment(ref _importedMethodsJoined); + return await existing.ConfigureAwait(false); + } + try + { + var result = await DispatchImportedAsync(port, condition, route, method, expected, comment, caller, deadline, started, + cancellationToken).ConfigureAwait(false); + mine.TrySetResult(result); + return result; + } + catch (Exception ex) + { + var unknown = new ServiceResult(StatusCodes.BadCommunicationError, new LocalizedText("OutcomeUnknown: " + ex.GetType().Name)); + mine.TrySetResult(unknown); + return unknown; + } + finally + { + _importedMethodsInFlight.TryRemove(new KeyValuePair>(key, mine.Task)); + } + } + catch (Exception ex) when (ex is ArgumentException or FormatException) + { + return Refuse(StatusCodes.BadInvalidArgument); + } + } + + private async Task DispatchImportedAsync(IProjectedConditionMethods port, ImportedCondition condition, + ImportedConditionMethodRoute route, DataConditionMethods method, DataActivationMarker expected, string? comment, + RoleCarryingUserIdentity caller, DateTime deadline, long started, CancellationToken cancellationToken) + { + // Step 4: timeout = min(request deadline, ConditionMethodTimeout). + var budget = route.Timeout; + if (deadline != DateTime.MaxValue && deadline > DateTime.MinValue) + { + var left = deadline - DateTime.UtcNow; + if (left < budget) budget = left; + } + budget -= Stopwatch.GetElapsedTime(started); + if (budget <= TimeSpan.Zero) return Refuse(StatusCodes.BadTimeout); + + if (!await _importedMethodSlots.WaitAsync(budget, cancellationToken).ConfigureAwait(false)) + return Refuse(StatusCodes.BadTooManyOperations); + try + { + var remaining = budget - Stopwatch.GetElapsedTime(started); + if (remaining <= TimeSpan.Zero) return Refuse(StatusCodes.BadTimeout); + var call = new ImportedConditionMethodCall(condition.ConnectionId, condition.ConditionKey, route.Placement, method, expected, + comment, "a3-" + Guid.NewGuid().ToString("N"), remaining, caller.Principal); + using var bounded = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + bounded.CancelAfter(remaining + ImportedMethodGrace); + Interlocked.Increment(ref _importedMethodsDispatched); + DataConditionMethodResult result; + try + { + result = await port.CallAsync(call, bounded.Token).WaitAsync(remaining + ImportedMethodGrace, CancellationToken.None) + .ConfigureAwait(false); + } + catch (TimeoutException) + { + // The port did not answer inside the budget: it may have reached the origin — OutcomeUnknown, never retried. + return Unknown(StatusCodes.BadTimeout, "OutcomeUnknown: no answer within the condition method timeout."); + } + catch (OperationCanceledException) when (bounded.IsCancellationRequested) + { + return Unknown(cancellationToken.IsCancellationRequested ? StatusCodes.BadCommunicationError : StatusCodes.BadTimeout, + "OutcomeUnknown: the call was cancelled after dispatch."); + } + return MapOutcome(result, Stopwatch.GetElapsedTime(started) >= budget); + } + finally + { + _importedMethodSlots.Release(); + } + } + + /// + /// §5.6 step 5 outcome mapping. Applied (scripted DriverConfirmedSuccess) and accepted (native + /// AcceptedUnconfirmed) ⇒ Good — the confirming record arrives on the stream; RejectedBeforeDispatch ⇒ the + /// origin's status; OutcomeUnknown ⇒ BadTimeout when the budget ran out, else BadCommunicationError + /// — always Bad (the client must not read it as done), with "OutcomeUnknown" in the diagnostic. + /// + internal ServiceResult MapOutcome(DataConditionMethodResult result, bool budgetElapsed) + { + switch (result.State) + { + case DataWriteState.DriverConfirmedSuccess: + case DataWriteState.AcceptedUnconfirmed: + return StatusCode.IsBad(new StatusCode(result.StatusCode)) ? new ServiceResult(new StatusCode(result.StatusCode)) : ServiceResult.Good; + case DataWriteState.RejectedBeforeDispatch: + var refused = new StatusCode(result.StatusCode); + if (!StatusCode.IsBad(refused)) refused = StatusCodes.BadInternalError; + return result.Diagnostic is { Length: > 0 } text ? new ServiceResult(refused, new LocalizedText(text)) : new ServiceResult(refused); + default: + return Unknown(budgetElapsed ? StatusCodes.BadTimeout : StatusCodes.BadCommunicationError, + "OutcomeUnknown: " + (result.Diagnostic ?? "the origin's outcome is unknown.")); + } + } + + private ServiceResult Unknown(StatusCode status, string diagnostic) + { + _logger.LogWarning("OtOpcUaNodeManager: imported condition method outcome unknown ({Status}): {Diagnostic}", status, diagnostic); + return new ServiceResult(status, new LocalizedText(diagnostic)); + } + + private ServiceResult Refuse(StatusCode status) + { + Interlocked.Increment(ref _importedMethodsRefused); + return new ServiceResult(status); + } + + /// The Part 9 method a MethodId names: the type's declaration or this condition's instance child. + private static DataConditionMethods ImportedMethodOf(NodeId methodId, string conditionIdentifier) + { + if (methodId == MethodIds.AcknowledgeableConditionType_Acknowledge) return DataConditionMethods.Acknowledge; + if (methodId == MethodIds.AcknowledgeableConditionType_Confirm) return DataConditionMethods.Confirm; + if (methodId == MethodIds.ConditionType_AddComment) return DataConditionMethods.AddComment; + if (!methodId.TryGetValue(out string identifier) + || !ImportedConditionIds.TryParse(identifier, out var owner, out _, out _, out var path) + || !string.Equals(owner, conditionIdentifier, StringComparison.Ordinal)) return DataConditionMethods.None; + return path switch + { + "Acknowledge" => DataConditionMethods.Acknowledge, + "Confirm" => DataConditionMethods.Confirm, + "AddComment" => DataConditionMethods.AddComment, + _ => DataConditionMethods.None, + }; + } + + /// Acknowledge / Confirm / AddComment all take (EventId ByteString, Comment LocalizedText). + private static bool TryReadMethodArguments(ArrayOf arguments, out ByteString eventId, out string? comment, out StatusCode error) + { + eventId = default; comment = null; error = StatusCodes.Good; + if (arguments.Count < 2) { error = StatusCodes.BadArgumentsMissing; return false; } + if (arguments.Count > 2) { error = StatusCodes.BadTooManyArguments; return false; } + if (!arguments[0].TryGetValue(out eventId) || eventId.IsEmpty) { error = StatusCodes.BadTypeMismatch; return false; } + if (arguments[1].IsNull) return true; + if (!arguments[1].TryGetValue(out LocalizedText text)) { error = StatusCodes.BadTypeMismatch; return false; } + comment = string.IsNullOrEmpty(text.Text) ? null : text.Text; + if (comment is { Length: > DataConditionMethodRequest.MaxCommentLength }) { error = StatusCodes.BadInvalidArgument; return false; } + return true; + } + + /// + /// N6 (§5.6 step 3) after a record that changed no state. A moved marker re-binds the retained EventIds only when the + /// record's time equals the one they were bound under (F6); otherwise a fresh EventId is bound to the new marker + /// (so a ConditionRefresh returns an ackable one) and the caller queues RefreshRequired. A condition with no bound + /// EventId yet (its first record reported nothing) gets one. Under Lock (the apply path). + /// + /// True when retained EventIds were invalidated (RefreshRequired). + private bool RebindImportedEventIds(ImportedCondition condition, DataActivationMarker? previous, DateTimeOffset? previousTime, + DataConditionState state) + { + var current = state.Activation; + lock (condition.MethodGate) + { + if (condition.RecentEvents.Count == 0) + { + MintImportedEventId(condition, current); + return false; + } + if (previous is null || current is null || previous == current) return false; + if (state.TimeUtc is { } time && previousTime == time) + { + var node = condition.RecentEvents.First; + while (node is not null) + { + if (node.Value.Activation == previous) node.Value = (node.Value.EventId, current); + node = node.Next; + } + return false; + } + MintImportedEventId(condition, current); + return true; + } + } + + private static void MintImportedEventId(ImportedCondition condition, DataActivationMarker? activation) + { + if (condition.Alarm.EventId is not { } field) return; + var eventId = ByteString.From(Guid.NewGuid().ToByteArray()); + field.Value = eventId; + condition.RecentEvents.AddFirst((eventId, activation)); + while (condition.RecentEvents.Count > ProjectedConditionRegistry.RecentEventIds) condition.RecentEvents.RemoveLast(); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs index 31236feca..d701e278a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs @@ -23,9 +23,18 @@ internal sealed class ImportedCondition(AlarmConditionState alarm, string connec public HashSet Folders { get; } = new(ReferenceEqualityComparer.Instance); /// The last origin record applied (state known), re-applied with another Quality on staleness. public AlarmConditionSnapshot? Last { get; set; } + /// The marker of the latest applied record. Written under (A3b reads it without Lock). public DataActivationMarker? Activation { get; set; } - /// N6: consumer-minted EventIds of this condition's recent events → the activation marker each described. + /// N6: consumer-minted EventIds of this condition's recent events → the activation marker each described. + /// Mutated and read under . public LinkedList<(ByteString EventId, DataActivationMarker? Activation)> RecentEvents { get; } = new(); + /// A3b (§5.6 step 2): the small EventId registry's own lock — a remote method resolves its EventId and the current + /// marker under it, never under the node manager's Lock. + public object MethodGate { get; } = new(); + /// The origin's supported_methods for the service principal (null until a listing carried it). + public uint? SupportedMethods { get; set; } + /// The time of the latest applied record (N6/F6: re-binding requires it unchanged). + public DateTimeOffset? LastTime { get; set; } /// Bumped on every placement change (verdict caches key on it). public long PlacementVersion { get; set; } /// Native (driver-fed) at the origin: Confirm / shelve / enable have no upstream path. @@ -216,9 +225,9 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink public bool TryResolveImportedEvent(NodeId conditionId, ByteString eventId, out ImportedConditionBinding? binding) { binding = null; - lock (Lock) + if (_importedConditions.Find(conditionId) is not { Placements.Count: > 0 } c) return false; + lock (c.MethodGate) { - if (_importedConditions.Find(conditionId) is not { Placements.Count: > 0 } c) return false; foreach (var (id, activation) in c.RecentEvents) { if (id != eventId) continue; @@ -238,6 +247,7 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink { ArgumentNullException.ThrowIfNull(updates); EnsureAddressSpaceCreated(); + var refresh = new HashSet(StringComparer.OrdinalIgnoreCase); for (var start = 0; start < updates.Count; start += ImportedApplyChunk) { lock (Lock) @@ -246,7 +256,7 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink var index = ProjectedFolderIndex(); for (var i = start; i < Math.Min(updates.Count, start + ImportedApplyChunk); i++) { - try { ApplyImported(updates[i], index); } + try { if (ApplyImported(updates[i], index)) refresh.Add(updates[i].ConnectionId); } catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or ServiceResultException) { _logger.LogWarning(ex, "OtOpcUaNodeManager: imported condition update refused (connection {Connection})", @@ -255,6 +265,8 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink } } } + // N6 (G4 step 3): a resync that left retained EventIds un-re-bindable ⇒ RefreshRequired, outside Lock. + foreach (var connectionId in refresh) RequireRefresh(connectionId); } /// @@ -323,7 +335,8 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink // Materialise / apply / remove (under Lock) // --------------------------------------------------------------------------------------------------------------------- - private void ApplyImported(ImportedConditionUpdate update, Dictionary<(string, string), FolderState> folders) + /// True when a resync left retained EventIds un-re-bindable (the caller queues RefreshRequired). + private bool ApplyImported(ImportedConditionUpdate update, Dictionary<(string, string), FolderState> folders) { var state = update.State; if (update.Placements.Count == 0) throw new ArgumentException("An imported condition needs a placement.", nameof(update)); @@ -331,7 +344,7 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink if (state.Removed) { if (_importedConditions.Find(id) is { } gone) RemoveImported(gone); - return; + return false; } var condition = _importedConditions.Find(id); @@ -364,9 +377,10 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink UpdatePlacements(condition, update.Placements, folders); if (condition.Alarm.SourceName is { } sourceName) sourceName.Value = update.SourceName; // display only; rides the next event + if ((update.Info ?? state.Info) is { } listed) condition.SupportedMethods = listed.SupportedMethods; // §5.1 T2: a record with state_known = false never changes the consumer's last state. - if (!state.StateKnown) return; + if (!state.StateKnown) return false; var snapshot = new AlarmConditionSnapshot(state.Active, state.Acknowledged, state.Confirmed, state.Enabled, Enum.IsDefined(typeof(AlarmShelvingKind), state.Shelving) ? (AlarmShelvingKind)state.Shelving : AlarmShelvingKind.Unshelved, (ushort)Math.Clamp(state.Severity, 1u, 1000u), state.Message ?? "", state.Quality, @@ -375,9 +389,17 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink var ts = state.TimeUtc?.UtcDateTime ?? UtcNow; if (condition.Alarm.Comment is { } comment && state.Comment is not null) comment.Value = new LocalizedText(state.Comment); if (condition.Alarm.ClientUserId is { } user && state.ClientUserId is not null) user.Value = state.ClientUserId; - condition.Activation = state.Activation; + var previous = condition.Activation; + var previousTime = condition.LastTime; + lock (condition.MethodGate) condition.Activation = state.Activation; condition.Last = snapshot; - if (ApplyConditionState(condition.Alarm, snapshot, ts)) ReportImported(condition, ts); + condition.LastTime = state.TimeUtc; + if (ApplyConditionState(condition.Alarm, snapshot, ts)) + { + ReportImported(condition, ts); + return false; + } + return RebindImportedEventIds(condition, previous, previousTime, state); } /// Reports one imported event (stamping a consumer-minted EventId, N6) through the shared reporter. @@ -387,8 +409,11 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink Interlocked.Increment(ref _importedEventsReported); if (condition.Alarm.EventId?.Value is { } eventId) { - condition.RecentEvents.AddFirst((eventId, condition.Activation)); - while (condition.RecentEvents.Count > ProjectedConditionRegistry.RecentEventIds) condition.RecentEvents.RemoveLast(); + lock (condition.MethodGate) + { + condition.RecentEvents.AddFirst((eventId, condition.Activation)); + while (condition.RecentEvents.Count > ProjectedConditionRegistry.RecentEventIds) condition.RecentEvents.RemoveLast(); + } } } From 28098a8d32ce1556bab4b3ad5ab897383689d26e Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 17:11:05 -0500 Subject: [PATCH 13/32] =?UTF-8?q?feat(grpc-data):=20A3b=20consumer=20metho?= =?UTF-8?q?d=20port=20=E2=80=94=20per-caller=20AlarmAcknowledge/AlarmConfi?= =?UTF-8?q?rm=20gate,=20mapping=20timeout,=20stream=20serving=20incarnatio?= =?UTF-8?q?n,=20lease=20condition=20methods,=20host=20wiring?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../OpcUa/OtOpcUaServerHostedService.cs | 2 + .../DataConnectionDeploymentRuntime.cs | 16 +++- .../ProjectedConditionAccess.Methods.cs | 93 +++++++++++++++++++ .../ProjectedConditionAccess.cs | 8 +- 4 files changed, 117 insertions(+), 2 deletions(-) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Methods.cs diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs index 614744bd3..5175283e4 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs @@ -278,6 +278,8 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl _server.NodeManager.ProjectedHistoryAccess = _projectedHistoryAccess; // A3: imported conditions — the gate/demand into the node manager, the node manager as the runtime's sink. _server.NodeManager.ProjectedConditionAccess = _projectedConditionAccess; + // A3b (§5.6): remote condition methods go through the same condition runtime (its per-caller method gate + the lease). + _server.NodeManager.ProjectedConditionMethods = _projectedConditionAccess as ZB.MOM.WW.OtOpcUa.OpcUaServer.IProjectedConditionMethods; if (_projectedConditionAccess is ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ProjectedConditionAccess conditions) conditions.Sink = _server.NodeManager; _server.NodeManager.ConditionStateSink = _conditionStateSink; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs index 307f0e3b0..6a2a904df 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs @@ -524,8 +524,22 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable } /// A non-owning handle with the deployed operation and resource policy. -public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistoryService, IHistoryBatchLimit, IDisposable +public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistoryService, IHistoryBatchLimit, IDataConditionMethodService, IDisposable { + /// + /// A3b: a remote condition method through the deployed connection — needs the row's AlarmAcknowledge / AlarmConfirm + /// bit (refused unsent otherwise) and an inner connection that serves methods. The outcome is passed through untouched + /// (no post-check: once sent, an answer is the only truth about whether the origin applied it). + /// + public Task CallConditionMethodAsync(DataConditionMethodRequest request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + Check(DataConditionMethodSets.OperationFor(request.Method)); + return _inner is IDataConditionMethodService methods + ? methods.CallConditionMethodAsync(request, cancellationToken) + : Task.FromResult(new DataConditionMethodResult(DataWriteState.RejectedBeforeDispatch, 0x803D0000u, "The connection does not serve condition methods.")); + } + /// /// H2 remote history through the deployed connection: needs the connection row's HistoryRead bit (masked to the /// understood set) and an inner connection that implements history; otherwise every item is unsupported. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Methods.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Methods.cs new file mode 100644 index 000000000..9583eb9f5 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Methods.cs @@ -0,0 +1,93 @@ +using Microsoft.Extensions.Logging; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// +/// A3b (plan §5.6): the consumer's remote condition method port. The gate is per LOCAL caller (the condition stream runs +/// under the connection's service principal, so nothing it carries authorizes a local session); the call goes through the +/// deployed connection lease to the origin's CallConditionMethod (A2b), addressed by the placement and the serving +/// incarnation of the stream the condition's records arrived on. +/// +public sealed partial class ProjectedConditionAccess : IProjectedConditionMethods +{ + private const uint BadNoCommunication = 0x80310000u; + private const uint BadNotSupported = 0x803D0000u; + private const uint BadUserAccessDenied = 0x801F0000u; + + /// + public ImportedConditionMethodRoute? AuthorizeMethod(RoleCarryingUserIdentity? caller, IReadOnlyList placements, + DataConditionMethods method) + { + if (caller is null || string.IsNullOrWhiteSpace(caller.Principal) || placements is null || placements.Count == 0 + || !DataConditionMethodSets.IsSingle(method)) return null; + var required = DataConditionMethodSets.OperationFor(method); + var operation = method == DataConditionMethods.Confirm ? OpcUaOperation.AlarmConfirm : OpcUaOperation.AlarmAcknowledge; + var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc); + var current = _mappings.Current; + foreach (var placement in placements) + { + var mapping = current.FirstOrDefault(x => string.Equals(x.Mapping.RemoteNamespaceMappingId, placement.MappingId, StringComparison.OrdinalIgnoreCase)); + if (mapping is null || !mapping.Authority.IsActive || !IsConditionBearing(mapping.Mapping) || mapping.Mapping.Realm != placement.Realm + || (mapping.Mapping.AllowedOperations & required) != required) continue; + if (!TryFolderScope(mapping, placement.FolderLocalSubject, out var scope)) continue; + try + { + // AuthorizeLocal re-checks the caller's key (usable, version, expiry: #563) on every call. + if (_policy.AuthorizeLocal(identity, operation, scope)) + return new ImportedConditionMethodRoute(placement, + TimeSpan.FromMilliseconds(Math.Max(1, mapping.Mapping.ConditionMethodTimeoutMilliseconds))); + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { } + } + return null; + } + + /// + public async Task CallAsync(ImportedConditionMethodCall call, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(call); + ServingIdentity? serving; + lock (_gate) serving = _runners.TryGetValue(call.ConnectionId, out var runner) ? runner.Serving : null; + // No open condition stream ⇒ no serving incarnation to address: the connection is down for this purpose. Nothing sent. + if (serving is null) + return new(DataWriteState.RejectedBeforeDispatch, BadNoCommunication, "No condition stream is open on the connection."); + + IGrpcDataAdapterConnectionLease? lease; + try { lease = await _connections.AcquireAsync(call.ConnectionId, cancellationToken).ConfigureAwait(false); } + catch (Exception ex) when (ex is InvalidOperationException or OperationCanceledException or TimeoutException) + { return new(DataWriteState.RejectedBeforeDispatch, BadNoCommunication, "The connection is unavailable."); } + if (lease is null) return new(DataWriteState.RejectedBeforeDispatch, BadNoCommunication, "The connection is unavailable."); + await using (lease.ConfigureAwait(false)) + { + if (lease.Connection is not IDataConditionMethodService methods) + return new(DataWriteState.RejectedBeforeDispatch, BadNotSupported, "The connection does not serve condition methods."); + var request = new DataConditionMethodRequest(call.OperationId, call.Placement.Placement, call.Method, call.ExpectedActivation, + call.Comment, serving.Incarnation, call.RemainingBudget, call.OnBehalfOf); + using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, lease.CancellationToken); + try + { + var result = await methods.CallConditionMethodAsync(request, linked.Token).ConfigureAwait(false); + if (result.State == DataWriteState.OutcomeUnknown) + _log.LogWarning("Imported condition method {Method} on {Connection}/{Key} (op {Operation}): outcome unknown — {Diagnostic}", + call.Method, call.ConnectionId, call.ConditionKey, call.OperationId, result.Diagnostic); + return result; + } + catch (UnauthorizedAccessException) + { + // The deployed connection row does not enable the method's operation: refused by the lease, nothing sent. + return new(DataWriteState.RejectedBeforeDispatch, BadUserAccessDenied, "The connection does not allow this condition method."); + } + catch (Exception ex) when (ex is InvalidOperationException or ObjectDisposedException + || (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested)) + { + // The lease's own scope check (connection no longer ready / disposed) refuses before anything is sent. + return new(DataWriteState.RejectedBeforeDispatch, BadNoCommunication, "The connection is no longer ready."); + } + } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs index 182bbca6d..482d45f2a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs @@ -77,7 +77,7 @@ public enum ProjectedConditionMappingStatus { Pending, Snapshotting, Complete, U /// BadNoCommunication (one event each) — never "known inactive" (§5.1 T2). /// /// -public sealed class ProjectedConditionAccess : IProjectedConditionAccess, IDisposable +public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess, IDisposable { private readonly IProjectedConditionMappings _mappings; private readonly IGrpcDataAdapterConnectionSource _connections; @@ -315,6 +315,9 @@ public sealed class ProjectedConditionAccess : IProjectedConditionAccess, IDispo public string Signature { get; } public int Barriers => Volatile.Read(ref _barriers); + private ServingIdentity? _serving; + /// A3b: the serving identity of the CURRENT condition stream (null while no stream is open). + public ServingIdentity? Serving => Volatile.Read(ref _serving); public IReadOnlyDictionary Statuses { @@ -333,6 +336,7 @@ public sealed class ProjectedConditionAccess : IProjectedConditionAccess, IDispo public void Stop(bool removeConditions) { _stop.Cancel(); + Volatile.Write(ref _serving, null); _stale?.Dispose(); if (!removeConditions) return; _ = _loop.ContinueWith(_ => @@ -355,6 +359,7 @@ public sealed class ProjectedConditionAccess : IProjectedConditionAccess, IDispo { _owner._log.LogInformation(ex, "Imported conditions: stream for connection {Connection} ended; re-snapshotting", _connectionId); } + finally { Volatile.Write(ref _serving, null); } // §5.5 lifetime rule: a stream end is "re-snapshot", never "conditions removed". Arm staleness instead. ArmStale(); OtOpcUaTelemetry.DataConnConditionResyncs.Add(1); @@ -400,6 +405,7 @@ public sealed class ProjectedConditionAccess : IProjectedConditionAccess, IDispo catch (Exception ex) when (ex is not OperationCanceledException) { } await using var subscription = await connection.SubscribeAsync(token).ConfigureAwait(false); + Volatile.Write(ref _serving, (subscription as IDataSubscriptionProvenance)?.Serving); var subscriptionId = "conditions-" + Guid.NewGuid().ToString("N"); var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); var items = states.Select(x => new DataSubscriptionItem(x.MappingId, x.Root, settings, new DataConditionScope(IncludeInfo: true))).ToArray(); From de51886d6a0b086eae658fd391b84336f15a982a Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 17:18:35 -0500 Subject: [PATCH 14/32] test(grpc-data): A3b over-the-wire imported-condition methods (once + join, child Call gate, EventId/native Confirm unsent, N6 re-binding, L3 lock-freedom, mixed base.Call batch, timeout/outcome mapping) --- .../ImportedConditionMethodWireTests.cs | 442 ++++++++++++++++++ 1 file changed, 442 insertions(+) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMethodWireTests.cs diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMethodWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMethodWireTests.cs new file mode 100644 index 000000000..6c0117226 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMethodWireTests.cs @@ -0,0 +1,442 @@ +using System.Collections.Concurrent; +using System.Diagnostics; +using System.Security.Cryptography; +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; +using SdkMonitoredItem = Opc.Ua.Client.MonitoredItem; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests; + +/// +/// A3b over the wire (plan §5.6): Part 9 methods on an imported condition are claimed by the node manager's +/// implementation and dispatched to the origin through the +/// port — never under the node manager's Lock, never applied locally (the +/// node changes only when the origin's record arrives), gated per local caller, with the EventId checked against this +/// consumer's own registry. The port here stands in for the origin (its handler can be stalled, can time out, can join). +/// +[Trait("Feature", "GrpcData"), Trait("Phase", "A3")] +public sealed class ImportedConditionMethodWireTests +{ + private const string Connection = "conn-a"; + private const string MappingA = "map-a"; + private const string Granted = ServerEventRig.KeyPrincipal; + private static readonly string Key1 = KeyOf("cond-1"); + private static readonly DataActivationMarker Marker1 = new("inc", 1); + + [Fact] + public async Task A_remote_Acknowledge_reaches_the_origin_once_a_duplicate_joins_and_local_state_changes_only_with_the_origin_record() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3b-ack", encrypted: false, ct); + var f = Fixture.Install(rig); + f.Apply(Update(version: 3, active: true, acked: false)); + using var session = await rig.ConnectAsync(anonymous: false, ct); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Port.Handler = async (_, _) => { await release.Task; return Applied(); }; + var eventId = f.CurrentEventId(); + + var first = CallAsync(session, f.ConditionId(session), MethodIds.AcknowledgeableConditionType_Acknowledge, eventId, "op ack", ct); + await WaitUntilAsync(() => f.Port.Calls.Count == 1); + var duplicate = CallAsync(session, f.ConditionId(session), MethodIds.AcknowledgeableConditionType_Acknowledge, eventId, "op ack", ct); + await WaitUntilAsync(() => rig.Nm.ImportedMethodsJoined == 1); + f.Acked().ShouldBeFalse("nothing is applied locally while the origin has not answered"); + + release.SetResult(); + (await first).ShouldBe(StatusCodes.Good); + (await duplicate).ShouldBe(StatusCodes.Good, "a duplicate of an in-flight call joins it and gets the same answer"); + f.Port.Calls.Count.ShouldBe(1, "the origin is called once"); + f.Acked().ShouldBeFalse("Good from the origin is not the confirming record: still unacknowledged locally"); + + var call = f.Port.Calls.Single(); + call.Method.ShouldBe(DataConditionMethods.Acknowledge); + call.ConnectionId.ShouldBe(Connection); + call.ConditionKey.ShouldBe(Key1); + call.Placement.ShouldBe(f.Placements[0], "the primary placement the caller passed the gate on"); + call.ExpectedActivation.ShouldBe(Marker1); + call.Comment.ShouldBe("op ack"); + call.OnBehalfOf.ShouldBe(Granted); + call.OperationId.ShouldStartWith("a3-"); + call.RemainingBudget.ShouldBeLessThanOrEqualTo(f.Port.Timeout); + + // The origin's record arrives on the stream: only now does the local node change (positive control). + f.Apply(Update(version: 4, active: true, acked: true)); + f.Acked().ShouldBeTrue(); + // A later call (nothing in flight) is a NEW dispatch with a fresh operation id — no retry, no stale join. + (await CallAsync(session, f.ConditionId(session), MethodIds.ConditionType_AddComment, f.CurrentEventId(), "note", ct)).ShouldBe(StatusCodes.Good); + f.Port.Calls.Count.ShouldBe(2); + f.Port.Calls.Select(c => c.OperationId).Distinct().Count().ShouldBe(2); + f.Port.Calls.Last().Method.ShouldBe(DataConditionMethods.AddComment); + } + + [Fact] + public async Task A_child_method_Call_is_authorized_through_the_condition_and_a_caller_without_the_grant_is_denied_unsent() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3b-child", encrypted: false, ct); + var f = Fixture.Install(rig); + f.Apply(Update(version: 3, active: true, acked: false)); + using var allowed = await rig.ConnectAsync(anonymous: false, ct); + using var denied = await rig.ConnectAsync(anonymous: true, ct); + var ns = (ushort)allowed.NamespaceUris.GetIndex(ImportedConditionIds.NamespaceUri); + var childMethod = new NodeId(ImportedConditionIds.ChildIdentifier(f.Identifier, "Acknowledge"), ns); + rig.Nm.FindImportedCondition(Connection, Key1)!.Acknowledge!.NodeId.ShouldBe(childMethod, "the instance-scoped method node (#629)"); + + (await CallAsync(denied, f.ConditionId(denied), childMethod, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadUserAccessDenied); + (await CallAsync(denied, f.ConditionId(denied), MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)) + .ShouldBe(StatusCodes.BadUserAccessDenied); + f.Port.Calls.ShouldBeEmpty("a caller without the grant sends nothing"); + f.Port.AuthorizedFor.ShouldContain(("anonymous", DataConditionMethods.Acknowledge), "re-gated per LOCAL caller"); + + // The grant is per method: AlarmAcknowledge does not authorize Confirm. + f.Port.GrantedMethods = DataConditionMethods.Acknowledge | DataConditionMethods.AddComment; + f.Apply(Update(version: 4, active: true, acked: false, native: false, message: "scripted")); + (await CallAsync(allowed, f.ConditionId(allowed), MethodIds.AcknowledgeableConditionType_Confirm, f.CurrentEventId(), "c", ct)) + .ShouldBe(StatusCodes.BadUserAccessDenied); + f.Port.Calls.ShouldBeEmpty(); + + // Positive control: the granted caller's child Call reaches the origin. + (await CallAsync(allowed, f.ConditionId(allowed), childMethod, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.Good); + f.Port.Calls.Single().Method.ShouldBe(DataConditionMethods.Acknowledge); + f.Acked().ShouldBeFalse(); + } + + [Fact] + public async Task An_unknown_or_superseded_EventId_is_BadEventIdUnknown_and_a_native_Confirm_or_a_shelve_is_BadNotSupported_all_unsent() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3b-eventid", encrypted: false, ct); + var f = Fixture.Install(rig); + f.Apply(Update(version: 3, active: true, acked: false)); + using var session = await rig.ConnectAsync(anonymous: false, ct); + var id = f.ConditionId(session); + var old = f.CurrentEventId(); + + (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, Guid.NewGuid().ToByteArray(), "x", ct)) + .ShouldBe(StatusCodes.BadEventIdUnknown); + // A new occurrence (Acked true→false bumps the marker at the origin): the old EventId no longer binds. + f.Apply(Update(version: 4, active: true, acked: true)); + f.Apply(Update(version: 5, active: true, acked: false, marker: new DataActivationMarker("inc", 2), message: "again")); + (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, old, "x", ct)).ShouldBe(StatusCodes.BadEventIdUnknown); + // Native Confirm has no upstream path; shelving is not imported at all. + (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Confirm, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadNotSupported); + var shelve = await session.CallAsync(null, [new CallMethodRequest { ObjectId = id, MethodId = MethodIds.AlarmConditionType_ShelvingState_OneShotShelve }], ct); + shelve.Results[0].StatusCode.Code.ShouldBe(StatusCodes.BadNotSupported.Code); + f.Port.Calls.ShouldBeEmpty("every refusal above is local and sends nothing"); + + // Positive control: the current EventId (new marker) reaches the origin with the CURRENT marker. + (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.Good); + f.Port.Calls.Single().ExpectedActivation.ShouldBe(new DataActivationMarker("inc", 2)); + } + + [Fact] + public async Task A_resync_with_a_new_marker_re_binds_EventIds_only_when_time_is_unchanged_else_RefreshRequired_and_a_fresh_ackable_EventId() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3b-rebind", encrypted: false, ct); + var f = Fixture.Install(rig); + var t0 = DateTimeOffset.UtcNow.AddMinutes(-1); + f.Apply(Update(version: 3, active: true, acked: false, time: t0)); + using var session = await rig.ConnectAsync(anonymous: false, ct); + var id = f.ConditionId(session); + var before = f.CurrentEventId(); + + // Origin restart, same state, same time ⇒ re-bound (F6): the pre-resync EventId still acknowledges. + f.Apply(Update(version: 1, active: true, acked: false, time: t0, marker: new DataActivationMarker("inc-b", 7))); + f.CurrentEventId().ShouldBe(before, "no event, no new EventId"); + (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, before, "x", ct)).ShouldBe(StatusCodes.Good); + f.Port.Calls.Last().ExpectedActivation.ShouldBe(new DataActivationMarker("inc-b", 7)); + + // Another resync whose time differs (a clear + re-raise may have happened in the gap) ⇒ NOT re-bound. + var refresh = rig.Nm.ImportedRefreshRequiredQueued; + f.Apply(Update(version: 1, active: true, acked: false, time: t0.AddSeconds(5), marker: new DataActivationMarker("inc-c", 9))); + (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, before, "x", ct)).ShouldBe(StatusCodes.BadEventIdUnknown); + var fresh = f.CurrentEventId(); + fresh.ShouldNotBe(before, "a fresh EventId bound to the new marker — what a ConditionRefresh now returns"); + (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, fresh, "x", ct)).ShouldBe(StatusCodes.Good); + f.Port.Calls.Count.ShouldBe(2); + f.Port.Calls.Last().ExpectedActivation.ShouldBe(new DataActivationMarker("inc-c", 9)); + // RequireRefresh ran (it queues only to items that exist; none here — the counter path is pinned by A3a's tests). + rig.Nm.ImportedRefreshRequiredQueued.ShouldBeGreaterThanOrEqualTo(refresh); + } + + /// + /// §5.6 step 6 / §9.3 L3 (hard gate): the origin's method handler stalls 5 s. Read, Browse and a data Publish on the + /// consumer complete in < 200 ms meanwhile, the node manager's Lock is free, and no acknowledged state is + /// observable before the origin's record (positive control: it arrives after release). + /// + [Fact] + public async Task Lock_freedom_a_5s_stalled_origin_method_delays_no_Read_Browse_or_data_Publish_and_applies_nothing_before_the_record() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3b-l3", encrypted: false, ct); + var f = Fixture.Install(rig); + var tag = rig.EnsureRawVariable("l3", "Double", writable: false); + rig.Sink.WriteValue(tag, 0.0, 0, DateTime.UtcNow, AddressSpaceRealm.Raw); + f.Apply(Update(version: 3, active: true, acked: false)); + using var caller = await rig.ConnectAsync(anonymous: false, ct); + using var observer = await rig.ConnectAsync(anonymous: false, ct); + var tagId = ExpandedNodeId.ToNodeId(ExpandedNodeId.Parse(ServerEventRig.RawNsu(tag)), observer.NamespaceUris); + var plant = rig.Nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; + var plantId = new NodeId(plant.IdentifierAsString, (ushort)observer.NamespaceUris.GetIndex(V3NodeIds.RawNamespaceUri)); + + var values = new ConcurrentDictionary(); + var subscription = new Subscription(observer.DefaultSubscription) { PublishingInterval = 20 }; + observer.AddSubscription(subscription); + await subscription.CreateAsync(ct); + var item = new SdkMonitoredItem(subscription.DefaultItem) { StartNodeId = tagId, AttributeId = Attributes.Value, SamplingInterval = 0, QueueSize = 100 }; + item.Notification += (mi, _) => + { + var now = Stopwatch.GetTimestamp(); + foreach (var v in mi.DequeueValues()) if (v.WrappedValue.TryGetValue(out double d)) values.TryAdd(d, now); + }; + subscription.AddItem(item); + await subscription.ApplyChangesAsync(ct); + + async Task<(double Read, double Browse, double Publish, double LockWait)> MeasureAsync(double value) + { + var sw = Stopwatch.StartNew(); + (await observer.ReadValueAsync(tagId, ct)).StatusCode.ShouldBe(StatusCodes.Good); + var read = sw.Elapsed.TotalMilliseconds; + sw.Restart(); + var browse = await observer.BrowseAsync(null, null, 0, [new BrowseDescription { NodeId = plantId, BrowseDirection = BrowseDirection.Forward, + ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All }], ct); + StatusCode.IsGood(browse.Results[0].StatusCode).ShouldBeTrue(); + var browseMs = sw.Elapsed.TotalMilliseconds; + var written = Stopwatch.GetTimestamp(); + rig.Sink.WriteValue(tag, value, 0, DateTime.UtcNow, AddressSpaceRealm.Raw); + await WaitUntilAsync(() => values.ContainsKey(value)); + var publish = Stopwatch.GetElapsedTime(written, values[value]).TotalMilliseconds; + sw.Restart(); + var taken = Monitor.TryEnter(rig.Nm.Lock, TimeSpan.FromMilliseconds(200)); + var lockWait = sw.Elapsed.TotalMilliseconds; + if (taken) Monitor.Exit(rig.Nm.Lock); + taken.ShouldBeTrue("the node manager Lock is free while the remote call is in flight"); + return (read, browseMs, publish, lockWait); + } + + var baseline = await MeasureAsync(1.0); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Port.Timeout = TimeSpan.FromSeconds(20); + f.Port.Handler = async (_, token) => { await Task.WhenAny(release.Task, Task.Delay(TimeSpan.FromSeconds(5), token)); return Applied(); }; + var stall = Stopwatch.StartNew(); + var ack = CallAsync(caller, f.ConditionId(caller), MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "l3", ct); + await WaitUntilAsync(() => f.Port.Calls.Count == 1); + + var during = new List<(double Read, double Browse, double Publish, double LockWait)>(); + for (var i = 0; i < 10 && !ack.IsCompleted; i++) + { + during.Add(await MeasureAsync(100 + i)); + f.Acked().ShouldBeFalse("no acknowledged state is observable before the origin's record"); + await Task.Delay(200, ct); + } + ack.IsCompleted.ShouldBeFalse("the measurements ran while the remote call was stalled"); + during.Count.ShouldBe(10); + (await ack).ShouldBe(StatusCodes.Good); + var stalled = stall.Elapsed; + f.Acked().ShouldBeFalse(); + f.Apply(Update(version: 4, active: true, acked: true)); + f.Acked().ShouldBeTrue("positive control: the record applies after release"); + + var maxRead = during.Max(m => m.Read); + var maxBrowse = during.Max(m => m.Browse); + var maxPublish = during.Max(m => m.Publish); + var maxLock = during.Max(m => m.LockWait); + var line = + $"L3: stall {stalled.TotalMilliseconds:F0} ms; baseline read {baseline.Read:F1} browse {baseline.Browse:F1} publish {baseline.Publish:F1} lock {baseline.LockWait:F2}; " + + $"during (n={during.Count}) max read {maxRead:F1} browse {maxBrowse:F1} publish {maxPublish:F1} lock {maxLock:F2} ms"; + TestContext.Current.TestOutputHelper?.WriteLine(line); + if (Environment.GetEnvironmentVariable("OTOPCUA_A3_MEASURE_OUT") is { Length: > 0 } outPath) File.AppendAllText(outPath, line + Environment.NewLine); + stalled.ShouldBeGreaterThanOrEqualTo(TimeSpan.FromSeconds(4.9)); + maxRead.ShouldBeLessThan(200); + maxBrowse.ShouldBeLessThan(200); + maxPublish.ShouldBeLessThan(200); + } + + [Fact] + public async Task One_Call_request_mixing_a_local_condition_and_an_imported_one_runs_the_local_one_through_base_Call_unchanged() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3b-mixed", encrypted: false, ct); + rig.Enforce(true, [ServerEventRig.Key()], ServerEventRig.ClusterGrant(Granted, "acl-key", NodePermissions.Browse | NodePermissions.Read | NodePermissions.Subscribe | NodePermissions.AlarmRead + | NodePermissions.AlarmAcknowledge | NodePermissions.AlarmConfirm | NodePermissions.MethodCall)); + rig.MaterialiseNative(); + var routed = 0; + rig.Nm.NativeAlarmAckRouter = _ => Interlocked.Increment(ref routed); + var f = Fixture.Install(rig); + f.Apply(Update(version: 3, active: true, acked: false)); + using var session = await rig.ConnectAsync(anonymous: false, ct); + var events = new RecordedEvents(); + var subscription = await RecordedEvents.SubscribeAsync(session, events, ct); + var serverItem = RecordedEvents.AddEventItem(subscription, ObjectIds.Server); + await subscription.ApplyChangesAsync(ct); + rig.Project(true, new AlarmConditionSnapshot(true, false, true, true, AlarmShelvingKind.Unshelved, 700, "local")); + await RecordedEvents.WaitUntilAsync(() => events.Has(serverItem, "local")); + var localEventId = events.LatestEventId(serverItem, "local"); + + var response = await session.CallAsync(null, + [ + new CallMethodRequest { ObjectId = ServerEventRig.ConditionNodeId(session, native: true), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge, + InputArguments = [new Variant(ByteString.From(localEventId)), new Variant(new LocalizedText("local ack"))] }, + new CallMethodRequest { ObjectId = f.ConditionId(session), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge, + InputArguments = [new Variant(f.CurrentEventId()), new Variant(new LocalizedText("remote ack"))] }, + ], ct); + + response.Results[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code, "the local native ack runs the SDK path (base.Call) unchanged"); + response.Results[1].StatusCode.Code.ShouldBe(StatusCodes.Good.Code, "the imported one is claimed and dispatched"); + Volatile.Read(ref routed).ShouldBe(1); + f.Port.Calls.Single().Comment.ShouldBe("remote ack"); + await RecordedEvents.WaitUntilAsync(() => events.ConditionEvents(serverItem, "local").Count >= 2); + events.ConditionEvents(serverItem, "local").Last()[RecordedEvents.AckedField].ClrValue()!.ShouldBe(true, "one local ack event (#587)"); + f.Acked().ShouldBeFalse("the imported condition did not change locally"); + } + + [Fact] + public async Task A_timed_out_call_answers_BadTimeout_OutcomeUnknown_is_BadCommunicationError_and_a_refusal_passes_the_origins_status_nothing_applied() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3b-timeout", encrypted: false, ct); + var f = Fixture.Install(rig); + f.Apply(Update(version: 3, active: true, acked: false)); + using var session = await rig.ConnectAsync(anonymous: false, ct); + var id = f.ConditionId(session); + + // ConditionMethodTimeoutMilliseconds = 300 ms; the origin never answers. + f.Port.Timeout = TimeSpan.FromMilliseconds(300); + var cancelled = false; + f.Port.Handler = async (_, token) => + { + try { await Task.Delay(Timeout.Infinite, token); } + catch (OperationCanceledException) { cancelled = true; throw; } + return Applied(); + }; + var sw = Stopwatch.StartNew(); + (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadTimeout); + sw.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(3), "bounded by the mapping's method timeout (+ grace), not the request's"); + await WaitUntilAsync(() => Volatile.Read(ref cancelled)); + f.Port.Calls.Count.ShouldBe(1, "dispatched once, never retried"); + f.Acked().ShouldBeFalse(); + + f.Port.Timeout = TimeSpan.FromSeconds(5); + f.Port.Handler = (_, _) => Task.FromResult(new DataConditionMethodResult(DataWriteState.OutcomeUnknown, 0x80050000u, "transport failed")); + (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadCommunicationError); + f.Port.Handler = (_, _) => Task.FromResult(new DataConditionMethodResult(DataWriteState.RejectedBeforeDispatch, StatusCodes.BadInvalidState.Code, "not Primary")); + (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadInvalidState); + f.Port.Handler = (_, _) => Task.FromResult(new DataConditionMethodResult(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "No condition stream")); + (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadNoCommunication); + f.Acked().ShouldBeFalse("no outcome applies anything locally"); + } + + // --------------------------------------------------------------------------------------------------------------------- + + private static DataConditionMethodResult Applied() => new(DataWriteState.AcceptedUnconfirmed, 0, null); + + private static string KeyOf(string seed) => + Convert.ToBase64String(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(seed))).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + + private static ImportedConditionUpdate Update(long version, bool active, bool acked, DataActivationMarker? marker = null, + string message = "HR200 high", bool native = true, DateTimeOffset? time = null) + { + var placements = Fixture.DefaultPlacements; + var info = new DataConditionInfo("http://opcfoundation.org/UA/:AlarmConditionType", "HR200", + native ? DataConditionSourceKind.Native : DataConditionSourceKind.Scripted, placements.Select(p => p.Placement).ToArray(), + (uint)(native ? DataConditionMethodSets.Native : DataConditionMethodSets.Scripted)); + var state = new DataConditionState(Key1, version, false, true, info, active, acked, true, true, 0, 777, message, + StatusCodes.Good.Code, null, 0, time ?? DateTimeOffset.UtcNow, active || !acked, marker ?? Marker1); + return new ImportedConditionUpdate(Connection, state, info, placements, "Plant/remote-a/" + placements[0].RelativePath); + } + + /// Calls one method and returns its status (never throws for a Bad result). + private static async Task CallAsync(ISession session, NodeId objectId, NodeId methodId, object eventId, string comment, CancellationToken ct) + { + var bytes = eventId switch { ByteString b => b, byte[] a => ByteString.From(a), _ => throw new ArgumentException(nameof(eventId)) }; + var response = await session.CallAsync(null, + [new CallMethodRequest { ObjectId = objectId, MethodId = methodId, InputArguments = [new Variant(bytes), new Variant(new LocalizedText(comment))] }], ct); + var code = response.Results[0].StatusCode; + return StatusCode.IsGood(code) ? StatusCodes.Good : code; + } + + private static async Task WaitUntilAsync(Func condition) + { + var deadline = DateTime.UtcNow.AddSeconds(15); + while (!condition()) + { + if (DateTime.UtcNow > deadline) condition().ShouldBeTrue("condition not met within 15 s"); + await Task.Delay(10); + } + } + + /// The fake origin port: a per-principal, per-method gate and a scriptable handler that records each dispatch. + internal sealed class FakePort : IProjectedConditionMethods + { + public HashSet Granted { get; } = new(StringComparer.Ordinal); + public DataConditionMethods GrantedMethods { get; set; } = DataConditionMethodSets.All; + public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(5); + public ConcurrentQueue<(string Principal, DataConditionMethods Method)> AuthorizedFor { get; } = new(); + public ConcurrentQueue Calls { get; } = new(); + public Func> Handler { get; set; } = + (_, _) => Task.FromResult(Applied()); + + public ImportedConditionMethodRoute? AuthorizeMethod(RoleCarryingUserIdentity? caller, IReadOnlyList placements, + DataConditionMethods method) + { + AuthorizedFor.Enqueue((caller?.Principal ?? "", method)); + return caller is not null && Granted.Contains(caller.Principal) && (GrantedMethods & method) == method + ? new ImportedConditionMethodRoute(placements[0], Timeout) : null; + } + + public Task CallAsync(ImportedConditionMethodCall call, CancellationToken cancellationToken) + { + Calls.Enqueue(call); + return Handler(call, cancellationToken); + } + } + + private sealed class Fixture + { + public required ServerEventRig Rig { get; init; } + public required FakePort Port { get; init; } + public string Identifier => ImportedConditionIds.Identifier(Connection, Key1); + + public static IReadOnlyList DefaultPlacements { get; } = + [ + new(MappingA, DataRealm.Raw, View("Plant/dev1/HR200"), "Plant/remote-a", "dev1/HR200"), + ]; + + public IReadOnlyList Placements => DefaultPlacements; + + public static Fixture Install(ServerEventRig rig) + { + var nm = rig.Nm; + nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); + var parent = nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; + var root = new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant"); + nm.TryEnsureProjectedAnchor(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(MappingA, root), parent, + "remote-a", "Plant/remote-a", MappingA, 1, () => true), out _).ShouldBeTrue(); + var access = new ImportedConditionEventWireTests.FakeConditionAccess(); + access.Allowed.Add(Granted); + nm.ProjectedConditionAccess = access; + var port = new FakePort(); + port.Granted.Add(Granted); + nm.ProjectedConditionMethods = port; + return new Fixture { Rig = rig, Port = port }; + } + + public NodeId ConditionId(ISession session) => + new(Identifier, (ushort)session.NamespaceUris.GetIndex(ImportedConditionIds.NamespaceUri)); + + public ByteString CurrentEventId() => Rig.Nm.FindImportedCondition(Connection, Key1)!.EventId!.Value; + + public bool Acked() => Rig.Nm.FindImportedCondition(Connection, Key1)!.AckedState!.Id!.Value; + + public void Apply(ImportedConditionUpdate update) => Rig.Nm.ApplyConditions([update]); + + private static DataView View(string path) => + new(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", path), DataRealm.Raw, null, 0, path); + } +} From 2d0147f9da4b91060db47b220a74da699c7201a8 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 17:20:50 -0500 Subject: [PATCH 15/32] test(grpc-data): A3b consumer method port runtime tests (per-caller gate with real policy, mapping bit + timeout, serving incarnation, connection down unsent, lease refusal) + A3 manifest --- scripts/validation/grpc-data/unit-phases.json | 3 +- .../GrpcDataProjectedConditionMethodTests.cs | 247 ++++++++++++++++++ 2 files changed, 249 insertions(+), 1 deletion(-) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionMethodTests.cs diff --git a/scripts/validation/grpc-data/unit-phases.json b/scripts/validation/grpc-data/unit-phases.json index e1e2681dc..d890eab97 100644 --- a/scripts/validation/grpc-data/unit-phases.json +++ b/scripts/validation/grpc-data/unit-phases.json @@ -1154,7 +1154,8 @@ "project": "tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj", "filter": "(Feature=GrpcData&Phase=A3)|FullyQualifiedName~.GrpcDataConditionStreamTests.|FullyQualifiedName~.GrpcDataConditionMethodClientTests.", "new_classes": [ - "GrpcDataProjectedConditionAccessTests" + "GrpcDataProjectedConditionAccessTests", + "GrpcDataProjectedConditionMethodTests" ], "existing_classes": [ "GrpcDataConditionStreamTests", diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionMethodTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionMethodTests.cs new file mode 100644 index 000000000..27a474368 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionMethodTests.cs @@ -0,0 +1,247 @@ +using System.Threading.Channels; +using Microsoft.Extensions.Logging.Abstractions; +using Opc.Ua; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using BrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest; +using ReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest; +using ReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// A3b (plan §5.6): the consumer condition runtime's method port — the per-LOCAL-caller gate with a real +/// (AlarmAcknowledge ⇒ Acknowledge/AddComment, AlarmConfirm ⇒ Confirm, the mapping's own +/// bit, the mapping's ConditionMethodTimeoutMilliseconds), and dispatch: addressed with the serving incarnation of the +/// condition stream the records arrive on; no open stream (connection down) ⇒ BadNoCommunication, nothing sent. +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "A3")] +public sealed class GrpcDataProjectedConditionMethodTests +{ + private const string Connection = "conn-a"; + private const uint BadNoCommunication = 0x80310000u; + private static readonly ServingIdentity Serving = new("origin-1", "serving-inc-7", "Primary", 1, 1); + + [Fact] + public async Task The_method_gate_is_the_local_callers_alarm_grant_on_the_placement_folder_and_the_mappings_own_bit() + { + await using var f = new Fixture(); + var placement = f.Placement(); + f.Grant(NodePermissions.Browse | NodePermissions.Subscribe | NodePermissions.AlarmAcknowledge); + var route = f.Access.AuthorizeMethod(f.Identity("reader"), [placement], DataConditionMethods.Acknowledge); + route.ShouldNotBeNull(); + route.Placement.ShouldBe(placement); + route.Timeout.ShouldBe(TimeSpan.FromMilliseconds(4321), "the mapping's ConditionMethodTimeoutMilliseconds"); + f.Access.AuthorizeMethod(f.Identity("reader"), [placement], DataConditionMethods.AddComment).ShouldNotBeNull(); + f.Access.AuthorizeMethod(f.Identity("reader"), [placement], DataConditionMethods.Confirm).ShouldBeNull("AlarmAcknowledge is not AlarmConfirm"); + f.Access.AuthorizeMethod(f.Identity("someone-else"), [placement], DataConditionMethods.Acknowledge).ShouldBeNull("per local caller"); + f.Access.AuthorizeMethod(null, [placement], DataConditionMethods.Acknowledge).ShouldBeNull(); + + f.Grant(NodePermissions.Browse | NodePermissions.Subscribe); + f.Access.AuthorizeMethod(f.Identity("reader"), [placement], DataConditionMethods.Acknowledge) + .ShouldBeNull("seeing a condition (Subscribe) does not authorize acknowledging it"); + + f.Grant(NodePermissions.Browse | NodePermissions.Subscribe | NodePermissions.AlarmAcknowledge | NodePermissions.AlarmConfirm); + f.Access.AuthorizeMethod(f.Identity("reader"), [placement], DataConditionMethods.Confirm).ShouldNotBeNull(); + f.Mapping.AllowedOperations &= ~DataOperations.AlarmConfirm; + f.Access.AuthorizeMethod(f.Identity("reader"), [placement], DataConditionMethods.Confirm) + .ShouldBeNull("the mapping must itself grant the method's bit"); + f.Access.AuthorizeMethod(f.Identity("reader"), [placement with { MappingId = "unknown" }], DataConditionMethods.Acknowledge).ShouldBeNull(); + } + + [Fact] + public async Task With_no_open_condition_stream_a_call_is_BadNoCommunication_and_nothing_is_sent() + { + await using var f = new Fixture(); + var result = await f.Access.CallAsync(f.Call(), TestContext.Current.CancellationToken); + result.State.ShouldBe(DataWriteState.RejectedBeforeDispatch); + result.StatusCode.ShouldBe(BadNoCommunication); + f.Connections.Acquired.ShouldBe(0, "the connection is never even leased"); + f.Connections.Sent.ShouldBeEmpty(); + } + + [Fact] + public async Task A_call_goes_through_the_lease_with_the_streams_serving_incarnation_and_a_stream_end_stops_dispatch() + { + await using var f = new Fixture(); + using var demand = f.Access.AcquireEventDemand(null); + var stream = await f.Connections.Streams.Reader.ReadAsync(TestContext.Current.CancellationToken); + await f.WaitAsync(async () => (await f.Access.CallAsync(f.Call(), TestContext.Current.CancellationToken)).StatusCode != BadNoCommunication); + + var sent = f.Connections.Sent.Last(); + sent.ExpectedServingIncarnation.ShouldBe(Serving.Incarnation, "addressed to the incarnation the records came from"); + sent.Placement.ShouldBe(f.Placement().Placement); + sent.Method.ShouldBe(DataConditionMethods.Acknowledge); + sent.ExpectedActivation.ShouldBe(new DataActivationMarker("inc", 3)); + sent.OperationId.ShouldBe("op-1"); + sent.RemainingBudget.ShouldBe(TimeSpan.FromMilliseconds(900)); + sent.OnBehalfOf.ShouldBe("operator"); + + f.Connections.Result = new(DataWriteState.OutcomeUnknown, 0x80050000u, "transport failed"); + (await f.Access.CallAsync(f.Call(), TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.OutcomeUnknown, "passed through"); + + // The connection goes down: the stream ends and cannot be re-opened. + var before = f.Connections.Sent.Count; + f.Connections.Down = true; + stream.End(); + await f.WaitAsync(async () => (await f.Access.CallAsync(f.Call(), TestContext.Current.CancellationToken)).StatusCode == BadNoCommunication); + var final = f.Connections.Sent.Count; + (final - before).ShouldBeLessThanOrEqualTo(1, "at most the call racing the stream end"); + (await f.Access.CallAsync(f.Call(), TestContext.Current.CancellationToken)).StatusCode.ShouldBe(BadNoCommunication); + f.Connections.Sent.Count.ShouldBe(final, "connection down: nothing sent"); + } + + [Fact] + public async Task A_lease_refusing_the_operation_is_BadUserAccessDenied_unsent() + { + await using var f = new Fixture(); + using var demand = f.Access.AcquireEventDemand(null); + await f.Connections.Streams.Reader.ReadAsync(TestContext.Current.CancellationToken); + await f.WaitAsync(async () => (await f.Access.CallAsync(f.Call(), TestContext.Current.CancellationToken)).StatusCode != BadNoCommunication); + var sent = f.Connections.Sent.Count; + f.Connections.Refuse = true; + var result = await f.Access.CallAsync(f.Call(), TestContext.Current.CancellationToken); + result.State.ShouldBe(DataWriteState.RejectedBeforeDispatch); + result.StatusCode.ShouldBe(0x801F0000u); + f.Connections.Sent.Count.ShouldBe(sent); + } + + // --------------------------------------------------------------------------------------------------------------------- + + private sealed class Fixture : IAsyncDisposable + { + private readonly DataPlaneAuthorityState _state = new(); + private readonly ApiKey _key = new() { ApiKeyId = "key-a", Name = "key-a", Principal = "reader", SecretHash = "hash", Enabled = true, + ExpiresUtc = DateTime.UtcNow.AddHours(1) }; + private readonly ProjectedMappingPlacement _placement; + public FakeConnections Connections { get; } = new(); + public ProjectedConditionAccess Access { get; } + public RemoteNamespaceMapping Mapping => _placement.Mapping; + + public Fixture() + { + Grant(NodePermissions.Browse | NodePermissions.Subscribe); + var mapping = new RemoteNamespaceMapping + { + RemoteNamespaceMappingId = "map-a", DataConnectionId = Connection, Enabled = true, Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw, + AllowedOperations = DataOperations.Browse | DataOperations.Subscribe | DataOperations.AlarmSubscribe + | DataOperations.AlarmAcknowledge | DataOperations.AlarmConfirm, + MaxConditions = 10, ConditionStaleTimeoutMilliseconds = 100, ConditionSnapshotTimeoutMilliseconds = 30_000, + ConditionMethodTimeoutMilliseconds = 4321, BranchName = "map-a", RemoteNamespaceUri = "https://zb.com/otopcua/raw", + RemoteIdentifierKind = "string", RemoteIdentifier = "Plant", + }; + var segments = new[] { "Plant", "map-a" }; + var anchor = new DataView(new DataAddress("origin", mapping.RemoteNamespaceUri, "string", "Plant"), DataRealm.Raw, "map-a", 1, "Plant/map-a"); + var scope = new NodeScope { ClusterId = "c1", Kind = NodeHierarchyKind.Raw, Segments = segments }; + _placement = new ProjectedMappingPlacement(mapping, anchor, anchor, scope, ["local-parent"], new ActiveAuthority()); + var policy = new DataOperationPolicy(_state, new TriePermissionEvaluator(_state.Tries, TimeProvider.System), TimeProvider.System); + Access = new ProjectedConditionAccess(new GrpcDataProjectedConditionAccessTests.FakeMappings([_placement]), Connections, policy, + () => new GrpcDataProjectedConditionAccessTests.FakeSink(), TimeProvider.System, + new ProjectedConditionOptions(TimeSpan.FromMilliseconds(200), 122_500, long.MaxValue, TimeSpan.FromMilliseconds(50)), NullLogger.Instance); + } + + public void Grant(NodePermissions permissions) => + _state.Apply("c1", "rev-" + (int)permissions, [_key], + [new NodeAcl { NodeAclId = "acl", ClusterId = "c1", Principal = "reader", ScopeKind = NodeAclScopeKind.RawFolder, + ScopeId = "folder", PermissionFlags = permissions }], + new Dictionary> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant"])] }); + + public RoleCarryingUserIdentity Identity(string principal) => new(new UserNameIdentityToken { UserName = "apikey" }, [], principal, + _key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(_key), DateTimeOffset.UtcNow.AddMinutes(5)); + + public ImportedConditionPlacement Placement() => + new("map-a", DataRealm.Raw, new DataView(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant/dev1/HR200"), + DataRealm.Raw, null, 0, "Plant/dev1/HR200"), "Plant/map-a/dev1", "dev1/HR200"); + + public ImportedConditionMethodCall Call() => new(Connection, "key", Placement(), DataConditionMethods.Acknowledge, + new DataActivationMarker("inc", 3), "c", "op-1", TimeSpan.FromMilliseconds(900), "operator"); + + public async Task WaitAsync(Func> condition) + { + var deadline = DateTime.UtcNow.AddSeconds(10); + while (!await condition()) + { + if (DateTime.UtcNow > deadline) (await condition()).ShouldBeTrue("condition not met within 10 s"); + await Task.Delay(20, TestContext.Current.CancellationToken); + } + } + + public ValueTask DisposeAsync() { Access.Dispose(); return ValueTask.CompletedTask; } + } + + private sealed class ActiveAuthority : IDataMappedCatalogAuthority + { + public long CatalogEpoch => 1; + public long AuthorityEpoch => 1; + public bool IsActive => true; + } + + private sealed class FakeConnections : IGrpcDataAdapterConnectionSource + { + private int _acquired; + public Channel Streams { get; } = Channel.CreateUnbounded(); + public List Sent { get; } = []; + public DataConditionMethodResult Result { get; set; } = new(DataWriteState.AcceptedUnconfirmed, 0, null); + public bool Refuse { get; set; } + public volatile bool Down; + public int Acquired => Volatile.Read(ref _acquired); + + public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken) + { + Interlocked.Increment(ref _acquired); + if (Down) return ValueTask.FromResult(null); + return ValueTask.FromResult(new Lease(new FakeConnection(this))); + } + + private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease + { + public IDataConnection Connection => connection; + public CancellationToken CancellationToken => CancellationToken.None; + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + } + + private sealed class FakeConnection(FakeConnections owner) : IDataConnection, IDataConditionMethodService + { + public DataTarget Target { get; } = new(DataTargetMode.Cluster, "origin", null); + public TimeProvider Clock => TimeProvider.System; + public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => + Task.FromResult>>([]); + public Task> ReadAsync(ReadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task SubscribeAsync(CancellationToken cancellationToken) + { + var stream = new FakeStream(); + owner.Streams.Writer.TryWrite(stream); + return Task.FromResult(stream); + } + public Task CallConditionMethodAsync(DataConditionMethodRequest request, CancellationToken cancellationToken) + { + if (owner.Refuse) throw new UnauthorizedAccessException("Operation is not enabled for this connection."); + lock (owner.Sent) owner.Sent.Add(request); + return Task.FromResult(owner.Result); + } + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + + /// A stream that carries the serving identity it was established with (as the production one does) and no frames. + private sealed class FakeStream : IDataSubscription, IDataSubscriptionProvenance + { + private readonly Channel _frames = Channel.CreateUnbounded(); + public ServingIdentity Serving => GrpcDataProjectedConditionMethodTests.Serving; + public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken) => Task.CompletedTask; + public IAsyncEnumerable ReadAllAsync(CancellationToken cancellationToken) => _frames.Reader.ReadAllAsync(cancellationToken); + public void End() => _frames.Writer.TryComplete(); + public ValueTask DisposeAsync() { _frames.Writer.TryComplete(); return ValueTask.CompletedTask; } + } +} From fecb178efae4e68aa2cc9b021ba6fd0ff73b07f9 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 17:23:40 -0500 Subject: [PATCH 16/32] =?UTF-8?q?perf(grpc-data):=20A3=20L2=20in-process?= =?UTF-8?q?=20memory=20harness=20(1,000=20imported=20conditions,=20one=20m?= =?UTF-8?q?apping)=20+=20MaxImportedConditionBytes=20from=20the=20measurem?= =?UTF-8?q?ent=20(205,665=20B=20=C3=97=202,500)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Configuration/DataConnectionOptions.cs | 4 +- .../ProjectedConditionAccess.cs | 15 ++- ...ImportedConditionMemoryMeasurementTests.cs | 95 +++++++++++++++++++ 3 files changed, 108 insertions(+), 6 deletions(-) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMemoryMeasurementTests.cs diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs index 3dedbbd93..2be47ff68 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs @@ -21,8 +21,8 @@ public sealed class DataConnectionOptions public long MaxTransportBytes { get; set; } = 64 * 1024 * 1024; /// A3 (§5.5): imported-condition node budget per consumer node (2,500 × 49 worst-case nodes per condition). public int MaxImportedConditionNodes { get; set; } = 122_500; - /// A3 (§5.5): imported-condition memory budget per consumer node (≈ 2,500 × 157 KiB; provisional until L2). - public long MaxImportedConditionBytes { get; set; } = 400L * 1024 * 1024; + /// A3 (§5.5): imported-condition memory budget per consumer node (§9.3 L2: measured 205,665 B/condition × 2,500 ≈ 490 MiB). + public long MaxImportedConditionBytes { get; set; } = ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ProjectedConditionOptions.DefaultMaxImportedConditionBytes; public long MaxPendingBytes { get; set; } = 1024 * 1024; public TimeSpan MaxSessionLifetime { get; set; } = TimeSpan.FromHours(1); /// A2b: remote condition-method operations the origin remembers at once for duplicate protection (all principals). diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs index 482d45f2a..9aeb14f49 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs @@ -40,18 +40,25 @@ public sealed class DeployedConditionMappings : IProjectedConditionMappings /// A3 host limits (§5.5 "Budget"). /// How long a connection's condition items stay open after the last event item goes (default 30 s). /// Per consumer node (default 122,500 = 2,500 × 49). -/// Per consumer node (default 400 MiB; provisional until L2). +/// Per consumer node (default = L2-measured × 2,500 ≈ 490 MiB). /// Pause before re-opening an ended condition stream. public sealed record ProjectedConditionOptions(TimeSpan Linger, int MaxImportedConditionNodes, long MaxImportedConditionBytes, TimeSpan ReconnectDelay) { /// Counted, not estimated (plan §5.5 table): the worst case per condition. public const int NodesPerCondition = 49; - /// Measured retained managed size per condition (≈ 157 KiB, SDK 2.0.1). - public const long BytesPerCondition = 160_997; + /// + /// Retained managed bytes per imported condition, measured by the A3 L2 harness (1,000 conditions in one mapping on a + /// running SDK 2.0.1 server: node + children + ids + registry/indexes + EventId registry + verdict cache; X0's + /// node-only harness measured 160,997). The managed-heap figure is used: it is higher than the working-set growth. + /// + public const long BytesPerCondition = 205_665; + + /// §9.3 L2: the host byte cap = measured per-condition bytes × 2,500 (the host condition cap). + public const long DefaultMaxImportedConditionBytes = BytesPerCondition * 2_500; public static ProjectedConditionOptions Default { get; } = - new(TimeSpan.FromSeconds(30), 122_500, 400L * 1024 * 1024, TimeSpan.FromSeconds(1)); + new(TimeSpan.FromSeconds(30), 122_500, DefaultMaxImportedConditionBytes, TimeSpan.FromSeconds(1)); } /// Why a condition-bearing mapping is not contributing conditions. diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMemoryMeasurementTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMemoryMeasurementTests.cs new file mode 100644 index 000000000..8a3ca14f8 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMemoryMeasurementTests.cs @@ -0,0 +1,95 @@ +using System.Diagnostics; +using System.Security.Cryptography; +using Opc.Ua; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests; + +/// +/// §9.3 L2 (A3 exit, m-T7) in-process measurement harness: consumer memory with 1,000 imported conditions in ONE mapping, +/// materialised through the real of a running SDK server — condition nodes and their +/// instance-scoped children, ids, the registry and its folder/notifier indexes, the verdict cache and the EventId registry +/// (every condition reports one event, filling its N6 slot) — plus the updates the runtime keeps per key (records + infos). +/// Opt-in: OTOPCUA_A3_L2=1 (it forces full GCs and is not a unit gate). Pass criterion: working-set growth ≤ 200 MiB. +/// +[Trait("Feature", "GrpcData"), Trait("Phase", "A3"), Trait("Category", "Perf")] +public sealed class ImportedConditionMemoryMeasurementTests +{ + private const string Connection = "conn-l2"; + private const string Mapping = "map-l2"; + private const int Conditions = 1_000; + + [Fact] + public async Task L2_one_thousand_imported_conditions_in_one_mapping_grow_the_working_set_by_at_most_200_MiB() + { + if (Environment.GetEnvironmentVariable("OTOPCUA_A3_L2") != "1") Assert.Skip("Set OTOPCUA_A3_L2=1 to run the A3 L2 memory measurement."); + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3-l2", encrypted: false, ct); + var nm = rig.Nm; + nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); + var parent = nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; + var root = new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant"); + nm.TryEnsureProjectedAnchor(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(Mapping, root), parent, + "remote", "Plant/remote", Mapping, 1, () => true), out _).ShouldBeTrue(); + var access = new ImportedConditionEventWireTests.FakeConditionAccess(); + access.Allowed.Add(ServerEventRig.KeyPrincipal); + nm.ProjectedConditionAccess = access; + + var (heap0, ws0) = Measure(); + var keys = Enumerable.Range(0, Conditions).Select(i => KeyOf("l2-" + i)).ToArray(); + var first = keys.Select((k, i) => Update(k, i, 3, active: true, acked: false)).ToList(); + var sw = Stopwatch.StartNew(); + nm.ApplyConditions(first); + var materialise = sw.Elapsed; + first.Clear(); + var (heapMid, _) = Measure(); + // One more transition each: every condition reports an event (consumer-minted EventId in its N6 registry). + var second = keys.Select((k, i) => Update(k, i, 4, active: true, acked: true)).ToList(); + sw.Restart(); + nm.ApplyConditions(second); + var transition = sw.Elapsed; + nm.ImportedConditionCount.ShouldBe(Conditions); + // Exercise the verdict cache once per condition (one identity). + var identity = new Security.RoleCarryingUserIdentity(new UserNameIdentityToken { UserName = "apikey" }, [], ServerEventRig.KeyPrincipal, + "k", null, null); + foreach (var k in keys) + nm.AuthorizeImportedCondition(identity, Core.Abstractions.OpcUaOperation.Read, nm.ImportedConditionNodeId(Connection, k)).ShouldBeTrue(); + + var (heap1, ws1) = Measure(); + GC.KeepAlive(second); + var heapGrowth = heap1 - heap0; + var wsGrowth = ws1 - ws0; + var line = $"L2: {Conditions} conditions, one mapping: managed heap +{heapGrowth / 1048576.0:F1} MiB ({heapGrowth / Conditions:N0} B/condition; after materialise {(heapMid - heap0) / Conditions:N0}), " + + $"working set +{wsGrowth / 1048576.0:F1} MiB ({wsGrowth / Conditions:N0} B/condition); materialise {materialise.TotalMilliseconds:F0} ms, " + + $"transition {transition.TotalMilliseconds:F0} ms; events reported {nm.ImportedEventsReported}"; + TestContext.Current.TestOutputHelper?.WriteLine(line); + if (Environment.GetEnvironmentVariable("OTOPCUA_A3_MEASURE_OUT") is { Length: > 0 } outPath) File.AppendAllText(outPath, line + Environment.NewLine); + wsGrowth.ShouldBeLessThanOrEqualTo(200L * 1024 * 1024); + } + + private static (long Heap, long WorkingSet) Measure() + { + for (var i = 0; i < 3; i++) { GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true); GC.WaitForPendingFinalizers(); } + using var process = Process.GetCurrentProcess(); + process.Refresh(); + return (GC.GetTotalMemory(forceFullCollection: true), process.WorkingSet64); + } + + private static string KeyOf(string seed) => + Convert.ToBase64String(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(seed))).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + + private static ImportedConditionUpdate Update(string key, int index, long version, bool active, bool acked) + { + var path = $"Plant/dev{index / 10}/HR{index}"; + var view = new DataView(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", path), DataRealm.Raw, null, 0, path); + var placements = new[] { new ImportedConditionPlacement(Mapping, DataRealm.Raw, view, "Plant/remote", path["Plant/".Length..]) }; + var info = new DataConditionInfo("http://opcfoundation.org/UA/:AlarmConditionType", $"HR{index}", DataConditionSourceKind.Native, + [view], (uint)DataConditionMethodSets.Native); + var state = new DataConditionState(key, version, false, true, info, active, acked, true, true, 0, 500, $"HR{index} high", + StatusCodes.Good.Code, null, 0, DateTimeOffset.UtcNow, true, new DataActivationMarker("inc", 1)); + return new ImportedConditionUpdate(Connection, state, info, placements, "Plant/remote/" + placements[0].RelativePath); + } +} From 4e6535ee1df6c667b15abab070574cbedb3fbcd9 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 17:25:31 -0500 Subject: [PATCH 17/32] =?UTF-8?q?test(grpc-data):=20A3=20live=20smoke=20?= =?UTF-8?q?=E2=80=94=20conditions=20profile=20makes=20the=20CONSUMER=20con?= =?UTF-8?q?dition-bearing;=20conditions=5Fa3=5Fsmoke.py=20acknowledges=20t?= =?UTF-8?q?he=20imported=20ScalarHigh=20through=20the=20consumer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../grpc-data/conditions_a3_smoke.py | 132 ++++++++++++++++++ scripts/validation/grpc-data/seed/Program.cs | 8 +- 2 files changed, 138 insertions(+), 2 deletions(-) create mode 100644 scripts/validation/grpc-data/conditions_a3_smoke.py diff --git a/scripts/validation/grpc-data/conditions_a3_smoke.py b/scripts/validation/grpc-data/conditions_a3_smoke.py new file mode 100644 index 000000000..da7f1393d --- /dev/null +++ b/scripts/validation/grpc-data/conditions_a3_smoke.py @@ -0,0 +1,132 @@ +"""A3 consumer-condition live smoke on a `rig.py up --conditions` run (plan §9 A3 exit; the full gate is A4). + +Raises the SOURCE scripted alarm `ScalarHigh` (scalar register 20 := 150) through the device control API, then: + +1. starts the CLI `alarms --refresh` on the SOURCE Primary (the origin's OWN subscriber) and on the CONSUMER Primary (whose + Server-object item opens condition demand, so the consumer imports ScalarHigh over its data connection); +2. waits for the IMPORTED `ScalarHigh` (Active, Unacknowledged) on the consumer, with its consumer-minted EventId and its + `mapped/conditions` ConditionNodeId; +3. refuses first: a bogus EventId must answer `BadEventIdUnknown` (nothing sent); +4. acknowledges it THROUGH THE CONSUMER with the CLI `ack` (§5.6: claimed by the node manager, dispatched to the origin's + `CallConditionMethod`, never applied locally); +5. requires the origin's own subscriber to see EXACTLY ONE `Active, Acknowledged` ScalarHigh event, and the consumer to + see the acknowledgement come back (the origin's record re-imported) — exactly one consumer `Active, Acknowledged` event; +6. clears the alarm. + +Evidence lands in the run's restricted `evidence/` folder (`A3-*.txt`, `A3-*.process.json`, `A3-conditions-consumer.json`). +""" +import argparse +import json +import os +import re +import signal +import subprocess +import sys +import time + +import scenarios + + +def watch(runner, node, name): + log = runner.folder / name + descriptor = os.open(log, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + process = subprocess.Popen(["dotnet", str(runner.cli_dll), "alarms", "-u", runner.endpoint(node), "-U", "apikey", "-P", runner.key, + "--refresh", "-i", "250"], stdout=descriptor, stderr=subprocess.STDOUT, start_new_session=True) + os.close(descriptor) + return process, log + + +def stop(process): + process.send_signal(signal.SIGINT) + try: + process.wait(timeout=20) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=10) + + +def blocks(log, condition="ScalarHigh"): + found = [] + for block in log.read_text(errors="replace").split("\n\n"): + if f"Condition: {condition}" not in block: + continue + fields = {} + for line in block.splitlines(): + match = re.match(r"\s*(State|ConditionNodeId|EventId|Message):\s*(.*)$", line) + if match: + fields[match.group(1)] = match.group(2).strip() + found.append(fields) + return found + + +def wait_for(predicate, timeout, step=1.0): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + value = predicate() + if value: + return value + time.sleep(step) + return predicate() + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--run-id", required=True) + parser.add_argument("--settle-seconds", type=int, default=8) + parser.add_argument("--import-timeout", type=int, default=120) + arguments = parser.parse_args(argv) + runner = scenarios.ScenarioRunner(arguments.run_id) + runner.active, runner.deadline = "A3", time.monotonic() + 900 + runner.publish() + runner.device("set", address=20, value=150) + time.sleep(arguments.settle_seconds) + source, consumer = runner.primary("source"), runner.primary("consumer") + origin_watch, origin_log = watch(runner, source, "A3-origin-alarms.txt") + consumer_watch, consumer_log = watch(runner, consumer, "A3-consumer-alarms.txt") + report = {"source_primary": source, "consumer_primary": consumer, "checks": {}} + try: + imported = wait_for(lambda: next((b for b in blocks(consumer_log) if b.get("State") == "Active, Unacknowledged" + and b.get("EventId") and b.get("ConditionNodeId")), None), arguments.import_timeout) + report["checks"]["imported_active_unacked"] = bool(imported) + if not imported: + raise scenarios.ScenarioError("the consumer never showed the imported ScalarHigh (Active, Unacknowledged)") + report["imported"] = {"condition_node_id": imported["ConditionNodeId"], "event_id_len": len(imported["EventId"])} + endpoint = runner.endpoint(consumer) + base = ["dotnet", str(runner.cli_dll), "ack", "-u", endpoint, "-U", "apikey", "-P", runner.key, "-n", imported["ConditionNodeId"]] + + bogus = runner.process(base + ["-e", "00" * 16, "-c", "A3 bogus"], "A3-ack-bogus-eventid", timeout=60) + bogus_text = bogus.stdout + bogus.stderr + report["checks"]["bogus_eventid_refused"] = ("BadEventIdUnknown" in bogus_text or "809A0000" in bogus_text.upper()) \ + and "successful" not in bogus_text + report["bogus"] = bogus_text[-300:] + time.sleep(3) + report["checks"]["nothing_acked_after_bogus"] = all(b.get("State") != "Active, Acknowledged" for b in blocks(origin_log)) + + started = time.monotonic() + ack = runner.process(base + ["-e", imported["EventId"], "-c", "A3 consumer ack"], "A3-ack-consumer", timeout=60) + report["ack"] = {"returncode": ack.returncode, "elapsed_ms": round((time.monotonic() - started) * 1000), + "stdout": ack.stdout[-400:]} + report["checks"]["ack_good"] = ack.returncode == 0 and "Acknowledge successful" in ack.stdout + + acked_back = wait_for(lambda: any(b.get("State") == "Active, Acknowledged" for b in blocks(consumer_log)), 30) + report["checks"]["consumer_sees_ack_back"] = bool(acked_back) + time.sleep(6) # let any duplicate arrive before counting + finally: + stop(consumer_watch) + stop(origin_watch) + runner.device("set", address=20, value=0) + + origin_states = [b.get("State") for b in blocks(origin_log)] + consumer_states = [b.get("State") for b in blocks(consumer_log)] + report["origin_subscriber"] = {"states": origin_states, "active_acknowledged_events": origin_states.count("Active, Acknowledged")} + report["consumer_subscriber"] = {"states": consumer_states, "active_acknowledged_events": consumer_states.count("Active, Acknowledged")} + report["checks"]["origin_exactly_one_ack_event"] = report["origin_subscriber"]["active_acknowledged_events"] == 1 + report["checks"]["consumer_exactly_one_ack_event"] = report["consumer_subscriber"]["active_acknowledged_events"] == 1 + report["passed"] = all(report["checks"].values()) + runner.save("A3-conditions-consumer.json", report) + print(json.dumps(report, indent=2)[:20000]) + return 0 if report["passed"] else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/validation/grpc-data/seed/Program.cs b/scripts/validation/grpc-data/seed/Program.cs index 5d7ed1d1c..8b30abfb5 100644 --- a/scripts/validation/grpc-data/seed/Program.cs +++ b/scripts/validation/grpc-data/seed/Program.cs @@ -388,7 +388,10 @@ try db.DataConnections.Add(new() { DataConnectionRowId = Guid.NewGuid(), DataConnectionId = "consumer-source", ClusterId = "CONSUMER", Enabled = true, ConsumerNodeIds = ["consumer-1:4053", "consumer-2:4053"], TargetMode = DataTargetMode.Cluster, ExpectedClusterId = "SOURCE", EligibleTargetNodeIds = ["source-1:4053", "source-2:4053"], Endpoints = ["https://source-1:4057", "https://source-2:4057"], - SecretReference = "secret:data/source", SecretScopeClusterId = "CONSUMER", AllowedOperations = grantedOperations, + // A3: the conditions profile makes the CONSUMER condition-bearing too (connection + mappings carry AlarmSubscribe and + // the method bits), so a consumer Server-object subscription imports ScalarHigh and can acknowledge it remotely. + SecretReference = "secret:data/source", SecretScopeClusterId = "CONSUMER", + AllowedOperations = grantedOperations | (conditions ? DataOperationSets.ConditionGrants : DataOperations.None), TimeoutMilliseconds = 30000 }); foreach (var realm in new[] { DataRealm.Raw, DataRealm.Uns }) { @@ -406,7 +409,8 @@ try ClusterId = "CONSUMER", DataConnectionId = "consumer-source", Enabled = true, ConsumerNodeIds = ["consumer-1:4053", "consumer-2:4053"], Realm = realm, RemoteRealm = realm, LocalParentKind = "Cluster", LocalParentId = "CONSUMER", BranchName = "remote-source", RemoteRootEntityId = entity, RemoteNamespaceUri = realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : V3NodeIds.UnsNamespaceUri, - RemoteIdentifierKind = "string", RemoteIdentifier = realm == DataRealm.Raw ? "modbus/plc" : equipment, AllowedOperations = grantedOperations, WriteThrough = true }); + RemoteIdentifierKind = "string", RemoteIdentifier = realm == DataRealm.Raw ? "modbus/plc" : equipment, + AllowedOperations = grantedOperations | (conditions ? DataOperationSets.ConditionGrants : DataOperations.None), WriteThrough = true }); if (history) db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "cli-history-map-" + name, ClusterId = "CONSUMER", Principal = "fixture-cli", ScopeKind = NodeAclScopeKind.RemoteNamespaceMapping, ScopeId = "map-" + name, PermissionFlags = NodePermissions.Browse | NodePermissions.HistoryRead }); From 404a664ca372faf14b6419a4277b52774c021176 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 17:37:23 -0500 Subject: [PATCH 18/32] fix(grpc-data): A3 ProjectedConditionAccess logs through the host logger (was NullLogger in production) + stream/item/barrier diagnostics --- .../Configuration/DataConnectionRegistration.cs | 3 ++- .../DataConnections/ProjectedConditionAccess.cs | 12 ++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs index 9953a7bb2..e37784937 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs @@ -1,5 +1,6 @@ using Akka.Hosting; using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using ZB.MOM.WW.OtOpcUa.Commons.Interfaces; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; @@ -152,7 +153,7 @@ public static class DataConnectionRegistration { MaxImportedConditionNodes = options.MaxImportedConditionNodes, MaxImportedConditionBytes = options.MaxImportedConditionBytes, - })); + }, sp.GetRequiredService().CreateLogger())); services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(sp => new ConfiguredProjectionDiscovery( sp.GetRequiredService(), sp.GetRequiredService(), diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs index 9aeb14f49..d28fbdac9 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs @@ -413,6 +413,8 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess await using var subscription = await connection.SubscribeAsync(token).ConfigureAwait(false); Volatile.Write(ref _serving, (subscription as IDataSubscriptionProvenance)?.Serving); + _owner._log.LogInformation("Imported conditions: stream {Epoch} for connection {Connection} opened ({Mappings} mapping(s), serving {Serving})", + epoch, _connectionId, states.Length, Serving?.NodeId ?? "(no provenance)"); var subscriptionId = "conditions-" + Guid.NewGuid().ToString("N"); var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); var items = states.Select(x => new DataSubscriptionItem(x.MappingId, x.Root, settings, new DataConditionScope(IncludeInfo: true))).ToArray(); @@ -464,6 +466,9 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess if (states.Any(x => x.Status is ProjectedConditionMappingStatus.Pending or ProjectedConditionMappingStatus.Snapshotting)) return false; Interlocked.Increment(ref _barriers); DisarmStale(); + _owner._log.LogInformation("Imported conditions: connection {Connection} snapshot barrier passed ({Statuses}; {Records} record(s){TimedOut})", + _connectionId, string.Join(", ", states.Select(x => x.MappingId + "=" + x.Status)), states.Where(x => x.Contributes).Sum(x => x.Records.Count), + _timedOut ? "; snapshot timed out" : ""); PassBarrier(states); if (_timedOut) _owner._sink()?.RequireRefresh(_connectionId); // an incomplete (re)snapshot return true; @@ -485,6 +490,9 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess if (itemAck.Status == DataItemStatus.Good && itemAck.Handle is { } handle) state.Handle = handle.Handle; else if (state.Status != ProjectedConditionMappingStatus.ConditionCapacity) state.Status = ProjectedConditionMappingStatus.Unavailable; } + if (itemAck.Status != DataItemStatus.Good) + _owner._log.LogWarning("Imported conditions: mapping {Mapping} item refused by the origin ({Status}: {Diagnostic})", + state.MappingId, itemAck.Status, itemAck.Diagnostic); } break; case DataSubscriptionConditions conditions: @@ -592,6 +600,7 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess var update = Merge(states, key); if (update is null) { + _owner._log.LogWarning("Imported conditions: connection {Connection} key has no placement in a complete mapping (not materialised)", _connectionId); if (_materialised.Remove(key)) removals.Add(key); continue; } @@ -600,6 +609,9 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess } if (removals.Count > 0) sink.RemoveConditions(_connectionId, removals); if (updates.Count > 0) sink.ApplyConditions(updates); + if (updates.Count + removals.Count > 0) + _owner._log.LogDebug("Imported conditions: connection {Connection} applied {Updates} update(s), {Removals} removal(s)", + _connectionId, updates.Count, removals.Count); } /// One key across the connection's complete mappings: placements (primary first), latest record, SourceName. From 82ecc1164c994d623b0953f00a54ff7df4ded021 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 17:48:16 -0500 Subject: [PATCH 19/32] =?UTF-8?q?fix(grpc-data):=20A3=20condition=20items?= =?UTF-8?q?=20carry=20the=20origin's=20canonical=20root=20view=20(metadata?= =?UTF-8?q?=20asked=20like=20the=20browse=20resolver)=20=E2=80=94=20live?= =?UTF-8?q?=20a3b-cond-2=20found=20map-uns=20refused=20Denied?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ProjectedConditionAccess.cs | 17 ++++++-- .../GrpcDataProjectedConditionMethodTests.cs | 43 ++++++++++++++++--- 2 files changed, 51 insertions(+), 9 deletions(-) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs index d28fbdac9..818300708 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs @@ -287,8 +287,15 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess { public ProjectedMappingPlacement Placement { get; } = placement; public string MappingId => Placement.Mapping.RemoteNamespaceMappingId; - public DataView Root { get; } = new(placement.Anchor.Address, placement.Mapping.Realm, null, 0, placement.Anchor.Address.Identifier); + // The origin view of the remote root, built exactly as RemoteNamespaceResolver builds it (subject = the mapping's + // RemoteRootEntityId): a UNS root's address identifier is an opaque id, and the origin refuses a root item whose subject + // is not its own (live a3b-cond-2: map-uns item Denied). + public DataView Root { get; } = new(placement.Anchor.Address, placement.Mapping.Realm, null, 0, + string.IsNullOrWhiteSpace(placement.Mapping.RemoteRootEntityId) ? placement.Anchor.Address.Identifier : placement.Mapping.RemoteRootEntityId); public string? RootSubject { get; set; } + /// The origin's canonical view of the remote root (from metadata): the root item must carry the origin's own + /// subject — a view built from the address alone (subject = identifier) is refused for an opaque-id UNS root. + public DataView? RootView { get; set; } public ulong? Handle { get; set; } public ProjectedConditionMappingStatus Status { get; set; } = ProjectedConditionMappingStatus.Pending; public int Total { get; set; } @@ -407,7 +414,11 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess var metadata = await connection.GetMetadataAsync(new MetadataRequest(states.Select(x => x.Root).ToArray(), budget), token) .ConfigureAwait(false); for (var i = 0; i < states.Length && i < metadata.Count; i++) - if (metadata[i] is { Status: DataItemStatus.Good, Value: { } root }) states[i].RootSubject = root.View.Subject; + if (metadata[i] is { Status: DataItemStatus.Good, Value: { } root }) + { + states[i].RootSubject = root.View.Subject; + states[i].RootView = root.View; + } } catch (Exception ex) when (ex is not OperationCanceledException) { } @@ -417,7 +428,7 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess epoch, _connectionId, states.Length, Serving?.NodeId ?? "(no provenance)"); var subscriptionId = "conditions-" + Guid.NewGuid().ToString("N"); var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); - var items = states.Select(x => new DataSubscriptionItem(x.MappingId, x.Root, settings, new DataConditionScope(IncludeInfo: true))).ToArray(); + var items = states.Select(x => new DataSubscriptionItem(x.MappingId, x.RootView ?? x.Root, settings, new DataConditionScope(IncludeInfo: true))).ToArray(); await subscription.SendAsync(new OpenSubscription(subscriptionId, epoch, "open", TimeSpan.FromSeconds(30), items, false, TimeSpan.FromMinutes(60), new DataBudget(TimeSpan.FromSeconds(30), 1000, 4 * 1024 * 1024)), token).ConfigureAwait(false); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionMethodTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionMethodTests.cs index 27a474368..b51db1785 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionMethodTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionMethodTests.cs @@ -114,6 +114,18 @@ public sealed class GrpcDataProjectedConditionMethodTests f.Connections.Sent.Count.ShouldBe(sent); } + [Fact] + public async Task The_condition_item_carries_the_origins_canonical_root_view_learned_from_metadata() + { + // Live a3b-cond-2: a UNS root item built from the address alone (subject = the opaque EquipmentId) was refused Denied. + await using var f = new Fixture(uns: true); + using var demand = f.Access.AcquireEventDemand(null); + var stream = await f.Connections.Streams.Reader.ReadAsync(TestContext.Current.CancellationToken); + var open = await stream.Opened.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + f.Connections.MetadataViews.Single().Subject.ShouldBe("EQ-0001", "metadata is asked as the browse resolver asks it (RemoteRootEntityId)"); + open.Items.Single().View.Subject.ShouldBe("area/line/plc", "the item uses the origin's own view of the root"); + } + // --------------------------------------------------------------------------------------------------------------------- private sealed class Fixture : IAsyncDisposable @@ -126,7 +138,7 @@ public sealed class GrpcDataProjectedConditionMethodTests public ProjectedConditionAccess Access { get; } public RemoteNamespaceMapping Mapping => _placement.Mapping; - public Fixture() + public Fixture(bool uns = false) { Grant(NodePermissions.Browse | NodePermissions.Subscribe); var mapping = new RemoteNamespaceMapping @@ -138,9 +150,16 @@ public sealed class GrpcDataProjectedConditionMethodTests ConditionMethodTimeoutMilliseconds = 4321, BranchName = "map-a", RemoteNamespaceUri = "https://zb.com/otopcua/raw", RemoteIdentifierKind = "string", RemoteIdentifier = "Plant", }; + if (uns) + { + mapping.Realm = mapping.RemoteRealm = DataRealm.Uns; + mapping.RemoteNamespaceUri = "https://zb.com/otopcua/uns"; + mapping.RemoteIdentifier = "EQ-0001"; + mapping.RemoteRootEntityId = "EQ-0001"; + } var segments = new[] { "Plant", "map-a" }; - var anchor = new DataView(new DataAddress("origin", mapping.RemoteNamespaceUri, "string", "Plant"), DataRealm.Raw, "map-a", 1, "Plant/map-a"); - var scope = new NodeScope { ClusterId = "c1", Kind = NodeHierarchyKind.Raw, Segments = segments }; + var anchor = new DataView(new DataAddress("origin", mapping.RemoteNamespaceUri, "string", mapping.RemoteIdentifier), mapping.Realm, "map-a", 1, "Plant/map-a"); + var scope = new NodeScope { ClusterId = "c1", Kind = uns ? NodeHierarchyKind.Uns : NodeHierarchyKind.Raw, Segments = segments }; _placement = new ProjectedMappingPlacement(mapping, anchor, anchor, scope, ["local-parent"], new ActiveAuthority()); var policy = new DataOperationPolicy(_state, new TriePermissionEvaluator(_state.Tries, TimeProvider.System), TimeProvider.System); Access = new ProjectedConditionAccess(new GrpcDataProjectedConditionAccessTests.FakeMappings([_placement]), Connections, policy, @@ -189,6 +208,7 @@ public sealed class GrpcDataProjectedConditionMethodTests private int _acquired; public Channel Streams { get; } = Channel.CreateUnbounded(); public List Sent { get; } = []; + public List MetadataViews { get; } = []; public DataConditionMethodResult Result { get; set; } = new(DataWriteState.AcceptedUnconfirmed, 0, null); public bool Refuse { get; set; } public volatile bool Down; @@ -215,8 +235,14 @@ public sealed class GrpcDataProjectedConditionMethodTests public TimeProvider Clock => TimeProvider.System; public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => throw new NotSupportedException(); public Task BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); - public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => - Task.FromResult>>([]); + public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) + { + lock (owner.MetadataViews) owner.MetadataViews.AddRange(request.Views); + // The origin answers with ITS canonical view of the root (subject = its browse path, not the opaque id). + return Task.FromResult>>(request.Views.Select(v => new DataItemResult("0", + DataItemStatus.Good, new DataMetadata(v with { Subject = "area/line/plc" }, "plc", "Folder", DataValueKind.Null, -1, [], false, + DataOperations.Browse, 1, null, null, false), null)).ToArray()); + } public Task> ReadAsync(ReadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => throw new NotSupportedException(); public Task SubscribeAsync(CancellationToken cancellationToken) @@ -239,7 +265,12 @@ public sealed class GrpcDataProjectedConditionMethodTests { private readonly Channel _frames = Channel.CreateUnbounded(); public ServingIdentity Serving => GrpcDataProjectedConditionMethodTests.Serving; - public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken) => Task.CompletedTask; + public TaskCompletionSource Opened { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken) + { + if (command is OpenSubscription open) Opened.TrySetResult(open); + return Task.CompletedTask; + } public IAsyncEnumerable ReadAllAsync(CancellationToken cancellationToken) => _frames.Reader.ReadAllAsync(cancellationToken); public void End() => _frames.Writer.TryComplete(); public ValueTask DisposeAsync() { _frames.Writer.TryComplete(); return ValueTask.CompletedTask; } From 3c941458f59106f3ca3188a93737e42f68544cca Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 18:14:57 -0500 Subject: [PATCH 20/32] =?UTF-8?q?docs(grpc-data):=20A3b=20evidence=20?= =?UTF-8?q?=E2=80=94=20implementation,=20A3a=20live=20defects,=20tests=20+?= =?UTF-8?q?=20red-on-revert,=20L2/L3=20numbers,=20live=20a3b-cond-3=20PASS?= =?UTF-8?q?,=20deviations,=20gates?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/plans/evidence/grpc-data-ext/A3.md | 213 +++++++++++++++++++++++- 1 file changed, 212 insertions(+), 1 deletion(-) diff --git a/docs/plans/evidence/grpc-data-ext/A3.md b/docs/plans/evidence/grpc-data-ext/A3.md index dcef51e2e..c8fea4c3b 100644 --- a/docs/plans/evidence/grpc-data-ext/A3.md +++ b/docs/plans/evidence/grpc-data-ext/A3.md @@ -1,4 +1,4 @@ -# A3 evidence — PART 1 (A3a): consumer condition registry, visibility and event delivery +# A3 evidence — consumer condition registry, visibility, event delivery (A3a) and remote methods (A3b) Phase A3 (first half) of `docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md`, 2026-11-24, branch `a3-consumer` (from master `83c7e586`). A3b (§5.6 remote methods: `ICallAsyncNodeManager`, claim / `base.Call` / await, @@ -161,3 +161,214 @@ own the live leg); the unit + OI wire tests above use a real SDK server and real - RefreshRequired to an item whose UNMARKED list the rewriter dropped (deviation 4); explicit Primary endpoint for condition items (deviation 9); the mapping-change runner hand-over (an old runner's in-flight batch can still reach the sink until its cancellation is observed — bounded by one frame). + +--- + +# A3 — PART 2 (A3b): methods on imported conditions, no `Lock` waits; A3 exit (L2, L3, live) + +2026-11-24, branch `a3-consumer`, on top of A3a (`b5ab6e7c`). Not merged, not pushed. + +## Progress log + +1. `c1be5725` NM: `ICallAsyncNodeManager` (`OpcUaServer/ImportedConditionMethods.cs`), EventId registry gate, N6 re-binding. +2. `28098a8d` Runtime/Host: `ProjectedConditionAccess : IProjectedConditionMethods` (`ProjectedConditionAccess.Methods.cs`), the + runner's stream serving identity, `DataConnectionDeploymentLease : IDataConditionMethodService`, host wiring. +3. `de51886d` OI wire tests; `2d0147f9` Runtime tests + `A3` manifest; `fecb178e` L2 harness + byte cap. +4. `4e6535ee` live smoke (`conditions_a3_smoke.py`, seeder conditions profile makes the CONSUMER condition-bearing). +5. Live `a3b-cond-1` / `-2` FAILED and found two A3a integration defects, fixed in `404a664c` (logger) and `82ecc116` (root view); + live `a3b-cond-3` PASS. + +## What is implemented (A3b, plan §5.6) + +- **Interception (step 1).** Verified against the pinned SDK 2.0.1 (ilspy): `CustomNodeManager2` has a public virtual + `CallAsync(OperationContext, ArrayOf, IList, IList, CancellationToken)` but + does NOT declare `ICallAsyncNodeManager`, so `AsyncNodeManagerAdapter.CallAsync` ran the synchronous `Call`. NM now declares + `ICallAsyncNodeManager` and overrides `CallAsync`: (a) claims every unprocessed request whose ObjectId is in the + `mapped/conditions` namespace — a namespace-index test, **no lock at all** — and marks it `Processed`; (b) calls + `base.Call(...)` unchanged (it skips the claimed ones; local behaviour incl. `ReportAfterMethod` under `Lock` is unchanged), + completed before any remote await; (c) runs the claimed calls concurrently and awaits them. No `Lock` is held at any point; + the SDK pre-validation `FindMethodState` takes `Lock` only for its lookup (plan's residual). +- **Local checks (step 2), no I/O, no NM `Lock`:** condition resolved from the ObjectId (`TryParse`, lock-free registry + `Find`) else `BadNodeIdUnknown`; method from the MethodId — the type declarations (`AcknowledgeableConditionType_Acknowledge` + / `_Confirm`, `ConditionType_AddComment`) or this condition's instance child (`c1.…/Acknowledge` etc.); anything else + (shelve, enable/disable) `BadNotSupported`; no port ⇒ `BadNotSupported`; **per-caller mapping gate** + `IProjectedConditionMethods.AuthorizeMethod(local caller, placements, method)` ⇒ `BadUserAccessDenied` unsent; native + Confirm ⇒ `BadNotSupported`; the origin's `supported_methods` (kept from the listing) lacks the method ⇒ `BadNotSupported`; + Warm Standby ⇒ the standby refusal; argument shape (`BadArgumentsMissing` / `BadTooManyArguments` / `BadTypeMismatch`); + **EventId**: must be one this consumer minted for that condition AND bound to the CURRENT marker, else `BadEventIdUnknown` + unsent. The EventId registry (`RecentEvents`, 32 per condition) and `Activation` are now read/written under a per-condition + `MethodGate` (the plan's "small registry with its own lock"); `TryResolveImportedEvent` also uses it instead of `Lock`. +- **The gate** (`ProjectedConditionAccess.AuthorizeMethod`, real `DataOperationPolicy`): for a placement in primary order whose + mapping is current, condition-bearing, of the placement's realm and itself grants the method's bit (AlarmAcknowledge for + Acknowledge/AddComment, AlarmConfirm for Confirm): `AuthorizeLocal(caller, AlarmAcknowledge|AlarmConfirm, folder scope)`, + which re-checks the caller's key (#563); regardless of `Security:Acl:Enabled` (as the A3a visibility gate). Returns the + placement to dispatch through and that mapping's `ConditionMethodTimeoutMilliseconds`. +- **Dispatch (steps 4–5).** Bounded by a per-node semaphore (8; waiting counts against the budget, exhausted ⇒ + `BadTooManyOperations` unsent). Budget = min(request `OperationDeadline`, the mapping's method timeout). A fresh operation id + (`a3-`) per dispatch; **an identical call already in flight** (same caller, condition, EventId, method, comment) **joins** + it — one dispatch, the same answer. The port call is bounded by budget + 250 ms (`WaitAsync` + `CancelAfter`). The Runtime + addresses the origin with the placement, `expected_activation` = the latest applied marker, `expected_serving_incarnation` = + the serving identity of the CURRENT condition stream (`IDataSubscriptionProvenance`), `on_behalf_of` = the local principal, + through the deployed lease (`DataConnectionDeploymentLease` now implements `IDataConditionMethodService`: the row's + AlarmAcknowledge/AlarmConfirm bit else `UnauthorizedAccessException` ⇒ `BadUserAccessDenied`, unsent). No open condition stream + (connection down / never opened) ⇒ `BadNoCommunication`, nothing leased or sent. +- **No local apply.** Imported conditions keep their A3a `BadNotSupported` SDK handlers; nothing in the claimed path touches + node state. The node changes only when the origin's record arrives on the condition stream. +- **Outcome mapping (documented choice).** `DriverConfirmedSuccess` (scripted) / `AcceptedUnconfirmed` (native) ⇒ `Good` (the + client may see Good before the confirming event); `RejectedBeforeDispatch` ⇒ the origin's status (+ its diagnostic); + **`OutcomeUnknown` ⇒ `BadTimeout` when the budget elapsed, otherwise `BadCommunicationError`**, always with + "OutcomeUnknown: …" in the diagnostic and a Warning log. Chosen over an Uncertain code: Part 4 gives a Call result no + "maybe applied" Uncertain meaning, and an Uncertain-family status reads as success to most clients; a Bad status plus the + confirming (or absent) condition event is the honest answer. Never retried. +- **N6 re-binding** (`RebindImportedEventIds`). After a record that changed no state: a moved marker re-binds retained EventIds + only when the record's `time` equals the time they were bound under (F6); otherwise a fresh EventId bound to the new marker is + stamped on the node (what a ConditionRefresh now returns) and `RequireRefresh(connection)` is queued after the apply + (outside `Lock`). A condition whose first record reported no event gets one bound EventId. + +## A3a defects found by the live gate (fixed) + +1. **`ProjectedConditionAccess` logged to `NullLogger` in production** (DI passed no logger): the first live failure + (`a3b-cond-1`, nothing imported) left no trace. Now the host logger; plus Information logs for stream open (serving), a + refused item (Warning, status + diagnostic) and each snapshot barrier (statuses, record count, timeout). +2. **The UNS root item was refused `Denied`** (`a3b-cond-2`: `map-uns item refused by the origin (Denied)`, `map-raw` Complete, + 0 records). The item view was built from the anchor address with subject = the address identifier (an opaque EquipmentId); + the origin requires its own subject (`area/line/plc`). Now metadata is asked exactly as `RemoteNamespaceResolver` asks it + (subject = `RemoteRootEntityId`) and the item carries the origin's canonical view from the metadata answer. Pinned by + `The_condition_item_carries_the_origins_canonical_root_view_learned_from_metadata` (red with the item view reverted). + The A3a unit tests could not see either: their fake origin accepted any view. + +## Tests (A3b) + +| Project | Class | What | +|---|---|---| +| OI | `ImportedConditionMethodWireTests` (7, Phase=A3) | real SDK server + client sessions; the port fakes the origin: **once + join** (duplicate in-flight call joins, one dispatch, both Good; still unacked until the origin record; record ⇒ acked; a later call = new dispatch, fresh op id); **child Call** via the instance method id, denied caller `BadUserAccessDenied` unsent, re-gated per local caller, Acknowledge grant ≠ Confirm; **unknown / superseded EventId** `BadEventIdUnknown`, native Confirm + OneShotShelve `BadNotSupported`, all unsent, positive control carries the current marker; **N6** same-time resync re-binds, other-time resync ⇒ old EventId unknown + fresh ackable EventId; **L3 lock-freedom**; **mixed batch** (local native Ack through `base.Call` = Good + routed once + one local ack event, imported Ack dispatched, imported unchanged); **timeout** (300 ms mapping timeout ⇒ `BadTimeout` < 3 s, port cancelled, one dispatch), OutcomeUnknown ⇒ `BadCommunicationError`, refusal statuses passed through (`BadInvalidState`, `BadNoCommunication`), nothing applied | +| Runtime | `GrpcDataProjectedConditionMethodTests` (5, Phase=A3, manifest `A3`) | gate with a real `DataOperationPolicy` (AlarmAcknowledge ⇒ Ack/AddComment not Confirm; Subscribe-only ⇒ denied; mapping lacking the bit ⇒ denied; mapping timeout 4321 ms carried; unknown mapping/caller/null denied); no open stream ⇒ `BadNoCommunication`, never leased, nothing sent; call carries the stream's serving incarnation, placement, marker, op id, budget, on-behalf-of; OutcomeUnknown passed through; connection down after a stream end ⇒ `BadNoCommunication`, nothing sent; lease refusal ⇒ `BadUserAccessDenied` unsent; canonical root view | +| OI | `ImportedConditionMemoryMeasurementTests` (opt-in `OTOPCUA_A3_L2=1`, Category=Perf) | L2 harness | + +OI suites run outside the unit-phase runner (it accepts unit projects only), as for A3a. + +**Red-on-revert (each mutation built, run, restored; `git status` clean after):** + +| Mutation | Test | Result | +|---|---|---| +| M1: port call waited synchronously under `lock (Lock)` | L3 lock-freedom | **red** (the first Read/Browse waited out the 5 s stall: `ack.IsCompleted` already true) | +| M2: in-flight join disabled | once + join | **red** (joined count never 1) | +| M3: `AuthorizeMethod` verdict ignored | child Call gate | **red** (denied caller got Good) | +| M4: EventId marker check ignored | unknown/superseded EventId | **red** (superseded EventId accepted) | +| M5: mapping timeout ignored (30 s budget) | timeout | **red** (elapsed > 3 s) | +| M6: N6 re-bind disabled | re-binding | **red** (same-time resync EventId refused) | +| M7: `base.Call` skipped when anything is claimed | mixed batch | **red** (local Ack not Good) | +| R1: no-stream check removed (Runtime) | connection down | **red** | +| R2: mapping-bit check removed (Runtime) | gate | **red** | +| R3: item view reverted to the address-only view | canonical root view | **red** | +| native-Confirm check removed (not run) | — | expected **masked**: `supported_methods` of a native condition (Native = 3) lacks Confirm, a second layer refusing the same call `BadNotSupported` unsent | + +## L3 — lock-freedom (§9.3, hard gate) — PASS + +Measured by the OI wire test (in-process, real SDK server; the origin's method handler is stalled 5 s at the consumer's +`IProjectedConditionMethods` port — the consumer-side boundary, below which everything is the remote origin). 10 rounds of +concurrent Read (raw variable), Browse (Plant folder) and a data Publish (value write → client notification, publishing interval +20 ms) while the call is in flight, plus `Monitor.TryEnter(Lock)` from the test thread; `AckedState` asserted false after every +round; the origin record applied after release flips it (positive control). Three runs: + +| Run | Stall | Read max | Browse max | Data Publish max | `Lock` acquire max | Baseline (no stall) read / browse / publish | +|---|---|---|---|---|---|---| +| 1 | 5003 ms | 1.8 ms | 1.2 ms | 99.7 ms | 0.01 ms | 1.3 / 5.0 / 105.8 ms | +| 2 | 5003 ms | 1.9 ms | 6.3 ms | 98.6 ms | 0.01 ms | 1.3 / 4.6 / 107.7 ms | +| 3 | 5002 ms | 2.6 ms | 1.1 ms | 99.7 ms | 0.01 ms | 1.2 / 5.4 / 105.9 ms | + +All < 200 ms. The ~100 ms publish figure is the server's minimum publishing interval (identical without a stall), not a delay. +Deviation: the plan lists L3 as a docker-dev measurement; the live rig has no hook to stall the origin's handler, so the gate is +this deterministic in-process measurement (its mutation M1 proves it detects a `Lock` wait). + +## L2 — consumer memory, 1,000 imported conditions in one mapping (§9.3) — PASS + +In-process harness (`ImportedConditionMemoryMeasurementTests`, opt-in): a running SDK server, 1,000 conditions materialised through +the real `IProjectedConditionSink` (nodes + instance-scoped children, ids, registry + folder/notifier indexes, one more transition +each so every N6 EventId slot is used, the verdict cache exercised once per condition) plus the update records the runtime keeps per +key. Forced compacting GCs before/after. Three runs: + +| Run | Working-set growth | Managed heap growth | per condition (heap) | materialise / transition | +|---|---|---|---|---| +| 1 | +107.1 MiB | +197.4 MiB | 207,036 B | 605 / 80 ms | +| 2 | +106.2 MiB | +197.4 MiB | 207,029 B | 704 / 91 ms | +| 3 | +112.2 MiB | +197.4 MiB | 207,029 B | 747 / 77 ms | +| 4 (after-materialise split) | +106.8 MiB | +196.1 MiB | 205,665 B (204,612 after materialise alone) | 602 / 83 ms | + +Working-set growth ≤ 200 MiB: **PASS** (the heap grows more than the working set because the process had already committed GC +regions at baseline). Per the plan, `MaxImportedConditionBytes` is now set from the measurement: `BytesPerCondition` 160,997 → +**205,665** (the managed-heap figure, the larger of the two) and the default `DataConnections:MaxImportedConditionBytes` = +205,665 × 2,500 = **514,162,500 B (≈ 490 MiB)** (was 400 MiB). `MaxConditions` (1,000 per mapping) needs no lowering. +Nearly all of it is the SDK condition node + children (X0's node-only figure was 160,997); the A3b EventId registry adds ~1 KB. + +## Live — run `a3b-cond-3` (build `82ecc116`, clean tree) — PASS + +```bash +python3 scripts/validation/grpc-data/rig.py up --run-id a3b-cond-3 --conditions --timeout 1200 +python3 scripts/validation/grpc-data/rig.py seed --run-id a3b-cond-3 +# ~90 s for CONTROL's ClusterNode contact refresh +python3 scripts/validation/grpc-data/rig.py deploy --run-id a3b-cond-3 --timeout 300 +python3 scripts/validation/grpc-data/conditions_a3_smoke.py --run-id a3b-cond-3 +python3 scripts/validation/grpc-data/rig.py down --run-id a3b-cond-3 +``` + +The conditions profile now also makes the CONSUMER condition-bearing (connection + both mappings carry 64|128|256; ConfigDb +showed 479 on both). `conditions_a3_smoke.py` raises ScalarHigh, runs CLI `alarms --refresh` on the SOURCE Primary (origin's own +subscriber) and the CONSUMER Primary, acks through the consumer with CLI `ack`, then clears. + +| Item | Observed | Result | +|---|---|---| +| Consumer import | `stream 1 … opened (2 mapping(s), serving source-1:4053)`; barrier `map-raw=Complete, map-uns=Complete; 1 record(s)`; consumer CLI shows ScalarHigh Active/Unacknowledged with ConditionNodeId `ns=6;s=c1.…` (mapped/conditions) and a consumer EventId | PASS | +| Bogus EventId via the consumer | `Acknowledge failed: BadEventIdUnknown [0x809A0000]`; origin shows no ack | PASS | +| Ack via the consumer (CLI `ack`) | `Acknowledge successful` in 580 ms | PASS | +| Origin audit (source-1) | `Data-connection condition method Acknowledge by fixture-consumer (key …) on Uns:…:source-scalar-high op a3-1eabf280…: DriverConfirmedSuccess 0x00000000; on behalf of fixture-cli` — the service principal, the consumer's fresh op id, the local caller as on-behalf-of | PASS | +| Origin's own subscriber | ScalarHigh: Active/Unacknowledged, **exactly one Active/Acknowledged** | PASS | +| Consumer subscriber | Active/Unacknowledged, **exactly one Active/Acknowledged** (the origin's record re-imported) | PASS | +| Teardown | no run-labelled containers / networks left | — | + +Failed attempts (history): `a3b-cond-1` — nothing imported, no log (A3a defect 1); `a3b-cond-2` — map-uns Denied (A3a defect 2). +Each fix changed the image inputs, so each run was torn down and a fresh run id brought up. + +## Deviations / decisions (A3b) + +1. **EventIds retained: 32** (A3a's `RecentEventIds`), not the plan's "last N (default 8)"; validity is "minted for this condition + under the current marker", as §5.6 step 3 specifies. +2. **Consumer-side join of identical in-flight calls** (the brief's "duplicate call joins"): each dispatch has a fresh operation id + (the origin's own registry joins duplicates of an id); two identical local calls in flight share one dispatch. A repeat after + completion is a new dispatch (no retry, no stale join). +3. **Dispatch placement** = the first placement (primary order) the CALLER passes the method gate on, not unconditionally the + primary placement: a caller authorized only via a second mapping is addressed through that mapping's placement. +4. **`expected_serving_incarnation`** = the serving identity of the condition stream the records arrived on (no stream ⇒ + `BadNoCommunication`, unsent). A stream that does not expose provenance cannot be called through (production streams do). +5. **OutcomeUnknown ⇒ Bad** (`BadTimeout` / `BadCommunicationError`), see "Outcome mapping". +6. **The node manager enforces the mapping timeout itself** (budget + 250 ms grace around the port), so a port that never answers + cannot hold a request past it; the Runtime passes the budget to `GrpcDataConnection`, whose own ceiling still applies. +7. **L3 measured in-process** (see L3). **L2 measured in-process** (allowed by the brief). +8. Defaults changed at the A3 exit: `BytesPerCondition` 205,665, `MaxImportedConditionBytes` ≈ 490 MiB (L2). +9. Two A3a files were edited beyond A3b's seams because the live gate required it: the ProjectedConditionAccess DI logger and the + condition item root view (defects above); plus the per-condition `MethodGate` and N6 re-binding hook in `ApplyImported` / + `ReportImported` / `TryResolveImportedEvent`. + +## Open / follow-ups + +- RefreshRequired after an un-re-bindable resync goes to every item that may see the connection's conditions (A3a's + `RequireRefresh`), not only the affected mapping's notifiers. +- The A3a deviation 9 (explicit Primary endpoint for condition items) is still open; the live run happened to stream from the + Primary (source-1). + +## Gates (A3b, at `82ecc116`) + +| Gate | Result | +|---|---| +| `dotnet build ZB.MOM.WW.OtOpcUa.slnx --no-incremental` | 0 warnings, 0 errors | +| `run-unit-phase.py A3` (Runtime + OpcUaServer + Host) | passed (`20261124T225624…`) | +| `run-unit-phase.py A2` | passed (`20261124T225724…`) | +| `run-unit-phase.py A1` | passed (`20261124T225845…`) | +| `run-unit-phase.py X0` | passed (`20261124T230234…`) | +| Host.Tests `.DataConnections.` (both v1 gates) | 207 passed | +| Runtime.Tests full (`Category!=E2E&Category!=LiveIntegration`) | 2035 passed, 3 skipped (no #920 rerun needed) | +| OpcUaServer.Tests full (same filter) | 1455 passed, 1 skipped | +| OI `Feature=GrpcData` + ConditionMethodEvent / NativeAlarmEventIdentityFieldDelivery / FolderConditionRefresh / ConditionRefreshDeferral | 123 passed, 1 skipped (the opt-in L2 harness) | +| OI `ImportedConditionMethodWireTests` ×3 | 7/7 each | +| `git diff master -- '*Goldens.cs'` | empty | +| Live `a3b-cond-3` | PASS (above) | From 69aeeb770bee41910947e79585f15c406caaeced Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 18:38:07 -0500 Subject: [PATCH 21/32] =?UTF-8?q?fix(grpc-data):=20A3a=20review=20r1=20?= =?UTF-8?q?=E2=80=94=20buffered=20in-stream=20re-snapshots,=20late=20compl?= =?UTF-8?q?etion=20+=20stale-on-incomplete=20+=20bounded=20retry,=20Primar?= =?UTF-8?q?y-pinned=20condition=20streams,=20node-wide=20host-cap=20ledger?= =?UTF-8?q?,=20runner=20hand-over=20after=20stop,=20metadata=20failure=20U?= =?UTF-8?q?navailable;=20NM:=20revalidation=20through=20the=20imported=20g?= =?UTF-8?q?ate,=20demand=20released=20first,=20rebuild=20unwires,=20instan?= =?UTF-8?q?ce-keyed=20promotion,=20incremental=20folder=20index,=20verdict?= =?UTF-8?q?=20TTL=20+=20expiry,=20removal=20RefreshRequired,=20chunked=20r?= =?UTF-8?q?efresh/replay,=20folder-only=20demand?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Runtime tests: B1 multi-frame + capacity re-snapshot, B2 late completion / stale-on-incomplete / refused retry, B4 cross-connection / reverse order / records>total / delta growth, S3/S4 hand-over, S6, deviation 9, S2 IsActive generation; absence assertions now follow must-arrive controls. --- .../DataConnections/IDataServices.cs | 10 + .../IProjectedConditionAccess.cs | 8 + .../OtOpcUaNodeManager.cs | 15 +- .../ProjectedConditionRegistry.cs | 296 ++++++--- .../DataConnectionDeploymentRuntime.cs | 14 +- .../DataConnections/GrpcDataConnection.cs | 24 +- .../ProjectedConditionAccess.Runner.cs | 565 ++++++++++++++++++ .../ProjectedConditionAccess.cs | 440 ++------------ .../ImportedConditionEventWireTests.cs | 32 +- .../ImportedConditionClassifierTests.cs | 1 + .../GrpcDataProjectedConditionAccessTests.cs | 366 +++++++++++- 11 files changed, 1242 insertions(+), 529 deletions(-) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs index a46dafb16..f2c9c7f54 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs @@ -148,6 +148,16 @@ public interface IDataSubscriptionFreshnessSupport bool SupportsFreshnessChallenges { get; } int FreshnessMaxItems { get; } } +/// +/// A3 (review r1, deviation 9): a connection that can open a subscription served by the origin's Primary only — +/// condition items are served by the Primary (a Secondary advertises the feature but refuses the item, A2 N7), so the +/// consumer's condition stream must not land on a ReadyReplica Secondary the v1 value path would accept. +/// +public interface IDataPrimarySubscriptionSource +{ + /// Like , admitting only an endpoint whose serving role is Primary. + Task SubscribePrimaryAsync(CancellationToken cancellationToken); +} /// Immutable serving identity captured when the subscription was established. public interface IDataSubscriptionProvenance { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedConditionAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedConditionAccess.cs index 41613492d..6f3d6ee18 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedConditionAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedConditionAccess.cs @@ -48,6 +48,10 @@ public interface IProjectedConditionSink /// The connection is gone past its stale timeout: Quality = BadNoCommunication, one event each. void MarkConnectionStale(string connectionId); + /// Review r1 B2: these conditions' state is unknown (their mapping did not complete a snapshot) — + /// Quality = BadNoCommunication, one event each, never removed and never "known inactive". + void MarkConditionsStale(string connectionId, IReadOnlyCollection conditionKeys); + /// Sends RefreshRequiredEventType to every item that may see a condition of the connection. void RequireRefresh(string connectionId); } @@ -65,6 +69,10 @@ public interface IProjectedConditionAccess /// bool CanSee(RoleCarryingUserIdentity? caller, IReadOnlyList placements); + /// Deviation 3 (review r1): the mapping gate on one projected folder of a condition-bearing mapping — admits a + /// folder event item (and its demand) before any imported condition is wired there. + bool CanSubscribeFolder(RoleCarryingUserIdentity? caller, string mappingId, string folderLocalSubject); + /// A generation that moves whenever anything the gate reads may have changed (verdict caches key on it). long AuthorityGeneration { get; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index 973446e88..b6ee1ffda 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -5655,6 +5655,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage retiredProofs = _projectedSamples.Values.Select(sample => sample.Proof).Distinct().ToArray(); Volatile.Write(ref _committedProjectedDefinitions, _committedProjectedDefinitions.Clear()); foreach (var item in _liveItems.Keys.OfType()) item.Retire(); + UnwireAllImportedFolders(); // A3 review r1 S1: the folders go; their notifier wiring and promotion go with them foreach (var id in _projectedVariables.Keys) PredefinedNodes?.Remove(id); foreach (var id in _projectedAnchors.Keys) PredefinedNodes?.Remove(id); foreach (var (id, definition) in _projectedDefinitions) RetireProjectedCharge(id, definition.Lifetime); @@ -6576,6 +6577,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage if (unsubscribe) { + // A3 review r1 B3: the item's condition demand goes FIRST — both early returns below skip the base call, and a + // lease released only after them leaked (demand never reached 0, streams and conditions held forever). + TrackImportedDemand(monitoredItem, unsubscribe: true); + // An item RevalidateMonitoredItems stood down is ALREADY off its notifier's fan-out, and so is // one whose notifier a rebuild / surgical remove tombstoned (review 01 L2, TombstoneMonitoredNode). // Handing either delete to the SDK would make it remove an item that is not there — at best a @@ -6599,7 +6604,6 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage } } - TrackImportedDemand(monitoredItem, unsubscribe: true); return base.SubscribeToEvents(context, sourceId, subscriptionId, monitoredItem, unsubscribe); } @@ -8753,8 +8757,13 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage foreach (var (item, tracked) in _eventItems) { - var permitted = IsSubscriptionStillPermitted( - item.EffectiveIdentity as RoleCarryingUserIdentity, tracked.Handle.NodeId, verdicts); + // A3 review r1 B3: an item on a projected notifier was admitted through the imported gate, not Permits (which + // blanket-denies a mapped CreateMonitoredItems) — revalidate it through the same gate, or every admitted folder + // item is stood down on the next ACL tick or deploy. + var identity = item.EffectiveIdentity as RoleCarryingUserIdentity; + var permitted = IsProjectedEventNotifier(tracked.Handle.NodeId) + ? ImportedNotifierAdmits(identity, tracked.Handle.NodeId) + : IsSubscriptionStillPermitted(identity, tracked.Handle.NodeId, verdicts); if (permitted != tracked.Suppressed) continue; lock (Lock) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs index d701e278a..90a2eaf63 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs @@ -21,6 +21,8 @@ internal sealed class ImportedCondition(AlarmConditionState alarm, string connec public string ConditionKey { get; } = conditionKey; public IReadOnlyList Placements { get; set; } = []; public HashSet Folders { get; } = new(ReferenceEqualityComparer.Instance); + /// NIT (review r1): an immutable copy of for the delivery paths that read off Lock. + public FolderState[] WiredFolders { get; set; } = []; /// The last origin record applied (state known), re-applied with another Quality on staleness. public AlarmConditionSnapshot? Last { get; set; } /// The marker of the latest applied record. Written under (A3b reads it without Lock). @@ -64,10 +66,17 @@ internal sealed class ProjectedConditionRegistry private readonly ConcurrentDictionary _byInstance = new(ReferenceEqualityComparer.Instance); /// (mapping, folder local subject) → conditions placed there (wired or waiting for the folder to materialise). internal readonly Dictionary<(string Mapping, string Subject), HashSet> ByFolderKey = new(); - /// Projected folder node → conditions wired into it. - internal readonly Dictionary> WiredByFolder = new(); + /// Projected folder node → the folder INSTANCE promoted for it and the conditions wired into it (review r1 S1: a + /// re-created folder with the same NodeId is a different notifier and is promoted afresh). + internal readonly Dictionary Conditions)> WiredByFolder = new(); + /// Review r1 S5: (mapping, local subject) → projected folder NodeId, maintained incrementally (was a scan of every + /// projected node per apply chunk); resolved against the live projected maps at use. + internal readonly Dictionary<(string Mapping, string Subject), NodeId> FolderIds = new(); + internal readonly Dictionary FolderKeys = new(); + /// Review r1 S2: a positive verdict is re-proved at least this often (credential expiry is honoured exactly). + internal static readonly TimeSpan PositiveVerdictTtl = TimeSpan.FromSeconds(5); private readonly object _verdictGate = new(); - private readonly Dictionary<(object Identity, NodeId Condition), (long Generation, long PlacementVersion, bool Allowed)> _verdicts = new(); + private readonly Dictionary<(object Identity, NodeId Condition), (long Generation, long PlacementVersion, bool Allowed, DateTimeOffset ValidUntil)> _verdicts = new(); public int Count => _byNode.Count; public IEnumerable All => _byNode.Values; @@ -76,7 +85,7 @@ internal sealed class ProjectedConditionRegistry node is AlarmConditionState alarm && _byInstance.TryGetValue(alarm, out var c) ? c : null; public ImportedCondition? Find(NodeId id) => _byNode.TryGetValue(id, out var c) ? c : null; public bool IsWiredTo(ImportedCondition condition, NodeState notifier) => - notifier is FolderState folder && condition.Folders.Contains(folder) && _byInstance.ContainsKey(condition.Alarm); + notifier is FolderState folder && Array.IndexOf(condition.WiredFolders, folder) >= 0 && _byInstance.ContainsKey(condition.Alarm); public void Add(ImportedCondition condition) { @@ -96,20 +105,28 @@ internal sealed class ProjectedConditionRegistry public static (string, string) FolderKey(ImportedConditionPlacement p) => (p.MappingId, p.FolderLocalSubject); - /// The §5.4 verdict, cached per (identity, condition, authority generation, placement version). - public bool Verdict(object identity, ImportedCondition condition, long generation, Func compute) + /// + /// The §5.4 verdict, cached per (identity, condition, authority generation, placement version). Review r1 S2: a positive + /// verdict also carries the caller's credential expiry and a short TTL — a Server-object item has no other revalidation, + /// so an expired key (or anything the generation does not capture) is never served from cache past either. + /// + public bool Verdict(object identity, ImportedCondition condition, long generation, DateTimeOffset now, DateTimeOffset? credentialExpires, + Func compute) { var key = (identity, condition.Alarm.NodeId); lock (_verdictGate) { - if (_verdicts.TryGetValue(key, out var cached) && cached.Generation == generation && cached.PlacementVersion == condition.PlacementVersion) + if (_verdicts.TryGetValue(key, out var cached) && cached.Generation == generation && cached.PlacementVersion == condition.PlacementVersion + && now < cached.ValidUntil) return cached.Allowed; } var allowed = compute(); + var validUntil = !allowed ? DateTimeOffset.MaxValue + : credentialExpires is { } expires && expires < now + PositiveVerdictTtl ? expires : now + PositiveVerdictTtl; lock (_verdictGate) { if (_verdicts.Count >= 65_536) _verdicts.Clear(); // bounded: a flood of identities only costs recomputation - _verdicts[key] = (generation, condition.PlacementVersion, allowed); + _verdicts[key] = (generation, condition.PlacementVersion, allowed, validUntil); } return allowed; } @@ -173,7 +190,8 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink if (ProjectedConditionAccess is not { } access || identity is not RoleCarryingUserIdentity caller) return false; var generation = access.AuthorityGeneration; var placements = condition.Placements; - return _importedConditions.Verdict(caller, condition, generation, () => access.CanSee(caller, placements)); + return _importedConditions.Verdict(caller, condition, generation, DateTimeOffset.UtcNow, caller.CredentialExpiresUtc, + () => access.CanSee(caller, placements)); } /// The marker a queued imported event carries: re-checked at every Publish and Republish (§5.4). @@ -247,16 +265,15 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink { ArgumentNullException.ThrowIfNull(updates); EnsureAddressSpaceCreated(); - var refresh = new HashSet(StringComparer.OrdinalIgnoreCase); + var unbindable = new List(); for (var start = 0; start < updates.Count; start += ImportedApplyChunk) { lock (Lock) { if (_disposing) return; - var index = ProjectedFolderIndex(); for (var i = start; i < Math.Min(updates.Count, start + ImportedApplyChunk); i++) { - try { if (ApplyImported(updates[i], index)) refresh.Add(updates[i].ConnectionId); } + try { if (ApplyImported(updates[i]) is { } c) unbindable.Add(c); } catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or ServiceResultException) { _logger.LogWarning(ex, "OtOpcUaNodeManager: imported condition update refused (connection {Connection})", @@ -265,32 +282,49 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink } } } - // N6 (G4 step 3): a resync that left retained EventIds un-re-bindable ⇒ RefreshRequired, outside Lock. - foreach (var connectionId in refresh) RequireRefresh(connectionId); + // N6 (G4 step 3): a resync that left retained EventIds un-re-bindable ⇒ RefreshRequired, outside Lock — only to the + // items that may see one of THOSE conditions (A3b open item, review r1). + if (unbindable.Count > 0) QueueImportedRefresh(unbindable); } /// public void RemoveConditions(string connectionId, IReadOnlyCollection conditionKeys) { var keys = conditionKeys.ToArray(); + var removed = new List(); + var targets = new RefreshTargets(); for (var start = 0; start < keys.Length; start += ImportedApplyChunk) { lock (Lock) { + var chunk = new List(); foreach (var key in keys.Skip(start).Take(ImportedApplyChunk)) { if (!ImportedConditionIds.IsWellFormedConditionKey(key)) continue; - if (_importedConditions.Find(ImportedConditionNodeId(connectionId, key)) is { } c) RemoveImported(c); + if (_importedConditions.Find(ImportedConditionNodeId(connectionId, key)) is { } c) chunk.Add(c); } + // Deviation 6 (review r1): who may have been holding these conditions is captured BEFORE they are unwired. + CollectRefreshTargets(chunk, targets); + foreach (var c in chunk) RemoveImported(c); + removed.AddRange(chunk); } } + // §5.2 "removal + RefreshRequired": a client holding a removed (e.g. Active/Retain) condition is told to refresh, after + // which it no longer lists it. Outside Lock. + if (removed.Count > 0) QueueRefreshRequired(targets, removed); } /// - public void MarkConnectionStale(string connectionId) + public void MarkConnectionStale(string connectionId) => + MarkStale(_importedConditions.All.Where(c => string.Equals(c.ConnectionId, connectionId, StringComparison.OrdinalIgnoreCase)).ToList()); + + /// + public void MarkConditionsStale(string connectionId, IReadOnlyCollection conditionKeys) => + MarkStale(conditionKeys.Where(ImportedConditionIds.IsWellFormedConditionKey) + .Select(key => _importedConditions.Find(ImportedConditionNodeId(connectionId, key))).OfType().ToList()); + + private void MarkStale(List targets) { - List targets; - lock (Lock) targets = _importedConditions.All.Where(c => string.Equals(c.ConnectionId, connectionId, StringComparison.OrdinalIgnoreCase)).ToList(); for (var start = 0; start < targets.Count; start += ImportedApplyChunk) { lock (Lock) @@ -306,22 +340,62 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink } /// + /// + /// A connection with no materialised condition returns early: nothing of it can be held by a client (a removal tells + /// its own holders, captured before the removal — deviation 6, review r1). + /// public void RequireRefresh(string connectionId) { - List<(IEventMonitoredItem Item, bool Allowed)> targets = []; - lock (Lock) - { - var conditions = _importedConditions.All.Where(c => string.Equals(c.ConnectionId, connectionId, StringComparison.OrdinalIgnoreCase)).ToList(); - if (conditions.Count == 0) return; - var items = new HashSet(_allEventsItems.Keys, ReferenceEqualityComparer.Instance); - foreach (var folder in conditions.SelectMany(c => c.Folders).Distinct()) + var conditions = _importedConditions.All.Where(c => string.Equals(c.ConnectionId, connectionId, StringComparison.OrdinalIgnoreCase)).ToList(); + if (conditions.Count > 0) QueueImportedRefresh(conditions); + } + + /// Event items that may be holding imported conditions: the Server-object items, and each direct item with the + /// conditions wired at its notifier. + private sealed class RefreshTargets + { + public HashSet ServerItems { get; } = new(ReferenceEqualityComparer.Instance); + public Dictionary> Direct { get; } = new(ReferenceEqualityComparer.Instance); + } + + /// Under Lock: the items that may see (bounded by the caller's chunk). + private void CollectRefreshTargets(IReadOnlyList conditions, RefreshTargets targets) + { + if (conditions.Count == 0) return; + foreach (var item in _allEventsItems.Keys) targets.ServerItems.Add(item); + foreach (var c in conditions) + foreach (var folder in c.Folders) if (MonitoredNodes.TryGetValue(folder.NodeId, out var monitored) && monitored.EventMonitoredItems is { } attached) - foreach (var item in attached.Values) if (item is not null) items.Add(item); - foreach (var item in items) targets.Add((item, conditions.Any(c => ImportedVisibleTo(item, c)))); - } - foreach (var (item, allowed) in targets) + foreach (var item in attached.Values) + { + if (item is null) continue; + if (!targets.Direct.TryGetValue(item, out var list)) targets.Direct[item] = list = []; + list.Add(c); + } + } + + /// Review r1 S5: the targets are gathered in 128-condition Lock holds; visibility is decided off Lock. + private void QueueImportedRefresh(IReadOnlyList conditions) + { + var targets = new RefreshTargets(); + for (var start = 0; start < conditions.Count; start += ImportedApplyChunk) + { + var chunk = conditions.Skip(start).Take(ImportedApplyChunk).ToList(); + lock (Lock) CollectRefreshTargets(chunk, targets); + } + QueueRefreshRequired(targets, conditions); + } + + /// Off Lock: one RefreshRequired per item that may see at least one of the conditions (§5.4 gate). + private void QueueRefreshRequired(RefreshTargets targets, IReadOnlyList conditions) + { + var send = new List(); + foreach (var item in targets.ServerItems) + if (conditions.Any(c => ImportedVisibleTo(item, c))) send.Add(item); + foreach (var (item, candidates) in targets.Direct) + if (!targets.ServerItems.Contains(item) && candidates.Any(c => ImportedVisibleTo(item, c))) send.Add(item); + foreach (var item in send) { - if (!allowed) continue; var e = new RefreshRequiredEventState(null); e.Initialize(SystemContext, null, EventSeverity.Low, new LocalizedText("RefreshRequired")); e.SetChildValue(SystemContext, BrowseNames.SourceNode, ObjectIds.Server, false); @@ -335,8 +409,8 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink // Materialise / apply / remove (under Lock) // --------------------------------------------------------------------------------------------------------------------- - /// True when a resync left retained EventIds un-re-bindable (the caller queues RefreshRequired). - private bool ApplyImported(ImportedConditionUpdate update, Dictionary<(string, string), FolderState> folders) + /// The condition when a resync left its retained EventIds un-re-bindable (the caller queues RefreshRequired). + private ImportedCondition? ApplyImported(ImportedConditionUpdate update) { var state = update.State; if (update.Placements.Count == 0) throw new ArgumentException("An imported condition needs a placement.", nameof(update)); @@ -344,7 +418,7 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink if (state.Removed) { if (_importedConditions.Find(id) is { } gone) RemoveImported(gone); - return false; + return null; } var condition = _importedConditions.Find(id); @@ -375,12 +449,12 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink _importedConditions.Add(condition); } - UpdatePlacements(condition, update.Placements, folders); + UpdatePlacements(condition, update.Placements); if (condition.Alarm.SourceName is { } sourceName) sourceName.Value = update.SourceName; // display only; rides the next event if ((update.Info ?? state.Info) is { } listed) condition.SupportedMethods = listed.SupportedMethods; // §5.1 T2: a record with state_known = false never changes the consumer's last state. - if (!state.StateKnown) return false; + if (!state.StateKnown) return null; var snapshot = new AlarmConditionSnapshot(state.Active, state.Acknowledged, state.Confirmed, state.Enabled, Enum.IsDefined(typeof(AlarmShelvingKind), state.Shelving) ? (AlarmShelvingKind)state.Shelving : AlarmShelvingKind.Unshelved, (ushort)Math.Clamp(state.Severity, 1u, 1000u), state.Message ?? "", state.Quality, @@ -397,9 +471,9 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink if (ApplyConditionState(condition.Alarm, snapshot, ts)) { ReportImported(condition, ts); - return false; + return null; } - return RebindImportedEventIds(condition, previous, previousTime, state); + return RebindImportedEventIds(condition, previous, previousTime, state) ? condition : null; } /// Reports one imported event (stamping a consumer-minted EventId, N6) through the shared reporter. @@ -435,21 +509,15 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink // Notifier wiring (N7): lazy, symmetric // --------------------------------------------------------------------------------------------------------------------- - /// (mapping, local subject) → materialised projected folder (anchors included). One scan per apply batch. - private Dictionary<(string, string), FolderState> ProjectedFolderIndex() + /// (mapping, local subject) → the live materialised projected folder (anchors included), or null. Under Lock. + private FolderState? FindProjectedFolder((string Mapping, string Subject) key) { - var index = new Dictionary<(string, string), FolderState>(); - if (_importedConditions.ByFolderKey.Count == 0 && _projectedVariables.Count + _projectedAnchors.Count == 0) return index; - foreach (var anchor in _projectedAnchors.Values) - if (anchor.Node is FolderState folder) index.TryAdd((anchor.Definition.MappingId, anchor.Definition.LocalSubject), folder); - foreach (var entry in _projectedVariables.Values) - if (entry.Node is FolderState folder && entry.Metadata.View.MappingId is { } mapping) - index.TryAdd((mapping, entry.Metadata.View.Subject), folder); - return index; + if (!_importedConditions.FolderIds.TryGetValue(key, out var id)) return null; + if (_projectedAnchors.TryGetValue(id, out var anchor) && anchor.Node is FolderState a) return a; + return _projectedVariables.TryGetValue(id, out var entry) && entry.Node is FolderState f ? f : null; } - private void UpdatePlacements(ImportedCondition condition, IReadOnlyList placements, - Dictionary<(string, string), FolderState> folders) + private void UpdatePlacements(ImportedCondition condition, IReadOnlyList placements) { var before = condition.Placements.Select(ProjectedConditionRegistry.FolderKey).ToHashSet(); var after = placements.Select(ProjectedConditionRegistry.FolderKey).ToHashSet(); @@ -464,34 +532,45 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink set.Add(condition.Alarm.NodeId); } var desired = new HashSet(ReferenceEqualityComparer.Instance); - foreach (var key in after) if (folders.TryGetValue(key, out var f)) desired.Add(f); + foreach (var key in after) if (FindProjectedFolder(key) is { } f) desired.Add(f); foreach (var folder in condition.Folders.Where(f => !desired.Contains(f)).ToList()) UnwireImportedFolder(condition, folder); foreach (var folder in desired) WireImportedFolder(condition, folder); } private void WireImportedFolder(ImportedCondition condition, FolderState folder) { - if (!condition.Folders.Add(folder)) return; + if (condition.Folders.Contains(folder)) return; + if (_importedConditions.WiredByFolder.TryGetValue(folder.NodeId, out var entry) && !ReferenceEquals(entry.Folder, folder)) + { + // S1 backstop: a dead instance with this NodeId is still recorded — unwire it, then promote the new one. + foreach (var id in entry.Conditions.ToList()) + if (_importedConditions.Find(id) is { } stale) UnwireImportedFolder(stale, entry.Folder); + _importedConditions.WiredByFolder.Remove(folder.NodeId); + } + condition.Folders.Add(folder); + condition.WiredFolders = [.. condition.Folders]; condition.Alarm.AddNotifier(SystemContext, NodeId.Null, isInverse: true, folder); folder.AddNotifier(SystemContext, NodeId.Null, isInverse: false, condition.Alarm); - if (!_importedConditions.WiredByFolder.TryGetValue(folder.NodeId, out var wired)) + if (!_importedConditions.WiredByFolder.TryGetValue(folder.NodeId, out entry)) { - _importedConditions.WiredByFolder[folder.NodeId] = wired = []; + _importedConditions.WiredByFolder[folder.NodeId] = entry = (folder, []); // Projected folders are created with EventNotifier = None (NM projected page sink); promoted only while wired. folder.EventNotifier = (byte)(folder.EventNotifier | EventNotifiers.SubscribeToEvents); AddRootNotifier(folder); folder.ClearChangeMasks(SystemContext, includeChildren: false); } - wired.Add(condition.Alarm.NodeId); + entry.Conditions.Add(condition.Alarm.NodeId); condition.PlacementVersion++; } private void UnwireImportedFolder(ImportedCondition condition, FolderState folder) { if (!condition.Folders.Remove(folder)) return; + condition.WiredFolders = [.. condition.Folders]; condition.Alarm.RemoveNotifier(SystemContext, folder, bidirectional: true); condition.PlacementVersion++; - if (_importedConditions.WiredByFolder.TryGetValue(folder.NodeId, out var wired) && wired.Remove(condition.Alarm.NodeId) && wired.Count == 0) + if (_importedConditions.WiredByFolder.TryGetValue(folder.NodeId, out var entry) && ReferenceEquals(entry.Folder, folder) + && entry.Conditions.Remove(condition.Alarm.NodeId) && entry.Conditions.Count == 0) { _importedConditions.WiredByFolder.Remove(folder.NodeId); RemoveRootNotifier(folder); @@ -500,24 +579,33 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink } } - /// A projected folder (or anchor) materialised: wire every imported condition placed there (N7). Under Lock. + /// A projected folder (or anchor) materialised: index it and wire every imported condition placed there (N7). Under Lock. private void OnProjectedFolderMaterialised(FolderState folder, string mappingId, string localSubject) { + if (_importedConditions.FolderKeys.Remove(folder.NodeId, out var previous)) _importedConditions.FolderIds.Remove(previous); + _importedConditions.FolderIds[(mappingId, localSubject)] = folder.NodeId; + _importedConditions.FolderKeys[folder.NodeId] = (mappingId, localSubject); if (_importedConditions.Count == 0 || !_importedConditions.ByFolderKey.TryGetValue((mappingId, localSubject), out var set)) return; foreach (var id in set.ToList()) if (_importedConditions.Find(id) is { } c) WireImportedFolder(c, folder); } - /// A projected folder is being removed: unwire it symmetrically first (N7). Under Lock. + /// A projected folder is being removed: unwire it symmetrically first (N7) and drop it from the index. Under Lock. private void OnProjectedFolderRemoving(NodeId folderId) { - if (!_importedConditions.WiredByFolder.TryGetValue(folderId, out var wired)) return; - foreach (var id in wired.ToList()) - { - if (_importedConditions.Find(id) is not { } c) continue; - var folder = c.Folders.FirstOrDefault(f => f.NodeId == folderId); - if (folder is not null) UnwireImportedFolder(c, folder); - } + if (_importedConditions.FolderKeys.Remove(folderId, out var key)) _importedConditions.FolderIds.Remove(key); + if (!_importedConditions.WiredByFolder.TryGetValue(folderId, out var entry)) return; + foreach (var id in entry.Conditions.ToList()) + if (_importedConditions.Find(id) is { } c) UnwireImportedFolder(c, entry.Folder); + } + + /// Review r1 S1: a full rebuild discards every projected folder — unwire all of them (and clear the index) before + /// the maps are cleared, so a re-materialised folder is promoted and wired afresh. Under Lock. + private void UnwireAllImportedFolders() + { + foreach (var folderId in _importedConditions.WiredByFolder.Keys.ToList()) OnProjectedFolderRemoving(folderId); + _importedConditions.FolderIds.Clear(); + _importedConditions.FolderKeys.Clear(); } /// @@ -525,26 +613,36 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink /// mapping removal still removes it, unwiring first). Under Lock. /// private bool IsPinnedEventFolder(NodeId nodeId) => - _importedConditions.WiredByFolder.ContainsKey(nodeId) + (_importedConditions.WiredByFolder.ContainsKey(nodeId) || _importedConditions.FolderKeys.ContainsKey(nodeId)) && MonitoredNodes.TryGetValue(nodeId, out var monitored) && monitored.EventMonitoredItems is { Count: > 0 }; - /// A projected folder currently wired as a notifier of an imported condition (event items there are admitted, §5.4). + /// + /// A projected folder (or anchor) event items are admitted on through the verified path (§5.4): one wired as a notifier of + /// an imported condition, or — deviation 3, review r1 — any materialised projected folder, so a folder-only client can + /// open condition demand before any condition is wired there. + /// private bool IsProjectedEventNotifier(NodeId nodeId) { - if (_importedConditions.Count == 0) return false; - lock (Lock) return _importedConditions.WiredByFolder.ContainsKey(nodeId); + if (ProjectedConditionAccess is null) return false; + lock (Lock) return _importedConditions.WiredByFolder.ContainsKey(nodeId) || _importedConditions.FolderKeys.ContainsKey(nodeId); } - /// §5.4 admission of an event item on a projected notifier: the caller sees at least one condition wired there. + /// + /// §5.4 admission (and revalidation, review r1 B3) of an event item on a projected notifier: the caller sees at least one + /// condition wired there, or passes the mapping gate on the folder's own (mapping, local subject) placement key. + /// private bool ImportedNotifierAdmits(RoleCarryingUserIdentity? identity, NodeId notifierId) { - List wired; + List wired = []; + (string Mapping, string Subject)? key = null; lock (Lock) { - if (!_importedConditions.WiredByFolder.TryGetValue(notifierId, out var ids)) return false; - wired = ids.Select(_importedConditions.Find).OfType().ToList(); + if (_importedConditions.WiredByFolder.TryGetValue(notifierId, out var entry)) + wired = entry.Conditions.Select(_importedConditions.Find).OfType().ToList(); + if (_importedConditions.FolderKeys.TryGetValue(notifierId, out var folderKey)) key = folderKey; } - return wired.Any(c => ImportedVisibleTo(identity, c)); + if (wired.Any(c => ImportedVisibleTo(identity, c))) return true; + return key is { } k && identity is not null && ProjectedConditionAccess is { } access && access.CanSubscribeFolder(identity, k.Mapping, k.Subject); } /// @@ -585,33 +683,43 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink /// /// ConditionRefresh for imported conditions: every retained one the item may see, through the marked path. Server-object - /// items see all; a direct item only those wired to its notifier. One Lock hold (consistent with synchronous events). + /// items see all; a direct item only those wired to its notifier. Review r1 (deviation 8): chunked at + /// conditions per Lock hold; each condition's snapshot and its queueing happen in the + /// same hold (so its ordering against its live events holds), and one per condition + /// snapshot is shared by every item it is queued to (one projection, not one per item). /// private void ReplayImportedConditions(List serverItems, List directItems) { if (_importedConditions.Count == 0) return; - lock (Lock) + var all = _importedConditions.All.ToList(); + for (var start = 0; start < all.Count; start += ImportedApplyChunk) { - var retained = _importedConditions.All.Where(c => c.Alarm.Retain?.Value == true).ToList(); - if (retained.Count == 0) return; - var snapshots = new Dictionary(ReferenceEqualityComparer.Instance); - InstanceStateSnapshot SnapshotOf(ImportedCondition c) + lock (Lock) { - if (snapshots.TryGetValue(c, out var s)) return s; - s = new InstanceStateSnapshot(); - s.Initialize(SystemContext, c.Alarm); - return snapshots[c] = s; - } - foreach (var item in serverItems) - foreach (var c in retained) - if (ImportedVisibleTo(item, c) && !ServiceResult.IsBad(ValidateEventRolePermissions(item, c.Alarm))) - new EventDeliveryCache().QueueMarked(Server, item, SnapshotOf(c), i => ImportedMarker(i, c)); - foreach (var item in directItems) - { - if (!MonitoredItems.ContainsKey(item.Id) || (item.ManagerHandle as NodeHandle)?.Node is not FolderState notifier) continue; - foreach (var c in retained) - if (c.Folders.Contains(notifier) && ImportedVisibleTo(item, c) && !ServiceResult.IsBad(ValidateEventRolePermissions(item, c.Alarm))) - new EventDeliveryCache().QueueMarked(Server, item, SnapshotOf(c), i => ImportedMarker(i, c)); + var direct = directItems.Where(item => MonitoredItems.ContainsKey(item.Id)) + .Select(item => (Item: item, Notifier: (item.ManagerHandle as NodeHandle)?.Node as FolderState)) + .Where(x => x.Notifier is not null).ToList(); + for (var i = start; i < Math.Min(all.Count, start + ImportedApplyChunk); i++) + { + var c = all[i]; + if (!_importedConditions.IsLive(c.Alarm) || c.Alarm.Retain?.Value != true) continue; + InstanceStateSnapshot? snapshot = null; + EventDeliveryCache? cache = null; + void Queue(IEventMonitoredItem item) + { + if (!ImportedVisibleTo(item, c) || ServiceResult.IsBad(ValidateEventRolePermissions(item, c.Alarm))) return; + if (snapshot is null) + { + snapshot = new InstanceStateSnapshot(); + snapshot.Initialize(SystemContext, c.Alarm); + cache = new EventDeliveryCache(); + } + cache!.QueueMarked(Server, item, snapshot, x => ImportedMarker(x, c)); + } + foreach (var item in serverItems) Queue(item); + foreach (var (item, notifier) in direct) + if (c.Folders.Contains(notifier!)) Queue(item); + } } } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs index 6a2a904df..0ac48a0bc 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs @@ -524,7 +524,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable } /// A non-owning handle with the deployed operation and resource policy. -public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistoryService, IHistoryBatchLimit, IDataConditionMethodService, IDisposable +public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistoryService, IHistoryBatchLimit, IDataConditionMethodService, IDataPrimarySubscriptionSource, IDisposable { /// /// A3b: a remote condition method through the deployed connection — needs the row's AlarmAcknowledge / AlarmConfirm @@ -679,9 +679,17 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistor catch (Exception ex) when (ex is OperationCanceledException or InvalidOperationException or UnauthorizedAccessException) { return request.Items.Select(x => new WriteItemResult(x.CorrelationId, new(DataWriteState.OutcomeUnknown, 0x800A0000u, "Write outcome unknown after scope change."))).ToArray(); } } - public async Task SubscribeAsync(CancellationToken cancellationToken) + public Task SubscribeAsync(CancellationToken cancellationToken) => SubscribeCoreAsync(primaryOnly: false, cancellationToken); + + /// + public Task SubscribePrimaryAsync(CancellationToken cancellationToken) => SubscribeCoreAsync(primaryOnly: true, cancellationToken); + + private async Task SubscribeCoreAsync(bool primaryOnly, CancellationToken cancellationToken) { - Check(DataOperations.Subscribe); var stream = await _inner.SubscribeAsync(cancellationToken).ConfigureAwait(false); + Check(DataOperations.Subscribe); + var stream = primaryOnly && _inner is IDataPrimarySubscriptionSource primary + ? await primary.SubscribePrimaryAsync(cancellationToken).ConfigureAwait(false) + : await _inner.SubscribeAsync(cancellationToken).ConfigureAwait(false); try { Check(DataOperations.Subscribe); return stream is IDataSubscriptionProvenance provenance ? new ProvenancedScopedSubscription(this, stream, provenance.Serving) : new ScopedSubscription(this, stream); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs index 50b5624cc..301d6141a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs @@ -23,7 +23,7 @@ public interface IDataConnectionSecurityProvider public sealed record DataConnectionChannelIdentity(string ConnectionId, Uri Endpoint, string CredentialVersion, string TrustFingerprint); /// Caller-bound remote facade. All channels and requests are bounded by configured local limits. -public sealed partial class GrpcDataConnection : IDataConnection +public sealed partial class GrpcDataConnection : IDataConnection, IDataPrimarySubscriptionSource { private sealed class ChannelEntry(DataConnectionChannelIdentity identity, GrpcChannel channel, string bearer) { @@ -531,7 +531,14 @@ public sealed partial class GrpcDataConnection : IDataConnection actual == expected || actual.NodeId == expected.NodeId && actual.Incarnation == expected.Incarnation && results.Count > 0 && results.All(x => x.Outcome.State == DataWriteState.RejectedBeforeDispatch); - public async Task SubscribeAsync(CancellationToken cancellationToken) + public Task SubscribeAsync(CancellationToken cancellationToken) => SubscribeCoreAsync(primaryOnly: false, cancellationToken); + + /// + /// A3 review r1 (deviation 9): condition streams skip a ReadyReplica Secondary. An endpoint refused only for its + /// role is not a discovery failure (no probe backoff for the value path). + public Task SubscribePrimaryAsync(CancellationToken cancellationToken) => SubscribeCoreAsync(primaryOnly: true, cancellationToken); + + private async Task SubscribeCoreAsync(bool primaryOnly, CancellationToken cancellationToken) { EnterWork(); var reserved = false; @@ -546,11 +553,18 @@ public sealed partial class GrpcDataConnection : IDataConnection } var budget = new DataBudget(TimeSpan.FromSeconds(5), 1000, _maxMessageBytes); var start = Clock.GetTimestamp(); Exception? failure = null; + var roleOnly = primaryOnly; foreach (var endpoint in _endpoints) { try { var selected = await SelectAsync(endpoint, start, budget, false, cancellationToken).ConfigureAwait(false); + if (primaryOnly && !string.Equals(selected.Capabilities.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)) + { + failure = new InvalidOperationException("Endpoint is not the Primary."); + continue; + } + roleOnly = false; if ((selected.Capabilities.Operations & DataOperations.Subscribe) == 0 || Volatile.Read(ref _activeStreams) > selected.Capabilities.Limits.MaxStreams) throw new InvalidOperationException("Subscriptions unavailable or peer stream capacity exhausted."); @@ -593,10 +607,10 @@ public sealed partial class GrpcDataConnection : IDataConnection } } catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException) - { failure = ex; RecordFailure(ex); } + { failure = ex; RecordFailure(ex); roleOnly = false; } } - ProbeFailed(); - throw new InvalidOperationException("No ready subscription endpoint.", failure); + if (!roleOnly) ProbeFailed(); + throw new InvalidOperationException(roleOnly ? "No Primary subscription endpoint." : "No ready subscription endpoint.", failure); } finally { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs new file mode 100644 index 000000000..6372e1341 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs @@ -0,0 +1,565 @@ +using Microsoft.Extensions.Logging; +using ZB.MOM.WW.OtOpcUa.Commons.Observability; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +public sealed partial class ProjectedConditionAccess +{ + // ----------------------------------------------------------------------------------------------------------------- + // The node-wide host-cap ledger (review r1 B4) + // ----------------------------------------------------------------------------------------------------------------- + + /// + /// §5.5 host caps, node-wide: one ledger across every connection. A connection is charged + /// max(materialised keys, Σ mapping claims) — conditions are charged once per key, a mapping's claim is its + /// admitted snapshot total while it snapshots and its record count afterwards (so post-snapshot growth is charged), + /// and a re-snapshot of keys the connection already holds is not double-charged. Admission is order-independent: a + /// begin is decided against everything already charged or claimed, whichever connection or mapping arrived first. + /// + private sealed class ConditionLedger(ProjectedConditionOptions options) + { + private sealed class Entry + { + public int Materialised; + public readonly Dictionary Claims = new(StringComparer.OrdinalIgnoreCase); + public long Charge => Math.Max(Materialised, Claims.Values.Sum(x => (long)x)); + } + + private readonly object _gate = new(); + private readonly Dictionary _connections = new(StringComparer.OrdinalIgnoreCase); + + public long Total { get { lock (_gate) return TotalLocked(); } } + + private long TotalLocked() => _connections.Values.Sum(x => x.Charge); + + private bool Over(long conditions) => + conditions * ProjectedConditionOptions.NodesPerCondition > options.MaxImportedConditionNodes + || conditions * ProjectedConditionOptions.BytesPerCondition > options.MaxImportedConditionBytes; + + public bool HighWater(long conditions) => + conditions * ProjectedConditionOptions.NodesPerCondition > options.MaxImportedConditionNodes * 8L / 10; + + /// Sets a mapping's claim when the node total stays within both caps; otherwise leaves it unchanged. + public bool TryClaim(string connection, string mapping, int count, out long total) + { + lock (_gate) + { + if (!_connections.TryGetValue(connection, out var entry)) _connections[connection] = entry = new Entry(); + var had = entry.Claims.TryGetValue(mapping, out var previous); + entry.Claims[mapping] = count; + total = TotalLocked(); + if (!Over(total) || count <= previous) return true; + if (had) entry.Claims[mapping] = previous; else entry.Claims.Remove(mapping); + return false; + } + } + + public void Release(string connection, string mapping) + { + lock (_gate) if (_connections.TryGetValue(connection, out var entry)) entry.Claims.Remove(mapping); + } + + public void ResetClaims(string connection) + { + lock (_gate) if (_connections.TryGetValue(connection, out var entry)) entry.Claims.Clear(); + } + + public void SetMaterialised(string connection, int count) + { + lock (_gate) + { + if (!_connections.TryGetValue(connection, out var entry)) _connections[connection] = entry = new Entry(); + entry.Materialised = count; + if (count == 0 && entry.Claims.Count == 0) _connections.Remove(connection); + } + } + } + + // ----------------------------------------------------------------------------------------------------------------- + // One connection: one stream, one root item per condition-bearing mapping + // ----------------------------------------------------------------------------------------------------------------- + + /// One mapping's records: versions per key, the listed infos, and (for a snapshot buffer) the begin's total. + private sealed class ConditionSet(int total) + { + public int Total { get; } = total; + public Dictionary Records { get; } = new(StringComparer.Ordinal); + public Dictionary Infos { get; } = new(StringComparer.Ordinal); + public Dictionary Versions { get; } = new(StringComparer.Ordinal); + + /// The per-key version rule: a removal bypasses the gate and forgets the key (and its info). + public void Apply(DataConditionState record, HashSet? changed) + { + var key = record.ConditionKey; + if (record.Removed) + { + Records.Remove(key); Versions.Remove(key); Infos.Remove(key); + changed?.Add(key); + return; + } + if (record.Info is { } info) Infos[key] = info; + if (Versions.TryGetValue(key, out var last) && record.Version <= last) return; + Versions[key] = record.Version; + Records[key] = record; + changed?.Add(key); + } + } + + private sealed class MappingState(ProjectedMappingPlacement placement) + { + public ProjectedMappingPlacement Placement { get; } = placement; + public string MappingId => Placement.Mapping.RemoteNamespaceMappingId; + // The origin view of the remote root, built exactly as RemoteNamespaceResolver builds it (subject = the mapping's + // RemoteRootEntityId): a UNS root's address identifier is an opaque id, and the origin refuses a root item whose subject + // is not its own (live a3b-cond-2: map-uns item Denied). + public DataView Root { get; } = new(placement.Anchor.Address, placement.Mapping.Realm, null, 0, + string.IsNullOrWhiteSpace(placement.Mapping.RemoteRootEntityId) ? placement.Anchor.Address.Identifier : placement.Mapping.RemoteRootEntityId); + public string? RootSubject { get; set; } + /// The origin's canonical view of the remote root (from metadata): the root item must carry the origin's own + /// subject — a view built from the address alone (subject = identifier) is refused for an opaque-id UNS root. + public DataView? RootView { get; set; } + public ulong? Handle { get; set; } + public DataItemHandle? ItemHandle { get; set; } + public ProjectedConditionMappingStatus Status { get; set; } = ProjectedConditionMappingStatus.Pending; + /// The origin refused the item (or its metadata failed): nothing more arrives on this stream. + public bool Refused { get; set; } + /// The mapping's committed complete set in this stream (null until its first snapshot completes). + public ConditionSet? Live { get; set; } + /// Review r1 B1: a (re-)snapshot in progress, swapped in only at snapshot_complete. + public ConditionSet? Buffer { get; set; } + public bool Contributes => Live is not null && Status != ProjectedConditionMappingStatus.ConditionCapacity; + /// Whether the mapping's key set is known: listed (complete) or known-empty (over capacity). + public bool Known => Contributes || Status == ProjectedConditionMappingStatus.ConditionCapacity; + public int Claim => Math.Max(Buffer?.Total ?? 0, Live?.Records.Count ?? 0); + } + + private sealed class ConnectionRunner + { + private readonly ProjectedConditionAccess _owner; + private readonly ProjectedMappingPlacement[] _mappings; + private readonly CancellationTokenSource _stop = new(); + private readonly object _statusGate = new(); + private readonly object _staleGate = new(); + private readonly ConnectionRunner? _predecessor; + private Task _loop = Task.CompletedTask; + private Task _stopped = Task.CompletedTask; + private MappingState[] _states = []; + /// Keys currently materialised at the sink. Owned by the loop; handed over only after the predecessor stopped. + private HashSet _materialised = new(StringComparer.Ordinal); + private ITimer? _stale; + private long _staleGeneration; + private int _barriers; + private int _consecutiveRetries; + + public ConnectionRunner(ProjectedConditionAccess owner, string connectionId, ProjectedMappingPlacement[] mappings, string signature, + ConnectionRunner? predecessor) + { + _owner = owner; ConnectionId = connectionId; _mappings = mappings; Signature = signature; _predecessor = predecessor; + } + + public string ConnectionId { get; } + public string Signature { get; } + public int Barriers => Volatile.Read(ref _barriers); + private ServingIdentity? _serving; + /// A3b: the serving identity of the CURRENT condition stream (null while no stream is open). + public ServingIdentity? Serving => Volatile.Read(ref _serving); + + /// Completes once the loop ended and (for a removing stop) its conditions were removed. + public Task Stopped => _stopped; + + public IReadOnlyDictionary Statuses + { + get { lock (_statusGate) return _states.ToDictionary(x => x.MappingId, x => x.Status, StringComparer.OrdinalIgnoreCase); } + } + + public void Start() => _loop = Task.Run(async () => + { + if (_predecessor is { } previous) + { + // S3/S4: never overlap the previous runner of this connection — its in-flight Publish or its removal would + // otherwise race this runner's materialisation (an orphaned key, or a fresh key removed by the old continuation). + try { await previous.Stopped.ConfigureAwait(false); } catch (Exception ex) { _owner._log.LogDebug(ex, "Imported conditions: predecessor stop faulted"); } + _materialised = previous._materialised; + previous._materialised = new HashSet(StringComparer.Ordinal); + } + await RunAsync(_stop.Token).ConfigureAwait(false); + }); + + public void Stop(bool removeConditions) + { + _stop.Cancel(); + Volatile.Write(ref _serving, null); + lock (_staleGate) { _staleGeneration++; _stale?.Dispose(); _stale = null; } + _stopped = _loop.ContinueWith(_ => + { + if (!removeConditions) return; + var keys = _materialised.ToArray(); + if (keys.Length > 0 && _owner._sink() is { } sink) sink.RemoveConditions(ConnectionId, keys); + _materialised.Clear(); + _owner._ledger.ResetClaims(ConnectionId); + _owner._ledger.SetMaterialised(ConnectionId, 0); + }, TaskScheduler.Default); + } + + private async Task RunAsync(CancellationToken ct) + { + var epoch = 0L; + while (!ct.IsCancellationRequested) + { + epoch++; + try { await RunStreamAsync(epoch, ct).ConfigureAwait(false); } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; } + catch (Exception ex) + { + _owner._log.LogInformation(ex, "Imported conditions: stream for connection {Connection} ended; re-snapshotting", ConnectionId); + } + finally { Volatile.Write(ref _serving, null); } + // §5.5 lifetime rule: a stream end is "re-snapshot", never "conditions removed". Arm staleness instead. + ArmStale(); + OtOpcUaTelemetry.DataConnConditionResyncs.Add(1); + try { await Task.Delay(_owner._options.ReconnectDelay, _owner._clock, ct).ConfigureAwait(false); } + catch (OperationCanceledException) { return; } + } + } + + private void ArmStale() + { + lock (_staleGate) + { + if (_stale is not null || _materialised.Count == 0 || _stop.IsCancellationRequested) return; + var generation = _staleGeneration; + var timeout = TimeSpan.FromMilliseconds(Math.Max(1, _mappings.Min(x => x.Mapping.ConditionStaleTimeoutMilliseconds))); + _stale = _owner._clock.CreateTimer(_ => + { + // NIT (review r1): a callback already in flight cannot land after a fresh barrier — the barrier bumps the + // generation under the same gate this mark runs under, so it either waits for the mark or wins the check. + lock (_staleGate) + if (generation == _staleGeneration && !_stop.IsCancellationRequested) _owner._sink()?.MarkConnectionStale(ConnectionId); + }, null, timeout, Timeout.InfiniteTimeSpan); + } + } + + private void DisarmStale() + { + lock (_staleGate) { _staleGeneration++; _stale?.Dispose(); _stale = null; } + } + + private async Task RunStreamAsync(long epoch, CancellationToken ct) + { + var states = _mappings.Select(x => new MappingState(x)).ToArray(); + lock (_statusGate) _states = states; + _owner._ledger.ResetClaims(ConnectionId); + await using var lease = await _owner._connections.AcquireAsync(ConnectionId, ct).ConfigureAwait(false) + ?? throw new InvalidOperationException("Connection unavailable."); + using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, lease.CancellationToken); + var token = linked.Token; + var connection = lease.Connection; + // The remote root's origin subject: placement addresses are made relative to it (SourceName, folder subject). + // S6: a root whose metadata fails is Unavailable (its item is not opened — a root item without the origin's own + // view is refused, and placements made relative to a missing root subject would be wrong). + try + { + var budget = new DataBudget(TimeSpan.FromSeconds(10), Math.Max(1, states.Length), 1024 * 1024); + var metadata = await connection.GetMetadataAsync(new MetadataRequest(states.Select(x => x.Root).ToArray(), budget), token) + .ConfigureAwait(false); + for (var i = 0; i < states.Length; i++) + { + if (i < metadata.Count && metadata[i] is { Status: DataItemStatus.Good, Value: { } root }) + { + states[i].RootSubject = root.View.Subject; + states[i].RootView = root.View; + continue; + } + MarkRefused(states[i]); + _owner._log.LogWarning("Imported conditions: mapping {Mapping} root metadata unavailable ({Status}) — Unavailable, retried on a new stream", + states[i].MappingId, i < metadata.Count ? metadata[i].Status : DataItemStatus.Unavailable); + } + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + foreach (var state in states) MarkRefused(state); + _owner._log.LogWarning(ex, "Imported conditions: connection {Connection} root metadata failed — every mapping Unavailable", ConnectionId); + } + var open = states.Where(x => !x.Refused).ToArray(); + if (open.Length == 0) throw new InvalidOperationException("No condition-bearing mapping root resolved."); + + // Deviation 9: condition items are served by the origin's Primary only (a Secondary advertises but refuses, A2 N7). + await using var subscription = connection is IDataPrimarySubscriptionSource primary + ? await primary.SubscribePrimaryAsync(token).ConfigureAwait(false) + : await connection.SubscribeAsync(token).ConfigureAwait(false); + var serving = (subscription as IDataSubscriptionProvenance)?.Serving; + if (serving is not null && !string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)) + throw new InvalidOperationException($"Condition stream served by a {serving.Role} ({serving.NodeId}); conditions are pinned to the Primary."); + Volatile.Write(ref _serving, serving); + _owner._log.LogInformation("Imported conditions: stream {Epoch} for connection {Connection} opened ({Mappings} mapping(s), serving {Serving})", + epoch, ConnectionId, open.Length, Serving?.NodeId ?? "(no provenance)"); + var subscriptionId = "conditions-" + Guid.NewGuid().ToString("N"); + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); + var items = open.Select(x => new DataSubscriptionItem(x.MappingId, x.RootView ?? x.Root, settings, new DataConditionScope(IncludeInfo: true))).ToArray(); + await subscription.SendAsync(new OpenSubscription(subscriptionId, epoch, "open", TimeSpan.FromSeconds(30), items, false, + TimeSpan.FromMinutes(60), new DataBudget(TimeSpan.FromSeconds(30), 1000, 4 * 1024 * 1024)), token).ConfigureAwait(false); + + var snapshotTimeout = TimeSpan.FromMilliseconds(Math.Max(1, states.Max(x => x.Placement.Mapping.ConditionSnapshotTimeoutMilliseconds))); + var barrierPassed = false; + var timeout = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var barrierTimer = _owner._clock.CreateTimer(_ => timeout.TrySetResult(), null, snapshotTimeout, Timeout.InfiniteTimeSpan); + // B2: a mapping still Unavailable a bounded wait after the barrier ends the stream (a fresh stream retries it). + var retry = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + ITimer? retryTimer = null; + var context = new StreamContext(subscription, subscriptionId, epoch, token); + try + { + await using var frames = subscription.ReadAllAsync(token).GetAsyncEnumerator(token); + Task? next = null; + while (true) + { + if (!barrierPassed && timeout.Task.IsCompleted) + { + // ConditionSnapshotTimeoutMilliseconds: the incomplete mappings are Unavailable and the rest proceed; a + // late completion still swaps in and re-runs the merge (B2). + lock (_statusGate) + foreach (var s in states.Where(s => s.Status is ProjectedConditionMappingStatus.Pending or ProjectedConditionMappingStatus.Snapshotting)) + s.Status = ProjectedConditionMappingStatus.Unavailable; + barrierPassed = TryPassBarrier(states, timedOut: true); + } + if (barrierPassed) + { + var unavailable = states.Any(x => x.Status == ProjectedConditionMappingStatus.Unavailable); + if (retry.Task.IsCompleted && unavailable) + { + _consecutiveRetries++; + _owner._log.LogWarning("Imported conditions: connection {Connection} mapping(s) {Mappings} still Unavailable — ending the stream to retry", + ConnectionId, string.Join(", ", states.Where(x => x.Status == ProjectedConditionMappingStatus.Unavailable).Select(x => x.MappingId))); + return; + } + if (!unavailable) + { + retryTimer?.Dispose(); retryTimer = null; _consecutiveRetries = 0; + if (retry.Task.IsCompleted) retry = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + } + else if (retryTimer is null) + { + var wait = snapshotTimeout * Math.Min(1 << Math.Min(_consecutiveRetries, 3), 8); + var signal = retry; + retryTimer = _owner._clock.CreateTimer(_ => signal.TrySetResult(), null, wait, Timeout.InfiniteTimeSpan); + } + } + next ??= frames.MoveNextAsync().AsTask(); + if (!next.IsCompleted) + { + var wake = barrierPassed ? retry.Task : timeout.Task; + if (await Task.WhenAny(next, wake).ConfigureAwait(false) != next) continue; + } + if (!await next.ConfigureAwait(false)) return; + next = null; + var outcome = await ProcessAsync(frames.Current, states, context).ConfigureAwait(false); + if (!barrierPassed) { barrierPassed = TryPassBarrier(states, timedOut: false); continue; } + if (outcome.Changed.Count > 0 || outcome.Reconcile) Reconcile(states, outcome.Changed, outcome.Reconcile); + if (outcome.Refresh) _owner._sink()?.RequireRefresh(ConnectionId); + } + } + finally { retryTimer?.Dispose(); } + } + + private sealed record StreamContext(IDataSubscription Subscription, string SubscriptionId, long Epoch, CancellationToken Token); + + private sealed record FrameOutcome(HashSet Changed, bool Reconcile, bool Refresh); + + private void MarkRefused(MappingState state) + { + lock (_statusGate) + { + state.Refused = true; + if (state.Status != ProjectedConditionMappingStatus.ConditionCapacity) state.Status = ProjectedConditionMappingStatus.Unavailable; + } + } + + private bool TryPassBarrier(MappingState[] states, bool timedOut) + { + lock (_statusGate) + if (states.Any(x => x.Status is ProjectedConditionMappingStatus.Pending or ProjectedConditionMappingStatus.Snapshotting)) return false; + Interlocked.Increment(ref _barriers); + DisarmStale(); + var incomplete = states.Any(x => !x.Known); + _owner._log.LogInformation("Imported conditions: connection {Connection} snapshot barrier passed ({Statuses}; {Records} record(s){TimedOut})", + ConnectionId, string.Join(", ", states.Select(x => x.MappingId + "=" + x.Status)), states.Where(x => x.Contributes).Sum(x => x.Live!.Records.Count), + timedOut ? "; snapshot timed out" : ""); + Reconcile(states, states.Where(x => x.Contributes).SelectMany(x => x.Live!.Records.Keys).ToHashSet(StringComparer.Ordinal), full: true); + // S7: an incomplete (re)snapshot — a timeout OR a refused item — tells clients to refresh. + if (incomplete) _owner._sink()?.RequireRefresh(ConnectionId); + return true; + } + + private async Task ProcessAsync(DataSubscriptionFrame frame, MappingState[] states, StreamContext context) + { + var changed = new HashSet(StringComparer.Ordinal); + var reconcile = false; + var refresh = false; + switch (frame) + { + case DataSubscriptionAck ack: + foreach (var itemAck in ack.Items) + { + var state = states.FirstOrDefault(x => x.MappingId == itemAck.ClientItemId); + if (state is null) continue; + if (itemAck.Status == DataItemStatus.Good && itemAck.Handle is { } handle) + { + lock (_statusGate) { state.Handle = handle.Handle; state.ItemHandle = handle; } + continue; + } + MarkRefused(state); + _owner._log.LogWarning("Imported conditions: mapping {Mapping} item refused by the origin ({Status}: {Diagnostic})", + state.MappingId, itemAck.Status, itemAck.Diagnostic); + } + break; + case DataSubscriptionConditions conditions: + var mapping = states.FirstOrDefault(x => x.Handle == conditions.Handle.Handle); + if (mapping is null || mapping.Refused || mapping.Status == ProjectedConditionMappingStatus.ConditionCapacity) break; + var limit = mapping.Placement.Mapping.MaxConditions; + if (conditions.IsSnapshot && conditions.Total is { } total) + { + // A snapshot begin: decided before anything of it is materialised; buffered until snapshot_complete (B1), + // so the committed set (and what is materialised) is untouched while it streams. + if (total > limit || !_owner._ledger.TryClaim(ConnectionId, mapping.MappingId, Math.Max(total, mapping.Live?.Records.Count ?? 0), out var after)) + { + await ResetToCapacityAsync(mapping, total, total > limit ? "over its MaxConditions" : "would cross the host condition caps", + changed, context).ConfigureAwait(false); + reconcile = refresh = true; + break; + } + if (_owner._ledger.HighWater(after)) + _owner._log.LogWarning("Imported conditions: host condition budget above 80% ({Count} conditions)", after); + mapping.Buffer = new ConditionSet(total); + lock (_statusGate) + if (mapping.Live is null && mapping.Status == ProjectedConditionMappingStatus.Pending) mapping.Status = ProjectedConditionMappingStatus.Snapshotting; + } + foreach (var record in conditions.Items) + { + if (!ImportedConditionIds.IsWellFormedConditionKey(record.ConditionKey)) continue; + if (mapping.Live is { } live && !conditions.IsSnapshot) + { + // A delta: applied to the committed set (published) and to any buffer, so the swap is current. + live.Apply(record, changed); + mapping.Buffer?.Apply(record, null); + } + else mapping.Buffer?.Apply(record, null); + } + // B4: records past the begin's total or the mapping limit, or committed growth past the node-wide caps. + string? over = null; + if (mapping.Buffer is { } buffer && buffer.Records.Count > Math.Min(buffer.Total, limit)) over = "listed more records than its snapshot total"; + else if (mapping.Live is { } grown && grown.Records.Count > limit) over = "grew past its MaxConditions"; + else if (mapping.Live is not null && !_owner._ledger.TryClaim(ConnectionId, mapping.MappingId, mapping.Claim, out _)) over = "grew past the host condition caps"; + if (over is not null) + { + await ResetToCapacityAsync(mapping, mapping.Claim, over, changed, context).ConfigureAwait(false); + reconcile = refresh = true; + break; + } + if (conditions.SnapshotComplete && mapping.Buffer is { } done) + { + // The swap: old ∪ new keys are re-merged — a key only the old set listed is removed (if nothing else + // lists it and every mapping is known), every other key keeps its node. + if (mapping.Live is { } old) changed.UnionWith(old.Records.Keys); + changed.UnionWith(done.Records.Keys); + mapping.Live = done; + mapping.Buffer = null; + lock (_statusGate) mapping.Status = ProjectedConditionMappingStatus.Complete; + _owner._ledger.TryClaim(ConnectionId, mapping.MappingId, done.Records.Count, out _); // ≤ the admitted total + reconcile = true; + } + break; + } + return new FrameOutcome(changed, reconcile, refresh); + } + + /// §5.5 Unavailable(ConditionCapacity): the item is removed and the mapping contributes nothing (all-or-nothing). + private async Task ResetToCapacityAsync(MappingState mapping, int observed, string reason, HashSet changed, StreamContext context) + { + lock (_statusGate) mapping.Status = ProjectedConditionMappingStatus.ConditionCapacity; + if (mapping.Live is { } live) changed.UnionWith(live.Records.Keys); + mapping.Live = null; + mapping.Buffer = null; + _owner._ledger.Release(ConnectionId, mapping.MappingId); + OtOpcUaTelemetry.DataConnConditionCapacityRejections.Add(1); + _owner._log.LogWarning("Imported conditions: mapping {Mapping} ({Count} conditions) {Reason} (MaxConditions {Max}) — Unavailable(ConditionCapacity)", + mapping.MappingId, observed, reason, mapping.Placement.Mapping.MaxConditions); + // §5.5: the over-limit item is REMOVED (it costs an item slot and the origin's re-listing). + if (mapping.ItemHandle is { } handle) + await context.Subscription.SendAsync(new RemoveSubscriptionItems(context.SubscriptionId, context.Epoch, "remove-" + mapping.MappingId, + TimeSpan.FromSeconds(30), [handle]), context.Token).ConfigureAwait(false); + } + + /// + /// Publishes across the connection's committed sets. also re-diffs + /// everything materialised against the union (the barrier, a swap, a capacity reset, a late completion). + /// A key no contributing mapping lists is removed only when every mapping's set is known; while any is unknown + /// (Unavailable, not yet complete) it is kept with BadNoCommunication (unknown ≠ gone, §5.1 T2, B2). + /// + private void Reconcile(MappingState[] states, HashSet keys, bool full) + { + if (_owner._sink() is not { } sink) return; + if (full) + { + var listed = states.Where(x => x.Contributes).SelectMany(x => x.Live!.Records.Keys).ToHashSet(StringComparer.Ordinal); + foreach (var key in _materialised) if (!listed.Contains(key)) keys.Add(key); + } + var unknown = states.Any(x => !x.Known); + var updates = new List(); + var removals = new List(); + var stale = new List(); + foreach (var key in keys) + { + var update = Merge(states, key); + if (update is not null) { updates.Add(update); _materialised.Add(key); continue; } + if (!_materialised.Contains(key)) continue; + if (unknown) stale.Add(key); + else { _materialised.Remove(key); removals.Add(key); } + } + if (removals.Count > 0) sink.RemoveConditions(ConnectionId, removals); + if (stale.Count > 0) sink.MarkConditionsStale(ConnectionId, stale); + if (updates.Count > 0) sink.ApplyConditions(updates); + _owner._ledger.SetMaterialised(ConnectionId, _materialised.Count); + if (updates.Count + removals.Count + stale.Count > 0) + _owner._log.LogDebug("Imported conditions: connection {Connection} applied {Updates} update(s), {Removals} removal(s), {Stale} kept stale", + ConnectionId, updates.Count, removals.Count, stale.Count); + } + + /// One key across the connection's complete mappings: placements (primary first), latest record, SourceName. + private ImportedConditionUpdate? Merge(MappingState[] states, string key) + { + DataConditionState? latest = null; + DataConditionInfo? info = null; + var placements = new List<(int Order, ImportedConditionPlacement Placement)>(); + for (var i = 0; i < states.Length; i++) + { + var state = states[i]; + if (!state.Contributes || !state.Live!.Records.TryGetValue(key, out var record)) continue; + if (latest is null || record.Version > latest.Version) latest = record; + if (!state.Live.Infos.TryGetValue(key, out var placementInfo)) continue; + info ??= placementInfo; + foreach (var view in placementInfo.Placements.Where(p => p.Realm == state.Placement.Mapping.Realm) + .OrderBy(p => p.Address.Identifier, StringComparer.Ordinal)) + placements.Add((i, ToPlacement(state, view))); + } + if (latest is null || placements.Count == 0) return null; + var ordered = placements.OrderBy(x => x.Order).Select(x => x.Placement).ToArray(); + var primary = ordered[0]; + var anchor = states[placements.Min(x => x.Order)].Placement.Anchor.Subject; + return new ImportedConditionUpdate(ConnectionId, latest, info, ordered, anchor + "/" + primary.RelativePath); + } + + private static ImportedConditionPlacement ToPlacement(MappingState state, DataView view) + { + var relative = view.Subject; + if (state.RootSubject is { Length: > 0 } root && relative.StartsWith(root + "/", StringComparison.Ordinal)) + relative = relative[(root.Length + 1)..]; + var cut = relative.LastIndexOf('/'); + var anchor = state.Placement.Anchor.Subject; + var folder = cut < 0 ? anchor : anchor + "/" + relative[..cut]; + return new ImportedConditionPlacement(state.MappingId, state.Placement.Mapping.Realm, view, folder, relative); + } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs index 818300708..3aba37b2a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs @@ -95,6 +95,10 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess private readonly ILogger _log; private readonly object _gate = new(); private readonly Dictionary _runners = new(StringComparer.OrdinalIgnoreCase); + /// Review r1 S3/S4: a stopped runner's completion (its loop AND its removal) per connection; the next runner of + /// that connection awaits it before opening a stream or taking the materialised set, so the two never overlap. + private readonly Dictionary _stopping = new(StringComparer.OrdinalIgnoreCase); + private readonly ConditionLedger _ledger; private int _demand; private long _mappingVersion = 1; private ITimer? _linger; @@ -111,6 +115,7 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess _clock = clock ?? throw new ArgumentNullException(nameof(clock)); _options = options ?? ProjectedConditionOptions.Default; _log = logger ?? NullLogger.Instance; + _ledger = new ConditionLedger(_options); _mappings.Changed += OnMappingsChanged; } @@ -123,7 +128,16 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess == (DataOperations.Subscribe | DataOperations.AlarmSubscribe); /// - public long AuthorityGeneration => unchecked((Interlocked.Read(ref _mappingVersion) << 32) ^ _policy.AuthorityEpoch); + /// Review r1 S2: also folds each current mapping's Authority.IsActive, which flips without a deploy. + public long AuthorityGeneration + { + get + { + var active = 17L; + foreach (var mapping in _mappings.Current) active = unchecked(active * 31 + (mapping.Authority.IsActive ? 1 : 2)); + return unchecked((Interlocked.Read(ref _mappingVersion) << 32) ^ _policy.AuthorityEpoch ^ (active << 1)); + } + } /// public bool CanSee(RoleCarryingUserIdentity? caller, IReadOnlyList placements) @@ -132,20 +146,30 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc); var current = _mappings.Current; foreach (var placement in placements) - { - var mapping = current.FirstOrDefault(x => string.Equals(x.Mapping.RemoteNamespaceMappingId, placement.MappingId, StringComparison.OrdinalIgnoreCase)); - if (mapping is null || !mapping.Authority.IsActive || !IsConditionBearing(mapping.Mapping) || mapping.Mapping.Realm != placement.Realm) - continue; - if (!TryFolderScope(mapping, placement.FolderLocalSubject, out var scope)) continue; - try - { - if (_policy.AuthorizeLocal(identity, OpcUaOperation.CreateMonitoredItems, scope)) return true; - } - catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { } - } + if (Gate(identity, current, placement.MappingId, placement.Realm, placement.FolderLocalSubject)) return true; return false; } + /// + public bool CanSubscribeFolder(RoleCarryingUserIdentity? caller, string mappingId, string folderLocalSubject) + { + if (caller is null || string.IsNullOrWhiteSpace(caller.Principal)) return false; + var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc); + return Gate(identity, _mappings.Current, mappingId, null, folderLocalSubject); + } + + /// The mapping gate for one (mapping, folder) placement; null = the mapping's own. + private bool Gate(DataCallerIdentity identity, IReadOnlyList current, string mappingId, DataRealm? realm, + string folderLocalSubject) + { + var mapping = current.FirstOrDefault(x => string.Equals(x.Mapping.RemoteNamespaceMappingId, mappingId, StringComparison.OrdinalIgnoreCase)); + if (mapping is null || !mapping.Authority.IsActive || !IsConditionBearing(mapping.Mapping) || (realm is { } r && mapping.Mapping.Realm != r)) + return false; + if (!TryFolderScope(mapping, folderLocalSubject, out var scope)) return false; + try { return _policy.AuthorizeLocal(identity, OpcUaOperation.CreateMonitoredItems, scope); } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; } + } + /// The local scope of a placement's folder: the mapping's local scope plus the folder's path below the anchor. internal static bool TryFolderScope(ProjectedMappingPlacement mapping, string folderLocalSubject, out NodeScope scope) { @@ -190,8 +214,8 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess if (_disposed || _demand > 0) return; stopped = _runners.Values.ToList(); _runners.Clear(); + foreach (var runner in stopped) { runner.Stop(removeConditions: true); _stopping[runner.ConnectionId] = runner; } } - foreach (var runner in stopped) runner.Stop(removeConditions: true); } private void OnMappingsChanged() @@ -215,6 +239,7 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess { _runners.Remove(id, out var gone); gone!.Stop(removeConditions: true); + _stopping[id] = gone; } foreach (var (id, mappings) in byConnection) { @@ -226,7 +251,9 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess // notifiers and SourceName follow the new set at its barrier. running.Stop(removeConditions: false); } - var runner = new ConnectionRunner(this, id, mappings, signature, running?.TakeMaterialised()); + // S3/S4: the predecessor (still running or still removing) hands over only after it has fully stopped. + var predecessor = running ?? (_stopping.Remove(id, out var stopping) ? stopping : null); + var runner = new ConnectionRunner(this, id, mappings, signature, predecessor); _runners[id] = runner; runner.Start(); } @@ -246,6 +273,9 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess lock (_gate) return _runners.TryGetValue(connectionId, out var runner) ? runner.Statuses : null; } + /// Test/diagnostic observation: imported conditions charged against the node-wide host caps (review r1 B4). + public long ChargedConditions => _ledger.Total; + /// Test observation: whether a connection has an open runner. public bool IsRunning(string connectionId) { @@ -278,386 +308,4 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess private int _disposed; public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) owner.ReleaseDemand(); } } - - // ----------------------------------------------------------------------------------------------------------------- - // One connection: one stream, one root item per condition-bearing mapping - // ----------------------------------------------------------------------------------------------------------------- - - private sealed class MappingState(ProjectedMappingPlacement placement) - { - public ProjectedMappingPlacement Placement { get; } = placement; - public string MappingId => Placement.Mapping.RemoteNamespaceMappingId; - // The origin view of the remote root, built exactly as RemoteNamespaceResolver builds it (subject = the mapping's - // RemoteRootEntityId): a UNS root's address identifier is an opaque id, and the origin refuses a root item whose subject - // is not its own (live a3b-cond-2: map-uns item Denied). - public DataView Root { get; } = new(placement.Anchor.Address, placement.Mapping.Realm, null, 0, - string.IsNullOrWhiteSpace(placement.Mapping.RemoteRootEntityId) ? placement.Anchor.Address.Identifier : placement.Mapping.RemoteRootEntityId); - public string? RootSubject { get; set; } - /// The origin's canonical view of the remote root (from metadata): the root item must carry the origin's own - /// subject — a view built from the address alone (subject = identifier) is refused for an opaque-id UNS root. - public DataView? RootView { get; set; } - public ulong? Handle { get; set; } - public ProjectedConditionMappingStatus Status { get; set; } = ProjectedConditionMappingStatus.Pending; - public int Total { get; set; } - /// The mapping's current records by key (the complete snapshot, then deltas). - public Dictionary Records { get; } = new(StringComparer.Ordinal); - public Dictionary Infos { get; } = new(StringComparer.Ordinal); - public Dictionary Versions { get; } = new(StringComparer.Ordinal); - public bool Contributes => Status == ProjectedConditionMappingStatus.Complete; - } - - private sealed class ConnectionRunner - { - private readonly ProjectedConditionAccess _owner; - private readonly string _connectionId; - private readonly ProjectedMappingPlacement[] _mappings; - private readonly CancellationTokenSource _stop = new(); - private readonly object _statusGate = new(); - private Task _loop = Task.CompletedTask; - private MappingState[] _states = []; - /// Keys currently materialised at the sink (owned by the loop; handed over on a restart). - private HashSet _materialised; - private ITimer? _stale; - private int _barriers; - - public ConnectionRunner(ProjectedConditionAccess owner, string connectionId, ProjectedMappingPlacement[] mappings, string signature, - HashSet? materialised) - { - _owner = owner; _connectionId = connectionId; _mappings = mappings; Signature = signature; - _materialised = materialised ?? new HashSet(StringComparer.Ordinal); - } - - public string Signature { get; } - public int Barriers => Volatile.Read(ref _barriers); - private ServingIdentity? _serving; - /// A3b: the serving identity of the CURRENT condition stream (null while no stream is open). - public ServingIdentity? Serving => Volatile.Read(ref _serving); - - public IReadOnlyDictionary Statuses - { - get { lock (_statusGate) return _states.ToDictionary(x => x.MappingId, x => x.Status, StringComparer.OrdinalIgnoreCase); } - } - - public void Start() => _loop = Task.Run(() => RunAsync(_stop.Token)); - - public HashSet TakeMaterialised() - { - var taken = _materialised; - _materialised = new HashSet(StringComparer.Ordinal); - return taken; - } - - public void Stop(bool removeConditions) - { - _stop.Cancel(); - Volatile.Write(ref _serving, null); - _stale?.Dispose(); - if (!removeConditions) return; - _ = _loop.ContinueWith(_ => - { - var keys = _materialised.ToArray(); - if (keys.Length > 0 && _owner._sink() is { } sink) sink.RemoveConditions(_connectionId, keys); - _materialised.Clear(); - }, TaskScheduler.Default); - } - - private async Task RunAsync(CancellationToken ct) - { - var epoch = 0L; - while (!ct.IsCancellationRequested) - { - epoch++; - try { await RunStreamAsync(epoch, ct).ConfigureAwait(false); } - catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; } - catch (Exception ex) - { - _owner._log.LogInformation(ex, "Imported conditions: stream for connection {Connection} ended; re-snapshotting", _connectionId); - } - finally { Volatile.Write(ref _serving, null); } - // §5.5 lifetime rule: a stream end is "re-snapshot", never "conditions removed". Arm staleness instead. - ArmStale(); - OtOpcUaTelemetry.DataConnConditionResyncs.Add(1); - try { await Task.Delay(_owner._options.ReconnectDelay, _owner._clock, ct).ConfigureAwait(false); } - catch (OperationCanceledException) { return; } - } - } - - private void ArmStale() - { - if (_stale is not null || _materialised.Count == 0) return; - var timeout = TimeSpan.FromMilliseconds(Math.Max(1, _mappings.Min(x => x.Mapping.ConditionStaleTimeoutMilliseconds))); - _stale = _owner._clock.CreateTimer(_ => - { - if (!_stop.IsCancellationRequested) _owner._sink()?.MarkConnectionStale(_connectionId); - }, null, timeout, Timeout.InfiniteTimeSpan); - } - - private void DisarmStale() - { - _stale?.Dispose(); - _stale = null; - } - - private async Task RunStreamAsync(long epoch, CancellationToken ct) - { - var states = _mappings.Select(x => new MappingState(x)).ToArray(); - lock (_statusGate) _states = states; - await using var lease = await _owner._connections.AcquireAsync(_connectionId, ct).ConfigureAwait(false) - ?? throw new InvalidOperationException("Connection unavailable."); - using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, lease.CancellationToken); - var token = linked.Token; - var connection = lease.Connection; - // The remote root's origin subject: placement addresses are made relative to it (SourceName, folder subject). - try - { - var budget = new DataBudget(TimeSpan.FromSeconds(10), Math.Max(1, states.Length), 1024 * 1024); - var metadata = await connection.GetMetadataAsync(new MetadataRequest(states.Select(x => x.Root).ToArray(), budget), token) - .ConfigureAwait(false); - for (var i = 0; i < states.Length && i < metadata.Count; i++) - if (metadata[i] is { Status: DataItemStatus.Good, Value: { } root }) - { - states[i].RootSubject = root.View.Subject; - states[i].RootView = root.View; - } - } - catch (Exception ex) when (ex is not OperationCanceledException) { } - - await using var subscription = await connection.SubscribeAsync(token).ConfigureAwait(false); - Volatile.Write(ref _serving, (subscription as IDataSubscriptionProvenance)?.Serving); - _owner._log.LogInformation("Imported conditions: stream {Epoch} for connection {Connection} opened ({Mappings} mapping(s), serving {Serving})", - epoch, _connectionId, states.Length, Serving?.NodeId ?? "(no provenance)"); - var subscriptionId = "conditions-" + Guid.NewGuid().ToString("N"); - var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); - var items = states.Select(x => new DataSubscriptionItem(x.MappingId, x.RootView ?? x.Root, settings, new DataConditionScope(IncludeInfo: true))).ToArray(); - await subscription.SendAsync(new OpenSubscription(subscriptionId, epoch, "open", TimeSpan.FromSeconds(30), items, false, - TimeSpan.FromMinutes(60), new DataBudget(TimeSpan.FromSeconds(30), 1000, 4 * 1024 * 1024)), token).ConfigureAwait(false); - - var snapshotTimeout = TimeSpan.FromMilliseconds(Math.Max(1, states.Max(x => x.Placement.Mapping.ConditionSnapshotTimeoutMilliseconds))); - var barrierPassed = false; - _timedOut = false; - var timeout = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - using var barrierTimer = _owner._clock.CreateTimer(_ => - { - // ConditionSnapshotTimeoutMilliseconds: the incomplete mappings are Unavailable and the rest proceed. - lock (_statusGate) - foreach (var s in states.Where(s => s.Status is ProjectedConditionMappingStatus.Pending or ProjectedConditionMappingStatus.Snapshotting)) - s.Status = ProjectedConditionMappingStatus.Unavailable; - _timedOut = true; - timeout.TrySetResult(); - }, null, snapshotTimeout, Timeout.InfiniteTimeSpan); - - await using var frames = subscription.ReadAllAsync(token).GetAsyncEnumerator(token); - Task? next = null; - while (true) - { - next ??= frames.MoveNextAsync().AsTask(); - if (!barrierPassed && !timeout.Task.IsCompleted - && await Task.WhenAny(next, timeout.Task).ConfigureAwait(false) != next) - { - barrierPassed = TryPassBarrier(states); - continue; - } - if (!barrierPassed && timeout.Task.IsCompleted && !next.IsCompleted) - { - barrierPassed = TryPassBarrier(states); - if (!barrierPassed) { await next.ConfigureAwait(false); } - else continue; - } - if (!await next.ConfigureAwait(false)) return; - next = null; - var changed = await ProcessAsync(frames.Current, states, subscription, subscriptionId, epoch, token).ConfigureAwait(false); - if (!barrierPassed) { barrierPassed = TryPassBarrier(states); continue; } - if (changed.Count > 0) Publish(states, changed); - } - } - - private bool TryPassBarrier(MappingState[] states) - { - lock (_statusGate) - if (states.Any(x => x.Status is ProjectedConditionMappingStatus.Pending or ProjectedConditionMappingStatus.Snapshotting)) return false; - Interlocked.Increment(ref _barriers); - DisarmStale(); - _owner._log.LogInformation("Imported conditions: connection {Connection} snapshot barrier passed ({Statuses}; {Records} record(s){TimedOut})", - _connectionId, string.Join(", ", states.Select(x => x.MappingId + "=" + x.Status)), states.Where(x => x.Contributes).Sum(x => x.Records.Count), - _timedOut ? "; snapshot timed out" : ""); - PassBarrier(states); - if (_timedOut) _owner._sink()?.RequireRefresh(_connectionId); // an incomplete (re)snapshot - return true; - } - - private async Task> ProcessAsync(DataSubscriptionFrame frame, MappingState[] states, IDataSubscription subscription, - string subscriptionId, long epoch, CancellationToken token) - { - var changed = new HashSet(StringComparer.Ordinal); - switch (frame) - { - case DataSubscriptionAck ack: - foreach (var itemAck in ack.Items) - { - var state = states.FirstOrDefault(x => x.MappingId == itemAck.ClientItemId); - if (state is null) continue; - lock (_statusGate) - { - if (itemAck.Status == DataItemStatus.Good && itemAck.Handle is { } handle) state.Handle = handle.Handle; - else if (state.Status != ProjectedConditionMappingStatus.ConditionCapacity) state.Status = ProjectedConditionMappingStatus.Unavailable; - } - if (itemAck.Status != DataItemStatus.Good) - _owner._log.LogWarning("Imported conditions: mapping {Mapping} item refused by the origin ({Status}: {Diagnostic})", - state.MappingId, itemAck.Status, itemAck.Diagnostic); - } - break; - case DataSubscriptionConditions conditions: - var mapping = states.FirstOrDefault(x => x.Handle == conditions.Handle.Handle); - if (mapping is null || mapping.Status is ProjectedConditionMappingStatus.Unavailable or ProjectedConditionMappingStatus.ConditionCapacity) break; - if (conditions.IsSnapshot && conditions.Total is { } total) - { - if (!Admit(mapping, total, states)) - { - // §5.5: the over-limit item is REMOVED (it costs an item slot and the origin's re-listing). - await subscription.SendAsync(new RemoveSubscriptionItems(subscriptionId, epoch, "remove-" + mapping.MappingId, - TimeSpan.FromSeconds(30), [conditions.Handle]), token).ConfigureAwait(false); - foreach (var key in mapping.Records.Keys) changed.Add(key); - mapping.Records.Clear(); - break; - } - // A snapshot begin bypasses the version gate: it resets every key. - foreach (var key in mapping.Records.Keys) changed.Add(key); - mapping.Records.Clear(); mapping.Versions.Clear(); - lock (_statusGate) mapping.Status = ProjectedConditionMappingStatus.Snapshotting; - } - foreach (var record in conditions.Items) - { - if (!ImportedConditionIds.IsWellFormedConditionKey(record.ConditionKey)) continue; - if (record.Info is { } info) mapping.Infos[record.ConditionKey] = info; - if (record.Removed) - { - // A removal is applied unconditionally and forgets the key's version. - mapping.Records.Remove(record.ConditionKey); - mapping.Versions.Remove(record.ConditionKey); - changed.Add(record.ConditionKey); - continue; - } - if (mapping.Versions.TryGetValue(record.ConditionKey, out var last) && record.Version <= last) continue; - mapping.Versions[record.ConditionKey] = record.Version; - mapping.Records[record.ConditionKey] = record; - changed.Add(record.ConditionKey); - } - if (conditions.SnapshotComplete) - lock (_statusGate) mapping.Status = ProjectedConditionMappingStatus.Complete; - break; - } - return changed; - } - - private volatile bool _timedOut; - - /// §5.5 admission at snapshot begin: the mapping limit, then the host caps (deployed order). - private bool Admit(MappingState mapping, int total, MappingState[] states) - { - mapping.Total = total; - if (total > mapping.Placement.Mapping.MaxConditions) - { - lock (_statusGate) mapping.Status = ProjectedConditionMappingStatus.ConditionCapacity; - OtOpcUaTelemetry.DataConnConditionCapacityRejections.Add(1); - _owner._log.LogWarning("Imported conditions: mapping {Mapping} lists {Total} conditions, over its MaxConditions {Max} — Unavailable(ConditionCapacity)", - mapping.MappingId, total, mapping.Placement.Mapping.MaxConditions); - return false; - } - // Host caps: conditions are charged once per key; before materialising, `total` is the bound. Mappings earlier in - // deployed order are charged first. - long charged = 0; - foreach (var other in states) - { - if (ReferenceEquals(other, mapping)) break; - if (other.Status is ProjectedConditionMappingStatus.Snapshotting or ProjectedConditionMappingStatus.Complete) charged += other.Total; - } - var after = charged + total; - if (after * ProjectedConditionOptions.NodesPerCondition > _owner._options.MaxImportedConditionNodes - || after * ProjectedConditionOptions.BytesPerCondition > _owner._options.MaxImportedConditionBytes) - { - lock (_statusGate) mapping.Status = ProjectedConditionMappingStatus.ConditionCapacity; - OtOpcUaTelemetry.DataConnConditionCapacityRejections.Add(1); - _owner._log.LogWarning("Imported conditions: mapping {Mapping} ({Total}) would cross the host condition caps — Unavailable(ConditionCapacity)", - mapping.MappingId, total); - return false; - } - if (after * ProjectedConditionOptions.NodesPerCondition > _owner._options.MaxImportedConditionNodes * 8L / 10) - _owner._log.LogWarning("Imported conditions: host condition budget above 80% ({Count} conditions)", after); - return true; - } - - /// The barrier: materialise the union; a key the previous materialisation held but this complete set lacks is removed. - private void PassBarrier(MappingState[] states) - { - var keys = states.Where(x => x.Contributes).SelectMany(x => x.Records.Keys).ToHashSet(StringComparer.Ordinal); - var gone = _materialised.Where(k => !keys.Contains(k)).ToArray(); - // Only a key no complete mapping lists is removed; a key of a mapping that did not complete is kept (unknown ≠ gone). - var incomplete = states.Any(x => !x.Contributes && x.Status != ProjectedConditionMappingStatus.ConditionCapacity); - if (gone.Length > 0 && !incomplete && _owner._sink() is { } sink) - { - sink.RemoveConditions(_connectionId, gone); - foreach (var key in gone) _materialised.Remove(key); - } - Publish(states, keys); - } - - private void Publish(MappingState[] states, IEnumerable keys) - { - if (_owner._sink() is not { } sink) return; - var updates = new List(); - var removals = new List(); - foreach (var key in keys) - { - var update = Merge(states, key); - if (update is null) - { - _owner._log.LogWarning("Imported conditions: connection {Connection} key has no placement in a complete mapping (not materialised)", _connectionId); - if (_materialised.Remove(key)) removals.Add(key); - continue; - } - updates.Add(update); - _materialised.Add(key); - } - if (removals.Count > 0) sink.RemoveConditions(_connectionId, removals); - if (updates.Count > 0) sink.ApplyConditions(updates); - if (updates.Count + removals.Count > 0) - _owner._log.LogDebug("Imported conditions: connection {Connection} applied {Updates} update(s), {Removals} removal(s)", - _connectionId, updates.Count, removals.Count); - } - - /// One key across the connection's complete mappings: placements (primary first), latest record, SourceName. - private ImportedConditionUpdate? Merge(MappingState[] states, string key) - { - DataConditionState? latest = null; - DataConditionInfo? info = null; - var placements = new List<(int Order, ImportedConditionPlacement Placement)>(); - for (var i = 0; i < states.Length; i++) - { - var state = states[i]; - if (!state.Contributes || !state.Records.TryGetValue(key, out var record)) continue; - if (latest is null || record.Version > latest.Version) latest = record; - if (state.Infos.TryGetValue(key, out var stateInfo)) info ??= stateInfo; - if (!state.Infos.TryGetValue(key, out var placementInfo)) continue; - foreach (var view in placementInfo.Placements.Where(p => p.Realm == state.Placement.Mapping.Realm) - .OrderBy(p => p.Address.Identifier, StringComparer.Ordinal)) - placements.Add((i, ToPlacement(state, view))); - } - if (latest is null || placements.Count == 0) return null; - var ordered = placements.OrderBy(x => x.Order).Select(x => x.Placement).ToArray(); - var primary = ordered[0]; - var anchor = states[placements.Min(x => x.Order)].Placement.Anchor.Subject; - return new ImportedConditionUpdate(_connectionId, latest, info, ordered, anchor + "/" + primary.RelativePath); - } - - private static ImportedConditionPlacement ToPlacement(MappingState state, DataView view) - { - var relative = view.Subject; - if (state.RootSubject is { Length: > 0 } root && relative.StartsWith(root + "/", StringComparison.Ordinal)) - relative = relative[(root.Length + 1)..]; - var cut = relative.LastIndexOf('/'); - var anchor = state.Placement.Anchor.Subject; - var folder = cut < 0 ? anchor : anchor + "/" + relative[..cut]; - return new ImportedConditionPlacement(state.MappingId, state.Placement.Mapping.Realm, view, folder, relative); - } - } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionEventWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionEventWireTests.cs index e53f52577..05364b43b 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionEventWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionEventWireTests.cs @@ -321,10 +321,21 @@ public sealed class ImportedConditionEventWireTests public bool CanSee(RoleCarryingUserIdentity? caller, IReadOnlyList placements) => caller is not null && Allowed.Contains(caller.Principal); public long AuthorityGeneration => Interlocked.Read(ref Generation); + public bool CanSubscribeFolder(RoleCarryingUserIdentity? caller, string mappingId, string folderLocalSubject) => + caller is not null && Allowed.Contains(caller.Principal); + /// Leases currently held (acquired minus released). + public int Outstanding; public IDisposable? AcquireEventDemand(RoleCarryingUserIdentity? caller) { Interlocked.Increment(ref Demands); - return null; + Interlocked.Increment(ref Outstanding); + return new Lease(this); + } + + private sealed class Lease(FakeConditionAccess owner) : IDisposable + { + private int _disposed; + public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) Interlocked.Decrement(ref owner.Outstanding); } } } @@ -340,7 +351,18 @@ public sealed class ImportedConditionEventWireTests public static Fixture Install(ServerEventRig rig, string grantedPrincipal) { - var nm = rig.Nm; + var (anchor, anchorB, device, definition) = Materialise(rig.Nm); + var access = new FakeConditionAccess(); + access.Allowed.Add(grantedPrincipal); + rig.Nm.ProjectedConditionAccess = access; + return new Fixture { Rig = rig, Access = access, Anchor = anchor, AnchorB = anchorB, DeviceFolder = device, DeviceDefinition = definition }; + } + + /// Re-creates the same projected folders (new instances, same NodeIds) — e.g. after a full rebuild. + public void Rematerialise() => Materialise(Rig.Nm); + + private static (NodeId Anchor, NodeId AnchorB, NodeId Device, ProjectedVariableDefinition Definition) Materialise(OtOpcUaNodeManager nm) + { nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); var parent = nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; var rootA = new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant"); @@ -355,11 +377,7 @@ public sealed class ImportedConditionEventWireTests var definition = new ProjectedVariableDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(MappingA, devAddress), anchor!.Value, metadata, 1, () => true); nm.TryEnsureProjectedVariable(definition, out var device).ShouldBeTrue(); - var access = new FakeConditionAccess(); - access.Allowed.Add(grantedPrincipal); - nm.ProjectedConditionAccess = access; - return new Fixture { Rig = rig, Access = access, Anchor = anchor.Value, AnchorB = anchorB!.Value, DeviceFolder = device!.Value, - DeviceDefinition = definition }; + return (anchor.Value, anchorB!.Value, device!.Value, definition); } /// Primary: the raw tag under dev1 (map-a); second: the same condition listed directly under the map-a root. diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs index 1fbe9484b..f26c2f63b 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs @@ -141,6 +141,7 @@ public sealed class ImportedConditionClassifierTests : IAsyncDisposable public bool CanSee(RoleCarryingUserIdentity? caller, IReadOnlyList placements) => caller is not null && Visible; public long AuthorityGeneration => Generation; public IDisposable? AcquireEventDemand(RoleCarryingUserIdentity? caller) => null; + public bool CanSubscribeFolder(RoleCarryingUserIdentity? caller, string mappingId, string folderLocalSubject) => caller is not null && Visible; } private sealed class Fixture diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs index 817ede9ec..b0bdb1821 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs @@ -37,13 +37,13 @@ public sealed class GrpcDataProjectedConditionAccessTests using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(); + stream.Begin("map-b", total: 2); + stream.Records("map-b", Record(Key("x"), 3), Record(Key("y"), 3)); stream.Begin("map-a", total: 3); + // Positive control: the removal is the must-arrive effect of the LAST frame, so every earlier frame was processed. await f.WaitAsync(() => stream.Removed.Count == 1); stream.Removed.Single().ShouldBe(stream.HandleOf("map-a"), "the over-limit item is removed, not held open"); f.Sink.Applied.ShouldBeEmpty("nothing is materialised before the barrier"); - stream.Begin("map-b", total: 2); - stream.Records("map-b", Record(Key("x"), 3), Record(Key("y"), 3)); - f.Sink.Applied.ShouldBeEmpty(); stream.Complete("map-b"); await f.WaitAsync(() => f.Sink.Applied.Count == 2); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity); @@ -73,9 +73,9 @@ public sealed class GrpcDataProjectedConditionAccessTests var cappedStream = await capped.NextStreamAsync(); cappedStream.Ack(); cappedStream.Begin("map-a", total: 2000); - await capped.WaitAsync(() => cappedStream.Removed.Count == 1); + await capped.WaitAsync(() => cappedStream.Removed.Count == 1 && capped.Access.BarriersCompleted(Connection) == 1); capped.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity); - capped.Sink.Applied.ShouldBeEmpty(); + capped.Sink.Applied.ShouldBeEmpty("the barrier (the positive control) passed with nothing to materialise"); } [Fact] @@ -100,10 +100,12 @@ public sealed class GrpcDataProjectedConditionAccessTests [Fact] public async Task A_stream_end_re_snapshots_without_removing_and_only_a_complete_re_snapshot_removes_staleness_in_between() { - await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); + // map-b (MaxConditions 0) is the positive control: its begin is refused, which must arrive as an item removal. + await using var f = new Fixture(("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 0)); using var demand = f.Access.AcquireEventDemand(null); var first = await f.NextStreamAsync(); first.Ack(); + first.Begin("map-b", total: 1); first.Begin("map-a", total: 2); first.Records("map-a", Record(Key("x"), 3), Record(Key("y"), 3)); first.Complete("map-a"); @@ -116,6 +118,8 @@ public sealed class GrpcDataProjectedConditionAccessTests second.Ack(); second.Begin("map-a", total: 1); second.Records("map-a", Record(Key("x"), 9)); + second.Begin("map-b", total: 1); + await f.WaitAsync(() => second.Removed.Count == 1); // positive control: every earlier frame was processed f.Sink.Removed.ShouldBeEmpty("an incomplete snapshot removes nothing"); second.Complete("map-a"); await f.WaitAsync(() => f.Sink.Removed.Count == 1); @@ -194,6 +198,269 @@ public sealed class GrpcDataProjectedConditionAccessTests await f.WaitAsync(() => !f.Access.IsRunning(Connection) && f.Sink.Removed.Count == 1); } + // --------------------------------------------------------------------------------------------------------------------- + // Review round 1 (a3a-review-round1.md) + // --------------------------------------------------------------------------------------------------------------------- + + private static async Task CompleteFirstAsync(Fixture f, params (string Mapping, DataConditionState[] Records)[] snapshots) + { + var stream = await f.NextStreamAsync(); + stream.Ack(); + foreach (var (mapping, records) in snapshots) + { + stream.Begin(mapping, records.Length); + stream.SnapshotRecords(mapping, records); + stream.Complete(mapping); + } + await f.WaitAsync(() => f.Access.BarriersCompleted(Connection) >= 1); + return stream; + } + + [Fact] + public async Task B1_an_in_stream_multi_frame_re_snapshot_keeps_every_condition_until_complete_then_removes_only_what_it_dropped() + { + await using var f = new Fixture(("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); + using var demand = f.Access.AcquireEventDemand(null); + var stream = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3), Record(Key("y"), 3), Record(Key("z"), 3)]), ("map-b", [])); + await f.WaitAsync(() => f.Sink.Live.Count == 3); + + // A2 re-snapshots inside a live stream (hub reader reset, retaken incomplete apply): begin, record frames, complete. + stream.Begin("map-a", total: 2); + stream.SnapshotRecords("map-a", Record(Key("x"), 4)); + stream.SnapshotRecords("map-a", Record(Key("y"), 4)); + stream.Records("map-b", Record(Key("ctl"), 1)); // positive control: a delta on the other mapping must be applied + await f.WaitAsync(() => f.Sink.Live.Contains(Key("ctl"))); + f.Sink.Removed.ShouldBeEmpty("a re-snapshot in progress removes nothing (B1)"); + f.Sink.Live.ShouldContain(Key("z")); + stream.Complete("map-a"); + await f.WaitAsync(() => f.Sink.Removed.Count == 1); + f.Sink.Removed.Single().ShouldBe(Key("z"), "only the key the COMPLETE re-snapshot no longer lists is removed"); + f.Sink.Live.ShouldBe([Key("x"), Key("y"), Key("ctl")], ignoreOrder: true); + } + + [Fact] + public async Task B1_an_in_stream_re_snapshot_over_capacity_removes_the_mapping_once_keeps_keys_another_mapping_lists_and_requires_refresh() + { + await using var f = new Fixture(("map-a", DataRealm.Raw, 2), ("map-b", DataRealm.Raw, 10)); + using var demand = f.Access.AcquireEventDemand(null); + var stream = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3), Record(Key("y"), 3)]), ("map-b", [Record(Key("y"), 3)])); + await f.WaitAsync(() => f.Sink.Live.Count == 2); + var refreshes = f.Sink.RefreshRequired; + + stream.Begin("map-a", total: 3); // the origin now lists more than MaxConditions + await f.WaitAsync(() => stream.Removed.Count == 1 && f.Sink.Removed.Count == 1); + stream.Removed.Single().ShouldBe(stream.HandleOf("map-a")); + f.Sink.Removed.Single().ShouldBe(Key("x"), "y is still listed by map-b"); + f.Sink.Live.ShouldBe([Key("y")]); + f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity); + f.Sink.RefreshRequired.ShouldBeGreaterThan(refreshes, "clients are told the removal happened (§5.2)"); + } + + private static Fixture TimedFixture(int timeoutMs, params (string Id, DataRealm Realm, int MaxConditions)[] mappings) + { + var f = new Fixture(mappings); + foreach (var m in f.Mappings.Current) m.Mapping.ConditionSnapshotTimeoutMilliseconds = timeoutMs; + return f; + } + + [Fact] + public async Task B2_a_snapshot_completing_after_the_timeout_is_merged_late_and_the_stream_is_kept() + { + await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); + using var demand = f.Access.AcquireEventDemand(null); + var stream = await f.NextStreamAsync(); + stream.Ack(); + stream.Begin("map-b", total: 1); + stream.Records("map-b", Record(Key("x"), 3)); + stream.Complete("map-b"); + await f.WaitAsync(() => f.Sink.Applied.Count == 1); + f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable); + + stream.Begin("map-a", total: 1); // 2,000 conditions arriving 1 s late, in miniature + stream.SnapshotRecords("map-a", Record(Key("w"), 3)); + stream.Complete("map-a"); + await f.WaitAsync(() => f.Sink.Live.Contains(Key("w"))); + f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Complete); + (await f.TryNextStreamAsync(TimeSpan.FromMilliseconds(900))).ShouldBeNull("a late completion cancels the retry"); + } + + [Fact] + public async Task B2_an_incomplete_barrier_marks_the_incomplete_mappings_materialised_keys_BadNoCommunication_never_removed() + { + await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); + using var demand = f.Access.AcquireEventDemand(null); + var first = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)]), ("map-b", [Record(Key("y"), 3)])); + await f.WaitAsync(() => f.Sink.Live.Count == 2); + first.End(); + + var second = await f.NextStreamAsync(); + second.Ack(); + second.Begin("map-b", total: 1); + second.SnapshotRecords("map-b", Record(Key("y"), 4)); + second.Complete("map-b"); // map-a never answers: the barrier passes at the timeout + await f.WaitAsync(() => f.Sink.StaleKeys.Contains(Key("x"))); + f.Sink.Removed.ShouldBeEmpty("unknown is not gone"); + f.Sink.StaleKeys.ShouldNotContain(Key("y")); + f.Sink.RefreshRequired.ShouldBeGreaterThanOrEqualTo(1); + } + + [Fact] + public async Task B2_S7_a_refused_item_is_an_incomplete_barrier_RefreshRequired_and_the_stream_is_retried_after_a_bounded_wait() + { + await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); + using var demand = f.Access.AcquireEventDemand(null); + var stream = await f.NextStreamAsync(); + stream.Ack(refused: "map-a"); // e.g. a Secondary that advertises but refuses (A2 N7) + stream.Begin("map-b", total: 1); + stream.Records("map-b", Record(Key("x"), 3)); + stream.Complete("map-b"); + await f.WaitAsync(() => f.Sink.Applied.Count == 1); + f.Sink.RefreshRequired.ShouldBe(1, "S7: an incomplete barrier from a non-Good ack also requires refresh"); + (await f.TryNextStreamAsync(TimeSpan.FromSeconds(5))).ShouldNotBeNull("B2: an Unavailable mapping ends the stream; a new one retries it"); + } + + [Fact] + public async Task Deviation9_a_condition_stream_served_by_a_Secondary_is_dropped_and_reopened_on_the_Primary() + { + await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); + f.Connections.Roles.Enqueue("Secondary"); + using var demand = f.Access.AcquireEventDemand(null); + var secondary = await f.NextStreamAsync(); + var primary = await f.NextStreamAsync(); + secondary.Disposed.ShouldBeTrue("never opened items on a Secondary"); + f.Connections.PrimarySubscribes.ShouldBeGreaterThanOrEqualTo(2, "the Primary-only open is asked for"); + primary.Ack(); + primary.Begin("map-a", 1); + primary.SnapshotRecords("map-a", Record(Key("x"), 3)); + primary.Complete("map-a"); + await f.WaitAsync(() => f.Sink.Live.Contains(Key("x"))); + } + + [Fact] + public async Task S6_a_root_whose_metadata_fails_is_Unavailable_and_its_item_is_not_opened() + { + await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); + f.Connections.MetadataFails.Add(0); + using var demand = f.Access.AcquireEventDemand(null); + var stream = await f.NextStreamAsync(); + stream.Mappings.ShouldBe(["map-b"]); + f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable); + } + + [Fact] + public async Task B4_the_host_caps_are_node_wide_across_connections() + { + var options = new ProjectedConditionOptions(TimeSpan.FromMilliseconds(200), 3 * 49, long.MaxValue, TimeSpan.FromMilliseconds(50)); + await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10, "conn-a"), ("map-b", DataRealm.Raw, 10, "conn-b")); + using var demand = f.Access.AcquireEventDemand(null); + var streams = new[] { await f.NextStreamAsync(), await f.NextStreamAsync() }; + foreach (var stream in streams) + { + var mapping = stream.Mappings.Single(); + stream.Ack(); + stream.Begin(mapping, 2); + stream.SnapshotRecords(mapping, Record(Key(mapping + "1"), 3), Record(Key(mapping + "2"), 3)); + stream.Complete(mapping); + } + await f.WaitAsync(() => f.Access.BarriersCompleted("conn-a") == 1 && f.Access.BarriersCompleted("conn-b") == 1); + streams.Sum(x => x.Removed.Count).ShouldBe(1, "two connections of 2 cannot both fit a 3-condition node cap"); + f.Sink.Live.Count.ShouldBe(2); + f.Access.ChargedConditions.ShouldBeLessThanOrEqualTo(3); + } + + [Fact] + public async Task B4_admission_is_order_independent_a_later_ordered_begin_arriving_first_still_counts() + { + var options = new ProjectedConditionOptions(TimeSpan.FromMilliseconds(200), 3 * 49, long.MaxValue, TimeSpan.FromMilliseconds(50)); + await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); + using var demand = f.Access.AcquireEventDemand(null); + var stream = await f.NextStreamAsync(); + stream.Ack(); + stream.Begin("map-b", 2); + stream.Begin("map-a", 2); + await f.WaitAsync(() => stream.Removed.Count == 1); + stream.Removed.Single().ShouldBe(stream.HandleOf("map-a"), "the second begin is decided against the first one's claim"); + f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity); + } + + [Fact] + public async Task B4_records_past_the_snapshot_total_reset_the_mapping_to_ConditionCapacity_before_materialising() + { + await using var f = new Fixture(("map-a", DataRealm.Raw, 100)); + using var demand = f.Access.AcquireEventDemand(null); + var stream = await f.NextStreamAsync(); + stream.Ack(); + stream.Begin("map-a", total: 1); + stream.SnapshotRecords("map-a", Enumerable.Range(0, 50).Select(i => Record(Key("k" + i), 3)).ToArray()); + stream.Complete("map-a"); + await f.WaitAsync(() => stream.Removed.Count == 1 && f.Access.BarriersCompleted(Connection) == 1); + f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity); + f.Sink.Applied.ShouldBeEmpty("an origin claiming total 1 cannot materialise 50 (the barrier is the positive control)"); + f.Access.ChargedConditions.ShouldBe(0); + } + + [Fact] + public async Task B4_post_snapshot_delta_growth_past_MaxConditions_resets_the_mapping_and_removes_its_conditions() + { + await using var f = new Fixture(("map-a", DataRealm.Raw, 2)); + using var demand = f.Access.AcquireEventDemand(null); + var stream = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)])); + await f.WaitAsync(() => f.Sink.Live.Count == 1); + stream.Records("map-a", Record(Key("y"), 3), Record(Key("z"), 3)); + await f.WaitAsync(() => stream.Removed.Count == 1 && f.Sink.Removed.Contains(Key("x"))); + f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity); + f.Sink.Live.ShouldBeEmpty(); + } + + [Fact] + public async Task S2_an_authority_deactivation_moves_the_authority_generation_so_cached_verdicts_are_re_proved() + { + await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); + var before = f.Access.AuthorityGeneration; + ((ActiveAuthority)f.Mappings.Current[0].Authority).Active = false; // no deploy, no epoch change + f.Access.AuthorityGeneration.ShouldNotBe(before); + } + + [Fact] + public async Task S3_a_new_runner_waits_for_the_old_runners_removal_so_a_re_materialised_key_survives() + { + await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); + var demand = f.Access.AcquireEventDemand(null)!; + await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)])); + await f.WaitAsync(() => f.Sink.Live.Count == 1); + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Sink.RemovalGate = gate; // hold the old runner's removal open + demand.Dispose(); + await f.WaitAsync(() => !f.Access.IsRunning(Connection)); // linger expired; its removal is now blocked in the sink + using var again = f.Access.AcquireEventDemand(null); + _ = Task.Delay(400, TestContext.Current.CancellationToken).ContinueWith(_ => gate.TrySetResult(), TaskScheduler.Default); + var stream = await f.NextStreamAsync(); + stream.Ack(); + stream.Begin("map-a", 1); + stream.SnapshotRecords("map-a", Record(Key("x"), 4)); + stream.Complete("map-a"); + await f.WaitAsync(() => f.Sink.Removed.Count == 1 && f.Sink.Applied.Count == 2); + f.Sink.Live.ShouldContain(Key("x"), "the old runner's removal must not land after the new runner materialised the key"); + } + + [Fact] + public async Task S4_a_mapping_change_hands_the_materialised_set_over_after_the_old_loop_stopped() + { + await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); + using var demand = f.Access.AcquireEventDemand(null); + await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)])); + await f.WaitAsync(() => f.Sink.Live.Count == 1); + f.Mappings.Current[0].Mapping.MaxConditions = 11; // a changed signature ⇒ a new runner, a new stream + f.Mappings.Raise(); + var stream = await f.NextStreamAsync(); + stream.Ack(); + stream.Begin("map-a", 1); + stream.SnapshotRecords("map-a", Record(Key("y"), 3)); + stream.Complete("map-a"); + await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x"))); + f.Sink.Live.ShouldBe([Key("y")], "x was handed over (not orphaned) and the new complete set removed it"); + } + // --------------------------------------------------------------------------------------------------------------------- internal static string Key(string seed) => @@ -223,12 +490,18 @@ public sealed class GrpcDataProjectedConditionAccessTests public ProjectedConditionAccess Access { get; } public Fixture(params (string Id, DataRealm Realm, int MaxConditions)[] mappings) - : this(new ProjectedConditionOptions(TimeSpan.FromMilliseconds(200), 122_500, long.MaxValue, TimeSpan.FromMilliseconds(50)), mappings) { } + : this(DefaultOptions, mappings) { } + + public static ProjectedConditionOptions DefaultOptions => + new(TimeSpan.FromMilliseconds(200), 122_500, long.MaxValue, TimeSpan.FromMilliseconds(50)); public Fixture(ProjectedConditionOptions options, params (string Id, DataRealm Realm, int MaxConditions)[] mappings) + : this(options, mappings.Select(m => (m.Id, m.Realm, m.MaxConditions, Connection)).ToArray()) { } + + public Fixture(ProjectedConditionOptions options, params (string Id, DataRealm Realm, int MaxConditions, string Connection)[] mappings) { Grant(NodePermissions.Browse | NodePermissions.Subscribe); - Mappings = new FakeMappings(mappings.Select(m => Placement(m.Id, m.Realm, m.MaxConditions)).ToList()); + Mappings = new FakeMappings(mappings.Select(m => Placement(m.Id, m.Realm, m.MaxConditions, m.Connection)).ToList()); var policy = new DataOperationPolicy(_state, new TriePermissionEvaluator(_state.Tries, TimeProvider.System), TimeProvider.System); Access = new ProjectedConditionAccess(Mappings, Connections, policy, () => Sink, TimeProvider.System, options, NullLogger.Instance); } @@ -242,11 +515,11 @@ public sealed class GrpcDataProjectedConditionAccessTests public RoleCarryingUserIdentity Identity(string principal) => new(new UserNameIdentityToken { UserName = "apikey" }, [], principal, _key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(_key), DateTimeOffset.UtcNow.AddMinutes(5)); - private static ProjectedMappingPlacement Placement(string id, DataRealm realm, int maxConditions) + private static ProjectedMappingPlacement Placement(string id, DataRealm realm, int maxConditions, string connection) { var mapping = new RemoteNamespaceMapping { - RemoteNamespaceMappingId = id, DataConnectionId = Connection, Enabled = true, Realm = realm, RemoteRealm = realm, + RemoteNamespaceMappingId = id, DataConnectionId = connection, Enabled = true, Realm = realm, RemoteRealm = realm, AllowedOperations = DataOperations.Browse | DataOperations.Subscribe | DataOperations.AlarmSubscribe, MaxConditions = maxConditions, ConditionStaleTimeoutMilliseconds = 100, ConditionSnapshotTimeoutMilliseconds = 30_000, BranchName = id, RemoteNamespaceUri = realm == DataRealm.Raw ? "https://zb.com/otopcua/raw" : "https://zb.com/otopcua/uns", @@ -261,6 +534,15 @@ public sealed class GrpcDataProjectedConditionAccessTests public async Task NextStreamAsync() => await Connections.Streams.Reader.ReadAsync(TestContext.Current.CancellationToken); + /// The next stream within , or null. + public async Task TryNextStreamAsync(TimeSpan within) + { + using var cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + cts.CancelAfter(within); + try { return await Connections.Streams.Reader.ReadAsync(cts.Token); } + catch (OperationCanceledException) when (!TestContext.Current.CancellationToken.IsCancellationRequested) { return null; } + } + public async Task WaitAsync(Func condition) { var deadline = DateTime.UtcNow.AddSeconds(10); @@ -278,7 +560,8 @@ public sealed class GrpcDataProjectedConditionAccessTests { public long CatalogEpoch => 1; public long AuthorityEpoch => 1; - public bool IsActive => true; + public bool Active { get; set; } = true; + public bool IsActive => Active; } internal sealed class FakeMappings(List current) : IProjectedConditionMappings @@ -294,20 +577,40 @@ public sealed class GrpcDataProjectedConditionAccessTests private readonly List _applied = []; private readonly List _removed = []; private readonly List _stale = []; + private readonly List _staleKeys = []; + private readonly HashSet _live = new(StringComparer.Ordinal); private int _refresh; public IReadOnlyList Applied { get { lock (_gate) return _applied.ToList(); } } public IReadOnlyList Removed { get { lock (_gate) return _removed.ToList(); } } public IReadOnlyList Stale { get { lock (_gate) return _stale.ToList(); } } + public IReadOnlyList StaleKeys { get { lock (_gate) return _staleKeys.ToList(); } } + /// The keys the sink holds right now (applied minus removed). + public IReadOnlyCollection Live { get { lock (_gate) return _live.ToList(); } } public int RefreshRequired => Volatile.Read(ref _refresh); - public void ApplyConditions(IReadOnlyList updates) { lock (_gate) _applied.AddRange(updates); } - public void RemoveConditions(string connectionId, IReadOnlyCollection conditionKeys) { lock (_gate) _removed.AddRange(conditionKeys); } + /// When set, a removal blocks until released (the S3 race window, held open). + public TaskCompletionSource? RemovalGate { get; set; } + public void ApplyConditions(IReadOnlyList updates) + { + lock (_gate) { _applied.AddRange(updates); foreach (var u in updates) _live.Add(u.State.ConditionKey); } + } + public void RemoveConditions(string connectionId, IReadOnlyCollection conditionKeys) + { + RemovalGate?.Task.Wait(TimeSpan.FromSeconds(10)); + lock (_gate) { _removed.AddRange(conditionKeys); foreach (var k in conditionKeys) _live.Remove(k); } + } public void MarkConnectionStale(string connectionId) { lock (_gate) _stale.Add(connectionId); } + public void MarkConditionsStale(string connectionId, IReadOnlyCollection conditionKeys) { lock (_gate) _staleKeys.AddRange(conditionKeys); } public void RequireRefresh(string connectionId) => Interlocked.Increment(ref _refresh); } internal sealed class FakeConnections : IGrpcDataAdapterConnectionSource { public Channel Streams { get; } = Channel.CreateUnbounded(); + /// Metadata answers Bad for these root indexes (deployed order). + public HashSet MetadataFails { get; } = []; + /// The serving roles of the next streams (Primary when empty). + public Queue Roles { get; } = new(); + public int PrimarySubscribes; public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken) => ValueTask.FromResult(new Lease(new FakeConnection(this))); @@ -319,29 +622,42 @@ public sealed class GrpcDataProjectedConditionAccessTests } } - private sealed class FakeConnection(FakeConnections owner) : IDataConnection + private sealed class FakeConnection(FakeConnections owner) : IDataConnection, IDataPrimarySubscriptionSource { + public Task SubscribePrimaryAsync(CancellationToken cancellationToken) + { + Interlocked.Increment(ref owner.PrimarySubscribes); + return SubscribeAsync(cancellationToken); + } + public DataTarget Target { get; } = new(DataTargetMode.Cluster, "origin", null); public TimeProvider Clock => TimeProvider.System; public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => throw new NotSupportedException(); public Task BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => - Task.FromResult>>(request.Views.Select(v => new DataItemResult("0", DataItemStatus.Good, - new DataMetadata(v with { Subject = v.Address.Identifier }, v.Address.Identifier, "Folder", DataValueKind.Null, -1, [], false, + Task.FromResult>>(request.Views.Select((v, i) => owner.MetadataFails.Contains(i) + ? new DataItemResult("0", DataItemStatus.Unavailable, null, null) + : new DataItemResult("0", DataItemStatus.Good, new DataMetadata(v with { Subject = v.Address.Identifier }, v.Address.Identifier, "Folder", DataValueKind.Null, -1, [], false, DataOperations.Browse, 1, null, null, false), null)).ToArray()); public Task> ReadAsync(ReadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => throw new NotSupportedException(); public Task SubscribeAsync(CancellationToken cancellationToken) { - var stream = new FakeStream(); + string role; + lock (owner.Roles) role = owner.Roles.TryDequeue(out var next) ? next : "Primary"; + var stream = new FakeStream(role); owner.Streams.Writer.TryWrite(stream); return Task.FromResult(stream); } public ValueTask DisposeAsync() => ValueTask.CompletedTask; } - internal sealed class FakeStream : IDataSubscription + internal sealed class FakeStream(string role = "Primary") : IDataSubscription, IDataSubscriptionProvenance { + public ServingIdentity Serving { get; } = new("origin-1", "inc-1", role, 1, 1); + public bool Disposed { get; private set; } + /// The mapping ids this stream opened items for. + public IReadOnlyList Mappings => Open.Items.Select(x => x.ClientItemId).ToArray(); private readonly Channel _frames = Channel.CreateUnbounded(); private readonly TaskCompletionSource _open = new(TaskCreationOptions.RunContinuationsAsynchronously); private long _sequence; @@ -355,7 +671,7 @@ public sealed class GrpcDataProjectedConditionAccessTests } public IAsyncEnumerable ReadAllAsync(CancellationToken cancellationToken) => _frames.Reader.ReadAllAsync(cancellationToken); - public ValueTask DisposeAsync() { _frames.Writer.TryComplete(); return ValueTask.CompletedTask; } + public ValueTask DisposeAsync() { Disposed = true; _frames.Writer.TryComplete(); return ValueTask.CompletedTask; } private OpenSubscription Open => _open.Task.Wait(TimeSpan.FromSeconds(10)) ? _open.Task.Result : throw new TimeoutException("no open"); @@ -365,8 +681,16 @@ public sealed class GrpcDataProjectedConditionAccessTests return new DataItemHandle(Open.SubscriptionId, Open.StreamEpoch, (ulong)(index + 1), 1); } - public void Ack() => _frames.Writer.TryWrite(new DataSubscriptionAck(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, "open", - Open.Items.Select(x => new DataSubscriptionItemAck(x.ClientItemId, DataItemStatus.Good, HandleOf(x.ClientItemId), x.Settings, null)).ToArray())); + public void Ack(params string[] refused) => _frames.Writer.TryWrite(new DataSubscriptionAck(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, "open", + Open.Items.Select(x => refused.Contains(x.ClientItemId) + ? new DataSubscriptionItemAck(x.ClientItemId, DataItemStatus.Unavailable, null, x.Settings, "secondary") + : new DataSubscriptionItemAck(x.ClientItemId, DataItemStatus.Good, HandleOf(x.ClientItemId), x.Settings, null)).ToArray())); + + /// Snapshot record frames exactly as the A2 origin frames them (is_snapshot, no total). + public void SnapshotRecords(string mapping, params DataConditionState[] records) + { + foreach (var chunk in records.Chunk(128)) Frame(mapping, true, null, chunk, false); + } public void Begin(string mapping, int total) => Frame(mapping, true, total, [], false); public void Records(string mapping, params DataConditionState[] records) From 14343bf08649ad2e92eb99b7e65d3beb28abf660 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 18:46:11 -0500 Subject: [PATCH 22/32] =?UTF-8?q?fix(grpc-data):=20A3a=20review=20r1=20?= =?UTF-8?q?=E2=80=94=20condition-bearing=20projected=20folders=20are=20eve?= =?UTF-8?q?nt=20notifiers=20from=20materialisation=20(folder-only=20demand?= =?UTF-8?q?),=20null-safe=20revalidation=20log;=20NM=20tests:=20B3=20reval?= =?UTF-8?q?idation=20+=20demand=20release,=20S1=20rebuild,=20deviation=203?= =?UTF-8?q?/6/8,=20S2=20verdict=20TTL,=20A3-SEC=20delivery=20gate=20isolat?= =?UTF-8?q?ed=20(DroppedOnPublish=200)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../IProjectedConditionAccess.cs | 4 + .../OtOpcUaNodeManager.cs | 3 +- .../ProjectedConditionRegistry.cs | 13 +- .../ProjectedConditionAccess.cs | 5 + .../ImportedConditionEventWireTests.cs | 199 +++++++++++++++++- .../ImportedConditionClassifierTests.cs | 22 ++ 6 files changed, 242 insertions(+), 4 deletions(-) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedConditionAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedConditionAccess.cs index 6f3d6ee18..9bb95fc71 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedConditionAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedConditionAccess.cs @@ -73,6 +73,10 @@ public interface IProjectedConditionAccess /// folder event item (and its demand) before any imported condition is wired there. bool CanSubscribeFolder(RoleCarryingUserIdentity? caller, string mappingId, string folderLocalSubject); + /// Deviation 3 (review r1): whether a deployed mapping is condition-bearing — its projected folders are event + /// notifiers from materialisation (the SDK refuses an event item on a node without SubscribeToEvents). + bool IsConditionBearingMapping(string mappingId); + /// A generation that moves whenever anything the gate reads may have changed (verdict caches key on it). long AuthorityGeneration { get; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index b6ee1ffda..47ef5bb04 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -8707,7 +8707,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage if (eventsStoodDown > 0 || eventsRestored > 0) { - _authorizer!.LogFiltered( + // An imported-notifier item is revalidated through the imported gate even where no authorizer is wired (A3 r1 B3). + _authorizer?.LogFiltered( "RevalidateEventSubscriptions", principal: null, eventsStoodDown, _eventItems.Count); } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs index 90a2eaf63..c70aaf338 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs @@ -73,6 +73,8 @@ internal sealed class ProjectedConditionRegistry /// projected node per apply chunk); resolved against the live projected maps at use. internal readonly Dictionary<(string Mapping, string Subject), NodeId> FolderIds = new(); internal readonly Dictionary FolderKeys = new(); + /// Deviation 3: projected folders of condition-bearing mappings, event notifiers from materialisation. + internal readonly HashSet PromotedFolders = new(); /// Review r1 S2: a positive verdict is re-proved at least this often (credential expiry is honoured exactly). internal static readonly TimeSpan PositiveVerdictTtl = TimeSpan.FromSeconds(5); private readonly object _verdictGate = new(); @@ -574,7 +576,8 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink { _importedConditions.WiredByFolder.Remove(folder.NodeId); RemoveRootNotifier(folder); - folder.EventNotifier = (byte)(folder.EventNotifier & ~EventNotifiers.SubscribeToEvents); + if (!_importedConditions.PromotedFolders.Contains(folder.NodeId)) + folder.EventNotifier = (byte)(folder.EventNotifier & ~EventNotifiers.SubscribeToEvents); folder.ClearChangeMasks(SystemContext, includeChildren: false); } } @@ -585,6 +588,12 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink if (_importedConditions.FolderKeys.Remove(folder.NodeId, out var previous)) _importedConditions.FolderIds.Remove(previous); _importedConditions.FolderIds[(mappingId, localSubject)] = folder.NodeId; _importedConditions.FolderKeys[folder.NodeId] = (mappingId, localSubject); + if (ProjectedConditionAccess is { } access && access.IsConditionBearingMapping(mappingId)) + { + // Deviation 3 (review r1): a folder-only client can subscribe (and so open condition demand) before anything is wired. + _importedConditions.PromotedFolders.Add(folder.NodeId); + folder.EventNotifier = (byte)(folder.EventNotifier | EventNotifiers.SubscribeToEvents); + } if (_importedConditions.Count == 0 || !_importedConditions.ByFolderKey.TryGetValue((mappingId, localSubject), out var set)) return; foreach (var id in set.ToList()) if (_importedConditions.Find(id) is { } c) WireImportedFolder(c, folder); @@ -594,6 +603,7 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink private void OnProjectedFolderRemoving(NodeId folderId) { if (_importedConditions.FolderKeys.Remove(folderId, out var key)) _importedConditions.FolderIds.Remove(key); + _importedConditions.PromotedFolders.Remove(folderId); if (!_importedConditions.WiredByFolder.TryGetValue(folderId, out var entry)) return; foreach (var id in entry.Conditions.ToList()) if (_importedConditions.Find(id) is { } c) UnwireImportedFolder(c, entry.Folder); @@ -606,6 +616,7 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink foreach (var folderId in _importedConditions.WiredByFolder.Keys.ToList()) OnProjectedFolderRemoving(folderId); _importedConditions.FolderIds.Clear(); _importedConditions.FolderKeys.Clear(); + _importedConditions.PromotedFolders.Clear(); } /// diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs index 3aba37b2a..14c0345fa 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs @@ -158,6 +158,11 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess return Gate(identity, _mappings.Current, mappingId, null, folderLocalSubject); } + /// + public bool IsConditionBearingMapping(string mappingId) => + _mappings.Current.Any(x => string.Equals(x.Mapping.RemoteNamespaceMappingId, mappingId, StringComparison.OrdinalIgnoreCase) + && x.Authority.IsActive && IsConditionBearing(x.Mapping)); + /// The mapping gate for one (mapping, folder) placement; null = the mapping's own. private bool Gate(DataCallerIdentity identity, IReadOnlyList current, string mappingId, DataRealm? realm, string folderLocalSubject) diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionEventWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionEventWireTests.cs index 05364b43b..d279585c3 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionEventWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionEventWireTests.cs @@ -245,6 +245,136 @@ public sealed class ImportedConditionEventWireTests // --------------------------------------------------------------------------------------------------------------------- + // --------------------------------------------------------------------------------------------------------------------- + // Review round 1 (a3a-review-round1.md) + // --------------------------------------------------------------------------------------------------------------------- + + private static bool IsRefreshRequired(ArrayOf e) => e[EventTypeF].GetNodeId() == ObjectTypeIds.RefreshRequiredEventType; + + [Fact] + public async Task B3_revalidation_keeps_an_admitted_folder_item_and_deleting_a_stood_down_item_releases_its_demand() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3-r1-reval", encrypted: false, ct); + var f = Fixture.Install(rig, Granted); + f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements())); + using var session = await rig.ConnectAsync(anonymous: false, ct); + var events = new Events(); + var subscription = await SubscribeAsync(session, events, ct); + var folder = AddItem(subscription, f.DeviceFolder); + await subscription.ApplyChangesAsync(ct); + f.Access.Outstanding.ShouldBe(1, "the admitted folder item opened demand"); + + rig.Nm.RevalidateMonitoredItems(); // the ACL timer tick / a deploy + f.Apply(Update(Key1, version: 4, active: true, acked: true, f.TwoPlacements(), message: "after-revalidation")); + await Events.WaitUntilAsync(() => events.Of(folder).Any(e => Message(e) == "after-revalidation")); + + // A revocation stands the item down; the client's later delete must still release the lease. + f.Access.Allowed.Clear(); + Interlocked.Increment(ref f.Access.Generation); + rig.Nm.RevalidateMonitoredItems(); + subscription.RemoveItem(folder); + await subscription.ApplyChangesAsync(ct); + f.Access.Outstanding.ShouldBe(0, "a stood-down item's delete releases its condition demand"); + } + + [Fact] + public async Task S1_a_full_rebuild_unwires_and_the_re_created_folder_is_promoted_and_delivers_again() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3-r1-rebuild", encrypted: false, ct); + var f = Fixture.Install(rig, Granted); + f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements())); + rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeTrue(); + + rig.Nm.RebuildAddressSpace(); + rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeFalse("the rebuild discarded the folder: its wiring goes with it"); + f.Rematerialise(); // the same NodeIds, new FolderState instances + + using var session = await rig.ConnectAsync(anonymous: false, ct); + var events = new Events(); + var subscription = await SubscribeAsync(session, events, ct); + var folder = AddItem(subscription, f.DeviceFolder); + await subscription.ApplyChangesAsync(ct); + (folder.Status.Error?.StatusCode ?? StatusCodes.Good).Code.ShouldBe(StatusCodes.Good.Code, "the new folder is an event notifier again"); + f.Apply(Update(Key1, version: 4, active: true, acked: true, f.TwoPlacements(), message: "after-rebuild")); + await Events.WaitUntilAsync(() => events.Of(folder).Any(e => Message(e) == "after-rebuild")); + } + + [Fact] + public async Task Deviation3_a_folder_only_client_opens_demand_on_a_projected_folder_with_no_condition_wired_yet() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3-r1-folderdemand", encrypted: false, ct); + var f = Fixture.Install(rig, Granted); + rig.Nm.ImportedConditionCount.ShouldBe(0, "nothing materialised (after a restart or a linger)"); + using var granted = await rig.ConnectAsync(anonymous: false, ct); + using var denied = await rig.ConnectAsync(anonymous: true, ct); + var events = new Events(); + var grantedSub = await SubscribeAsync(granted, events, ct); + var deniedSub = await SubscribeAsync(denied, new Events(), ct); + var grantedItem = AddItem(grantedSub, f.AnchorB); + var deniedItem = AddItem(deniedSub, f.AnchorB); + await grantedSub.ApplyChangesAsync(ct); + await deniedSub.ApplyChangesAsync(ct); + (grantedItem.Status.Error?.StatusCode ?? StatusCodes.Good).Code.ShouldBe(StatusCodes.Good.Code); + deniedItem.Status.Error?.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code, "the mapping gate still decides"); + f.Access.Outstanding.ShouldBe(1, "the folder-only client opened condition demand"); + + // The condition that demand brings in is delivered to that folder item. + f.Apply(Update(Key2, version: 3, active: true, acked: false, [f.BPlacement()], message: "arrived")); + await Events.WaitUntilAsync(() => events.Of(grantedItem).Any(e => Message(e) == "arrived")); + } + + [Fact] + public async Task Deviation6_removing_an_imported_condition_sends_RefreshRequired_only_to_the_items_that_could_see_it() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3-r1-remove", encrypted: false, ct); + var f = Fixture.Install(rig, Granted); + f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements())); + using var session = await rig.ConnectAsync(anonymous: false, ct); + var events = new Events(); + var subscription = await SubscribeAsync(session, events, ct); + var server = AddItem(subscription, ObjectIds.Server); + var device = AddItem(subscription, f.DeviceFolder); + var other = AddItem(subscription, f.AnchorB); // map-b: Key1 is never wired here + await subscription.ApplyChangesAsync(ct); + var before = rig.Nm.ImportedRefreshRequiredQueued; + + rig.Nm.RemoveConditions(Connection, [Key1]); + rig.Nm.ImportedConditionCount.ShouldBe(0); + await Events.WaitUntilAsync(() => events.Of(server).Any(IsRefreshRequired) && events.Of(device).Any(IsRefreshRequired)); + (rig.Nm.ImportedRefreshRequiredQueued - before).ShouldBe(2, "one per item that held it"); + // Must-arrive control on the map-b item, queued AFTER the removal. + f.Apply(Update(Key2, version: 3, active: true, acked: false, [f.BPlacement()], message: "control")); + await Events.WaitUntilAsync(() => events.Of(other).Any(e => Message(e) == "control")); + events.Of(other).Any(IsRefreshRequired).ShouldBeFalse("an item that never saw the removed condition is not told to refresh"); + } + + [Fact] + public async Task Deviation8_ConditionRefresh_replays_hundreds_of_imported_conditions_in_chunks_between_RefreshStart_and_RefreshEnd() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3-r1-replay", encrypted: false, ct); + var f = Fixture.Install(rig, Granted); + const int count = 300; // > 2 × the 128-condition chunk + rig.Nm.ApplyConditions(Enumerable.Range(0, count) + .Select(i => Update(KeyOf("bulk-" + i), version: 3, active: true, acked: false, f.TwoPlacements(), message: "bulk")).ToList()); + using var session = await rig.ConnectAsync(anonymous: false, ct); + var events = new Events(); + var subscription = await SubscribeAsync(session, events, ct); + var server = AddItem(subscription, ObjectIds.Server); + await subscription.ApplyChangesAsync(ct); + await subscription.ConditionRefreshAsync(ct); + await Events.WaitUntilAsync(() => events.Of(server).Any(e => e[EventTypeF].GetNodeId() == ObjectTypeIds.RefreshEndEventType)); + var list = events.Of(server).ToList(); + var startAt = list.FindIndex(e => e[EventTypeF].GetNodeId() == ObjectTypeIds.RefreshStartEventType); + var endAt = list.FindIndex(e => e[EventTypeF].GetNodeId() == ObjectTypeIds.RefreshEndEventType); + list.Skip(startAt + 1).Take(endAt - startAt - 1).Count(e => Message(e) == "bulk") + .ShouldBe(count, "every retained imported condition once, inside the refresh bracket"); + } + private static string KeyOf(string seed) => Convert.ToBase64String(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(seed))).TrimEnd('=').Replace('+', '-').Replace('/', '_'); @@ -323,6 +453,7 @@ public sealed class ImportedConditionEventWireTests public long AuthorityGeneration => Interlocked.Read(ref Generation); public bool CanSubscribeFolder(RoleCarryingUserIdentity? caller, string mappingId, string folderLocalSubject) => caller is not null && Allowed.Contains(caller.Principal); + public bool IsConditionBearingMapping(string mappingId) => true; /// Leases currently held (acquired minus released). public int Outstanding; public IDisposable? AcquireEventDemand(RoleCarryingUserIdentity? caller) @@ -351,10 +482,10 @@ public sealed class ImportedConditionEventWireTests public static Fixture Install(ServerEventRig rig, string grantedPrincipal) { - var (anchor, anchorB, device, definition) = Materialise(rig.Nm); var access = new FakeConditionAccess(); access.Allowed.Add(grantedPrincipal); - rig.Nm.ProjectedConditionAccess = access; + rig.Nm.ProjectedConditionAccess = access; // bound before projections materialise, as the host does + var (anchor, anchorB, device, definition) = Materialise(rig.Nm); return new Fixture { Rig = rig, Access = access, Anchor = anchor, AnchorB = anchorB, DeviceFolder = device, DeviceDefinition = definition }; } @@ -396,3 +527,67 @@ public sealed class ImportedConditionEventWireTests public void Apply(ImportedConditionUpdate update) => Rig.Nm.ApplyConditions([update]); } } + +/// +/// Review r1 (test adequacy): A3-SEC with the DELIVERY gate isolated — on the denied path nothing is queued at all, so the +/// publish-time marker re-check (the second layer) has nothing to drop: ProjectedEventFieldList.DroppedOnPublish +/// does not move. Non-parallel: the counter is process-wide. +/// +[Collection(ImportedDeliveryGateCollection.Name)] +[Trait("Feature", "GrpcData"), Trait("Phase", "A3")] +public sealed class ImportedConditionDeliveryGateTests +{ + [Fact] + public async Task A3_SEC_the_delivery_gate_alone_withholds_a_denied_sessions_event_nothing_is_dropped_on_publish() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3-r1-gate", encrypted: false, ct); + var nm = rig.Nm; + var access = new ImportedConditionEventWireTests.FakeConditionAccess(); + access.Allowed.Add(ServerEventRig.KeyPrincipal); + nm.ProjectedConditionAccess = access; + using var allowed = await rig.ConnectAsync(anonymous: false, ct); + using var denied = await rig.ConnectAsync(anonymous: true, ct); + var received = new System.Collections.Concurrent.ConcurrentBag<(string Who, uint Handle, string? Message)>(); + async Task Subscribe(ISession session, string who) + { + var subscription = new Subscription(session.DefaultSubscription) { PublishingInterval = 100 }; + subscription.FastEventCallback = (_, n, _) => + { + foreach (var e in n.Events) + received.Add((who, e.ClientHandle, e.EventFields[0].TryGetValue(out LocalizedText text) ? text.Text : null)); + }; + session.AddSubscription(subscription); + await subscription.CreateAsync(ct); + var filter = new EventFilter(); + filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.Message)); + subscription.AddItem(new SdkMonitoredItem(subscription.DefaultItem) + { StartNodeId = ObjectIds.Server, AttributeId = Attributes.EventNotifier, Filter = filter, QueueSize = 1000, SamplingInterval = 0 }); + await subscription.ApplyChangesAsync(ct); + return subscription; + } + await Subscribe(allowed, "allowed"); + var deniedSub = await Subscribe(denied, "denied"); + var dropped = ProjectedEventFieldList.DroppedOnPublish; + + var key = Convert.ToBase64String(SHA256.HashData("gate"u8.ToArray())).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + var view = new DataView(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant/dev1/HR"), DataRealm.Raw, null, 0, "Plant/dev1/HR"); + var placement = new ImportedConditionPlacement("map-a", DataRealm.Raw, view, "Plant/remote-a/dev1", "dev1/HR"); + var info = new DataConditionInfo("AlarmConditionType", "HR", DataConditionSourceKind.Native, [view], 3); + var state = new DataConditionState(key, 1, false, true, info, true, false, true, true, 0, 500, "gated", 0, null, 0, + DateTimeOffset.UtcNow, true, new DataActivationMarker("i", 1)); + nm.ApplyConditions([new ImportedConditionUpdate("conn-a", state, info, [placement], "Plant/remote-a/dev1/HR")]); + await RecordedEvents.WaitUntilAsync(() => received.Any(r => r.Who == "allowed" && r.Message == "gated")); // positive control + await deniedSub.ConditionRefreshAsync(ct); // must-arrive on the denied session: its own RefreshStart/End + await RecordedEvents.WaitUntilAsync(() => received.Count(r => r.Who == "denied") >= 2); + received.ShouldNotContain(r => r.Who == "denied" && r.Message == "gated"); + (ProjectedEventFieldList.DroppedOnPublish - dropped).ShouldBe(0, "the delivery gate withheld it; nothing reached the publish-time drop"); + } +} + +[CollectionDefinition(Name, DisableParallelization = true)] +public sealed class ImportedDeliveryGateCollection +{ + public const string Name = "Imported delivery gate (process-wide counter)"; +} + diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs index f26c2f63b..5799e02f8 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs @@ -116,6 +116,27 @@ public sealed class ImportedConditionClassifierTests : IAsyncDisposable ReferenceEquals(ProjectedNotificationRewriter.Project(plain, republish: false, null), plain).ShouldBeTrue(); } + [Fact] + public void S2_a_cached_positive_verdict_is_re_proved_past_the_credential_expiry_and_past_the_positive_TTL() + { + var registry = new ProjectedConditionRegistry(); + var condition = new ImportedCondition(new AlarmConditionState(null) { NodeId = new NodeId("c", 9) }, "conn", "k"); + var computes = 0; + bool Allow() { computes++; return true; } + var now = DateTimeOffset.UtcNow; + var expiringKey = new object(); + registry.Verdict(expiringKey, condition, 1, now, now.AddSeconds(2), Allow).ShouldBeTrue(); + registry.Verdict(expiringKey, condition, 1, now.AddSeconds(1), now.AddSeconds(2), Allow).ShouldBeTrue(); + computes.ShouldBe(1, "served from cache inside both bounds"); + registry.Verdict(expiringKey, condition, 1, now.AddSeconds(3), now.AddSeconds(2), () => { computes++; return false; }) + .ShouldBeFalse("past the key's expiry the verdict is re-proved (and the policy now denies)"); + + var longLived = new object(); + registry.Verdict(longLived, condition, 1, now, null, Allow).ShouldBeTrue(); + registry.Verdict(longLived, condition, 1, now + ProjectedConditionRegistry.PositiveVerdictTtl + TimeSpan.FromSeconds(1), null, Allow); + computes.ShouldBe(4, "a positive verdict lives at most the TTL"); + } + private async Task BootAsync() { var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions @@ -142,6 +163,7 @@ public sealed class ImportedConditionClassifierTests : IAsyncDisposable public long AuthorityGeneration => Generation; public IDisposable? AcquireEventDemand(RoleCarryingUserIdentity? caller) => null; public bool CanSubscribeFolder(RoleCarryingUserIdentity? caller, string mappingId, string folderLocalSubject) => caller is not null && Visible; + public bool IsConditionBearingMapping(string mappingId) => true; } private sealed class Fixture From 01a4e8db9d0c4cd172a99f50fced71089a077e56 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 19:24:54 -0500 Subject: [PATCH 23/32] =?UTF-8?q?docs(grpc-data):=20A3a=20review=20round?= =?UTF-8?q?=201=20=E2=80=94=20finding=20=E2=86=92=20resolution=20=E2=86=92?= =?UTF-8?q?=20test=20=E2=86=92=20red-on-revert=20table,=20gates,=20live=20?= =?UTF-8?q?a3r1-cond-1=20PASS?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/plans/evidence/grpc-data-ext/A3.md | 63 +++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/docs/plans/evidence/grpc-data-ext/A3.md b/docs/plans/evidence/grpc-data-ext/A3.md index c8fea4c3b..1a474b258 100644 --- a/docs/plans/evidence/grpc-data-ext/A3.md +++ b/docs/plans/evidence/grpc-data-ext/A3.md @@ -372,3 +372,66 @@ Each fix changed the image inputs, so each run was torn down and a fresh run id | OI `ImportedConditionMethodWireTests` ×3 | 7/7 each | | `git diff master -- '*Goldens.cs'` | empty | | Live `a3b-cond-3` | PASS (above) | + +--- + +# A3 — Review round 1 (A3a adversarial review, `a3a-review-round1.md`, written against `b5ab6e7c`) + +2026-11-24, branch `a3-consumer`, on top of A3b (`3c941458`). Not merged, not pushed. Commits: `69aeeb77` (runner + NM fixes, +Runtime tests), `14343bf0` (folder promotion for folder-only demand, NM tests). + +"Red on revert": the test was run with the fix removed (Runtime: the whole HEAD runner restored with interface stubs; NM: the +single fix line(s) removed by a scripted mutation) and failed; the fix was then restored and the test passed. + +| Finding | Resolution | Test(s) | Red on revert | +|---|---|---|---| +| **B1** in-stream re-snapshot removes conditions | `ProjectedConditionAccess.Runner.cs`: a begin opens a per-mapping `Buffer`; snapshot records fill it; the committed `Live` set (and every node) is untouched until `snapshot_complete`, which swaps and re-merges old ∪ new keys — only a key the complete set no longer lists (and no other mapping lists) is removed. Deltas apply to `Live` and the buffer. An in-stream capacity refusal removes the mapping's keys once (keys another mapping lists survive) and requires refresh | `B1_an_in_stream_multi_frame_re_snapshot…` (begin + 2 record frames + positive control on map-b, then complete); `B1_an_in_stream_re_snapshot_over_capacity…` | yes / yes (refresh assertion; the removal shape itself was already right) | +| **B2** timed-out / non-Good mapping frozen Good | frames of a timed-out mapping keep being processed: a late `snapshot_complete` swaps in and re-runs the merge (full re-diff); at an incomplete barrier the keys no contributing mapping lists are `MarkConditionsStale` (new sink method, `BadNoCommunication`, one event each, never removed); after the barrier a still-`Unavailable` mapping ends the stream after a bounded wait (`ConditionSnapshotTimeout` × 1,2,4,8 backoff), cancelled by a late completion | `B2_a_snapshot_completing_after_the_timeout…`; `B2_an_incomplete_barrier_marks…`; `B2_S7_a_refused_item…` (new stream within 5 s) | yes / yes / yes | +| **Deviation 9** Primary endpoint | new `IDataPrimarySubscriptionSource.SubscribePrimaryAsync` (Abstractions) on `GrpcDataConnection` (skips a non-Primary endpoint; a role-only miss is not a discovery failure, no probe backoff) and the deployment lease; the runner uses it and also drops any stream whose provenance role is not Primary | `Deviation9_a_condition_stream_served_by_a_Secondary…` | yes (hangs: the old runner keeps the Secondary stream) | +| **B3** revalidation stands down folder items; demand leak | `RevalidateEventItems` asks `ImportedNotifierAdmits` for a projected notifier; the unsubscribe arm releases demand before both early returns; `_authorizer?.LogFiltered` (a rig without an authorizer NRE'd once an item was stood down) | `B3_revalidation_keeps_an_admitted_folder_item_and_deleting_a_stood_down_item_releases_its_demand` (real `RevalidateMonitoredItems()`, lease counter) | yes (revalidation mutation) / yes (demand-order mutation) | +| **B4** host caps per connection / order / trust `total` | one node-wide `ConditionLedger`: connection charge = max(materialised keys, Σ mapping claims); a claim is the admitted `total` while snapshotting, the record count after (growth is charged); admission is against everything charged or claimed, order-independent. Records past `total`, `Live` past `MaxConditions`, or growth past the node caps ⇒ `ConditionCapacity` (item removed, keys removed, refresh). `ChargedConditions` observation | `B4_the_host_caps_are_node_wide_across_connections`; `B4_admission_is_order_independent…`; `B4_records_past_the_snapshot_total…`; `B4_post_snapshot_delta_growth…` | yes ×4 | +| **S1** rebuild leaves stale wiring | `RebuildAddressSpace` calls `UnwireAllImportedFolders()` before clearing; `WiredByFolder` keeps the promoted folder INSTANCE — a re-created folder with the same NodeId unwires the dead instance and is promoted afresh | `S1_a_full_rebuild_unwires_and_the_re_created_folder_is_promoted_and_delivers_again` | yes (rebuild-unwire removed), yes (both removed) | +| **S2** verdict cache outlives expiry / IsActive | `Verdict` stores `ValidUntil` = min(credential expiry, now + 5 s) for a positive verdict; `AuthorityGeneration` folds every current mapping's `Authority.IsActive` | `S2_a_cached_positive_verdict_is_re_proved…` (OpcUaServer.Tests); `S2_an_authority_deactivation_moves_the_authority_generation…` (Runtime) | yes / yes (by construction: the old formula ignores IsActive) | +| **S3** removal races a new runner | a new runner of a connection awaits its predecessor's `Stopped` (loop end + removal) before opening a stream; stopped runners are kept per connection in `_stopping` | `S3_a_new_runner_waits_for_the_old_runners_removal…` (the sink holds the old removal open 400 ms) | yes | +| **S4** `TakeMaterialised` cross-thread | the materialised set is handed over inside the new runner's loop after the predecessor stopped (no concurrent mutation, no orphaned key) | `S4_a_mapping_change_hands_the_materialised_set_over…` | **no** — the race window is one in-flight frame; the test pins the hand-over, it cannot force the interleaving | +| **S5** Lock-hold bounds | `ProjectedFolderIndex()` scan replaced by the incremental `FolderIds`/`FolderKeys` index (maintained in `OnProjectedFolderMaterialised`/`Removing`, cleared on rebuild, resolved against the live projected maps); refresh targets gathered 128 conditions per hold, visibility decided off Lock | covered by every OI wiring test (index correctness); no timing test | n/a (not behaviour-observable) | +| **S6** metadata failure swallowed | a root whose metadata is not Good (or a failed call) is `Unavailable` (logged), its item is not opened; all roots failing ends the stream | `S6_a_root_whose_metadata_fails…` | yes | +| **S7** RefreshRequired only on timeout | any incomplete barrier (a mapping not `Known`: timed out, refused, metadata) requires refresh | `B2_S7_a_refused_item…` (`RefreshRequired == 1`) | yes | +| **Deviation 3** folder-only demand | event items on any projected folder are admitted through `ImportedNotifierAdmits` = a wired condition the caller sees, OR the mapping gate on the folder's own (mapping, subject) key (`IProjectedConditionAccess.CanSubscribeFolder`); projected folders of a condition-bearing mapping (`IsConditionBearingMapping`) are `SubscribeToEvents` from materialisation (the SDK answers `BadNotSupported` before `SubscribeToEvents` otherwise) and never demoted by an unwire | `Deviation3_a_folder_only_client_opens_demand…` (granted Good + demand + the condition then delivered; anonymous denied) | yes (promotion removed ⇒ `BadNotSupported`) | +| **Deviation 6** removal tells nobody | `RemoveConditions` captures the items that may see the conditions BEFORE unwiring, removes, then queues `RefreshRequired` (off Lock) to those passing the gate. `RequireRefresh`'s early return on a connection with no conditions stays: nothing of it can be held any more — the removal itself now notifies | `Deviation6_removing_an_imported_condition_sends_RefreshRequired_only_to_the_items_that_could_see_it` (Server + folder get it; a map-b folder item does not, after a must-arrive control) | yes | +| **Deviation 8** one-hold replay | `ReplayImportedConditions` runs 128 conditions per Lock hold; each condition's snapshot and its queueing share a hold (ordering vs. live events kept) and one `EventDeliveryCache` per snapshot is shared across items | `Deviation8_ConditionRefresh_replays_hundreds…` (300 conditions inside RefreshStart/End) | **no** — chunking is not observable; the test guards correctness of the chunked replay | +| **A3b open item** RefreshRequired scope after an EventId-invalidating resync | `ApplyConditions` collects the un-re-bindable CONDITIONS and refreshes only the items that may see one of them (shared `QueueImportedRefresh`) | via the shared targeting in `Deviation6_…` (a folder item of another mapping is not refreshed); the A3b re-binding test still passes | not separately reverted | +| NIT `IsWiredTo` reads `Folders` off Lock | `ImportedCondition.WiredFolders` immutable array, replaced under Lock on wire/unwire | — | n/a | +| NIT `Infos` never pruned | `ConditionSet.Apply` drops the info with a removed key; a swap discards the old set | — | n/a | +| NIT stale callback after a fresh barrier | stale mark and barrier serialize on the runner's stale gate + generation | — | n/a (race) | +| Test adequacy: vacuous absence assertions | `Applied.ShouldBeEmpty` / `Removed.ShouldBeEmpty` now follow a must-arrive control (a later frame's item removal; the barrier) | the three original tests rewritten | — | +| Test adequacy: delivery gate not isolated | `ImportedConditionDeliveryGateTests` (non-parallel collection): the denied Server-object session gets nothing AND `ProjectedEventFieldList.DroppedOnPublish` does not move | `A3_SEC_the_delivery_gate_alone_withholds…` | yes — removing only the Server-object delivery gate turns it red while the original A3-SEC test stays green | + +Residual / recorded: +- A projected folder materialised while its mapping was NOT condition-bearing (or before `ProjectedConditionAccess` is bound) is + not promoted until it re-materialises; the host binds access before any projection deploys. +- The B2 retry ends the whole stream (complete mappings re-snapshot too), bounded by the backoff; a per-item re-add is A4 material. +- In-stream capacity refusal removes the mapping's keys (all-or-nothing, §5.5) rather than keeping them stale. + +## Gates (review round 1, at `14343bf0`) + +| Gate | Result | +|---|---| +| `dotnet build ZB.MOM.WW.OtOpcUa.slnx --no-incremental` | 0 warnings, 0 errors | +| `run-unit-phase.py A3` | passed (`20261124T234716…`) | +| `run-unit-phase.py A2` | passed (`20261124T234814…`) | +| `run-unit-phase.py A1` | passed (`20261124T234927…`) | +| `run-unit-phase.py X0` | passed (`20261124T235258…`) | +| Host.Tests `.DataConnections.` (both v1 gates) | 207 passed | +| Runtime.Tests full (`Category!=E2E&Category!=LiveIntegration`) | 2049 passed, 3 skipped (no #920 rerun needed) | +| OpcUaServer.Tests full (same filter) | 1456 passed, 1 skipped | +| OI `Feature=GrpcData` + ConditionMethodEvent / NativeAlarmEventIdentityFieldDelivery / FolderConditionRefresh / ConditionRefreshDeferral | 129 passed, 1 skipped in 2 of 4 runs; the other 2 runs failed 2 and 6 of the #854 deferral stress tests (`ConditionRefreshDeferralWireTests` / `FolderConditionRefreshWireTests` `Deferred_events_older_than_a_refresh…`, `A_condition_removed_during_a_plain_refresh…`) — **pre-existing**: the same suite at the unchanged base `3c941458` failed 2 of them in 1 of 3 runs; the classes pass 3/3 in isolation on this branch; no imported-condition code is reached in those rigs (no `ProjectedConditionAccess`). Root cause not established (load-sensitive local-condition deferral) — to be filed as an issue, not closed as a flake | +| `git diff master -- '*Goldens.cs'` | empty | + +## Live — run `a3r1-cond-1` (build `14343bf0` + docs) — PASS + +Same procedure as `a3b-cond-3` (`rig.py up --conditions`, seed, ~88 s, deploy, `conditions_a3_smoke.py`, `rig.py down`). +Consumer: `stream 1 for connection consumer-source opened (2 mapping(s), serving source-1:4053)` (the Primary, now via +`SubscribePrimaryAsync`); barrier `map-raw=Complete, map-uns=Complete; 1 record(s)`. Bogus EventId ⇒ `BadEventIdUnknown`; ack +through the consumer `Acknowledge successful` (608 ms); origin subscriber and consumer subscriber each saw exactly one +Active/Acknowledged. Teardown: no run-labelled containers or networks left. From 72dece7f4564c1ae72459f6576528f00020e644a Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 19:59:21 -0500 Subject: [PATCH 24/32] =?UTF-8?q?fix(grpc-data):=20A3b=20review=20r1=20?= =?UTF-8?q?=E2=80=94=20per-item=20results=20after=20base.Call=20(S1),=20ma?= =?UTF-8?q?pping=20timeout=20honoured=20+=20transport-known=20BadTimeout?= =?UTF-8?q?=20(S2),=20unsent=20vs=20OutcomeUnknown=20+=20origin=20failure?= =?UTF-8?q?=20status=20(S3),=20per-connection=20sub-limit=20+=20dispatch?= =?UTF-8?q?=20floor=20(S4),=20N1/N2/N3/N7/N8;=20tests:=20real-path=20L3,?= =?UTF-8?q?=20worst-case=20L2=20harness,=20RefreshRequired=20over=20the=20?= =?UTF-8?q?wire,=20Confirm=20guards=20isolated,=20gate=20placements/realm,?= =?UTF-8?q?=20slots,=20standby,=20faults,=20principals?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ImportedConditionMethods.cs | 139 ++++++-- .../ProjectedConditionRegistry.cs | 24 +- .../GrpcDataConnection.ConditionMethods.cs | 23 +- .../ProjectedConditionAccess.Methods.cs | 9 +- ...ImportedConditionMemoryMeasurementTests.cs | 73 ++++- .../ImportedConditionMethodWireTests.cs | 306 +++++++++++++++++- .../RealConditionMethodPath.cs | 206 ++++++++++++ .../GrpcDataConditionMethodClientTests.cs | 45 ++- .../GrpcDataProjectedConditionMethodTests.cs | 38 +++ 9 files changed, 787 insertions(+), 76 deletions(-) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/RealConditionMethodPath.cs diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ImportedConditionMethods.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ImportedConditionMethods.cs index 21476a2a8..5ded216f2 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ImportedConditionMethods.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ImportedConditionMethods.cs @@ -62,10 +62,25 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager /// Most remote condition methods in flight on this node (§5.6: bounds upstream load, not threads). internal const int DefaultImportedMethodConcurrency = 8; + /// + /// A3b review S4: most remote condition methods in flight to ONE connection — a sub-limit inside the node-wide + /// , so a stalled origin holds at most half the node's slots and acks to + /// healthy origins still dispatch. + /// + internal const int DefaultImportedMethodConcurrencyPerConnection = 4; + /// How long past the call's own budget the node manager waits for the port before answering BadTimeout. internal static readonly TimeSpan ImportedMethodGrace = TimeSpan.FromMilliseconds(250); + /// + /// A3b review S4: a call whose remaining budget at dispatch is below this is refused BadTimeout UNSENT — the origin + /// could apply it while the consumer had already answered BadTimeout. + /// + internal static readonly TimeSpan ImportedMethodMinimumDispatchBudget = TimeSpan.FromMilliseconds(250); + private readonly SemaphoreSlim _importedMethodSlots = new(DefaultImportedMethodConcurrency, DefaultImportedMethodConcurrency); + // One per connection that ever dispatched (connections are few and long-lived; never removed — a SemaphoreSlim is small). + private readonly ConcurrentDictionary _importedMethodConnectionSlots = new(StringComparer.Ordinal); private readonly ConcurrentDictionary> _importedMethodsInFlight = new(StringComparer.Ordinal); private long _importedMethodsDispatched, _importedMethodsJoined, _importedMethodsRefused; @@ -85,7 +100,8 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager /// §5.6 step 1: (a) claim every unprocessed request whose ObjectId is in mapped/conditions — a namespace-index /// test, no lock; (b) the unchanged synchronous base.Call for everything else (it skips claimed requests), run /// and completed before any remote await; (c) the claimed calls concurrently, bounded by the per-node semaphore. - /// No Lock is held by this method at any point. + /// No Lock is held by this method at any point. Review S1: nothing after base.Call throws — local items are + /// already applied by then, so a fault there must become a per-item status, never a ServiceFault for the batch. /// public override async ValueTask CallAsync(OperationContext context, ArrayOf methodsToCall, IList results, IList errors, CancellationToken cancellationToken = default) @@ -109,10 +125,26 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager for (var k = 0; k < claimed.Count; k++) { results[claimed[k]] = new CallMethodResult(); - calls[k] = CallImportedAsync(caller, methodsToCall[claimed[k]], deadline, linked.Token); + calls[k] = CallImportedGuardedAsync(caller, methodsToCall[claimed[k]], deadline, linked.Token); + } + // Each task is guarded (never faults), so WhenAll never throws; results are collected per item regardless. + await Task.WhenAll(calls).ConfigureAwait(false); + for (var k = 0; k < claimed.Count; k++) errors[claimed[k]] = calls[k].Result; + } + + /// Review S1: as a task that cannot fault (a synchronous throw included). + private async Task CallImportedGuardedAsync(RoleCarryingUserIdentity? caller, CallMethodRequest request, DateTime deadline, + CancellationToken cancellationToken) + { + try + { + return await CallImportedAsync(caller, request, deadline, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) + { + _logger.LogError(ex, "OtOpcUaNodeManager: imported condition method failed before dispatch"); + return Refuse(StatusCodes.BadInternalError); } - var outcomes = await Task.WhenAll(calls).ConfigureAwait(false); - for (var k = 0; k < claimed.Count; k++) errors[claimed[k]] = outcomes[k]; } /// @@ -133,7 +165,8 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager if (method == DataConditionMethods.None) return Refuse(StatusCodes.BadNotSupported); // shelve, enable/disable, … if (ProjectedConditionMethods is not { } port) return Refuse(StatusCodes.BadNotSupported); - // Step 2 local checks (no I/O, no Lock). The mapping gate first: an unauthorized caller learns nothing else. + // Step 2 local checks (no I/O, no Lock). The mapping gate first: an unauthorized caller learns nothing else + // (review N5: the two answers above are the SDK pre-validation's own — the node and its method exist publicly). var placements = condition.Placements; var route = port.AuthorizeMethod(caller, placements, method); if (route is null || caller is null) return Refuse(StatusCodes.BadUserAccessDenied); @@ -157,6 +190,8 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager if (expected is null) return Refuse(StatusCodes.BadEventIdUnknown); // An identical call already in flight (same caller, condition, EventId, method, comment) joins it: one dispatch. + // Review N4: a joiner shares the first caller's outcome — its cancellation and budget included (it asked for the + // same thing at the same moment; a joiner never dispatches a second time). var key = string.Join('\n', caller.Principal, condition.Alarm.NodeId.ToString(), Convert.ToHexString(eventId.Span), ((uint)method).ToString(System.Globalization.CultureInfo.InvariantCulture), comment ?? "\u0001"); var mine = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); @@ -168,17 +203,22 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager } try { - var result = await DispatchImportedAsync(port, condition, route, method, expected, comment, caller, deadline, started, - cancellationToken).ConfigureAwait(false); + ServiceResult result; + try + { + result = await DispatchImportedAsync(port, condition, route, method, expected, comment, caller, deadline, started, + cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) + { + // DispatchImportedAsync answers every post-dispatch failure itself: anything escaping it was thrown before + // the port was called — nothing was sent (review S1/S3). + _logger.LogError(ex, "OtOpcUaNodeManager: imported condition method failed before dispatch"); + result = Refuse(StatusCodes.BadInternalError); + } mine.TrySetResult(result); return result; } - catch (Exception ex) - { - var unknown = new ServiceResult(StatusCodes.BadCommunicationError, new LocalizedText("OutcomeUnknown: " + ex.GetType().Name)); - mine.TrySetResult(unknown); - return unknown; - } finally { _importedMethodsInFlight.TryRemove(new KeyValuePair>(key, mine.Task)); @@ -194,22 +234,40 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager ImportedConditionMethodRoute route, DataConditionMethods method, DataActivationMarker expected, string? comment, RoleCarryingUserIdentity caller, DateTime deadline, long started, CancellationToken cancellationToken) { - // Step 4: timeout = min(request deadline, ConditionMethodTimeout). - var budget = route.Timeout; + // Step 4: timeout = min(request deadline, ConditionMethodTimeout), as ONE end instant (review N7: elapsed time was + // subtracted from the request-deadline leg twice). When the request deadline binds, the grace the node manager waits + // past the budget is taken out of it, so the answer still lands inside the client's TimeoutHint. + var end = started + (long)(route.Timeout.TotalSeconds * Stopwatch.Frequency); if (deadline != DateTime.MaxValue && deadline > DateTime.MinValue) { - var left = deadline - DateTime.UtcNow; - if (left < budget) budget = left; + var byDeadline = Stopwatch.GetTimestamp() + (long)((deadline - DateTime.UtcNow - ImportedMethodGrace).TotalSeconds * Stopwatch.Frequency); + if (byDeadline < end) end = byDeadline; } - budget -= Stopwatch.GetElapsedTime(started); - if (budget <= TimeSpan.Zero) return Refuse(StatusCodes.BadTimeout); + TimeSpan Remaining() => Stopwatch.GetElapsedTime(Stopwatch.GetTimestamp(), end); + if (Remaining() < ImportedMethodMinimumDispatchBudget) return Refuse(StatusCodes.BadTimeout); - if (!await _importedMethodSlots.WaitAsync(budget, cancellationToken).ConfigureAwait(false)) - return Refuse(StatusCodes.BadTooManyOperations); + // Review S4: the connection's sub-limit first, then the node-wide slots. Review S3: a cancel while WAITING is unsent. + var perConnection = _importedMethodConnectionSlots.GetOrAdd(condition.ConnectionId, + static _ => new SemaphoreSlim(DefaultImportedMethodConcurrencyPerConnection, DefaultImportedMethodConcurrencyPerConnection)); + bool connectionSlot = false, nodeSlot = false; try { - var remaining = budget - Stopwatch.GetElapsedTime(started); - if (remaining <= TimeSpan.Zero) return Refuse(StatusCodes.BadTimeout); + try + { + connectionSlot = await perConnection.WaitAsync(Remaining() is var w && w > TimeSpan.Zero ? w : TimeSpan.Zero, cancellationToken) + .ConfigureAwait(false); + if (!connectionSlot) return Refuse(StatusCodes.BadTooManyOperations); + nodeSlot = await _importedMethodSlots.WaitAsync(Remaining() is var n && n > TimeSpan.Zero ? n : TimeSpan.Zero, cancellationToken) + .ConfigureAwait(false); + if (!nodeSlot) return Refuse(StatusCodes.BadTooManyOperations); + } + catch (OperationCanceledException) + { + return Refuse(StatusCodes.BadRequestCancelledByClient); // nothing sent + } + + var remaining = Remaining(); + if (remaining < ImportedMethodMinimumDispatchBudget) return Refuse(StatusCodes.BadTimeout); // review S4 floor: unsent var call = new ImportedConditionMethodCall(condition.ConnectionId, condition.ConditionKey, route.Placement, method, expected, comment, "a3-" + Guid.NewGuid().ToString("N"), remaining, caller.Principal); using var bounded = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); @@ -224,6 +282,8 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager catch (TimeoutException) { // The port did not answer inside the budget: it may have reached the origin — OutcomeUnknown, never retried. + // Review N1: WaitAsync and CancelAfter share a due time; cancel explicitly so the port's call ends with it. + bounded.Cancel(); return Unknown(StatusCodes.BadTimeout, "OutcomeUnknown: no answer within the condition method timeout."); } catch (OperationCanceledException) when (bounded.IsCancellationRequested) @@ -231,21 +291,29 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager return Unknown(cancellationToken.IsCancellationRequested ? StatusCodes.BadCommunicationError : StatusCodes.BadTimeout, "OutcomeUnknown: the call was cancelled after dispatch."); } - return MapOutcome(result, Stopwatch.GetElapsedTime(started) >= budget); + catch (Exception ex) + { + // The port is contracted not to throw for a remote failure; one that does may have sent the request. + return Unknown(StatusCodes.BadCommunicationError, "OutcomeUnknown: " + ex.GetType().Name); + } + return MapOutcome(result); } finally { - _importedMethodSlots.Release(); + if (nodeSlot) _importedMethodSlots.Release(); + if (connectionSlot) perConnection.Release(); } } /// /// §5.6 step 5 outcome mapping. Applied (scripted DriverConfirmedSuccess) and accepted (native - /// AcceptedUnconfirmed) ⇒ Good — the confirming record arrives on the stream; RejectedBeforeDispatch ⇒ the - /// origin's status; OutcomeUnknown ⇒ BadTimeout when the budget ran out, else BadCommunicationError - /// — always Bad (the client must not read it as done), with "OutcomeUnknown" in the diagnostic. + /// AcceptedUnconfirmed) ⇒ Good — the confirming record arrives on the stream; RejectedBeforeDispatch and + /// DriverConfirmedFailure ⇒ the origin's status (review S3: a definite failure is not "unknown"); + /// OutcomeUnknown ⇒ the status the transport KNEW (review S2: BadTimeout on a deadline, else + /// BadCommunicationError) — always Bad (the client must not read it as done), with "OutcomeUnknown" in the + /// diagnostic. /// - internal ServiceResult MapOutcome(DataConditionMethodResult result, bool budgetElapsed) + internal ServiceResult MapOutcome(DataConditionMethodResult result) { switch (result.State) { @@ -253,11 +321,13 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager case DataWriteState.AcceptedUnconfirmed: return StatusCode.IsBad(new StatusCode(result.StatusCode)) ? new ServiceResult(new StatusCode(result.StatusCode)) : ServiceResult.Good; case DataWriteState.RejectedBeforeDispatch: + case DataWriteState.DriverConfirmedFailure: var refused = new StatusCode(result.StatusCode); if (!StatusCode.IsBad(refused)) refused = StatusCodes.BadInternalError; return result.Diagnostic is { Length: > 0 } text ? new ServiceResult(refused, new LocalizedText(text)) : new ServiceResult(refused); default: - return Unknown(budgetElapsed ? StatusCodes.BadTimeout : StatusCodes.BadCommunicationError, + var known = new StatusCode(result.StatusCode); + return Unknown(StatusCode.IsBad(known) && known.Code == StatusCodes.BadTimeout.Code ? StatusCodes.BadTimeout : StatusCodes.BadCommunicationError, "OutcomeUnknown: " + (result.Diagnostic ?? "the origin's outcome is unknown.")); } } @@ -324,8 +394,13 @@ public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager MintImportedEventId(condition, current); return false; } - if (previous is null || current is null || previous == current) return false; - if (state.TimeUtc is { } time && previousTime == time) + if (previous == current) return false; + // Review N3: a marker appearing or disappearing is a marker change too — mint and refresh, never leave the current + // EventId bound to a marker no record carries. Review N2: re-binding (F6) is for an origin RESTART only — a new + // incarnation re-announcing the same state at the same time; a same-incarnation sequence bump is, by the origin's + // definition, a new occurrence. + if (previous is not null && current is not null && previous.Incarnation != current.Incarnation + && state.TimeUtc is { } time && previousTime == time) { var node = condition.RecentEvents.First; while (node is not null) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs index c70aaf338..201603370 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs @@ -19,7 +19,15 @@ internal sealed class ImportedCondition(AlarmConditionState alarm, string connec public AlarmConditionState Alarm { get; } = alarm; public string ConnectionId { get; } = connectionId; public string ConditionKey { get; } = conditionKey; - public IReadOnlyList Placements { get; set; } = []; + private IReadOnlyList _placements = []; + private long _supportedMethods = -1; + + /// Written under Lock; read without it by A3b methods (review N8: a volatile publication of an immutable list). + public IReadOnlyList Placements + { + get => Volatile.Read(ref _placements); + set => Volatile.Write(ref _placements, value); + } public HashSet Folders { get; } = new(ReferenceEqualityComparer.Instance); /// NIT (review r1): an immutable copy of for the delivery paths that read off Lock. public FolderState[] WiredFolders { get; set; } = []; @@ -34,7 +42,12 @@ internal sealed class ImportedCondition(AlarmConditionState alarm, string connec /// marker under it, never under the node manager's Lock. public object MethodGate { get; } = new(); /// The origin's supported_methods for the service principal (null until a listing carried it). - public uint? SupportedMethods { get; set; } + /// Review N8: read without Lock by A3b methods — stored as one atomic 64-bit word (-1 = not listed yet). + public uint? SupportedMethods + { + get => Interlocked.Read(ref _supportedMethods) is var v && v >= 0 ? (uint)v : null; + set => Interlocked.Exchange(ref _supportedMethods, value is { } m ? m : -1); + } /// The time of the latest applied record (N6/F6: re-binding requires it unchanged). public DateTimeOffset? LastTime { get; set; } /// Bumped on every placement change (verdict caches key on it). @@ -155,6 +168,13 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink /// Imported condition events reported (one per genuine origin transition). internal long ImportedEventsReported => Interlocked.Read(ref _importedEventsReported); + /// How many N6 EventId slots a condition holds (test/diagnostic observation, the L2 harness). + internal int FindImportedConditionRecentEventCount(string connectionId, string conditionKey) + { + if (_importedConditions.Find(ImportedConditionNodeId(connectionId, conditionKey)) is not { } c) return 0; + lock (c.MethodGate) return c.RecentEvents.Count; + } + /// RefreshRequired events queued for imported conditions. internal long ImportedRefreshRequiredQueued => Interlocked.Read(ref _importedRefreshRequired); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.ConditionMethods.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.ConditionMethods.cs index 4e60bec48..9a8e5effd 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.ConditionMethods.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.ConditionMethods.cs @@ -16,9 +16,17 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; public sealed partial class GrpcDataConnection : IDataConditionMethodService { internal const uint BadCommunicationError = 0x80050000u; - private TimeSpan _conditionMethodTimeout = TimeSpan.FromSeconds(5); + /// + /// The validator's ceiling for a mapping's ConditionMethodTimeoutMilliseconds (3,600,000 ms) — the client's default + /// backstop. A3b review S2: the per-MAPPING ceiling arrives in + /// (the consumer node manager computes min(request deadline, mapping timeout) − elapsed); a connection-wide 5 s default + /// here silently capped a 30 s mapping at 5 s. + /// + public static readonly TimeSpan MaxConditionMethodTimeout = TimeSpan.FromMilliseconds(3_600_000); - /// The per-call method ceiling (the mapping's ConditionMethodTimeoutMilliseconds; A3 binds it per mapping). + private TimeSpan _conditionMethodTimeout = MaxConditionMethodTimeout; + + /// An optional connection-wide backstop over the per-call budget (default ). public TimeSpan ConditionMethodTimeout { get => _conditionMethodTimeout; @@ -29,7 +37,9 @@ public sealed partial class GrpcDataConnection : IDataConditionMethodService public async Task CallConditionMethodAsync(DataConditionMethodRequest request, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(request); - request.Validate(); + // A3b review S3: an invalid request is refused unsent, never thrown into a caller that would read it as "unknown". + try { request.Validate(); } + catch (ArgumentException ex) { return new(DataWriteState.RejectedBeforeDispatch, BadInvalidArgument, "Invalid request: " + ex.Message); } var start = Clock.GetTimestamp(); var deadline = request.RemainingBudget < ConditionMethodTimeout ? request.RemainingBudget : ConditionMethodTimeout; if (deadline <= TimeSpan.Zero) return new(DataWriteState.RejectedBeforeDispatch, BadTimeout, "Budget expired before dispatch."); @@ -82,6 +92,12 @@ public sealed partial class GrpcDataConnection : IDataConditionMethodService ex.StatusCode is StatusCode.PermissionDenied or StatusCode.Unauthenticated ? 0x801F0000u : BadNotSupportedMethod, "Refused by the origin transport: " + ex.StatusCode); } + catch (RpcException ex) when (ex.StatusCode == StatusCode.DeadlineExceeded && !cancellationToken.IsCancellationRequested) + { + // A3b review S2: the deadline is a KNOWN timeout — say BadTimeout here instead of letting the caller infer it + // from its own clock. Still OutcomeUnknown: the origin may have applied it. + return new(DataWriteState.OutcomeUnknown, BadTimeout, "OutcomeUnknown: no answer before the method deadline."); + } catch (Exception ex) when (ex is RpcException or HttpRequestException or OperationCanceledException or InvalidOperationException or ArgumentException or IOException) { @@ -99,4 +115,5 @@ public sealed partial class GrpcDataConnection : IDataConditionMethodService } private const uint BadNotSupportedMethod = 0x803D0000u; + private const uint BadInvalidArgument = 0x80AB0000u; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Methods.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Methods.cs index 9583eb9f5..b54bd3119 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Methods.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Methods.cs @@ -18,6 +18,7 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionMethod private const uint BadNoCommunication = 0x80310000u; private const uint BadNotSupported = 0x803D0000u; private const uint BadUserAccessDenied = 0x801F0000u; + private const uint BadInvalidArgument = 0x80AB0000u; /// public ImportedConditionMethodRoute? AuthorizeMethod(RoleCarryingUserIdentity? caller, IReadOnlyList placements, @@ -57,6 +58,12 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionMethod if (serving is null) return new(DataWriteState.RejectedBeforeDispatch, BadNoCommunication, "No condition stream is open on the connection."); + var request = new DataConditionMethodRequest(call.OperationId, call.Placement.Placement, call.Method, call.ExpectedActivation, + call.Comment, serving.Incarnation, call.RemainingBudget, call.OnBehalfOf); + // A3b review S3: validated before the lease — an invalid request is refused unsent, never an "unknown" outcome. + try { request.Validate(); } + catch (ArgumentException ex) { return new(DataWriteState.RejectedBeforeDispatch, BadInvalidArgument, "Invalid request: " + ex.Message); } + IGrpcDataAdapterConnectionLease? lease; try { lease = await _connections.AcquireAsync(call.ConnectionId, cancellationToken).ConfigureAwait(false); } catch (Exception ex) when (ex is InvalidOperationException or OperationCanceledException or TimeoutException) @@ -66,8 +73,6 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionMethod { if (lease.Connection is not IDataConditionMethodService methods) return new(DataWriteState.RejectedBeforeDispatch, BadNotSupported, "The connection does not serve condition methods."); - var request = new DataConditionMethodRequest(call.OperationId, call.Placement.Placement, call.Method, call.ExpectedActivation, - call.Comment, serving.Incarnation, call.RemainingBudget, call.OnBehalfOf); using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, lease.CancellationToken); try { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMemoryMeasurementTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMemoryMeasurementTests.cs index 8a3ca14f8..4154676d6 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMemoryMeasurementTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMemoryMeasurementTests.cs @@ -20,6 +20,7 @@ public sealed class ImportedConditionMemoryMeasurementTests { private const string Connection = "conn-l2"; private const string Mapping = "map-l2"; + private const string MappingB = "map-l2b"; private const int Conditions = 1_000; [Fact] @@ -29,29 +30,57 @@ public sealed class ImportedConditionMemoryMeasurementTests var ct = TestContext.Current.CancellationToken; await using var rig = await ServerEventRig.StartAsync("a3-l2", encrypted: false, ct); var nm = rig.Nm; - nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); - var parent = nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; - var root = new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant"); - nm.TryEnsureProjectedAnchor(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(Mapping, root), parent, - "remote", "Plant/remote", Mapping, 1, () => true), out _).ShouldBeTrue(); + // Access first: a condition-bearing mapping's anchor folders are event notifiers from materialisation. var access = new ImportedConditionEventWireTests.FakeConditionAccess(); access.Allowed.Add(ServerEventRig.KeyPrincipal); nm.ProjectedConditionAccess = access; + nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); + var parent = nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; + var root = new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant"); + // A3b review S5: worst case — TWO placements per condition (two mappings, two folders it is wired into). + nm.TryEnsureProjectedAnchor(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(Mapping, root), parent, + "remote", "Plant/remote", Mapping, 1, () => true), out var anchorA).ShouldBeTrue(); + nm.TryEnsureProjectedAnchor(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(MappingB, root), parent, + "remote-b", "Plant/remote-b", MappingB, 1, () => true), out var anchorB).ShouldBeTrue(); + + // Event items: the Server object and both placement folders, publishing OFF so the server-side queues hold their events. + using var session = await rig.ConnectAsync(anonymous: false, ct); + var subscription = new Opc.Ua.Client.Subscription(session.DefaultSubscription) { PublishingInterval = 1000, PublishingEnabled = false }; + session.AddSubscription(subscription); + await subscription.CreateAsync(ct); + foreach (var source in new[] { ObjectIds.Server, Local(session, anchorA!.Value), Local(session, anchorB!.Value) }) + { + var item = new Opc.Ua.Client.MonitoredItem(subscription.DefaultItem) + { + StartNodeId = source, AttributeId = Attributes.EventNotifier, QueueSize = 1000, + Filter = new EventFilter { SelectClauses = [new SimpleAttributeOperand(ObjectTypeIds.BaseEventType, new QualifiedName(BrowseNames.EventId)), + new SimpleAttributeOperand(ObjectTypeIds.BaseEventType, new QualifiedName(BrowseNames.Message))] }, + }; + subscription.AddItem(item); + } + await subscription.ApplyChangesAsync(ct); + subscription.MonitoredItems.All(m => ServiceResult.IsGood(m.Status.Error)).ShouldBeTrue("all three event items are admitted"); var (heap0, ws0) = Measure(); var keys = Enumerable.Range(0, Conditions).Select(i => KeyOf("l2-" + i)).ToArray(); - var first = keys.Select((k, i) => Update(k, i, 3, active: true, acked: false)).ToList(); + // Runner state (worst case): the committed Live records AND a full re-snapshot Buffer of the same keys. + var live = keys.Select((k, i) => Update(k, i, 3, active: true, acked: false, sequence: 1)).ToList(); var sw = Stopwatch.StartNew(); - nm.ApplyConditions(first); + nm.ApplyConditions(live); var materialise = sw.Elapsed; - first.Clear(); var (heapMid, _) = Measure(); - // One more transition each: every condition reports an event (consumer-minted EventId in its N6 registry). - var second = keys.Select((k, i) => Update(k, i, 4, active: true, acked: true)).ToList(); + // Every N6 EventId slot filled: RecentEventIds transitions per condition, each a reported event minting an EventId. + List buffer = []; sw.Restart(); - nm.ApplyConditions(second); + for (var t = 0; t < OpcUaServer.ProjectedConditionRegistry.RecentEventIds; t++) + { + buffer = keys.Select((k, i) => Update(k, i, 4 + t, active: true, acked: t % 2 == 0, sequence: (ulong)(2 + t / 2))).ToList(); + nm.ApplyConditions(buffer); + } var transition = sw.Elapsed; nm.ImportedConditionCount.ShouldBe(Conditions); + var slots = nm.FindImportedConditionRecentEventCount(Connection, keys[0]); + slots.ShouldBe(OpcUaServer.ProjectedConditionRegistry.RecentEventIds, "every N6 slot is in use"); // Exercise the verdict cache once per condition (one identity). var identity = new Security.RoleCarryingUserIdentity(new UserNameIdentityToken { UserName = "apikey" }, [], ServerEventRig.KeyPrincipal, "k", null, null); @@ -59,17 +88,23 @@ public sealed class ImportedConditionMemoryMeasurementTests nm.AuthorizeImportedCondition(identity, Core.Abstractions.OpcUaOperation.Read, nm.ImportedConditionNodeId(Connection, k)).ShouldBeTrue(); var (heap1, ws1) = Measure(); - GC.KeepAlive(second); + GC.KeepAlive(live); + GC.KeepAlive(buffer); + GC.KeepAlive(subscription); var heapGrowth = heap1 - heap0; var wsGrowth = ws1 - ws0; - var line = $"L2: {Conditions} conditions, one mapping: managed heap +{heapGrowth / 1048576.0:F1} MiB ({heapGrowth / Conditions:N0} B/condition; after materialise {(heapMid - heap0) / Conditions:N0}), " + + var line = $"L2 (worst case: 2 placements, {slots} EventId slots, 3 event items, Live+Buffer records): {Conditions} conditions: " + + $"managed heap +{heapGrowth / 1048576.0:F1} MiB ({heapGrowth / Conditions:N0} B/condition; after materialise {(heapMid - heap0) / Conditions:N0}), " + $"working set +{wsGrowth / 1048576.0:F1} MiB ({wsGrowth / Conditions:N0} B/condition); materialise {materialise.TotalMilliseconds:F0} ms, " + - $"transition {transition.TotalMilliseconds:F0} ms; events reported {nm.ImportedEventsReported}"; + $"{OpcUaServer.ProjectedConditionRegistry.RecentEventIds} transitions {transition.TotalMilliseconds:F0} ms; events reported {nm.ImportedEventsReported}"; TestContext.Current.TestOutputHelper?.WriteLine(line); if (Environment.GetEnvironmentVariable("OTOPCUA_A3_MEASURE_OUT") is { Length: > 0 } outPath) File.AppendAllText(outPath, line + Environment.NewLine); wsGrowth.ShouldBeLessThanOrEqualTo(200L * 1024 * 1024); } + private static NodeId Local(Opc.Ua.Client.ISession session, NodeId serverId) => + new(serverId.IdentifierAsString, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri)); + private static (long Heap, long WorkingSet) Measure() { for (var i = 0; i < 3; i++) { GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true); GC.WaitForPendingFinalizers(); } @@ -81,15 +116,19 @@ public sealed class ImportedConditionMemoryMeasurementTests private static string KeyOf(string seed) => Convert.ToBase64String(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(seed))).TrimEnd('=').Replace('+', '-').Replace('/', '_'); - private static ImportedConditionUpdate Update(string key, int index, long version, bool active, bool acked) + private static ImportedConditionUpdate Update(string key, int index, long version, bool active, bool acked, ulong sequence) { var path = $"Plant/dev{index / 10}/HR{index}"; var view = new DataView(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", path), DataRealm.Raw, null, 0, path); - var placements = new[] { new ImportedConditionPlacement(Mapping, DataRealm.Raw, view, "Plant/remote", path["Plant/".Length..]) }; + var placements = new[] + { + new ImportedConditionPlacement(Mapping, DataRealm.Raw, view, "Plant/remote", path["Plant/".Length..]), + new ImportedConditionPlacement(MappingB, DataRealm.Raw, view, "Plant/remote-b", path["Plant/".Length..]), + }; var info = new DataConditionInfo("http://opcfoundation.org/UA/:AlarmConditionType", $"HR{index}", DataConditionSourceKind.Native, [view], (uint)DataConditionMethodSets.Native); var state = new DataConditionState(key, version, false, true, info, active, acked, true, true, 0, 500, $"HR{index} high", - StatusCodes.Good.Code, null, 0, DateTimeOffset.UtcNow, true, new DataActivationMarker("inc", 1)); + StatusCodes.Good.Code, null, 0, DateTimeOffset.UtcNow, true, new DataActivationMarker("inc", sequence)); return new ImportedConditionUpdate(Connection, state, info, placements, "Plant/remote/" + placements[0].RelativePath); } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMethodWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMethodWireTests.cs index 6c0117226..4619bddfb 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMethodWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMethodWireTests.cs @@ -161,8 +161,7 @@ public sealed class ImportedConditionMethodWireTests (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, fresh, "x", ct)).ShouldBe(StatusCodes.Good); f.Port.Calls.Count.ShouldBe(2); f.Port.Calls.Last().ExpectedActivation.ShouldBe(new DataActivationMarker("inc-c", 9)); - // RequireRefresh ran (it queues only to items that exist; none here — the counter path is pinned by A3a's tests). - rig.Nm.ImportedRefreshRequiredQueued.ShouldBeGreaterThanOrEqualTo(refresh); + _ = refresh; // review S6: the RefreshRequired itself is pinned over the wire by A_resync_that_cannot_re_bind_… } /// @@ -170,12 +169,26 @@ public sealed class ImportedConditionMethodWireTests /// consumer complete in < 200 ms meanwhile, the node manager's Lock is free, and no acknowledged state is /// observable before the origin's record (positive control: it arrives after release). /// - [Fact] - public async Task Lock_freedom_a_5s_stalled_origin_method_delays_no_Read_Browse_or_data_Publish_and_applies_nothing_before_the_record() + /// + /// Review S5: false = the stall sits at the consumer's port (the original measurement); true = behind a REAL + /// ProjectedConditionAccess + lease + GrpcDataConnection, the in-process origin's handler stalling 5 s. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Lock_freedom_a_5s_stalled_origin_method_delays_no_Read_Browse_or_data_Publish_and_applies_nothing_before_the_record(bool realPath) { var ct = TestContext.Current.CancellationToken; await using var rig = await ServerEventRig.StartAsync("a3b-l3", encrypted: false, ct); var f = Fixture.Install(rig); + await using var real = realPath ? new RealConditionMethodPath(Connection, MappingA, f.Port, TimeSpan.FromSeconds(5)) : null; + if (real is not null) + { + rig.Nm.ProjectedConditionMethods = real.Port; + // The condition stream is open (its serving incarnation addresses the call) before anything is measured. + await WaitUntilAsync(() => real.Access.CallAsync(new ImportedConditionMethodCall(Connection, Key1, Fixture.DefaultPlacements[0], + DataConditionMethods.Acknowledge, Marker1, null, "probe", TimeSpan.Zero, null), ct).Result.StatusCode != 0x80310000u); + } var tag = rig.EnsureRawVariable("l3", "Double", writable: false); rig.Sink.WriteValue(tag, 0.0, 0, DateTime.UtcNow, AddressSpaceRealm.Raw); f.Apply(Update(version: 3, active: true, acked: false)); @@ -226,7 +239,7 @@ public sealed class ImportedConditionMethodWireTests f.Port.Handler = async (_, token) => { await Task.WhenAny(release.Task, Task.Delay(TimeSpan.FromSeconds(5), token)); return Applied(); }; var stall = Stopwatch.StartNew(); var ack = CallAsync(caller, f.ConditionId(caller), MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "l3", ct); - await WaitUntilAsync(() => f.Port.Calls.Count == 1); + await WaitUntilAsync(() => real is null ? f.Port.Calls.Count == 1 : Volatile.Read(ref real.Server.MethodCalls) == 1); var during = new List<(double Read, double Browse, double Publish, double LockWait)>(); for (var i = 0; i < 10 && !ack.IsCompleted; i++) @@ -238,6 +251,7 @@ public sealed class ImportedConditionMethodWireTests ack.IsCompleted.ShouldBeFalse("the measurements ran while the remote call was stalled"); during.Count.ShouldBe(10); (await ack).ShouldBe(StatusCodes.Good); + if (real is not null) Volatile.Read(ref real.Server.MethodAnswers).ShouldBe(1, "the origin's stalled handler answered once, after the stall"); var stalled = stall.Elapsed; f.Acked().ShouldBeFalse(); f.Apply(Update(version: 4, active: true, acked: true)); @@ -248,7 +262,7 @@ public sealed class ImportedConditionMethodWireTests var maxPublish = during.Max(m => m.Publish); var maxLock = during.Max(m => m.LockWait); var line = - $"L3: stall {stalled.TotalMilliseconds:F0} ms; baseline read {baseline.Read:F1} browse {baseline.Browse:F1} publish {baseline.Publish:F1} lock {baseline.LockWait:F2}; " + + $"L3 ({(realPath ? "real ProjectedConditionAccess + GrpcDataConnection" : "port")}): stall {stalled.TotalMilliseconds:F0} ms; baseline read {baseline.Read:F1} browse {baseline.Browse:F1} publish {baseline.Publish:F1} lock {baseline.LockWait:F2}; " + $"during (n={during.Count}) max read {maxRead:F1} browse {maxBrowse:F1} publish {maxPublish:F1} lock {maxLock:F2} ms"; TestContext.Current.TestOutputHelper?.WriteLine(line); if (Environment.GetEnvironmentVariable("OTOPCUA_A3_MEASURE_OUT") is { Length: > 0 } outPath) File.AppendAllText(outPath, line + Environment.NewLine); @@ -312,12 +326,14 @@ public sealed class ImportedConditionMethodWireTests f.Port.Handler = async (_, token) => { try { await Task.Delay(Timeout.Infinite, token); } - catch (OperationCanceledException) { cancelled = true; throw; } + catch (OperationCanceledException) { Volatile.Write(ref cancelled, true); throw; } return Applied(); }; var sw = Stopwatch.StartNew(); (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadTimeout); sw.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(3), "bounded by the mapping's method timeout (+ grace), not the request's"); + // Review N1: the port's call is cancelled explicitly on the timeout (it used to rely on a timer sharing WaitAsync's due + // time, disposed unfired when WaitAsync won). await WaitUntilAsync(() => Volatile.Read(ref cancelled)); f.Port.Calls.Count.ShouldBe(1, "dispatched once, never retried"); f.Acked().ShouldBeFalse(); @@ -325,6 +341,13 @@ public sealed class ImportedConditionMethodWireTests f.Port.Timeout = TimeSpan.FromSeconds(5); f.Port.Handler = (_, _) => Task.FromResult(new DataConditionMethodResult(DataWriteState.OutcomeUnknown, 0x80050000u, "transport failed")); (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadCommunicationError); + // Review S2: the transport's KNOWN timeout passes through (it used to be inferred from the consumer's own clock, so a + // deadline the transport hit before the consumer's budget elapsed read as BadCommunicationError). + f.Port.Handler = (_, _) => Task.FromResult(new DataConditionMethodResult(DataWriteState.OutcomeUnknown, StatusCodes.BadTimeout.Code, "deadline")); + (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadTimeout); + // Review S3: a definite failure at the origin is the origin's status, not "unknown". + f.Port.Handler = (_, _) => Task.FromResult(new DataConditionMethodResult(DataWriteState.DriverConfirmedFailure, StatusCodes.BadConditionAlreadyEnabled.Code, "refused")); + (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadConditionAlreadyEnabled); f.Port.Handler = (_, _) => Task.FromResult(new DataConditionMethodResult(DataWriteState.RejectedBeforeDispatch, StatusCodes.BadInvalidState.Code, "not Primary")); (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadInvalidState); f.Port.Handler = (_, _) => Task.FromResult(new DataConditionMethodResult(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "No condition stream")); @@ -332,6 +355,251 @@ public sealed class ImportedConditionMethodWireTests f.Acked().ShouldBeFalse("no outcome applies anything locally"); } + /// + /// A3b review S6 (non-vacuous RefreshRequired) + N2: a same-incarnation marker move at an unchanged time is a NEW + /// occurrence — not re-bound; the old EventId is unknown, a fresh one is ackable, and a subscriber that can see the + /// condition receives RefreshRequired over the wire. + /// + [Fact] + public async Task A_resync_that_cannot_re_bind_sends_RefreshRequired_to_a_subscriber_and_a_same_incarnation_bump_is_not_re_bound() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3b-refreshreq", encrypted: false, ct); + var f = Fixture.Install(rig); + var t0 = DateTimeOffset.UtcNow.AddMinutes(-1); + f.Apply(Update(version: 3, active: true, acked: false, time: t0)); + using var session = await rig.ConnectAsync(anonymous: false, ct); + var events = new RecordedEvents(); + var subscription = await RecordedEvents.SubscribeAsync(session, events, ct); + var serverItem = RecordedEvents.AddEventItem(subscription, ObjectIds.Server); + await subscription.ApplyChangesAsync(ct); + var id = f.ConditionId(session); + var before = f.CurrentEventId(); + events.HasType(serverItem, ObjectTypeIds.RefreshRequiredEventType).ShouldBeFalse(); + + // Same incarnation, sequence bumped, same time and state: by the origin's definition a new occurrence (review N2). + f.Apply(Update(version: 4, active: true, acked: false, time: t0, marker: new DataActivationMarker(Marker1.Incarnation, 2))); + await RecordedEvents.WaitUntilAsync(() => events.HasType(serverItem, ObjectTypeIds.RefreshRequiredEventType)); + (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, before, "x", ct)).ShouldBe(StatusCodes.BadEventIdUnknown); + var fresh = f.CurrentEventId(); + fresh.ShouldNotBe(before); + (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, fresh, "x", ct)).ShouldBe(StatusCodes.Good); + f.Port.Calls.Single().ExpectedActivation.ShouldBe(new DataActivationMarker(Marker1.Incarnation, 2)); + } + + /// Review N3: a record that first carries a marker (the previous one had none) binds a fresh, ackable EventId. + [Fact] + public async Task A_marker_appearing_on_an_unchanged_state_mints_an_ackable_EventId() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3b-nullmarker", encrypted: false, ct); + var f = Fixture.Install(rig); + var t0 = DateTimeOffset.UtcNow.AddMinutes(-1); + f.Apply(Update(version: 3, active: true, acked: false, time: t0, noMarker: true)); + using var session = await rig.ConnectAsync(anonymous: false, ct); + var id = f.ConditionId(session); + (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)) + .ShouldBe(StatusCodes.BadEventIdUnknown, "no marker: nothing to address the origin's occurrence with"); + + f.Apply(Update(version: 4, active: true, acked: false, time: t0)); + (await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.Good); + f.Port.Calls.Single().ExpectedActivation.ShouldBe(Marker1); + } + + /// + /// Review S6: the native-Confirm guard and the supported-methods guard, each isolated — a native condition whose listing + /// DOES carry Confirm is still refused; a scripted one whose listing lacks it is refused; a scripted one with it dispatches. + /// + [Fact] + public async Task Native_Confirm_is_refused_even_when_listed_and_a_scripted_Confirm_follows_the_listing() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3b-confirm", encrypted: false, ct); + var f = Fixture.Install(rig); + var native = KeyOf("native-listed"); var scriptedNo = KeyOf("scripted-no"); var scriptedYes = KeyOf("scripted-yes"); + var all = (uint)DataConditionMethodSets.All; + f.Apply(Update(version: 3, active: true, acked: true, key: native, methods: all)); + f.Apply(Update(version: 3, active: true, acked: true, native: false, key: scriptedNo, + methods: (uint)(DataConditionMethods.Acknowledge | DataConditionMethods.AddComment))); + f.Apply(Update(version: 3, active: true, acked: true, native: false, key: scriptedYes, methods: all)); + using var session = await rig.ConnectAsync(anonymous: false, ct); + + (await CallAsync(session, f.ConditionId(session, key: native), MethodIds.AcknowledgeableConditionType_Confirm, f.CurrentEventId(key: native), "c", ct)) + .ShouldBe(StatusCodes.BadNotSupported, "native: no upstream confirm path, whatever the listing says"); + (await CallAsync(session, f.ConditionId(session, key: scriptedNo), MethodIds.AcknowledgeableConditionType_Confirm, f.CurrentEventId(key: scriptedNo), "c", ct)) + .ShouldBe(StatusCodes.BadNotSupported, "the origin's supported_methods lacks Confirm"); + f.Port.Calls.ShouldBeEmpty(); + (await CallAsync(session, f.ConditionId(session, key: scriptedYes), MethodIds.AcknowledgeableConditionType_Confirm, f.CurrentEventId(key: scriptedYes), "c", ct)) + .ShouldBe(StatusCodes.Good); + f.Port.Calls.Single().Method.ShouldBe(DataConditionMethods.Confirm); + } + + /// + /// Review S1 + S6: a fault BEFORE dispatch (the gate throws) is that item's BadInternalError, unsent — the batch + /// still answers and a local item after the imported one is applied and Good (imported-first ordering); a batch + /// carrying a pre-validation failure answers it per item while its imported call dispatches; a port that THROWS after + /// dispatch is OutcomeUnknown (BadCommunicationError), dispatched once. + /// + [Fact] + public async Task A_fault_before_dispatch_is_a_per_item_BadInternalError_and_the_rest_of_the_batch_still_answers() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3b-fault", encrypted: false, ct); + rig.Enforce(true, [ServerEventRig.Key()], ServerEventRig.ClusterGrant(Granted, "acl-key", NodePermissions.Browse | NodePermissions.Read | NodePermissions.Subscribe | NodePermissions.AlarmRead + | NodePermissions.AlarmAcknowledge | NodePermissions.AlarmConfirm | NodePermissions.MethodCall)); + rig.MaterialiseNative(); + var routed = 0; + rig.Nm.NativeAlarmAckRouter = _ => Interlocked.Increment(ref routed); + var f = Fixture.Install(rig); + f.Apply(Update(version: 3, active: true, acked: false)); + using var session = await rig.ConnectAsync(anonymous: false, ct); + var events = new RecordedEvents(); + var subscription = await RecordedEvents.SubscribeAsync(session, events, ct); + var serverItem = RecordedEvents.AddEventItem(subscription, ObjectIds.Server); + await subscription.ApplyChangesAsync(ct); + rig.Project(true, new AlarmConditionSnapshot(true, false, true, true, AlarmShelvingKind.Unshelved, 700, "local")); + await RecordedEvents.WaitUntilAsync(() => events.Has(serverItem, "local")); + var localEventId = events.LatestEventId(serverItem, "local"); + + f.Port.AuthorizeThrows = true; + var response = await session.CallAsync(null, + [ + new CallMethodRequest { ObjectId = f.ConditionId(session), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge, + InputArguments = [new Variant(f.CurrentEventId()), new Variant(new LocalizedText("remote ack"))] }, + new CallMethodRequest { ObjectId = ServerEventRig.ConditionNodeId(session, native: true), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge, + InputArguments = [new Variant(ByteString.From(localEventId)), new Variant(new LocalizedText("local ack"))] }, + ], ct); + response.Results[0].StatusCode.Code.ShouldBe(StatusCodes.BadInternalError.Code, "the imported item faulted before dispatch"); + response.Results[1].StatusCode.Code.ShouldBe(StatusCodes.Good.Code, "the local item after it was applied and answers"); + Volatile.Read(ref routed).ShouldBe(1); + f.Port.Calls.ShouldBeEmpty("nothing was sent"); + + // A pre-validation failure in the same batch as a good imported call: answered per item, the imported one dispatched. + f.Port.AuthorizeThrows = false; + response = await session.CallAsync(null, + [ + new CallMethodRequest { ObjectId = f.ConditionId(session), MethodId = NodeId.Null }, + new CallMethodRequest { ObjectId = f.ConditionId(session), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge, + InputArguments = [new Variant(f.CurrentEventId()), new Variant(new LocalizedText("remote ack"))] }, + ], ct); + StatusCode.IsBad(response.Results[0].StatusCode).ShouldBeTrue(); + response.Results[1].StatusCode.Code.ShouldBe(StatusCodes.Good.Code); + f.Port.Calls.Count.ShouldBe(1); + + // A port that throws after dispatch: OutcomeUnknown, never retried. + f.Port.Handler = (_, _) => throw new InvalidOperationException("port fault"); + (await CallAsync(session, f.ConditionId(session), MethodIds.ConditionType_AddComment, f.CurrentEventId(), "n", ct)) + .ShouldBe(StatusCodes.BadCommunicationError); + f.Port.Calls.Count.ShouldBe(2); + f.Acked().ShouldBeFalse(); + } + + /// + /// Review S4: one stalled connection holds at most its sub-limit (4) of the node's 8 slots — a call to another connection + /// still dispatches at once; the stalled connection's further calls wait out their budget and answer + /// BadTooManyOperations unsent (slot exhaustion). + /// + [Fact] + public async Task One_stalled_connection_cannot_starve_another_and_its_excess_calls_are_BadTooManyOperations_unsent() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3b-slots", encrypted: false, ct); + var f = Fixture.Install(rig); + const string other = "conn-b"; + f.Apply(Update(version: 3, active: true, acked: false)); + f.Apply(Update(version: 3, active: true, acked: false, connection: other)); + using var session = await rig.ConnectAsync(anonymous: false, ct); + f.Port.Timeout = TimeSpan.FromSeconds(3); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Port.Handler = async (call, token) => + { + if (call.ConnectionId == Connection) await release.Task.WaitAsync(token); + return Applied(); + }; + var stalled = Enumerable.Range(0, OtOpcUaNodeManager.DefaultImportedMethodConcurrency) + .Select(i => CallAsync(session, f.ConditionId(session), MethodIds.ConditionType_AddComment, f.CurrentEventId(), $"c{i}", ct)).ToArray(); + await WaitUntilAsync(() => f.Port.Calls.Count == OtOpcUaNodeManager.DefaultImportedMethodConcurrencyPerConnection); + + var sw = Stopwatch.StartNew(); + (await CallAsync(session, f.ConditionId(session, other), MethodIds.ConditionType_AddComment, f.CurrentEventId(other), "b", ct)) + .ShouldBe(StatusCodes.Good, "a healthy origin is not starved by a stalled one"); + sw.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(1.5)); + + var outcomes = await Task.WhenAll(stalled); + outcomes.Count(o => o == StatusCodes.BadTooManyOperations).ShouldBe( + OtOpcUaNodeManager.DefaultImportedMethodConcurrency - OtOpcUaNodeManager.DefaultImportedMethodConcurrencyPerConnection); + outcomes.Count(o => o == StatusCodes.BadTimeout).ShouldBe(OtOpcUaNodeManager.DefaultImportedMethodConcurrencyPerConnection); + f.Port.Calls.Count(c => c.ConnectionId == Connection).ShouldBe(OtOpcUaNodeManager.DefaultImportedMethodConcurrencyPerConnection, + "the excess calls never dispatched"); + release.SetResult(); + } + + /// Review S4 floor: a request whose own deadline leaves less than the minimum dispatch budget is BadTimeout, unsent. + [Fact] + public async Task A_request_deadline_below_the_dispatch_floor_is_BadTimeout_unsent() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3b-floor", encrypted: false, ct); + var f = Fixture.Install(rig); + f.Apply(Update(version: 3, active: true, acked: false)); + using var session = await rig.ConnectAsync(anonymous: false, ct); + var response = await session.CallAsync(new RequestHeader { TimeoutHint = 450 }, + [new CallMethodRequest { ObjectId = f.ConditionId(session), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge, + InputArguments = [new Variant(f.CurrentEventId()), new Variant(new LocalizedText("x"))] }], ct); + response.Results[0].StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code); + f.Port.Calls.ShouldBeEmpty("450 ms − 250 ms grace leaves less than the 250 ms floor: refused before dispatch"); + + // Positive control: a roomy deadline dispatches, and the port's budget ends before the client's TimeoutHint (N7). + response = await session.CallAsync(new RequestHeader { TimeoutHint = 2_000 }, + [new CallMethodRequest { ObjectId = f.ConditionId(session), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge, + InputArguments = [new Variant(f.CurrentEventId()), new Variant(new LocalizedText("x"))] }], ct); + response.Results[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code); + f.Port.Calls.Single().RemainingBudget.ShouldBeLessThanOrEqualTo(TimeSpan.FromMilliseconds(2_000) - OtOpcUaNodeManager.ImportedMethodGrace); + } + + /// Review S6: a Warm standby refuses an imported method locally (BadInvalidState), nothing sent. + [Fact] + public async Task A_warm_standby_refuses_an_imported_method_unsent() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await WarmRedundancyWireTests.StartModeAsync("a3b-standby", "Warm", ct); + var f = Fixture.Install(rig); + f.Apply(Update(version: 3, active: true, acked: false)); + var projection = rig.Server.CreateStandbyProjection()!; + WarmRedundancyWireTests.Demote(projection); + using var session = await rig.ConnectAsync(anonymous: false, ct); + (await CallAsync(session, f.ConditionId(session), MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)) + .ShouldBe(StatusCodes.BadInvalidState); + f.Port.Calls.ShouldBeEmpty(); + WarmRedundancyWireTests.Promote(projection); + (await CallAsync(session, f.ConditionId(session), MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)) + .ShouldBe(StatusCodes.Good); + } + + /// Review S6: identical calls from DIFFERENT principals never join — each is its own dispatch. + [Fact] + public async Task Identical_calls_from_different_principals_do_not_join() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3b-nojoin", encrypted: false, ct); + var f = Fixture.Install(rig); + f.Port.Granted.Add("anonymous"); + f.Apply(Update(version: 3, active: true, acked: false)); + using var keyed = await rig.ConnectAsync(anonymous: false, ct); + using var anonymous = await rig.ConnectAsync(anonymous: true, ct); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Port.Handler = async (_, _) => { await release.Task; return Applied(); }; + var eventId = f.CurrentEventId(); + var a = CallAsync(keyed, f.ConditionId(keyed), MethodIds.AcknowledgeableConditionType_Acknowledge, eventId, "same", ct); + var b = CallAsync(anonymous, f.ConditionId(anonymous), MethodIds.AcknowledgeableConditionType_Acknowledge, eventId, "same", ct); + await WaitUntilAsync(() => f.Port.Calls.Count == 2); + rig.Nm.ImportedMethodsJoined.ShouldBe(0); + release.SetResult(); + (await a).ShouldBe(StatusCodes.Good); + (await b).ShouldBe(StatusCodes.Good); + f.Port.Calls.Select(c => c.OnBehalfOf).Order().ShouldBe(new[] { "anonymous", Granted }.Order()); + } + // --------------------------------------------------------------------------------------------------------------------- private static DataConditionMethodResult Applied() => new(DataWriteState.AcceptedUnconfirmed, 0, null); @@ -340,15 +608,16 @@ public sealed class ImportedConditionMethodWireTests Convert.ToBase64String(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(seed))).TrimEnd('=').Replace('+', '-').Replace('/', '_'); private static ImportedConditionUpdate Update(long version, bool active, bool acked, DataActivationMarker? marker = null, - string message = "HR200 high", bool native = true, DateTimeOffset? time = null) + string message = "HR200 high", bool native = true, DateTimeOffset? time = null, string connection = Connection, string? key = null, + uint? methods = null, bool noMarker = false) { var placements = Fixture.DefaultPlacements; var info = new DataConditionInfo("http://opcfoundation.org/UA/:AlarmConditionType", "HR200", native ? DataConditionSourceKind.Native : DataConditionSourceKind.Scripted, placements.Select(p => p.Placement).ToArray(), - (uint)(native ? DataConditionMethodSets.Native : DataConditionMethodSets.Scripted)); - var state = new DataConditionState(Key1, version, false, true, info, active, acked, true, true, 0, 777, message, - StatusCodes.Good.Code, null, 0, time ?? DateTimeOffset.UtcNow, active || !acked, marker ?? Marker1); - return new ImportedConditionUpdate(Connection, state, info, placements, "Plant/remote-a/" + placements[0].RelativePath); + methods ?? (uint)(native ? DataConditionMethodSets.Native : DataConditionMethodSets.Scripted)); + var state = new DataConditionState(key ?? Key1, version, false, true, info, active, acked, true, true, 0, 777, message, + StatusCodes.Good.Code, null, 0, time ?? DateTimeOffset.UtcNow, active || !acked, noMarker ? null : marker ?? Marker1); + return new ImportedConditionUpdate(connection, state, info, placements, "Plant/remote-a/" + placements[0].RelativePath); } /// Calls one method and returns its status (never throws for a Bad result). @@ -379,6 +648,8 @@ public sealed class ImportedConditionMethodWireTests public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(5); public ConcurrentQueue<(string Principal, DataConditionMethods Method)> AuthorizedFor { get; } = new(); public ConcurrentQueue Calls { get; } = new(); + /// The gate throws (an unexpected fault BEFORE dispatch — review S1). + public bool AuthorizeThrows { get; set; } public Func> Handler { get; set; } = (_, _) => Task.FromResult(Applied()); @@ -386,6 +657,7 @@ public sealed class ImportedConditionMethodWireTests DataConditionMethods method) { AuthorizedFor.Enqueue((caller?.Principal ?? "", method)); + if (AuthorizeThrows) throw new InvalidOperationException("gate fault"); return caller is not null && Granted.Contains(caller.Principal) && (GrantedMethods & method) == method ? new ImportedConditionMethodRoute(placements[0], Timeout) : null; } @@ -427,12 +699,14 @@ public sealed class ImportedConditionMethodWireTests return new Fixture { Rig = rig, Port = port }; } - public NodeId ConditionId(ISession session) => - new(Identifier, (ushort)session.NamespaceUris.GetIndex(ImportedConditionIds.NamespaceUri)); + public NodeId ConditionId(ISession session, string connection = Connection, string? key = null) => + new(ImportedConditionIds.Identifier(connection, key ?? Key1), (ushort)session.NamespaceUris.GetIndex(ImportedConditionIds.NamespaceUri)); - public ByteString CurrentEventId() => Rig.Nm.FindImportedCondition(Connection, Key1)!.EventId!.Value; + public ByteString CurrentEventId(string connection = Connection, string? key = null) => + Rig.Nm.FindImportedCondition(connection, key ?? Key1)!.EventId!.Value; - public bool Acked() => Rig.Nm.FindImportedCondition(Connection, Key1)!.AckedState!.Id!.Value; + public bool Acked(string connection = Connection, string? key = null) => + Rig.Nm.FindImportedCondition(connection, key ?? Key1)!.AckedState!.Id!.Value; public void Apply(ImportedConditionUpdate update) => Rig.Nm.ApplyConditions([update]); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/RealConditionMethodPath.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/RealConditionMethodPath.cs new file mode 100644 index 000000000..9fbbdd587 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/RealConditionMethodPath.cs @@ -0,0 +1,206 @@ +using System.Buffers.Binary; +using System.Net; +using System.Runtime.CompilerServices; +using Google.Protobuf; +using Microsoft.Extensions.Logging.Abstractions; +using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests; + +/// +/// A3b review S5 (L3 on the REAL dispatch path): the consumer's method port is a real +/// whose lease hands out a real ; the origin is an in-process gRPC endpoint (HTTP/2 framing +/// over an ) whose CallConditionMethod handler stalls for . Only the +/// condition STREAM is a quiet stand-in (it opens, carries the Primary's provenance and never delivers) — the conditions +/// themselves are applied by the test, as in every other A3b wire test. The per-caller gate stays the test's fake (its own +/// tests are the Runtime gate tests); everything after it is production code. +/// +internal sealed class RealConditionMethodPath : IAsyncDisposable +{ + public const string Incarnation = "boot-a"; + private readonly IProjectedConditionMethods _gate; + private readonly DataConnectionManager _manager = new("consumer", 1); + private readonly GrpcDataConnection _grpc; + private readonly IDisposable? _demand; + public Origin Server { get; } + public ProjectedConditionAccess Access { get; } + public IProjectedConditionMethods Port { get; } + + public RealConditionMethodPath(string connectionId, string mappingId, IProjectedConditionMethods gate, TimeSpan stall) + { + _gate = gate; + Server = new Origin(stall); + _manager.ApplyScope(new Dictionary> { [connectionId] = new HashSet { "consumer" } }); + _grpc = new GrpcDataConnection(connectionId, new(DataTargetMode.Cluster, "c", null), [new Uri("https://origin.test")], + new Security(Server), _manager.Acquire(connectionId), 1 << 22, 1, eligibleNodeIds: new HashSet { "origin" }); + var mapping = new RemoteNamespaceMapping + { + RemoteNamespaceMappingId = mappingId, DataConnectionId = connectionId, Enabled = true, Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw, + AllowedOperations = DataOperations.Browse | DataOperations.Subscribe | DataOperations.AlarmSubscribe + | DataOperations.AlarmAcknowledge | DataOperations.AlarmConfirm, + MaxConditions = 10, ConditionStaleTimeoutMilliseconds = 60_000, ConditionSnapshotTimeoutMilliseconds = 60_000, + ConditionMethodTimeoutMilliseconds = 20_000, BranchName = mappingId, RemoteNamespaceUri = "https://zb.com/otopcua/raw", + RemoteIdentifierKind = "string", RemoteIdentifier = "Plant", + }; + var anchor = new DataView(new DataAddress("origin", mapping.RemoteNamespaceUri, "string", "Plant"), DataRealm.Raw, mappingId, 1, "Plant/" + mappingId); + var scope = new NodeScope { ClusterId = "c1", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", mappingId] }; + var placement = new ProjectedMappingPlacement(mapping, anchor, anchor, scope, ["local-parent"], new ActiveAuthority()); + var state = new DataPlaneAuthorityState(); + var policy = new DataOperationPolicy(state, new TriePermissionEvaluator(state.Tries, TimeProvider.System), TimeProvider.System); + Access = new ProjectedConditionAccess(new Mappings([placement]), new Connections(new Hybrid(_grpc)), policy, () => new NoSink(), + TimeProvider.System, new ProjectedConditionOptions(TimeSpan.FromSeconds(30), 122_500, long.MaxValue, TimeSpan.FromSeconds(1)), + NullLogger.Instance); + _demand = Access.AcquireEventDemand(null); // opens the condition stream (the serving incarnation calls are addressed to) + Port = new Adapter(this); + } + + public async ValueTask DisposeAsync() + { + _demand?.Dispose(); + Access.Dispose(); + await _grpc.DisposeAsync(); + _manager.Dispose(); + } + + private sealed class Adapter(RealConditionMethodPath owner) : IProjectedConditionMethods + { + public ImportedConditionMethodRoute? AuthorizeMethod(RoleCarryingUserIdentity? caller, IReadOnlyList placements, + DataConditionMethods method) => owner._gate.AuthorizeMethod(caller, placements, method); + + public Task CallAsync(ImportedConditionMethodCall call, CancellationToken cancellationToken) => + owner.Access.CallAsync(call, cancellationToken); + } + + /// The in-process origin: capabilities (Primary, conditions with every method) and a stalling method handler. + internal sealed class Origin(TimeSpan stall) : HttpMessageHandler + { + private static readonly DataLimits Limits = new(16, 16, 1 << 20, 16, 4, 1 << 20, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5)); + private static readonly ServingIdentity Serving = new("origin", Incarnation, "Primary", 1, 1, 1); + public int MethodCalls; + public int MethodAnswers; + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken token) + { + var path = request.RequestUri!.AbsolutePath; + IMessage message; + if (path.EndsWith("/GetCapabilities", StringComparison.Ordinal)) + { + var asked = request.Headers.Contains("x-otopcua-data-features"); + message = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 5, Serving, DataReadiness.Ready, + DataOperationSets.V1 | (asked ? DataOperationSets.ConditionGrants : DataOperations.None), + new HashSet { DataValueKind.Double }, Limits, false, 0, "c", true, true, true, true, true, + Conditions: asked ? new DataConditionCapabilities(true, 7, 1000) : null)); + } + else + { + Interlocked.Increment(ref MethodCalls); + var bytes = await request.Content!.ReadAsByteArrayAsync(token); + _ = W.ConditionMethodRequest.Parser.ParseFrom(bytes.AsSpan(5).ToArray()); + await Task.Delay(stall, token); // the origin's handler stalls + Interlocked.Increment(ref MethodAnswers); + message = DataConditionProtoMapper.EncodeMethodResponse(new(DataWriteState.AcceptedUnconfirmed, 0, "AcceptedUnconfirmed", Serving)); + } + var payload = message.ToByteArray(); var framed = new byte[payload.Length + 5]; + BinaryPrimitives.WriteInt32BigEndian(framed.AsSpan(1, 4), payload.Length); payload.CopyTo(framed, 5); + var ok = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new ByteArrayContent(framed) }; + ok.Content.Headers.ContentType = new("application/grpc"); ok.TrailingHeaders.Add("grpc-status", "0"); + return ok; + } + } + + private sealed class Security(HttpMessageHandler handler) : IDataConnectionSecurityProvider + { + public event Action? Changed { add { } remove { } } + public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => + ValueTask.FromResult(new("v1", "ca1", "key", () => new NonDisposing(handler))); + } + + private sealed class NonDisposing(HttpMessageHandler inner) : HttpMessageHandler + { + private readonly HttpMessageInvoker _invoker = new(inner, disposeHandler: false); + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => + _invoker.SendAsync(request, cancellationToken); + } + + private sealed class Mappings(IReadOnlyList current) : IProjectedConditionMappings + { + public IReadOnlyList Current { get; } = current; + public event Action? Changed { add { } remove { } } + } + + private sealed class ActiveAuthority : IDataMappedCatalogAuthority + { + public long CatalogEpoch => 1; + public long AuthorityEpoch => 1; + public bool IsActive => true; + } + + private sealed class Connections(IDataConnection connection) : IGrpcDataAdapterConnectionSource + { + public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken) => + ValueTask.FromResult(new Lease(connection)); + + private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease + { + public IDataConnection Connection => connection; + public CancellationToken CancellationToken => CancellationToken.None; + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + } + + /// The real gRPC connection for everything but the condition stream and root metadata (quiet stand-ins). + private sealed class Hybrid(GrpcDataConnection grpc) : IDataConnection, IDataPrimarySubscriptionSource, IDataConditionMethodService + { + public DataTarget Target => grpc.Target; + public TimeProvider Clock => grpc.Clock; + public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => grpc.GetCapabilitiesAsync(budget, cancellationToken); + public Task BrowseAsync(Core.Abstractions.DataConnections.BrowseRequest request, CancellationToken cancellationToken) => + grpc.BrowseAsync(request, cancellationToken); + public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => + Task.FromResult>>(request.Views.Select(v => new DataItemResult("0", DataItemStatus.Good, + new DataMetadata(v with { Subject = v.Address.Identifier }, v.Address.Identifier, "Folder", DataValueKind.Null, -1, [], false, + DataOperations.Browse, 1, null, null, false), null)).ToArray()); + public Task> ReadAsync(Core.Abstractions.DataConnections.ReadRequest request, + CancellationToken cancellationToken) => grpc.ReadAsync(request, cancellationToken); + public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => grpc.WriteAsync(request, cancellationToken); + public Task SubscribeAsync(CancellationToken cancellationToken) => Task.FromResult(new QuietStream()); + public Task SubscribePrimaryAsync(CancellationToken cancellationToken) => SubscribeAsync(cancellationToken); + public Task CallConditionMethodAsync(DataConditionMethodRequest request, CancellationToken cancellationToken) => + grpc.CallConditionMethodAsync(request, cancellationToken); + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + + private sealed class QuietStream : IDataSubscription, IDataSubscriptionProvenance + { + private readonly CancellationTokenSource _closed = new(); + public ServingIdentity Serving { get; } = new("origin", Incarnation, "Primary", 1, 1); + public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken) => Task.CompletedTask; + + public async IAsyncEnumerable ReadAllAsync([EnumeratorCancellation] CancellationToken cancellationToken) + { + using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _closed.Token); + try { await Task.Delay(Timeout.Infinite, linked.Token); } + catch (OperationCanceledException) { } + yield break; + } + + public ValueTask DisposeAsync() { _closed.Cancel(); return ValueTask.CompletedTask; } + } + + private sealed class NoSink : IProjectedConditionSink + { + public void ApplyConditions(IReadOnlyList updates) { } + public void RemoveConditions(string connectionId, IReadOnlyCollection conditionKeys) { } + public void MarkConnectionStale(string connectionId) { } + public void MarkConditionsStale(string connectionId, IReadOnlyCollection conditionKeys) { } + public void RequireRefresh(string connectionId) { } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionMethodClientTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionMethodClientTests.cs index 4a63c0446..52c924e32 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionMethodClientTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionMethodClientTests.cs @@ -97,14 +97,51 @@ public sealed class GrpcDataConditionMethodClientTests a.MethodCalls.ShouldBe(1); } - private static GrpcDataConnection Connect(Endpoint[] endpoints, TimeSpan? methodTimeout = null) + [Fact] + public async Task Without_a_connection_ceiling_the_deadline_is_the_requests_budget_not_a_hidden_5s() + { + // A3b review S2: the per-mapping timeout rides RemainingBudget; a 30 s mapping must not be cut at a client-wide 5 s. + var a = new Endpoint("a"); + await using var connection = Connect([a], methodTimeout: null, setCeiling: false); + (await connection.CallConditionMethodAsync(Request(budget: TimeSpan.FromSeconds(8)), Ct)).State.ShouldBe(DataWriteState.AcceptedUnconfirmed); + a.LastTimeout.ShouldNotBeNull().ShouldBeGreaterThan(TimeSpan.FromSeconds(6)); + TimeSpan.FromTicks(a.LastRequest!.RemainingBudgetTicks).ShouldBeGreaterThan(TimeSpan.FromSeconds(6)); + } + + [Fact] + public async Task A_deadline_passing_after_send_is_OutcomeUnknown_with_BadTimeout_known_not_inferred() + { + var a = new Endpoint("a") { Hang = true }; + await using var connection = Connect([a]); + var result = await connection.CallConditionMethodAsync(Request(budget: TimeSpan.FromMilliseconds(400)), Ct); + result.State.ShouldBe(DataWriteState.OutcomeUnknown); + result.StatusCode.ShouldBe(0x800A0000u, "BadTimeout: the transport knows the deadline passed"); + a.MethodCalls.ShouldBe(1); + } + + [Fact] + public async Task An_invalid_request_is_RejectedBeforeDispatch_never_thrown() + { + var a = new Endpoint("a"); + await using var connection = Connect([a]); + var result = await connection.CallConditionMethodAsync(Request() with { OperationId = new string('x', 10_000) }, Ct); + result.State.ShouldBe(DataWriteState.RejectedBeforeDispatch); + result.StatusCode.ShouldBe(0x80AB0000u); + a.MethodCalls.ShouldBe(0); + } + + private static GrpcDataConnection Connect(Endpoint[] endpoints, TimeSpan? methodTimeout = null, bool setCeiling = true) { var manager = new DataConnectionManager("consumer", 1); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); var router = new Router(endpoints); - return new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), endpoints.Select(e => new Uri($"https://{e.Name}.test")), - new Security(router), manager.Acquire("link"), 1 << 22, endpoints.Length, - eligibleNodeIds: endpoints.Select(e => e.Name).ToHashSet()) { ConditionMethodTimeout = methodTimeout ?? TimeSpan.FromSeconds(5) }; + var uris = endpoints.Select(e => new Uri($"https://{e.Name}.test")).ToArray(); + var eligible = endpoints.Select(e => e.Name).ToHashSet(); + return setCeiling + ? new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), uris, new Security(router), manager.Acquire("link"), 1 << 22, + endpoints.Length, eligibleNodeIds: eligible) { ConditionMethodTimeout = methodTimeout ?? TimeSpan.FromSeconds(5) } + : new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), uris, new Security(router), manager.Acquire("link"), 1 << 22, + endpoints.Length, eligibleNodeIds: eligible); } private sealed class Endpoint(string name) diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionMethodTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionMethodTests.cs index b51db1785..a455936c9 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionMethodTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionMethodTests.cs @@ -57,6 +57,44 @@ public sealed class GrpcDataProjectedConditionMethodTests f.Access.AuthorizeMethod(f.Identity("reader"), [placement with { MappingId = "unknown" }], DataConditionMethods.Acknowledge).ShouldBeNull(); } + [Fact] + public async Task The_gate_routes_through_the_first_authorized_placement_and_refuses_a_realm_mismatch() + { + // A3b review S6: the real gate with several placements (the "first authorized placement" deviation) and a realm mismatch. + await using var f = new Fixture(); + f.Grant(NodePermissions.Browse | NodePermissions.Subscribe | NodePermissions.AlarmAcknowledge); + var good = f.Placement(); + var realmMismatch = good with { Realm = DataRealm.Uns }; + var unknownMapping = good with { MappingId = "map-x" }; + var ungranted = good with { FolderLocalSubject = "Elsewhere/map-a/dev1" }; + var alsoGood = good with { RelativePath = "dev1/HR200-b" }; + var id = f.Identity("reader"); + + f.Access.AuthorizeMethod(id, [realmMismatch], DataConditionMethods.Acknowledge).ShouldBeNull("a placement's realm must be its mapping's"); + f.Access.AuthorizeMethod(id, [unknownMapping, realmMismatch, good, alsoGood], DataConditionMethods.Acknowledge) + .ShouldNotBeNull().Placement.ShouldBe(good, "the first placement the caller passes the gate on, in primary order"); + f.Access.AuthorizeMethod(id, [alsoGood, good], DataConditionMethods.Acknowledge).ShouldNotBeNull().Placement.ShouldBe(alsoGood); + f.Access.AuthorizeMethod(id, [ungranted], DataConditionMethods.Acknowledge).ShouldBeNull("the grant is on the placement's folder scope"); + f.Access.AuthorizeMethod(id, [ungranted, good], DataConditionMethods.Acknowledge).ShouldNotBeNull().Placement.ShouldBe(good); + } + + [Fact] + public async Task An_invalid_request_is_refused_unsent_before_the_lease() + { + // A3b review S3: a validation failure is RejectedBeforeDispatch, never an exception the node manager reads as "unknown". + await using var f = new Fixture(); + using var demand = f.Access.AcquireEventDemand(null); + await f.Connections.Streams.Reader.ReadAsync(TestContext.Current.CancellationToken); + await f.WaitAsync(async () => (await f.Access.CallAsync(f.Call(), TestContext.Current.CancellationToken)).StatusCode != BadNoCommunication); + var acquired = f.Connections.Acquired; + var sent = f.Connections.Sent.Count; + var result = await f.Access.CallAsync(f.Call() with { OperationId = new string('x', 10_000) }, TestContext.Current.CancellationToken); + result.State.ShouldBe(DataWriteState.RejectedBeforeDispatch); + result.StatusCode.ShouldBe(0x80AB0000u); + f.Connections.Sent.Count.ShouldBe(sent); + f.Connections.Acquired.ShouldBe(acquired, "not even leased"); + } + [Fact] public async Task With_no_open_condition_stream_a_call_is_BadNoCommunication_and_nothing_is_sent() { From e5e0780f5ec80acac574d28a012193d58ebe89b5 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 20:05:26 -0500 Subject: [PATCH 25/32] =?UTF-8?q?perf(grpc-data):=20A3b=20review=20S5=20?= =?UTF-8?q?=E2=80=94=20BytesPerCondition=20from=20the=20worst-case=20L2=20?= =?UTF-8?q?harness=20(max=20228,353=20B=20=E2=87=92=20230,000;=20cap=20?= =?UTF-8?q?=E2=89=88=20548=20MiB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Configuration/DataConnectionOptions.cs | 2 +- .../DataConnections/ProjectedConditionAccess.cs | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs index 2be47ff68..ca67a3563 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs @@ -21,7 +21,7 @@ public sealed class DataConnectionOptions public long MaxTransportBytes { get; set; } = 64 * 1024 * 1024; /// A3 (§5.5): imported-condition node budget per consumer node (2,500 × 49 worst-case nodes per condition). public int MaxImportedConditionNodes { get; set; } = 122_500; - /// A3 (§5.5): imported-condition memory budget per consumer node (§9.3 L2: measured 205,665 B/condition × 2,500 ≈ 490 MiB). + /// A3 (§5.5): imported-condition memory budget per consumer node (§9.3 L2: worst-case measured 230,000 B/condition × 2,500 ≈ 548 MiB). public long MaxImportedConditionBytes { get; set; } = ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ProjectedConditionOptions.DefaultMaxImportedConditionBytes; public long MaxPendingBytes { get; set; } = 1024 * 1024; public TimeSpan MaxSessionLifetime { get; set; } = TimeSpan.FromHours(1); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs index 14c0345fa..1aaf9b93c 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs @@ -40,7 +40,7 @@ public sealed class DeployedConditionMappings : IProjectedConditionMappings /// A3 host limits (§5.5 "Budget"). /// How long a connection's condition items stay open after the last event item goes (default 30 s). /// Per consumer node (default 122,500 = 2,500 × 49). -/// Per consumer node (default = L2-measured × 2,500 ≈ 490 MiB). +/// Per consumer node (default = L2-measured × 2,500 ≈ 548 MiB). /// Pause before re-opening an ended condition stream. public sealed record ProjectedConditionOptions(TimeSpan Linger, int MaxImportedConditionNodes, long MaxImportedConditionBytes, TimeSpan ReconnectDelay) @@ -50,9 +50,10 @@ public sealed record ProjectedConditionOptions(TimeSpan Linger, int MaxImportedC /// /// Retained managed bytes per imported condition, measured by the A3 L2 harness (1,000 conditions in one mapping on a /// running SDK 2.0.1 server: node + children + ids + registry/indexes + EventId registry + verdict cache; X0's - /// node-only harness measured 160,997). The managed-heap figure is used: it is higher than the working-set growth. + /// node-only harness measured 160,997). A3b review S5: the WORST case — two placements, all 32 EventId slots, three + /// event items, the runner's Live + Buffer records — max of three runs 228,353 B (managed heap), rounded up. /// - public const long BytesPerCondition = 205_665; + public const long BytesPerCondition = 230_000; /// §9.3 L2: the host byte cap = measured per-condition bytes × 2,500 (the host condition cap). public const long DefaultMaxImportedConditionBytes = BytesPerCondition * 2_500; From c82ea04e4d0efa080510ce9d75ab36033096a1b9 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 20:38:24 -0500 Subject: [PATCH 26/32] =?UTF-8?q?docs(grpc-data):=20A3b=20review=20round?= =?UTF-8?q?=201=20=E2=80=94=20finding=20=E2=86=92=20resolution=20=E2=86=92?= =?UTF-8?q?=20test=20=E2=86=92=20red-on-revert,=20real-path=20L3,=20worst-?= =?UTF-8?q?case=20L2=20(fails=20200=20MiB),=20OI=20refresh-failure=20inves?= =?UTF-8?q?tigation,=20gates?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/plans/evidence/grpc-data-ext/A3.md | 118 ++++++++++++++++++++++++ 1 file changed, 118 insertions(+) diff --git a/docs/plans/evidence/grpc-data-ext/A3.md b/docs/plans/evidence/grpc-data-ext/A3.md index 1a474b258..dc2b5f353 100644 --- a/docs/plans/evidence/grpc-data-ext/A3.md +++ b/docs/plans/evidence/grpc-data-ext/A3.md @@ -435,3 +435,121 @@ Consumer: `stream 1 for connection consumer-source opened (2 mapping(s), serving `SubscribePrimaryAsync`); barrier `map-raw=Complete, map-uns=Complete; 1 record(s)`. Bogus EventId ⇒ `BadEventIdUnknown`; ack through the consumer `Acknowledge successful` (608 ms); origin subscriber and consumer subscriber each saw exactly one Active/Acknowledged. Teardown: no run-labelled containers or networks left. + +--- + +# A3 — Review round 1 (A3b adversarial review, `a3b-review-round1.md`, written against `3c941458`) + +2026-11-25, branch `a3-consumer`, on top of the A3a fix round (`01a4e8db`). Not merged, not pushed. Commits: `72dece7f` (fixes + +tests), `perf(grpc-data): … BytesPerCondition` (L2 re-derivation), this docs commit. + +"Red on revert": the single fix was removed by a scripted mutation (`mut.py`, one mutation per build), the named test run and seen +red, the file restored (`git status` clean after the 19 mutations). + +| Finding | Resolution | Test(s) | Red on revert | +|---|---|---|---| +| **S1** a throw after `base.Call` faults the batch | `CallAsync` runs each claimed item through `CallImportedGuardedAsync` (never faults, a synchronous throw included) and collects per-item results; a fault before the port is called ⇒ that item's `BadInternalError`, unsent (logged); `DispatchImportedAsync` answers every post-dispatch failure itself | `A_fault_before_dispatch_is_a_per_item_BadInternalError…` (gate throws: imported-first batch ⇒ `[BadInternalError, Good]`, local ack routed once, nothing sent; a pre-validation failure (`MethodId` null) answered per item beside a dispatched call; a port THROWING after dispatch ⇒ `BadCommunicationError`, one dispatch) | yes (both catch-alls removed ⇒ ServiceFault) | +| **S2** mapping timeout capped at 5 s; BadTimeout inferred | the mapping's `ConditionMethodTimeoutMilliseconds` is honoured (up to the validator's 3,600,000 ms): it rides `RemainingBudget`, and `GrpcDataConnection.ConditionMethodTimeout` defaults to that validator ceiling (`MaxConditionMethodTimeout`) instead of 5 s. The client maps gRPC `DeadlineExceeded` ⇒ `OutcomeUnknown` + `BadTimeout`; `MapOutcome` takes the transport's status (BadTimeout stays BadTimeout, anything else unknown ⇒ BadCommunicationError) — no clock comparison | Runtime `Without_a_connection_ceiling_the_deadline_is_the_requests_budget_not_a_hidden_5s` (8 s budget ⇒ grpc-timeout > 6 s); `A_deadline_passing_after_send_is_OutcomeUnknown_with_BadTimeout_known_not_inferred`; OI timeout test: port answers `OutcomeUnknown/BadTimeout` at once ⇒ `BadTimeout` | yes / yes / yes | +| **S3** unsent / definite failures labelled unknown | cancel while waiting for a slot ⇒ `BadRequestCancelledByClient` unsent; an invalid request is `RejectedBeforeDispatch` `BadInvalidArgument` in `ProjectedConditionAccess.CallAsync` (before the lease) and in the client (never thrown); `DriverConfirmedFailure` ⇒ the origin's status (+ diagnostic) | Runtime `An_invalid_request_is_refused_unsent_before_the_lease` (not even leased); client `An_invalid_request_is_RejectedBeforeDispatch_never_thrown`; OI timeout test (`DriverConfirmedFailure`/`BadConditionAlreadyEnabled` passes through) | yes / yes / yes. Slot-wait cancellation: **not tested** — the SDK 2.0.1 server gives no client-driven way to cancel an in-flight Call (no Cancel wiring into `OperationContext.CancellationToken` found); by inspection only | +| **S4** no fairness; dispatch with a few ms left | per-connection sub-limit `DefaultImportedMethodConcurrencyPerConnection = 4` inside the node-wide 8 (connection slot first, then node slot, both released in `finally`); a dispatch with < `ImportedMethodMinimumDispatchBudget` (250 ms) left is `BadTimeout` UNSENT (checked before the waits and again after them). Per-principal fairness not added (a principal is bounded by the per-connection limit; documented) | `One_stalled_connection_cannot_starve_another_and_its_excess_calls_are_BadTooManyOperations_unsent` (8 stalled calls on conn-a: 4 dispatched, 4 `BadTooManyOperations` unsent, a conn-b call Good < 1.5 s — slot exhaustion included); `A_request_deadline_below_the_dispatch_floor_is_BadTimeout_unsent` (TimeoutHint 450 ms ⇒ unsent; 2,000 ms ⇒ dispatched with budget ≤ 1,750 ms) | yes / yes | +| **S5 L3** stall below the port only | the L3 test is now a Theory: `realPath: true` puts a REAL `ProjectedConditionAccess` (runner, serving incarnation, lease) and a REAL `GrpcDataConnection` (capabilities, eligibility, deadline, HTTP/2 gRPC framing) between the node manager and an in-process origin whose `CallConditionMethod` handler stalls 5 s (`RealConditionMethodPath`); only the condition stream is a quiet stand-in carrying Primary provenance. The per-caller gate stays the fake (pinned by the Runtime gate tests) | L3 numbers below | yes (M1 on the real path: port awaited under `Lock` ⇒ both cases red) | +| **S5 L2** not worst case | harness now: two placements per condition (two mappings, both folders wired), all 32 EventId slots filled (asserted), three event items (Server object + both folders, publishing off, queue 1000), runner Live + Buffer record copies; max of three runs, rounded up: `BytesPerCondition` 205,665 → **230,000**, `MaxImportedConditionBytes` default = 230,000 × 2,500 = **575,000,000 B (≈ 548 MiB)** | L2 numbers below | n/a (measurement) | +| **S6** test gaps | RefreshRequired after an un-re-bindable resync asserted over the wire (Server-object item receives `RefreshRequiredEventType`); native Confirm with a listing that HAS Confirm (still refused) and scripted lacking it (refused) / having it (dispatched); real gate: first authorized placement of several, realm mismatch, unknown mapping, ungranted folder; Warm standby refusal; different principals never join; imported-first mixed batch; batch with a pre-validation failure; throwing port; slot exhaustion; the `cancelled` flag is written/read with `Volatile` | `A_resync_that_cannot_re_bind_sends_RefreshRequired…`; `Native_Confirm_is_refused_even_when_listed…`; Runtime `The_gate_routes_through_the_first_authorized_placement_and_refuses_a_realm_mismatch`; `A_warm_standby_refuses_an_imported_method_unsent`; `Identical_calls_from_different_principals_do_not_join`; S1/S4 tests above | native guard yes; supported-methods guard yes; gate (stop at first refusal) yes; standby yes; principal dropped from the join key yes. **ACL-on gate variant: not added** — `AuthorizeMethod` has no `Security:Acl:Enabled` input at all (`DataOperationPolicy.AuthorizeLocal` regardless of the flag, by design §5.6); the mixed/fault batches run with enforcement on. **Mid-call cancel: not tested** (see S3) | +| **N1** `bounded` not cancelled on TimeoutException | `bounded.Cancel()` in the `TimeoutException` catch | timeout test (`cancelled` observed) | **no** — the CancelAfter timer usually still fires first; the race the fix closes is not forceable | +| **N2** re-bind on any marker move | F6 re-binding only when the INCARNATION changed at an unchanged time; a same-incarnation sequence bump mints + RefreshRequired | `A_resync_that_cannot_re_bind…` | yes | +| **N3** null-marker transition | a marker appearing or disappearing is a marker change: mint + RefreshRequired | `A_marker_appearing_on_an_unchanged_state_mints_an_ackable_EventId` | yes | +| **N4** joiner inherits the first caller's cancel/deadline | kept (documented in code): a joiner asked for the same thing at the same moment and never dispatches twice; the key includes the principal | — | n/a | +| **N5** existence answers before the gate | kept; the comment corrected — `BadNodeIdUnknown`/`BadNotSupported` are what SDK pre-validation reveals anyway | — | n/a | +| **N6** "OutcomeUnknown" text only with diagnostics | kept: the status is always Bad (never read as done); the text reaches a client requesting diagnostics and the Warning log | — | n/a | +| **N7** grace past TimeoutHint; elapsed subtracted twice | one end instant = min(start + mapping timeout, request deadline − grace); waits and the port budget derive from it, so the answer lands inside the client's TimeoutHint | floor test positive control (budget ≤ hint − grace) | not separately reverted | +| **N8** unsynchronised reads | `ImportedCondition.Placements` volatile publication; `SupportedMethods` an atomic 64-bit word | — | n/a (memory model) | +| **N9** method gate does not require visibility | documented: Ack on placement B suffices without seeing it via A; the EventId (128-bit, minted per consumer, only delivered to items that see the condition) is the practical visibility requirement | — | n/a | + +## L3 — real dispatch path (review S5) + +The A3b measurement repeated with the stall behind a real `ProjectedConditionAccess` + `GrpcDataConnection` (in-process origin +handler stalling 5 s), and with the original port-level stall, 10 rounds each: + +| Run | Path | Stall | Read max | Browse max | Data Publish max | `Lock` acquire max | +|---|---|---|---|---|---|---| +| 1 | port | 5002 ms | 0.4 ms | 0.3 ms | 100.0 ms | 0.01 ms | +| 1 | **real** | 5044 ms | 0.5 ms | 0.3 ms | 101.6 ms | 0.01 ms | +| 2 | port | 5003 ms | 1.5 ms | 2.2 ms | 102.1 ms | 0.01 ms | +| 2 | **real** | 5051 ms | 2.3 ms | 0.3 ms | 100.8 ms | 0.01 ms | +| 3 | port | 5002 ms | 0.7 ms | 0.3 ms | 94.6 ms | 0.00 ms | +| 3 | **real** | 5040 ms | 0.4 ms | 0.3 ms | 102.6 ms | 0.00 ms | +| 4 | port | 5002 ms | 0.5 ms | 0.3 ms | 96.7 ms | 0.01 ms | +| 4 | **real** | 5042 ms | 0.4 ms | 0.3 ms | 109.1 ms | 0.01 ms | + +(Measured inside the 4 combined OI gate runs, i.e. under the whole suite's parallel load.) All < 200 ms; the ~100 ms publish +figure is the minimum publishing interval, as before. The real-path stall is ~40 ms longer (capabilities probe + channel set-up +of the first call). **L3: PASS on the real dispatch path.** + +## L2 — worst case (review S5) — **FAILS the 200 MiB gate** + +Two placements per condition, every EventId slot (32) filled, three event items holding up to 1,000 events each (publishing off), +Live + Buffer record copies; forced compacting GCs; three runs: + +| Run | Managed heap growth | Working-set growth | heap B/condition | after materialise (heap) | +|---|---|---|---|---| +| 1 | +92.3 MiB (GC noise: below the after-materialise figure) | +125.7 MiB | 96,770 | 217,948 | +| 2 | **+217.8 MiB** | **+210.0 MiB** | 228,353 | 217,979 | +| 3 | **+217.7 MiB** | **+206.1 MiB** | 228,299 | 217,931 | + +At this worst case BOTH the managed heap (≈ 218 MiB) and the working set (206–210 MiB in 2 of 3 runs) exceed the 200 MiB gate; +the A3b single-placement figure (heap 197.4 MiB, WS ≈ 107 MiB) passed it only because it was not worst case. Recorded, not +adjusted: the harness keeps asserting ≤ 200 MiB and fails when opted in. The byte cap is now derived from the worst case +(230,000 B × 2,500 ≈ 548 MiB), so admission accounting is honest; whether the §9.3 L2 gate (200 MiB for 1,000 conditions) is +re-scoped to the single-placement case or the per-condition cost is reduced (≈ 210 KB is the SDK condition node + children — +X0's node-only figure was 161 KB — plus the second wiring) is an owner decision. + +## Task: the OI condition-refresh failures (`ConditionRefreshDeferralWireTests` / `FolderConditionRefreshWireTests`) + +**Conclusion: reproduces only with the A3 test classes in the run; NOT reproduced on master; root cause NOT established. +Not marked flaky.** No A3 production path is reached in the failing rigs (no imported condition exists in them; +`ReplayImportedConditions` returns at `Count == 0`; every other A3 hunk on the delivery/refresh path is a namespace-index test or a +`Find` returning null). + +Evidence (combined filter `Feature=GrpcData|…ConditionMethodEvent|…NativeAlarmEventIdentityFieldDelivery|…FolderConditionRefresh| +…ConditionRefreshDeferral`, `--blame-hang-timeout 120s`, one run at a time): + +| Build | Runs | Failed runs | Failures | +|---|---|---|---| +| master `83c7e586` (109 tests) | 4 | **0** | — | +| master `83c7e586`, only the two deferral classes, 14 busy-loop CPU burners | 2 | 0 | — | +| A3a r1 `01a4e8db` (130 tests) | 4 | 2 | gate test `A_refresh_waits_for_a_deferred_delivery…` (`window.Count` 4, expected 2); folder `Deferred_events_older…(enforced: False, …, modify: True)` (RefreshEnd not seen in 10 s, line 93) | +| `01a4e8db` + diagnostics (window dump on failure) | 6 | 0 | — (the failure did not recur, so no window dump was captured) | +| this round `72dece7f`+ (139 tests) | 4 | 3 | folder `Deferred_events_older…(enforced: True…)` ×2 (RefreshEnd not seen, line 93); folder `A_condition_removed_during_a_plain_refresh_is_not_replayed(serverObject: False)` (RefreshEnd not seen, line 527 — **no stall, no deferral involved**) | +| same + thread-pool latency sampler (50 ms probe) | 4 | 1 | folder `Deferred_events_older…` ×2; pool dispatch latency max **11 ms** in the failing run (≤ 21 ms in all), ≤ 21 pool threads | +| same + `DOTNET_ThreadPool_ForceMinWorkerThreads=64` | 1 | 1 | `ConditionRefreshDeferralWireTests.Deferred_events_older…(enforced: True…)`; pool max 15 ms | + +Ruled out: +- **A3 production code in those rigs** — not reached (above); the shared helpers (`ApplyConditionState`, `CreateConditionNode`) are + pure extractions. +- **Thread-pool starvation** (the SDK's ConditionRefresh worker blocks a pool thread in `WaitOne` per server, which made it the + first suspect) — dispatch latency stayed ≤ 21 ms in failing runs and forcing 64 minimum workers did not prevent a failure. +- **Plain CPU load** — 14 burners on master's two classes: 0 failures. + +What it is: mostly **a RefreshEnd that never reaches a folder (direct) event item** within 10 s — once in the plain +(non-deferring) refresh path with no stall at all — plus, once, two extra deferred events inside a Server-object refresh window. +It needs other tests running in the same process at the same time (it scales with the size of the parallel suite: 0/4 at 109 +tests, 2/4 at 130, 3/4 at 139). Process-wide shared state is the remaining lead — e.g. `ProjectedEventDelivery`'s static +`FilterGroup` registry keyed by filter text, which every rig's server shares — but no mechanism was demonstrated. Pre-existing +code (#854/#855), exposed by suite composition rather than introduced by A3 behaviour as far as the evidence goes; to be filed. + +## Gates (review round 1 A3b) + +| Gate | Result | +|---|---| +| `dotnet build ZB.MOM.WW.OtOpcUa.slnx --no-incremental` | 0 warnings, 0 errors | +| `run-unit-phase.py A3` | passed (`20261125T010625…`) | +| `run-unit-phase.py A2` | passed (`20261125T010724…`) | +| `run-unit-phase.py A1` | passed (`20261125T010836…`) | +| `run-unit-phase.py X0` | passed (`20261125T011156…`) | +| Host.Tests `.DataConnections.` (both v1 gates) | 207 passed | +| Runtime.Tests full (`Category!=E2E&Category!=LiveIntegration`) | 2054 passed, 3 skipped | +| OpcUaServer.Tests full (same filter) | 1456 passed, 1 skipped | +| OI combined (139) | **not 3 clean**: 1 of 4 clean; every failure is in `FolderConditionRefreshWireTests` / `ConditionRefreshDeferralWireTests` (see the investigation above); every A3/GrpcData test passed in every run | +| OI `ImportedConditionMethodWireTests` (16) | 16/16 (and in each combined run) | +| L2 worst case (opt-in) | **FAIL** 2 of 3 runs (above) | +| `git diff master -- '*Goldens.cs'` | empty | From 159ce9d13d82ded963bad7e68a353c43525219f3 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 20:45:32 -0500 Subject: [PATCH 27/32] =?UTF-8?q?docs(grpc-data):=20A3b=20review=20r1=20?= =?UTF-8?q?=E2=80=94=20live=20a3br1-cond-1=20PASS?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/plans/evidence/grpc-data-ext/A3.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/plans/evidence/grpc-data-ext/A3.md b/docs/plans/evidence/grpc-data-ext/A3.md index dc2b5f353..5e8f318e8 100644 --- a/docs/plans/evidence/grpc-data-ext/A3.md +++ b/docs/plans/evidence/grpc-data-ext/A3.md @@ -553,3 +553,11 @@ code (#854/#855), exposed by suite composition rather than introduced by A3 beha | OI `ImportedConditionMethodWireTests` (16) | 16/16 (and in each combined run) | | L2 worst case (opt-in) | **FAIL** 2 of 3 runs (above) | | `git diff master -- '*Goldens.cs'` | empty | + +## Live — run `a3br1-cond-1` (build `c82ea04e`, clean tree) — PASS + +Same procedure as `a3b-cond-3` (`rig.py up --conditions`, seed, 90 s, deploy, `conditions_a3_smoke.py`, `rig.py down`). Imported +ScalarHigh at the consumer (`ns=6;s=c1.…`, 32-char EventId); bogus EventId ⇒ `BadEventIdUnknown [809A0000]`; ack through the +consumer `Acknowledge successful` (596 ms, through the new per-connection slot + dispatch floor + mapping-timeout path); origin +subscriber and consumer subscriber each saw exactly one Active/Acknowledged; `passed: true`. Teardown: no run-labelled containers +or networks left. From 6be0b8dc4b424bfd76f3a08c9ab0aeb24c3139a2 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 21:36:47 -0500 Subject: [PATCH 28/32] =?UTF-8?q?fix(grpc-data):=20A3=20r2=20=E2=80=94=20a?= =?UTF-8?q?=20released=20marked=20EventFieldList=20never=20re-enters=20the?= =?UTF-8?q?=20SDK's=20process-wide=20pool?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SDK 2.0.1 pools EventFieldList (PooledEncodeableType); SentMessageQueue Reuse()s every list of an acknowledged message and the base ReuseCore returns it, whatever its runtime type, to the shared stock pool. A recycled ProjectedEventFieldList was then rented by any server's GetEventFields (an unrelated session's RefreshStart/RefreshEnd or local event) still carrying an imported condition's marker, and ProjectedNotificationRewriter dropped it when that marker's gate denied. Root cause of the intermittent OI ConditionRefresh failures (#854/#855 classes). Mirrors ProjectedSdkNotification on the data path: override ReuseCore, clear the marker, never return to the pool; a released (marker-less) list fails closed. --- .../ProjectedEventDelivery.cs | 21 +++++++++++- .../WarmStandby.cs | 2 +- .../ImportedConditionClassifierTests.cs | 33 +++++++++++++++++++ 3 files changed, 54 insertions(+), 2 deletions(-) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedEventDelivery.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedEventDelivery.cs index 17cacc98a..b20cc7981 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedEventDelivery.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedEventDelivery.cs @@ -461,11 +461,30 @@ internal sealed record ProjectedEventMarker(object? Identity, NodeId ConditionId /// ProjectedNotificationRewriter sees this instance on every Publish and Republish and drops it when the re-check /// fails. /// +/// +/// A3 review round 2 (root cause of the OI refresh failures): SDK 2.0.1 POOLS process-wide +/// (EventFieldListActivator : PooledEncodeableType). SentMessageQueue calls Reuse() on every list of an +/// acknowledged/evicted message, and the base ReuseCore returns the instance — whatever its runtime type — to the +/// shared stock pool, from which ANY server's MonitoredItem.GetEventFields rents its next list. A recycled +/// instance of this subclass therefore became some unrelated session's RefreshStart/RefreshEnd or local condition event, +/// still carrying THIS marker: the rewriter judged it by another condition's (possibly revoked) gate and dropped it. +/// Like ProjectedSdkNotification on the data path, this subclass stays out of the stock pool. +/// internal sealed class ProjectedEventFieldList(ProjectedEventMarker marker) : EventFieldList { internal static long s_unservable, s_droppedOnPublish, s_droppedUnmarked, s_keptUnmarked; - public ProjectedEventMarker Marker { get; } = marker; + /// The captured authority; null once the SDK has released the list (it is never published again). + public ProjectedEventMarker? Marker { get; private set; } = marker; + + /// + protected override void ReuseCore() + { + // ACK, eviction and message disposal reach this through IPooledEncodeable.Reuse: reset, drop the marker (and with it + // the closure over the condition and identity), and let the GC have it — never the shared EventFieldList pool. + Marker = null; + ResetForReuse(); + } /// Imported events an item could not receive through the marked path (fail closed). internal static long Unservable => Interlocked.Read(ref s_unservable); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/WarmStandby.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/WarmStandby.cs index 68786bb82..c0fc1f500 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/WarmStandby.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/WarmStandby.cs @@ -938,7 +938,7 @@ internal static class ProjectedNotificationRewriter { if (list is ProjectedEventFieldList marked) { - if (marked.Marker.Permits()) kept.Add(list); + if (marked.Marker?.Permits() == true) kept.Add(list); // a released list (no marker) fails closed else Interlocked.Increment(ref ProjectedEventFieldList.s_droppedOnPublish); continue; } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs index 5799e02f8..31265cb63 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs @@ -116,6 +116,39 @@ public sealed class ImportedConditionClassifierTests : IAsyncDisposable ReferenceEquals(ProjectedNotificationRewriter.Project(plain, republish: false, null), plain).ShouldBeTrue(); } + /// + /// A3 review round 2 (root cause of the intermittent OI ConditionRefresh failures): SDK 2.0.1 pools EventFieldList + /// process-wide, and SentMessageQueue calls Reuse() on every list of an acknowledged message. A marked + /// list that went back to the stock pool was rented by an unrelated server/session's GetEventFields (its + /// RefreshStart/RefreshEnd), carrying a revoked marker, and the rewriter dropped it. A released marked list must never + /// be rentable, and must not keep its marker (closure over condition + identity) alive. + /// + [Fact] + public void A_released_marked_event_list_never_returns_to_the_SDK_pool_so_no_other_session_rents_its_marker() + { + var marked = new ProjectedEventFieldList(new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => false)) { ClientHandle = 77 }; + ((IPooledEncodeable)marked).Reuse(); // exactly what SentMessageQueue.ReuseNotificationPayloads does on ACK / eviction + marked.Marker.ShouldBeNull("a released list holds no authority (and keeps no closure alive)"); + + // Drain more than the pool can hold: had the marked instance been returned, it would come out here. + var rented = new List(); + try + { + for (var i = 0; i < PooledEncodeableType.DefaultMaximumRetained + 64; i++) + rented.Add((EventFieldList)EventFieldListActivator.Instance.CreateInstance()); + rented.ShouldNotContain(l => l is ProjectedEventFieldList, "a stock list rented for any event is never a marked one"); + } + finally + { + foreach (var l in rented) ((IPooledEncodeable)l).Reuse(); + } + + // A released marked list that somehow reached the rewriter fails closed (never judged by a stale marker). + var message = new NotificationMessage { SequenceNumber = 10, + NotificationData = [new ExtensionObject(new EventNotificationList { Events = [marked] })] }; + ProjectedNotificationRewriter.Project(message, republish: false, null).NotificationData.Count.ShouldBe(0); + } + [Fact] public void S2_a_cached_positive_verdict_is_re_proved_past_the_credential_expiry_and_past_the_positive_TTL() { From b884db5fb12ae0055427b6087cc4a2a7a8397228 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 21:46:21 -0500 Subject: [PATCH 29/32] =?UTF-8?q?perf(grpc-data):=20A3=20r2=20L2=20?= =?UTF-8?q?=E2=80=94=20EventId=20window=20back=20to=20the=20plan's=208;=20?= =?UTF-8?q?measure=20the=20retained=20heap,=20not=20GC.GetTotalMemory?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GC.GetTotalMemory on .NET 10 regions reported +92 or +218 MiB (bimodal) for the same state; GCMemoryInfo heap size and a heap dump (136 MB of objects, eeheap allocated 136,318,696 / committed 236,208,128) show the extra was committed-but-free regions. The harness now takes HeapSizeBytes-FragmentedBytes after a full blocking GC and the settled working set, and asserts BOTH <= 200 MiB. Worst case (2 placements, 8 slots, 3 event items, Live+Buffer): heap +106.5 MiB, WS +151.3 MiB max of 3 runs. BytesPerCondition 230,000 -> 160,000 (max WS/condition 158,629, rounded up); MaxImportedConditionBytes default 160,000 x 2,500 = 400,000,000 B (~381 MiB). --- .../Configuration/DataConnectionOptions.cs | 2 +- .../ProjectedConditionRegistry.cs | 8 +++-- .../ProjectedConditionAccess.cs | 10 +++--- ...ImportedConditionMemoryMeasurementTests.cs | 33 +++++++++++++++++-- 4 files changed, 44 insertions(+), 9 deletions(-) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs index ca67a3563..9ffd79ca9 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs @@ -21,7 +21,7 @@ public sealed class DataConnectionOptions public long MaxTransportBytes { get; set; } = 64 * 1024 * 1024; /// A3 (§5.5): imported-condition node budget per consumer node (2,500 × 49 worst-case nodes per condition). public int MaxImportedConditionNodes { get; set; } = 122_500; - /// A3 (§5.5): imported-condition memory budget per consumer node (§9.3 L2: worst-case measured 230,000 B/condition × 2,500 ≈ 548 MiB). + /// A3 (§5.5): imported-condition memory budget per consumer node (§9.3 L2: worst-case measured 160,000 B/condition × 2,500 ≈ 381 MiB). public long MaxImportedConditionBytes { get; set; } = ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ProjectedConditionOptions.DefaultMaxImportedConditionBytes; public long MaxPendingBytes { get; set; } = 1024 * 1024; public TimeSpan MaxSessionLifetime { get; set; } = TimeSpan.FromHours(1); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs index 201603370..3daba583f 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs @@ -72,8 +72,12 @@ public sealed record ImportedConditionBinding(string ConnectionId, string Condit /// internal sealed class ProjectedConditionRegistry { - /// Recent EventIds kept per condition for N6 re-binding. - internal const int RecentEventIds = 32; + /// + /// Recent EventIds kept per condition (§5.6 step 3: "within its last N (default 8) events"). A3 review round 2: back to + /// the plan's 8 — A3a's 32 had no recorded need (validity is "minted under the current marker", which only the newest + /// few can satisfy; an older EventId already answers BadEventIdUnknown at the origin). + /// + internal const int RecentEventIds = 8; private readonly ConcurrentDictionary _byNode = new(); private readonly ConcurrentDictionary _byInstance = new(ReferenceEqualityComparer.Instance); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs index 1aaf9b93c..24b4176c2 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs @@ -40,7 +40,7 @@ public sealed class DeployedConditionMappings : IProjectedConditionMappings /// A3 host limits (§5.5 "Budget"). /// How long a connection's condition items stay open after the last event item goes (default 30 s). /// Per consumer node (default 122,500 = 2,500 × 49). -/// Per consumer node (default = L2-measured × 2,500 ≈ 548 MiB). +/// Per consumer node (default = L2-measured × 2,500 ≈ 381 MiB). /// Pause before re-opening an ended condition stream. public sealed record ProjectedConditionOptions(TimeSpan Linger, int MaxImportedConditionNodes, long MaxImportedConditionBytes, TimeSpan ReconnectDelay) @@ -50,10 +50,12 @@ public sealed record ProjectedConditionOptions(TimeSpan Linger, int MaxImportedC /// /// Retained managed bytes per imported condition, measured by the A3 L2 harness (1,000 conditions in one mapping on a /// running SDK 2.0.1 server: node + children + ids + registry/indexes + EventId registry + verdict cache; X0's - /// node-only harness measured 160,997). A3b review S5: the WORST case — two placements, all 32 EventId slots, three - /// event items, the runner's Live + Buffer records — max of three runs 228,353 B (managed heap), rounded up. + /// node-only harness measured 160,997). A3b review S5: the WORST case — two placements, every EventId slot, three + /// event items, the runner's Live + Buffer records. A3 review round 2: measured with the retained heap + /// (GCMemoryInfo, not GC.GetTotalMemory, which counted ~125 MiB of committed-but-free regions) and the + /// settled working set, 8 EventId slots (§5.6): max of three runs = 158,629 B (working set; heap 111,715 B), rounded up. /// - public const long BytesPerCondition = 230_000; + public const long BytesPerCondition = 160_000; /// §9.3 L2: the host byte cap = measured per-condition bytes × 2,500 (the host condition cap). public const long DefaultMaxImportedConditionBytes = BytesPerCondition * 2_500; diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMemoryMeasurementTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMemoryMeasurementTests.cs index 4154676d6..daedc50dd 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMemoryMeasurementTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMemoryMeasurementTests.cs @@ -62,6 +62,7 @@ public sealed class ImportedConditionMemoryMeasurementTests subscription.MonitoredItems.All(m => ServiceResult.IsGood(m.Status.Error)).ShouldBeTrue("all three event items are admitted"); var (heap0, ws0) = Measure(); + var totalMemory0 = GC.GetTotalMemory(forceFullCollection: true); var keys = Enumerable.Range(0, Conditions).Select(i => KeyOf("l2-" + i)).ToArray(); // Runner state (worst case): the committed Live records AND a full re-snapshot Buffer of the same keys. var live = keys.Select((k, i) => Update(k, i, 3, active: true, acked: false, sequence: 1)).ToList(); @@ -88,6 +89,7 @@ public sealed class ImportedConditionMemoryMeasurementTests nm.AuthorizeImportedCondition(identity, Core.Abstractions.OpcUaOperation.Read, nm.ImportedConditionNodeId(Connection, k)).ShouldBeTrue(); var (heap1, ws1) = Measure(); + var (reportedHeap0, reportedHeap1) = (totalMemory0, GC.GetTotalMemory(forceFullCollection: true)); GC.KeepAlive(live); GC.KeepAlive(buffer); GC.KeepAlive(subscription); @@ -96,21 +98,48 @@ public sealed class ImportedConditionMemoryMeasurementTests var line = $"L2 (worst case: 2 placements, {slots} EventId slots, 3 event items, Live+Buffer records): {Conditions} conditions: " + $"managed heap +{heapGrowth / 1048576.0:F1} MiB ({heapGrowth / Conditions:N0} B/condition; after materialise {(heapMid - heap0) / Conditions:N0}), " + $"working set +{wsGrowth / 1048576.0:F1} MiB ({wsGrowth / Conditions:N0} B/condition); materialise {materialise.TotalMilliseconds:F0} ms, " + - $"{OpcUaServer.ProjectedConditionRegistry.RecentEventIds} transitions {transition.TotalMilliseconds:F0} ms; events reported {nm.ImportedEventsReported}"; + $"{OpcUaServer.ProjectedConditionRegistry.RecentEventIds} transitions {transition.TotalMilliseconds:F0} ms; events reported {nm.ImportedEventsReported}; " + + $"GC.GetTotalMemory delta (not used, see Measure) +{(reportedHeap1 - reportedHeap0) / 1048576.0:F1} MiB"; TestContext.Current.TestOutputHelper?.WriteLine(line); if (Environment.GetEnvironmentVariable("OTOPCUA_A3_MEASURE_OUT") is { Length: > 0 } outPath) File.AppendAllText(outPath, line + Environment.NewLine); wsGrowth.ShouldBeLessThanOrEqualTo(200L * 1024 * 1024); + heapGrowth.ShouldBeLessThanOrEqualTo(200L * 1024 * 1024, "the retained managed heap is under the same bound"); } private static NodeId Local(Opc.Ua.Client.ISession session, NodeId serverId) => new(serverId.IdentifierAsString, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri)); + /// + /// Retained managed heap and settled working set after forced compacting GCs. + /// + /// + /// A3 review round 2: GC.GetTotalMemory is NOT the retained heap on this runtime (.NET 10, regions). In the same + /// process state it reported either +92 MiB or +218 MiB (bimodal, run to run) while GC.GetGCMemoryInfo's heap size + /// was 135.5 MB in both, and a heap dump of a "+218 MiB" run held 136 MB of objects in total (eeheap -gc: allocated + /// 136,318,696, committed 236,208,128) — the extra ~125 MiB was committed-but-free region space. The live heap is therefore + /// taken from the last full blocking GC's HeapSizeBytes − FragmentedBytes, and the working set is sampled until the GC + /// has decommitted those free regions (two samples 500 ms apart within 1 MiB, at most 10 s): the instant after the forced + /// GCs it still counts them (+214 MiB seen; +133 MiB two seconds later in the same run). + /// private static (long Heap, long WorkingSet) Measure() { for (var i = 0; i < 3; i++) { GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true); GC.WaitForPendingFinalizers(); } + GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true); + var info = GC.GetGCMemoryInfo(GCKind.FullBlocking); using var process = Process.GetCurrentProcess(); process.Refresh(); - return (GC.GetTotalMemory(forceFullCollection: true), process.WorkingSet64); + var ws = process.WorkingSet64; + var settle = Stopwatch.StartNew(); + while (settle.Elapsed < TimeSpan.FromSeconds(10)) + { + Thread.Sleep(500); + process.Refresh(); + var next = process.WorkingSet64; + var stable = Math.Abs(next - ws) < 1024 * 1024; + ws = next; + if (stable) break; + } + return (info.HeapSizeBytes - info.FragmentedBytes, ws); } private static string KeyOf(string seed) => From 5bece2a5a5210e54dee6671da23c45c9d6d509ae Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 22:11:28 -0500 Subject: [PATCH 30/32] =?UTF-8?q?docs(grpc-data):=20A3=20round=202=20?= =?UTF-8?q?=E2=80=94=20pooled=20EventFieldList=20root=20cause,=20L2=20re-m?= =?UTF-8?q?easured=20(PASS),=20gates,=20live=20a3r2-cond-1=20PASS?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/plans/evidence/grpc-data-ext/A3.md | 133 ++++++++++++++++++++++++ 1 file changed, 133 insertions(+) diff --git a/docs/plans/evidence/grpc-data-ext/A3.md b/docs/plans/evidence/grpc-data-ext/A3.md index 5e8f318e8..51d333540 100644 --- a/docs/plans/evidence/grpc-data-ext/A3.md +++ b/docs/plans/evidence/grpc-data-ext/A3.md @@ -561,3 +561,136 @@ ScalarHigh at the consumer (`ns=6;s=c1.…`, 32-char EventId); bogus EventId ⇒ consumer `Acknowledge successful` (596 ms, through the new per-connection slot + dispatch floor + mapping-timeout path); origin subscriber and consumer subscriber each saw exactly one Active/Acknowledged; `passed: true`. Teardown: no run-labelled containers or networks left. + +# A3 — Round 2 (merge blocker: the OI condition-refresh failures; L2 worst-case memory) + +2026-11-25, branch `a3-consumer`. Not merged, not pushed. Commits: `6be0b8dc` (fix + red/green test), `b884db5f` (L2), this docs +commit. + +## Root cause of the OI condition-refresh failures — an A3 defect, now fixed + +**SDK 2.0.1 pools `EventFieldList` process-wide, and `ProjectedEventFieldList` (A3a, §5.4) went back into that pool.** +`EventFieldListActivator : PooledEncodeableType` (bounded, process-global, 1,024); `MonitoredItem.GetEventFields` +rents every event's list from it; `SentMessageQueue.ReuseNotificationPayloads` calls `Reuse()` on every list of an acknowledged / +evicted message, and the base `ReuseCore` resets the instance and returns it — **whatever its runtime type** — to the stock pool. +A released `ProjectedEventFieldList` was therefore rented by ANY server's next `GetEventFields` — an unrelated session's +`RefreshStart`/`RefreshEnd` or local condition event — still carrying the imported condition's `ProjectedEventMarker`, and +`ProjectedNotificationRewriter` judged that unrelated event by the stale marker: when its gate denied (a revoked caller, a removed +condition), the event was **dropped**. The data path already knew this trap (`ProjectedSdkNotification` overrides `ReuseCore` and +"stays out of the shared stock pool"; `OrdinaryTagMarker` validates itself against its notification); the A3a event subclass did +not follow it. + +This is a production defect, not a test artifact: in one server process, any session's events (refresh markers, local alarms, +acks) could be dropped by another session's imported-condition gate, and every recycled list pinned a marker closure (condition + +identity) for as long as it sat in the pool. + +How it was found (one test run at a time, `--blame-hang-timeout 120s`): + +| Step | Set | Runs | Failed runs | +|---|---|---|---| +| A3 build, full combined filter (139) | — | 1 | 1 | +| A3 build, master's 109 only (`FullyQualifiedName!~ImportedCondition`) | **A3 production code alone** | 4 | **0** ⇒ the A3 tests trigger it | +| without `ImportedConditionMethodWireTests` (123) | event wire tests in | 4 | 2 | +| deferral + folder classes + event wire tests only (52) | — | 4 | **4** | +| … + half A (6 tests) | — | 3 | 2 | +| … + `Exactly_one…`, `A3_SEC_with_ACLs_off…`, `A_condition_child_Read…` | — | 3 | 3 | +| … + `A_condition_child_Read…` only (no event subscription) | — | 3 | 0 | +| … + `Exactly_one…` only (no revocation) | — | 3 | 0 | +| … + `A3_SEC_with_ACLs_off…` only (**revokes** a marked event's caller) | — | 3 | 2 | + +Then a temporary publish-path trace (server: the SDK's message before and after the rewriter; client: RefreshStart/End received; +reverted, never committed) on a failing run showed it directly: + +``` +PUBraw app=urn:OtOpcUa.Refresh855.… sub=3999762809 seq=2 h=19 START EventFieldList +PUBraw app=urn:OtOpcUa.Refresh855.… sub=3999762809 seq=2 h=19 END ProjectedEventFieldList ← a non-imported rig's RefreshEnd +PUB app=urn:OtOpcUa.Refresh855.… sub=3999762809 seq=2 h=19 START EventFieldList ← END dropped by the rewriter +RCV sub=3999762809 h=19 START +PUBraw app=urn:OtOpcUa.Refresh854Gate.… sub=990727810 seq=3 h=30 END ProjectedEventFieldList (never published) +``` + +That explains every symptom: "RefreshEnd never arrives" (the recycled list was the RefreshEnd), "RefreshStart missing but +RefreshEnd present" (the recycled list was the RefreshStart), "no stall/deferral at all" (plain refresh, same pool), extra events +inside a window (a recycled list whose stale marker PERMITTED), the scaling with suite size and the need for other tests in the +process (more marked lists in the pool), and master never reproducing (no marked lists). The earlier leads (thread-pool +starvation, CPU load, the static `FilterGroup` registry) were not it. + +**Fix** (`ProjectedEventDelivery.cs`): `ProjectedEventFieldList` overrides `ReuseCore` — clears its marker, `ResetForReuse()`, +never returns to the stock pool (the GC takes it), exactly like `ProjectedSdkNotification`. `Marker` is nullable; the rewriter +treats a released (marker-less) list as denied (fail closed; it is never published again anyway). No `Lock` involvement. + +**Red/green** (`ImportedConditionClassifierTests.A_released_marked_event_list_never_returns_to_the_SDK_pool_so_no_other_session_rents_its_marker`, +OpcUaServer.Tests, deterministic): `Reuse()` a marked list as `SentMessageQueue` does, drain `DefaultMaximumRetained + 64` lists +from `EventFieldListActivator.Instance`, assert none is a `ProjectedEventFieldList`, the marker is gone, and a released list +through the rewriter is dropped. Red on revert, both ways: override body → `base.ReuseCore()` ⇒ `marked.Marker should be null`; +`Marker = null; base.ReuseCore()` ⇒ `rented should not contain an element satisfying the condition`. + +After the fix: the 52-test reproducer 0/3 (was 4/4); the combined OI filter — see gates. + +## L2 worst-case memory — PASS (the round-1 "FAIL" was a measurement artifact) + +1. **EventId window → 8** (`ProjectedConditionRegistry.RecentEventIds`), the plan's §5.6 step 3 "within its last N (default 8)". + A3a's 32 had no recorded need (deviation 1 only stated it); validity is "minted under the current marker", which only the + newest few EventIds can meet. No test depended on 32 (only the L2 harness reads the constant). +2. **`GC.GetTotalMemory` is not the retained heap on .NET 10 regions.** In the same process state it reported **+92 or +218 MiB** + run to run (bimodal; it is the source of round 1's "+217.8 MiB" and run 1's "GC noise"). In those very runs + `GC.GetGCMemoryInfo().HeapSizeBytes` was 135.5 MB both times, and a heap dump of a "+218" run (`dotnet-dump`, taken while + paused after the measurement) held **136 MB of objects in total** (`eeheap -gc`: allocated 136,318,696 B, committed + 236,208,128 B): the extra ~125 MiB was committed-but-free region space, and the working set measured the instant after the + forced GCs counted it too (+214 MiB; +133 MiB two seconds later in the same run). The harness now takes + `HeapSizeBytes − FragmentedBytes` after a full blocking GC, samples the working set until the GC has decommitted (two samples + 500 ms apart within 1 MiB, ≤ 10 s), still logs the `GetTotalMemory` delta for comparison, and asserts **both** heap and working + set ≤ 200 MiB (stricter than before, not looser). +3. **What dominates** (end-of-run dump, 32-slot build): of 136 MB live, our own types are 6.4 MB — 3.1 MB of it the 32-slot + EventId window (32,000 `LinkedListNode` + 33,000 `DataActivationMarker`, now ÷4), the rest registry entries, placements, + 1,000 `ImportedCondition`, 3,000 marked lists/markers (queues capped at 1,000 per item), the harness's Live + Buffer records + (~0.6 MB). ~86 MB is SDK `Opc.Ua.*` node state (property/variable/method states, `ReferenceDictionary`, 158 `Lock`s and 400 + `object`s per condition), not ours to cut without touching the SDK node model. + +Worst case (2 placements per condition, all 8 EventId slots filled, 3 event items with publishing off, Live + Buffer records): + +| Run | Managed heap growth | Working-set growth (settled) | heap B/condition | WS B/condition | `GetTotalMemory` delta (not used) | +|---|---|---|---|---|---| +| 1 | +106.5 MiB | +151.3 MiB | 111,715 | 158,629 | +211.6 MiB | +| 2 | +106.5 MiB | +149.2 MiB | 111,682 | 156,434 | +211.5 MiB | +| 3 | +106.5 MiB | +149.4 MiB | 111,654 | 156,663 | +211.5 MiB | + +**L2: PASS** (both ≤ 200 MiB in every run). `BytesPerCondition` = the larger of the two per-condition figures, max of three runs, +rounded up: 158,629 → **160,000** (was 230,000); `MaxImportedConditionBytes` default = 160,000 × 2,500 = **400,000,000 B +(≈ 381 MiB)** (was ≈ 548 MiB). The X0 node-only figure (160,997) and A3b's 197.4 MiB were taken with `GetTotalMemory` too and are +likely inflated the same way (not re-measured here). + +## Gates (round 2, at `b884db5f`) + +| Gate | Result | +|---|---| +| `dotnet build ZB.MOM.WW.OtOpcUa.slnx --no-incremental` | 0 warnings, 0 errors | +| `run-unit-phase.py A3` | passed (`20261125T024649…`) | +| `run-unit-phase.py A2` | passed (`20261125T024744…`) | +| `run-unit-phase.py A1` | passed (`20261125T024855…`) | +| `run-unit-phase.py X0` | passed (`20261125T025234…`) | +| Host.Tests `.DataConnections.` (both v1 gates) | 207 passed | +| Runtime.Tests full (`Category!=E2E&Category!=LiveIntegration`) | 2054 passed, 3 skipped (see note) | +| OpcUaServer.Tests full (same filter) | 1457 passed, 1 skipped | +| OI combined (139) | **3 consecutive clean runs**: 138 passed, 1 skipped (the opt-in L2 harness) each | +| L2 worst case (opt-in) | PASS 3/3 (above) | +| `git diff master -- '*Goldens.cs'` | empty | + +Note (Runtime): the first full run, made while the live rig's images were building (heavy CPU), failed one test, +`GrpcDataConditionStreamTests.Overflow_before_the_snapshot_is_drained_resets_the_stream` (A2, unchanged by A3 — it races 6 raises +against the condition item's read position to force a hub eviction). Not touched by round 2 (no Runtime behaviour changed; only the +`BytesPerCondition` constant). The class passed 5/5 alone and the full suite passed on the re-run without load. Not root-caused +here and not called a flake: to be filed as a load-sensitivity follow-up. + +## Live — run `a3r2-cond-1` (build `b884db5f`, clean tree) — PASS + +Same procedure as `a3b-cond-3` (`rig.py up --conditions`, seed, 90 s, deploy, `conditions_a3_smoke.py`, `rig.py down`). Imported +ScalarHigh at the consumer (`ns=6;s=c1.…`, 32-char EventId); bogus EventId ⇒ `BadEventIdUnknown [809A0000]`; ack through the +consumer `Acknowledge successful` (1,990 ms); origin subscriber and consumer subscriber each saw exactly one +Active/Acknowledged; `passed: true`. Teardown: no run-labelled containers or networks left. + +## Left over + +- File: the `GrpcDataConditionStreamTests.Overflow_before_the_snapshot_is_drained_resets_the_stream` load sensitivity (above). +- The plan's L2 / X0 figures (≈ 157–161 KiB per condition node, §5.5 table) came from `GC.GetTotalMemory` and are likely + inflated by the same region accounting; the plan's §5.5 table was not edited (evidence only). From c8b35d494fb7bd1a985856d4a0feb7136ecc10af Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 22:26:09 -0500 Subject: [PATCH 31/32] =?UTF-8?q?fix(grpc-data):=20A3=20verification=20r2?= =?UTF-8?q?=20=E2=80=94=20N1=20runner=20predecessor=20chain=20dropped=20af?= =?UTF-8?q?ter=20hand-over=20+=20stopped=20runner=20clears=20its=20record?= =?UTF-8?q?=20sets;=20correct=20the=20SentMessageQueue=20clone=20comment?= =?UTF-8?q?=20and=20pin=20the=20EventFieldList=20MemberwiseClone=20depende?= =?UTF-8?q?ncy?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ProjectedEventDelivery.cs | 13 +++++--- .../ProjectedConditionAccess.Runner.cs | 31 +++++++++++++------ .../ProjectedConditionAccess.cs | 7 +++++ .../ImportedConditionClassifierTests.cs | 28 +++++++++++++++++ .../GrpcDataProjectedConditionAccessTests.cs | 29 +++++++++++++++++ 5 files changed, 94 insertions(+), 14 deletions(-) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedEventDelivery.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedEventDelivery.cs index b20cc7981..780b53781 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedEventDelivery.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedEventDelivery.cs @@ -455,11 +455,14 @@ internal sealed record ProjectedEventMarker(object? Identity, NodeId ConditionId } /// -/// A3 (§5.4): an carrying its . The SDK never clones a -/// queued list on its way to the wire (SDK 2.0.1: QueueEvent(EventFieldList) enqueues the instance, -/// Publish dequeues it, ConstructMessage places it, Republish returns the stored message), so -/// ProjectedNotificationRewriter sees this instance on every Publish and Republish and drops it when the re-check -/// fails. +/// A3 (§5.4): an carrying its . The rewriter does NOT see +/// the queued instance: SDK 2.0.1 SentMessageQueue stores the constructed message and returns a +/// CoreUtils.Clone of it on Publish and on Republish. The gate still works because +/// is MemberwiseClone, so every copy keeps this subclass, its +/// and its handle, and ProjectedNotificationRewriter drops the copy when the re-check fails. +/// That clone dependency is pinned by +/// ImportedConditionClassifierTests.Cloning_a_marked_event_list_the_way_the_SDK_does_keeps_the_subclass_and_the_marker: +/// an SDK that cloned through the activator would turn it red. /// /// /// A3 review round 2 (root cause of the OI refresh failures): SDK 2.0.1 POOLS process-wide diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs index 6372e1341..75b4dd8af 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs @@ -143,7 +143,8 @@ public sealed partial class ProjectedConditionAccess private readonly CancellationTokenSource _stop = new(); private readonly object _statusGate = new(); private readonly object _staleGate = new(); - private readonly ConnectionRunner? _predecessor; + /// Verification r2 N1: dropped right after the hand-over, so runners never chain (R3 → R2 → R1 …). + private ConnectionRunner? _predecessor; private Task _loop = Task.CompletedTask; private Task _stopped = Task.CompletedTask; private MappingState[] _states = []; @@ -177,17 +178,27 @@ public sealed partial class ProjectedConditionAccess public void Start() => _loop = Task.Run(async () => { - if (_predecessor is { } previous) - { - // S3/S4: never overlap the previous runner of this connection — its in-flight Publish or its removal would - // otherwise race this runner's materialisation (an orphaned key, or a fresh key removed by the old continuation). - try { await previous.Stopped.ConfigureAwait(false); } catch (Exception ex) { _owner._log.LogDebug(ex, "Imported conditions: predecessor stop faulted"); } - _materialised = previous._materialised; - previous._materialised = new HashSet(StringComparer.Ordinal); - } + await HandOverAsync().ConfigureAwait(false); await RunAsync(_stop.Token).ConfigureAwait(false); }); + /// + /// S3/S4: never overlap the previous runner of this connection — its in-flight Publish or its removal would otherwise + /// race this runner's materialisation (an orphaned key, or a fresh key removed by the old continuation). The + /// materialised set moves over only after the predecessor stopped. Verification r2 N1: the predecessor reference is + /// dropped once the hand-over is done (its own method, so no hoisted local outlives it either) — otherwise every + /// linger expiry or mapping change would add a link to a chain that keeps each old runner reachable. + /// + private async Task HandOverAsync() + { + var previous = _predecessor; + if (previous is null) return; + try { await previous.Stopped.ConfigureAwait(false); } catch (Exception ex) { _owner._log.LogDebug(ex, "Imported conditions: predecessor stop faulted"); } + _materialised = previous._materialised; + previous._materialised = new HashSet(StringComparer.Ordinal); + _predecessor = null; + } + public void Stop(bool removeConditions) { _stop.Cancel(); @@ -195,6 +206,8 @@ public sealed partial class ProjectedConditionAccess lock (_staleGate) { _staleGeneration++; _stale?.Dispose(); _stale = null; } _stopped = _loop.ContinueWith(_ => { + // Verification r2 N1: a stopped runner keeps no stream's record sets (it may sit in _stopping until the next demand). + lock (_statusGate) _states = []; if (!removeConditions) return; var keys = _materialised.ToArray(); if (keys.Length > 0 && _owner._sink() is { } sink) sink.RemoveConditions(ConnectionId, keys); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs index 24b4176c2..b3a43ccda 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs @@ -290,6 +290,13 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess lock (_gate) return _runners.ContainsKey(connectionId); } + /// Test observation (verification r2 N1): a weak reference to the connection's current (or still stopping) runner. + public WeakReference? RunnerReference(string connectionId) + { + lock (_gate) + return _runners.TryGetValue(connectionId, out var runner) || _stopping.TryGetValue(connectionId, out runner) ? new WeakReference(runner) : null; + } + /// Test observation: snapshot barriers a connection completed. public int BarriersCompleted(string connectionId) { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs index 31265cb63..7625958b1 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs @@ -149,6 +149,34 @@ public sealed class ImportedConditionClassifierTests : IAsyncDisposable ProjectedNotificationRewriter.Project(message, republish: false, null).NotificationData.Count.ShouldBe(0); } + /// + /// Verification review r2: the rewriter never sees the queued instance — SDK 2.0.1 SentMessageQueue hands Publish + /// and Republish a CoreUtils.Clone of the stored message. The gate holds only because + /// is MemberwiseClone, which keeps the subclass, the marker and the handle. Pins + /// that dependency: an SDK that cloned through the activator (a stock list) would turn this red. + /// + [Fact] + public void Cloning_a_marked_event_list_the_way_the_SDK_does_keeps_the_subclass_and_the_marker() + { + var marker = new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => false); + var marked = new ProjectedEventFieldList(marker) { ClientHandle = 42 }; + + var direct = marked.Clone().ShouldBeOfType(); + direct.Marker.ShouldBeSameAs(marker); + direct.ClientHandle.ShouldBe(42u); + + var message = new NotificationMessage { SequenceNumber = 11, + NotificationData = [new ExtensionObject(new EventNotificationList { Events = [marked] })] }; + var delivered = CoreUtils.Clone(message)!; // exactly what SentMessageQueue returns for Publish / Republish + delivered.NotificationData[0].TryGetValue(out var list).ShouldBeTrue(); + var events = list!.Events; + var cloned = events[0].ShouldBeOfType(); + cloned.ShouldNotBeSameAs(marked, "the SDK delivers a copy, not the queued instance"); + cloned.Marker.ShouldBeSameAs(marker); + ProjectedNotificationRewriter.Project(delivered, republish: false, null).NotificationData.Count + .ShouldBe(0, "the copy is still judged by its marker (and dropped when the re-check fails)"); + } + [Fact] public void S2_a_cached_positive_verdict_is_re_proved_past_the_credential_expiry_and_past_the_positive_TTL() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs index b0bdb1821..4f8d42454 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs @@ -461,6 +461,35 @@ public sealed class GrpcDataProjectedConditionAccessTests f.Sink.Live.ShouldBe([Key("y")], "x was handed over (not orphaned) and the new complete set removed it"); } + [Fact] + public async Task N1_demand_cycles_and_mapping_changes_do_not_chain_runners_so_an_old_runner_is_collectable() + { + // Verification review r2 N1: each runner kept its predecessor (and that one's record sets), so every linger expiry + // + re-subscribe or mapping change added a link R3 → R2 → R1 and memory grew without bound. + await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); + var demand = f.Access.AcquireEventDemand(null)!; + await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)])); + var first = f.Access.RunnerReference(Connection)!; + var version = 3L; + for (var cycle = 0; cycle < 3; cycle++) + { + demand.Dispose(); + await f.WaitAsync(() => !f.Access.IsRunning(Connection)); // linger expired + demand = f.Access.AcquireEventDemand(null)!; + await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), ++version)])); + } + for (var change = 0; change < 2; change++) + { + f.Mappings.Current[0].Mapping.MaxConditions++; // a changed signature ⇒ a new runner, a new stream + f.Mappings.Raise(); + await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), ++version)])); + } + f.Sink.Live.ShouldBe([Key("x")], "the hand-over still works across every cycle"); + for (var i = 0; i < 3; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } + first.IsAlive.ShouldBeFalse("the current runner must not keep a chain of predecessors reachable"); + demand.Dispose(); + } + // --------------------------------------------------------------------------------------------------------------------- internal static string Key(string seed) => From 81ac1d52633751d3290ebcb4eb384a447123a14c Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 22:46:42 -0500 Subject: [PATCH 32/32] =?UTF-8?q?docs(grpc-data):=20A3=20verification=20re?= =?UTF-8?q?view=20round=202=20=E2=80=94=20N1=20fix=20+=20red/green,=20clon?= =?UTF-8?q?e=20pin,=20gates,=20live=20a3v2-cond-1=20PASS?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/plans/evidence/grpc-data-ext/A3.md | 52 +++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/docs/plans/evidence/grpc-data-ext/A3.md b/docs/plans/evidence/grpc-data-ext/A3.md index 51d333540..ccac46fab 100644 --- a/docs/plans/evidence/grpc-data-ext/A3.md +++ b/docs/plans/evidence/grpc-data-ext/A3.md @@ -694,3 +694,55 @@ Active/Acknowledged; `passed: true`. Teardown: no run-labelled containers or net - File: the `GrpcDataConditionStreamTests.Overflow_before_the_snapshot_is_drained_resets_the_stream` load sensitivity (above). - The plan's L2 / X0 figures (≈ 157–161 KiB per condition node, §5.5 table) came from `GC.GetTotalMemory` and are likely inflated by the same region accounting; the plan's §5.5 table was not edited (evidence only). + +# A3 — Verification review round 2 + +2026-11-25, branch `a3-consumer`. Not merged, not pushed. **Verdict: approve-with-changes** — one must-fix (N1) and one +comment/test fix; both done in `c8b35d49`. N2/N3 filed as #930; N4–N8 filed as #931. + +## N1 — the runner predecessor chain leaked one runner per demand cycle — fixed + +`ConnectionRunner._predecessor` was `readonly` and never cleared, and every runner kept `_states` (its last stream's Live/Buffer +record sets). Each linger expiry + re-subscribe, or mapping change, added a link R3 → R2 → R1, so memory grew without bound. +Fix (`ProjectedConditionAccess.Runner.cs`): the hand-over moved into `HandOverAsync` (its own state machine, so no hoisted +`previous` local outlives it), which awaits the old runner's `Stopped` (loop end + removal), takes its materialised set, and only +then sets `_predecessor = null` — the S3/S4 ordering is unchanged. A stopping runner's continuation now resets `_states = []` +before (optionally) removing its conditions, so a runner parked in `_stopping` until the next demand holds no record sets. +New test observation `ProjectedConditionAccess.RunnerReference(connectionId)` (a `WeakReference`, never a strong one). + +**Red/green** — `GrpcDataProjectedConditionAccessTests.N1_demand_cycles_and_mapping_changes_do_not_chain_runners_so_an_old_runner_is_collectable` +(Runtime.Tests): first runner completes a snapshot, then 3 linger-expiry + re-demand cycles and 2 mapping changes, each with a +complete snapshot; asserts the hand-over still holds (`Sink.Live == [x]`) and, after forced GCs, that the first runner's weak +reference is dead. Red with the original `Runner.cs` restored (`first.IsAlive should be False`); green with the fix, 5/5 repeats. +S3/S4 hand-over tests still pass. + +## Pool-fix comment corrected + clone dependency pinned + +The `ProjectedEventFieldList` summary claimed the SDK never clones a queued list. Wrong: SDK 2.0.1 `SentMessageQueue` returns +`CoreUtils.Clone` of the stored message on Publish and Republish, so the rewriter never sees the queued instance. The gate works +because `EventFieldList.Clone()` is `MemberwiseClone`, which keeps the subclass, the marker and the handle. The comment now says +that. New test `ImportedConditionClassifierTests.Cloning_a_marked_event_list_the_way_the_SDK_does_keeps_the_subclass_and_the_marker` +(OpcUaServer.Tests): `Clone()` and `CoreUtils.Clone(NotificationMessage)` both yield a `ProjectedEventFieldList` with the same +marker and handle, and the rewriter still drops the copy when its re-check fails. Shown to discriminate: a temporary +`Clone()` override returning a stock `EventFieldList` (what an activator-based clone would do) turns it red +(`marked.Clone() should be of type ProjectedEventFieldList`); reverted. + +## Gates (verification round 2, at `c8b35d49`) + +| Gate | Result | +|---|---| +| `dotnet build ZB.MOM.WW.OtOpcUa.slnx --no-incremental` | 0 warnings, 0 errors | +| `run-unit-phase.py A3` | passed (`20261125T032703…`) | +| `run-unit-phase.py A2` | passed (`20261125T032802…`) | +| Runtime.Tests full (`Category!=E2E&Category!=LiveIntegration`) | 2055 passed, 3 skipped | +| OpcUaServer.Tests full (same filter) | 1458 passed, 1 skipped | +| Host.Tests `.DataConnections.` | 207 passed | +| OI combined (139) | clean: 138 passed, 1 skipped (the opt-in L2 harness) | +| `git diff master -- '*Goldens.cs'` | empty | + +## Live — run `a3v2-cond-1` (build `c8b35d49`) — PASS + +Same procedure as `a3b-cond-3` (`rig.py up --conditions`, seed, 90 s, deploy, `conditions_a3_smoke.py`, `rig.py down`). Imported +ScalarHigh at the consumer (`ns=6;s=c1.…`, 32-char EventId); bogus EventId ⇒ `BadEventIdUnknown [809A0000]`; ack through the +consumer `Acknowledge successful` (540 ms); origin subscriber and consumer subscriber each saw exactly one Active/Acknowledged; +`passed: true`. Teardown: no run-labelled containers or networks left.