From 0cac09cee36a6a8cbfb93eab72a4fcd1332a90ca Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Wed, 25 Nov 2026 00:22:54 -0500 Subject: [PATCH] =?UTF-8?q?fix(grpc-data):=20A4=20review=20r1=20=E2=80=94?= =?UTF-8?q?=20AdminUI=20helpers=20null-safe=20+=20doc=20comments=20restore?= =?UTF-8?q?d;=20metric=20descriptions=20name=20both=20sides;=20docs:=20S1/?= =?UTF-8?q?S2/S3=20behaviour,=20RefreshRequired=20only=20on=20a=20changed?= =?UTF-8?q?=20incomplete=20set,=20SourceName=20vs=20runtime=20status=20(S4?= =?UTF-8?q?),=20scripted=20Good=20=3D=20applied,=20A4-docs=20citations?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/AlarmTracking.md | 14 ++++++++++--- docs/DataConnections.md | 20 ++++++++++++++++--- docs/ScriptedAlarms.md | 4 ++-- docs/plans/evidence/grpc-data-ext/A4-docs.md | 11 ++++++++-- .../Observability/OtOpcUaTelemetry.cs | 8 ++++---- .../DataConnectionDiagnostics.cs | 10 ++++++---- .../DataConnectionConditionDiagnostics.cs | 2 +- ...rpcDataConditionDiagnosticsDisplayTests.cs | 10 ++++++++++ 8 files changed, 60 insertions(+), 19 deletions(-) diff --git a/docs/AlarmTracking.md b/docs/AlarmTracking.md index 577e8a622..2cd31d1bc 100644 --- a/docs/AlarmTracking.md +++ b/docs/AlarmTracking.md @@ -816,8 +816,14 @@ This section is what an OPC UA client of the **consumer** sees. Code: `OpcUaServ - re-creating the connection under a new id. - One origin condition seen through several mappings or placements (a native alarm under a Raw mapping and two equipment references) is **one** consumer condition with several placements. -- **Primary placement** (chooses `SourceName`) comes from deployed config only: Raw mappings before UNS, then mapping id - ordinal, then placement address ordinal. It never depends on stream order. +- **Primary placement** (chooses `SourceName`) follows the deployed order: Raw mappings before UNS, then mapping id + ordinal, then placement address ordinal. It never depends on stream order, and not on a mapping's runtime status + (A4 review r1 S4): when the mapping that chose a condition's `SourceName` is merely not contributing (refused, + `Unavailable`, retrying, `ConditionCapacity`, or not yet complete on a new stream), the condition keeps that `SourceName` + even though only the other placements are materialised. It moves only when that mapping is known again and no longer + lists the condition, or is no longer deployed (disabled, removed), or when a higher-priority mapping starts listing it. + One residual case: a condition **first** seen while a higher-priority mapping is unavailable takes the best + `SourceName` known, and moves to the deployed primary once that mapping lists it. ### Notifiers and delivery @@ -839,7 +845,9 @@ This section is what an OPC UA client of the **consumer** sees. Code: `OpcUaServ conditions per `Lock` hold. Imported conditions are excluded from the local replay paths. - `RefreshRequiredEventType` (`SourceName = "Server"`) is queued, off `Lock`, only to the items that may see an affected condition. It is sent when: - - a snapshot barrier is incomplete (a mapping timed out, was refused or its metadata failed); + - a snapshot barrier is incomplete (a mapping timed out, was refused or its metadata failed) **and** its set of incomplete + mappings differs from the previous barrier's (#930: a mapping that stays refused across streams does not repeat it; one + that completes leaves the set, so a relapse is announced again); - an imported condition is removed (a complete re-snapshot no longer lists it, a `removed` record, a capacity eviction, or a secret rotation). Removal emits **no** `NodeDeleted` model change; - a resync leaves retained EventIds un-re-bindable (see EventIds below). diff --git a/docs/DataConnections.md b/docs/DataConnections.md index 3ce2dfd88..e6fb105d9 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -416,9 +416,15 @@ refresh, EventIds) is documented in [Alarm tracking § Imported conditions](Alar - Retry delay, per mapping. A **definitive** refusal (`Denied`, `NotFound` or `Unsupported`, for the item or the root metadata) or `ConditionCapacity` waits `LongRetryDelay` (5 min) × 2ⁿ, capped at 4× (20 min). Any other refusal or a snapshot timeout waits `ConditionSnapshotTimeoutMilliseconds` × 2ⁿ, capped at 8×. A retry whose snapshot has not - completed by its deadline goes back to `Unavailable` and releases its claim; a late completion is still taken. A + completed by its deadline goes back to `Unavailable` but keeps its buffer and claim, exactly like a mapping that missed + the first barrier: a late completion is still swapped in, until the next retry removes that item and starts over. A completed snapshot resets the count. While a retry runs the mapping is `Pending` (unknown), so nothing it might list is removed or marked known-inactive (T2). + - Every command on the stream has a unique id (the transport refuses a reused one and the stream would end). + - An item ack that arrives after its retry was already replaced (a slow origin) is not ignored: a Good one means the + origin opened an item the consumer no longer tracks, so it is removed at once — otherwise every later re-add would be + refused `InvalidArgument` ("Duplicate client item id"). As a backstop, 3 consecutive `InvalidArgument` refusals of a + mapping's in-stream re-adds end the stream (a new stream clears the origin's items). - `ConditionCapacity` therefore recovers in-stream: after the origin's listing shrinks (or the limit is raised) the next retry's snapshot is admitted and swapped in. - `RefreshRequired` is sent at an incomplete barrier only when its set of incomplete mappings differs from the previous @@ -558,7 +564,15 @@ most clients read an Uncertain status as success. Two charges are made against the host caps: a snapshotting mapping is charged its admitted `total`, and a completed mapping its record count. Growth is charged as it happens. Records beyond `total`, live records beyond `MaxConditions`, or growth past a host cap make that mapping `ConditionCapacity`. Its item is removed, its conditions are removed (except keys another -mapping lists) and clients get `RefreshRequired`. The deploy gate also logs a non-blocking `DataConditionCapacityWarning` +mapping lists) and clients get `RefreshRequired`. + +Held keys that no contributing mapping lists (an `Unavailable` mapping's stale conditions, kept as `BadNoCommunication`) +are charged too, beside every new claim. The one allowance: a mapping with no complete set yet on this stream may be +re-listing keys **it** listed when it was last known, so those held keys are not charged twice. A mapping that never listed +them gets no allowance, so another mapping's held keys cannot make room for it. The remaining overshoot is narrow: a mapping +whose origin retired its old keys and lists new ones, while another mapping is unknown so the old ones stay held, can +exceed the caps by at most its own previous count until that mapping is known. It is logged ("over its host condition +caps") and visible as the node budget line in the AdminUI. The deploy gate also logs a non-blocking `DataConditionCapacityWarning` when Σ `MaxConditions` × 49 of a consumer node's mappings exceeds `MaxImportedConditionNodes`. ### Diagnostics and troubleshooting @@ -569,7 +583,7 @@ ones carry `side` = origin | consumer, because a node can be both: | Instrument | Type | Labels | Meaning | |---|---|---|---| | `otopcua.dataconn.conditions.items` | up/down counter `{item}` | `side` | Origin: root-scoped condition items open for peers. Consumer: the items its condition streams hold open (one per acked mapping item). | -| `otopcua.dataconn.conditions.resyncs` | counter `{resync}` | `side` | Origin: an item re-snapshotted after a hub reader reset. Consumer: a condition stream that ended (the next one re-snapshots). | +| `otopcua.dataconn.conditions.resyncs` | counter `{resync}` | `side` | Origin: an item re-snapshotted after a hub reader reset. Consumer: a condition stream that opened and ended (the next one re-snapshots); a connect attempt that never opened a stream is not counted. | | `otopcua.dataconn.conditions.capacity_rejections` | counter `{item}` | `side` | Origin: an item snapshot over its `MaxConditions` (or refused by the snapshot memory budget). Consumer: a mapping reset to `ConditionCapacity` (over its `MaxConditions` or the host caps). | | `otopcua.dataconn.condition_methods` | counter `{call}` | `method`, `outcome` (the `DataWriteState`), `side` | Origin: calls served. Consumer: calls forwarded (a call the local node manager refuses before forwarding is not counted). | | `otopcua.dataconn.conditions.refresh_required` | counter `{request}` | `side` = consumer | RefreshRequired requests the consumer runtime made: an incomplete barrier with a changed incomplete set, a capacity reset that removed nothing, each removal batch. Not per client item. | diff --git a/docs/ScriptedAlarms.md b/docs/ScriptedAlarms.md index fac922732..42f2615cc 100644 --- a/docs/ScriptedAlarms.md +++ b/docs/ScriptedAlarms.md @@ -433,8 +433,8 @@ apply. - They advertise Acknowledge, AddComment **and Confirm** (`supported_methods` = all three), gated by the export, connection and mapping bits `AlarmAcknowledge` (128) and `AlarmConfirm` (256). - A remote call is dispatched through the same wrapped handler as a local OPC UA call, so the engine receives the same, - unchanged `AlarmCommand` (`User` = the connection's service principal). The consumer answers `Good` once the origin has accepted - the call and routed the command (`DriverConfirmedSuccess`). The consumer's node changes only when the resulting record arrives. + unchanged `AlarmCommand` (`User` = the connection's service principal). The consumer answers `Good` once the origin's handler has + applied the call (`DriverConfirmedSuccess`; native conditions answer `AcceptedUnconfirmed` instead, see DataConnections.md). The consumer's node changes only when the resulting record arrives. - Shelve/Unshelve/Enable/Disable are not forwarded (`BadNotSupported` on the consumer; bit 512 reserved). Operators shelve at the origin, where `/alerts` and the shelving timers live. - The activation marker survives a rebuild for scripted conditions, so the engine's re-assert of a still-active alarm is not diff --git a/docs/plans/evidence/grpc-data-ext/A4-docs.md b/docs/plans/evidence/grpc-data-ext/A4-docs.md index 7f4bcc232..a547cb2d8 100644 --- a/docs/plans/evidence/grpc-data-ext/A4-docs.md +++ b/docs/plans/evidence/grpc-data-ext/A4-docs.md @@ -36,7 +36,7 @@ The sources were the code at `91438049` and the evidence logs X0–A3. The plan | D3 | §6 metrics list `…conditions.refresh_required`. | Not present (`OtOpcUaTelemetry.cs:233-265` has `unsignalled`, `partition_overflows`, `items`, `resyncs`, `capacity_rejections`, `condition_methods`, `marks_discarded`). A4 diagnostics work; TODO 2. | | D4 | §5.4/§5.5: demand per connection the caller could see. | Demand is node-wide: the first admitted event item opens every condition-bearing connection, and the per-event gate still decides visibility (A3a deviation 2). | | D5 | §6: local visibility uses "the Subscribe grant on the `RemoteNamespaceMapping` scope". | `Subscribe` on the **placement folder's** scope, within a current mapping of the placement's realm that grants `AlarmSubscribe`, not `AlarmRead` (`ProjectedConditionAccess.cs:170-190`; A3 Runtime gate tests). Narrower than the mapping scope, and consistent with it. | -| D6 | A07: "RefreshRequired observed if refresh preceded snapshot". | RefreshRequired is sent only at an **incomplete** barrier, on removal and on an un-re-bindable resync (`ProjectedConditionAccess.Runner.cs:374`, `:405`; `ProjectedConditionRegistry.cs:311-340`, `:412`). A ConditionRefresh before a *complete* first barrier gets no RefreshRequired; the conditions then arrive as their records apply (A3a deviation 4, never closed). The A4 live gate should decide whether A07's expectation or the code is right. | +| D6 | A07: "RefreshRequired observed if refresh preceded snapshot". | RefreshRequired is sent only at an **incomplete** barrier whose incomplete set changed (#930), on a capacity reset that removed nothing, on removal and on an un-re-bindable resync (`ProjectedConditionAccess.Runner.cs:703`, `:521`; `ProjectedConditionRegistry.cs:311-340`, `:412`). A ConditionRefresh before a *complete* first barrier gets no RefreshRequired; the conditions then arrive as their records apply (A3a deviation 4, never closed). The A4 live gate should decide whether A07's expectation or the code is right. | | D7 | A03: "an ack with a pre-failover EventId ⇒ `BadEventIdUnknown`". | Holds only when the resynced record's `time` differs. With the same `time` and unchanged state, a new incarnation re-binds the retained EventIds and the old EventId stays ackable (F6, `ImportedConditionMethods.cs:386-415`). This matches plan §5.6 step 3 N6/F6, so A03's wording is the narrower case. A03 should drive a failover where `time` changes. | | D8 | `RemoteNamespaceMapping.ConditionMethodTimeoutMilliseconds` doc comment: "ack/confirm/shelve". | Shelve is not forwarded (bit 512 reserved, `BadNotSupported`). The comment is stale; code is not changed here. | | D9 | §5.2/§6: secret rotation = "removal + addition + RefreshRequired". | True after an origin restart: the next complete snapshot carries new keys, and the old ones are removed with RefreshRequired (Deviation 6 fix). The docs add that the two pair members must hold the same secret, or a failover changes every id (`ConditionKeys.cs:17-20`). This is not a disagreement, only an operational consequence the plan does not state. | @@ -49,13 +49,20 @@ are cited at `~/Desktop/ScadaBridge` `a87c0575`. **This is to be recorded in `si gate.** Two findings need a ScadaBridge change; they are not yet filed as issues. 1. **`SourceName` shape: `/`.** - - Evidence: `ProjectedConditionAccess.Runner.cs:563-564` builds `anchor + "/" + primary.RelativePath`. `:567-575` + - Evidence: `ProjectedConditionAccess.Runner.cs:951` builds `anchor + "/" + primary.RelativePath` (`:955-962` keep a held + `SourceName`, A4 review r1 S4). `:966-974` strips the remote root subject and computes the folder. `ProjectedConditionRegistry.cs:458` sets it at creation, and `:479` updates it on every record ("display only; rides the next event"). - Impact: ScadaBridge builds its per-condition key from `SourceName` + `.` + `ConditionName` (`OpcUaAlarmMapper.cs:45-51`; `RealOpcUaClient.cs:1228-1240`). For an imported condition, that key is therefore the projected path, not the origin's RawPath. It **changes when the primary-placement mapping changes**, for example when the Raw mapping is disabled and a UNS mapping becomes primary. ScadaBridge would then see a different alarm, even though `ConditionId` did not move. + - Runtime status (A4 review r1 S4, decided at `a4-code`): before the fix, a Raw mapping that was merely refused, + `Unavailable` or retrying made the UNS placement primary, so `SourceName` flipped on a transient refusal and flipped + back on recovery (A4 made that state long-lived). Now a held `SourceName` is kept while its mapping is not contributing; + it moves only on a deployed-config change or when that mapping, known again, no longer lists the condition. Residual: a + condition **first** seen while the Raw mapping is unavailable starts with the UNS `SourceName` and moves once Raw lists + it. Add both cases to ScadaBridge#147. - **Finding:** ScadaBridge should key imported conditions on `ConditionId`/`SourceNode`, or accept that a mapping change re-keys them. 2. **`ConditionId` is opaque and stable for the life of the connection. Mapping changes do not move it; secret rotation does.** diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Observability/OtOpcUaTelemetry.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Observability/OtOpcUaTelemetry.cs index 7158a833c..eddfaadfb 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Observability/OtOpcUaTelemetry.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Observability/OtOpcUaTelemetry.cs @@ -242,22 +242,22 @@ public static class OtOpcUaTelemetry /// A2: origin root-scoped condition items currently open (plan §6 metrics). public static readonly UpDownCounter DataConnConditionItems = Meter.CreateUpDownCounter("otopcua.dataconn.conditions.items", unit: "{item}", - description: "Open root-scoped condition items on this origin."); + description: "Open condition items (tag side: origin = root-scoped items served to peers; consumer = items its condition streams hold open)."); /// A2: condition-item re-snapshots after a hub reader reset (records evicted before the item read them). public static readonly Counter DataConnConditionResyncs = Meter.CreateCounter("otopcua.dataconn.conditions.resyncs", unit: "{resync}", - description: "Root-scoped condition items re-snapshotted after a condition-state hub reader reset."); + description: "Condition resyncs (tag side: origin = an item re-snapshotted after a condition-state hub reader reset; consumer = a condition stream that opened and ended)."); /// A2: root-scoped condition items whose listing exceeded the item's MaxConditions (total reported, no records). public static readonly Counter DataConnConditionCapacityRejections = Meter.CreateCounter("otopcua.dataconn.conditions.capacity_rejections", unit: "{item}", - description: "Root-scoped condition items over their MaxConditions at snapshot begin."); + description: "Condition capacity rejections (tag side: origin = an item over its MaxConditions at snapshot begin; consumer = a mapping reset to ConditionCapacity)."); /// A2b: remote condition method calls served by this origin, by method and outcome (plan §6 metrics; no ids). public static readonly Counter DataConnConditionMethods = Meter.CreateCounter("otopcua.dataconn.condition_methods", unit: "{call}", - description: "Remote condition method calls served by this origin (tags: method, outcome)."); + description: "Remote condition method calls (tags: method, outcome, side: origin = served, consumer = forwarded)."); /// A1 (G3): deferred MarkConditionsKnown discarded because an alarm projection of the same source did not land. public static readonly Counter DataConnConditionMarksDiscarded = diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataConnectionDiagnostics.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataConnectionDiagnostics.cs index b271d09fb..78bb7d0a8 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataConnectionDiagnostics.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataConnectionDiagnostics.cs @@ -62,7 +62,6 @@ public static class DataConnectionDiagnostics { } b => Bits((uint)(int)b, bit => Enum.IsDefined((DataOperations)(int)bit) ? DataOperationAuthoring.Label((DataOperations)(int)bit) : null), }; - /// #919: true when the drop deserves the "node build is older than the authored feature" hint. /// A4 §6: a count against its limit is a warning at or above 80 % (the budget the plan sizes defaults by). public static bool NearLimit(long observed, long limit) => limit > 0 && observed * 10 >= limit * 8; @@ -84,10 +83,12 @@ public static class DataConnectionDiagnostics /// A4: whether any part of the connection's condition evidence warrants the notice style. public static bool ConditionsNeedAttention(ConsumerConditionDiagnostics? c) => c is not null && (NearLimit(c.ChargedConditions, c.HostConditionLimit) - || c.Mappings.Any(m => NearLimit(m.Observed, m.Limit) || m.Status is "Unavailable" or "ConditionCapacity")); + || (c.Mappings?.Any(m => m is not null && (NearLimit(m.Observed, m.Limit) || m.Status is "Unavailable" or "ConditionCapacity")) ?? false)); - public static string MethodCounts(ConditionMethodCounts m) => - $"succeeded {m.Succeeded} · rejected {m.Rejected} · failed {m.Failed} · unknown {m.Unknown}"; + /// A4: method outcome classes; "unavailable" when a (partial) payload carries none (review r1 NIT: never throws). + public static string MethodCounts(ConditionMethodCounts? m) => m is null + ? "unavailable" + : $"succeeded {m.Succeeded} · rejected {m.Rejected} · failed {m.Failed} · unknown {m.Unknown}"; /// A4: the origin's served-conditions line. public static string OriginConditions(OriginConditionDiagnostics? o) => o is null @@ -99,6 +100,7 @@ public static class DataConnectionDiagnostics + $" · state unknown (unsignalled) {(o.UnsignalledConditions is { } u ? u.ToString() : "unavailable")}" + $" · methods served {MethodCounts(o.Methods)}"; + /// #919: true when the drop deserves the "node build is older than the authored feature" hint. public static bool HasDrops(DataOperations? bits, int? mappings = null) => bits is { } b && b != DataOperations.None || mappings is > 0; public static string Endpoint(string? value) => Uri.TryCreate(value, UriKind.Absolute, out var uri) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionConditionDiagnostics.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionConditionDiagnostics.cs index a5ea53f50..ddf819d8e 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionConditionDiagnostics.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionConditionDiagnostics.cs @@ -19,7 +19,7 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; /// otopcua.dataconn.conditions.items{side} — open condition items: origin = root-scoped items served to peers; /// consumer = the items its condition streams hold open (one per acked mapping). /// otopcua.dataconn.conditions.resyncs{side} — origin: an item re-snapshotted after a hub reader reset; -/// consumer: a condition stream that ended (it re-snapshots on the next). +/// consumer: a condition stream that opened and ended (it re-snapshots on the next; a failed connect attempt is not counted). /// {side=consumer} — RefreshRequired requests the consumer runtime /// made (an incomplete barrier with a changed incomplete set, a capacity reset that removed nothing, each removal batch). /// otopcua.dataconn.conditions.capacity_rejections{side} — origin: an item snapshot over its limit; consumer: a diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/GrpcDataConditionDiagnosticsDisplayTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/GrpcDataConditionDiagnosticsDisplayTests.cs index f4df5d951..745d14f9e 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/GrpcDataConditionDiagnosticsDisplayTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/GrpcDataConditionDiagnosticsDisplayTests.cs @@ -54,4 +54,14 @@ public sealed class GrpcDataConditionDiagnosticsDisplayTests DataConnectionDiagnostics.OriginConditions(new OriginConditionDiagnostics(2, 850, 1000, null, 1, 0, 3, new ConditionMethodCounts(1, 0, 0, 0))) .ShouldContain("condition items open 2 · largest listing 850/1000 (≥ 80% of MaxConditions)"); } + + [Fact] + public void A_partial_payload_without_mappings_or_methods_renders_instead_of_throwing() + { + // A4 review r1 NIT: an older or partial payload decodes these collections as null. + var partial = new ConsumerConditionDiagnostics("live", null, 0, 0, 0, 0, 0, null!, 10, 2500, null!); + DataConnectionDiagnostics.ConditionsNeedAttention(partial).ShouldBeFalse(); + DataConnectionDiagnostics.ConsumerConditions(partial).ShouldEndWith("methods unavailable"); + DataConnectionDiagnostics.OriginConditions(new OriginConditionDiagnostics(0, 0, 0, null, 0, 0, null, null!)).ShouldEndWith("methods served unavailable"); + } }