From 310b42e3fc759889f36d045759479069da3508ce Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Mon, 23 Nov 2026 16:37:49 -0500 Subject: [PATCH] =?UTF-8?q?docs(plans):=20history+alarms=20plan=20rev=204?= =?UTF-8?q?=20=E2=80=94=20settle=20B5,=20node=20budget,=20state=5Fknown;?= =?UTF-8?q?=20Fable=20third=20pass?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit B5 settled: OtOpcUaNodeManager implements ICallAsyncNodeManager.CallAsync for imported conditions, awaiting the owner with no Lock (verified against SDK 2.0.1). 48-49 nodes / ~157 KiB per imported condition; budgets recomputed. state_known mechanism named; live measurements L1-L5 listed (§9.3). Third Fable pass: X0 + H approved; A approved with changes (T1-T3). Pre-existing v1 defects: #916, #917. --- ...pc-data-connections-history-alarms-plan.md | 298 +++++++++++++----- ...ctions-history-alarms-relay-plan-review.md | 152 +++++++++ 2 files changed, 369 insertions(+), 81 deletions(-) diff --git a/docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md b/docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md index 4239fedef..f85929dc9 100644 --- a/docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md +++ b/docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md @@ -1,6 +1,6 @@ # gRPC data connections: remote history and alarm/event forwarding -Date: 2026-11-23 (revision 3, after the independent review's first and second passes; owner decisions of 2026-11-23 applied) +Date: 2026-11-23 (revision 4: open items settled from code and the pinned SDK; revision 3 folded in the review's two passes and the owner decisions of 2026-11-23) Status: **Design + phased plan, not approved, not implemented.** No code, schema or issue changes accompany this document. It extends the merged v1 feature (`95c5e484`), whose design is [`2026-11-15-grpc-data-connections-design.md`](2026-11-15-grpc-data-connections-design.md) ("v1 design") and whose @@ -9,8 +9,9 @@ plan/gate structure is [`2026-11-15-grpc-data-connections-implementation-plan.md Independent review (first pass of revision 1; "Second pass" section of revision 2): [`2026-11-23-grpc-data-connections-history-alarms-relay-plan-review.md`](2026-11-23-grpc-data-connections-history-alarms-relay-plan-review.md) (the review's file name refers to this plan's earlier name; revision 1 also covered relay, now deferred — §8). -Conventions: "verified" claims cite a file read at `649f2ecd2`. Claims marked **(inferred)** are not proven from source and -are explicit X0 tasks. Path shorthand: `Runtime/` = `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/`, `OpcUaServer/` = +Conventions: "verified" claims cite a file read at `649f2ecd2`; SDK claims cite the decompiled +`OPCFoundation.NetStandard.Opc.Ua.Server` 2.0.1 package the repo pins. Revision 4 settled every former **(inferred)** item from +code or from an offline SDK harness; only the live measurements in §9.3 remain. Path shorthand: `Runtime/` = `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/`, `OpcUaServer/` = `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/`, `Host/` = `src/Server/ZB.MOM.WW.OtOpcUa.Host/`, `AdminUI/` = `src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/`, `Abstractions/` = `src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/`, `Commons/` = `src/Core/ZB.MOM.WW.OtOpcUa.Commons/`, `Configuration/` = `src/Core/ZB.MOM.WW.OtOpcUa.Configuration/`, `Core/` = @@ -29,7 +30,7 @@ found while verifying M1 (row M1). | B2 tap point misses SDK-applied method transitions; snapshot lacks Retain/comment/EventId | Accepted (verified `NM:3198-3202`, `DriverHostActor.cs:2612-2637`, `NM:3003-3037`); second pass: partially closed ⇒ closed by N1 | §5.1: snapshot from live nodes, callback for deltas only | | B3 remote native ack via preflight+route acknowledges nothing at the origin | Accepted (verified `NM:3197-3202`, `DriverHostActor.cs:2612`, `NM:2577`) | §5.6 session-less `TryExecuteConditionMethod` entry point, A2 | | B4 `AlarmRead` unenforced; Server-object delivery unfiltered with ACLs off | Accepted (verified `NodePermissions.cs:24`, no `OpcUaOperation.AlarmRead`; `NM:7155-7171`) | §5.4 visibility gate independent of `AclEnforced`; permission = `CreateMonitoredItems`/Subscribe on mapping scope | -| B5 Part 9 handlers run under `Lock` | Accepted (verified `NM:3001-3009`); second pass: closed conditional on X0 | §5.6 step 1: `ICallAsyncNodeManager` path preferred (symbols verified in SDK 2.0.1), sync partition fallback; if X0 finds neither lock-free, A3 is blocked — no local-apply fallback; lock-freedom is a hard A3 gate | +| B5 Part 9 handlers run under `Lock` | Accepted (verified `NM:3001-3009`); closed in revision 4 (SDK dispatch traced) | §5.6 step 1: `ICallAsyncNodeManager.CallAsync` claims imported-condition calls, delegates the rest to `base.Call`, awaits with no `Lock`; lock-freedom stays a hard A3 gate (L3) | | B6 relay vs origin==expected-cluster binding | Accepted | Relay removed from this plan; constraints recorded in §8 | | M1 hard-coded operation masks abort the snapshot on old nodes | Accepted (verified `DataConnectionValidator.cs:12`, `DataConnectionDeploymentRuntime.cs:151-152`, `DataContracts.cs:271-276`, `DataProtoMapper.cs:1054-1062`, `:284`); **plus** `ProjectedDataAccess.cs:157` (acquisition allowlist); second pass adds the sixth, `LocalDataServices.cs:47` `Implemented(target)` (verified; used at `:81,204,216`) | §4.3: four tolerance sites in X0; three grow sites (`DataConnectionValidator`, `Implemented(target)`, `ProjectedDataAccess`) in H2/H3/A2/A3 | | M2 no per-call negotiation on unary RPCs; v1 client faults on unknown frame arm | Accepted (verified `DataConnectionGrpcService.cs:26`, `LocalDataServices.cs:222`, `GrpcDataConnection.cs:548,762-767`, `DataProtoMapper.cs:1207`) | §4.1 feature header on every RPC; X0's open question is closed | @@ -45,7 +46,7 @@ found while verifying M1 (row M1). | m3 `HistoryEventRow` fields | Accepted (verified `HistoryReadContracts.cs:194-204`) | §7 deferred event history defines the row from `HistoricalEvent` | | m4 `SubscriptionFrame` field 8 taken | Accepted | §4.2: new arm = 9 | | m5 origin EventId round-trip unnecessary | Accepted | §5.6: consumer validates its own EventIds; origin precondition = `expected_activation_time` | -| m6 Galaxy ack-identity lookup unverified | Accepted | X0 task; §5.6 marked (inferred) | +| m6 Galaxy ack-identity lookup unverified | Accepted; settled in revision 4 | §6 Galaxy: keyed on the service key's `ApiKeyId`; provisioning step named | | m7 assembly budget per node | Accepted | §3.2: per-request budget | | m8 aggregate configuration judged by consumer | Accepted | §4.2: configuration fields sent; origin `IsServable` decides | | m9 consumer redundancy not gated | Accepted | A4 scenarios A06/A07 | @@ -58,10 +59,16 @@ found while verifying M1 (row M1). | N2 no condition-subscription contract | Accepted (verified `SubscriptionItem` names a single `View`) | §4.2 `SubscriptionItem.condition_scope`; §5.5 root-scoped item, `total`, `removed`, `snapshot_complete` | | N3 cross-realm home leaks RawPath | Accepted (verified `LocalExportCatalog.cs:42-48`, `NM:4885`, `DataPlaneAuthorizer.cs:182`); **refinement:** `stable_source_id` cannot be the dedupe key — it embeds driver id + RawPath (`SourceSamplePublisher.cs:32-33`, `LocalExportCatalog.Compilation.cs:92,123`) | §5.2 realm-local placement addresses + keyed `condition_key`; pre-existing v1 disclosure filed as #916 | | N4 ConditionId depends on stream order / home | Accepted | §5.2: NodeId = (connection, `condition_key`) in a new `mapped/conditions` namespace; mapping changes never change it; primary placement (SourceName only) from deployed config | -| N5 default budgets | Accepted (verified `RemoteNamespaceMapping.cs:29` = 10,000) | §5.5 arithmetic: 10,000 / 21 ≈ 476; own budget, `MaxConditions` 2,000 per mapping, node cap 210,000 nodes, admission at snapshot begin, 80% warning, validator warning | +| N5 default budgets | Accepted (verified `RemoteNamespaceMapping.cs:29` = 10,000); recomputed in revision 4 | §5.5: counted 49 nodes ⇒ 10,000 / 49 ≈ 204; own budget, `MaxConditions` 1,000, host caps 122,500 nodes / 400 MiB, admission at snapshot begin, 80% warning | | N6 `occurrence` across failover | Accepted | §5.6 step 3: `expected_activation_time` + EventId re-binding on unchanged resync; gated in A03 | | N7 notifier wiring vs lazy folders | Accepted (verified projected folders created `EventNotifier = None`, `NM:4919`) | §5.3 lazy, symmetric wiring; folders with event items pinned | | N8 G0 deferral consequences | Accepted | Recorded-v1-client gate repeated at H2, A2 and A3 exits; §1.1: #915's soak should run on an X0-or-later build | +| **Revision 4 (settled offline)** | | | +| B5 interception point | Settled: works | §5.6 step 1 — NM implements `ICallAsyncNodeManager`; SDK 2.0.1 dispatch traced (validation's `FindMethodState` holds `Lock` only for the lookup; per-manager `CallAsync` awaited with `ConfigureAwait(false)`); A3 not blocked | +| N5 node count | Settled: 48–49 nodes, ≈ 157 KiB each (was "~21") | §5.5 recomputed: 10,000 / 49 ≈ 204; `MaxConditions` 1,000; host caps 122,500 nodes / 400 MiB | +| `state_known` field | Settled: does not exist; named additions | §5.1: `_conditionStateKnown`, quality-settle timestamp, `MarkScriptedConditionsKnown` | +| Event re-gating, Galaxy keying, build reporting, opc-plc alarms, alarm-tag export | Settled from code/SDK | §5.4, §6, §4.3, A02, §5.2 (+ second pre-existing v1 defect) | +| Remaining live items | Listed | §9.3 L1–L5 with pass criteria | | Owner decisions 2026-11-23 | Applied | Q1 → §5.5 (service principal upstream, per-caller re-gating); Q2 → §5.2 (NodeIds stable across mapping disable; residual change accepted) | --- @@ -159,7 +166,13 @@ has accepted the call. | Condition state (B2, N1) | `NM:1540` `ReportConditionEvent` (callers `NM:1418,1505,3034,5650`), Warm-Standby early return `NM:1561-1565`; delta gate `NM:1363-1418`, ConditionClass silent `NM:1386-1388`; rebuild re-report `NM:5639-5651`; method wrapper `NM:2998-3037` under `lock (Lock)`; native SDK-applied ack `NM:3197-3202`; `DriverHostActor.cs:2612-2637` | Snapshot from live nodes (`_alarmConditions`) under `Lock`; callback for deltas only, raised before the standby return and on silent applies | | Namespaces (N4) | `NM:117-118` `RegisteredNamespaceUris` (Raw, UNS, mapped/raw, mapped/uns); `NM:283-284` `RealmOf` folds every index but 0/2 into Uns | A fifth URI `mapped/conditions` is a registration change; it must be classified before `RealmOf` | | Stable source id (N3) | `SourceSamplePublisher.cs:32-33` (`":"`), emitted in `Metadata.stable_source_id` at `LocalExportCatalog.Compilation.cs:92,123` | Not usable as a condition dedupe key (discloses RawPath); pre-existing disclosure on UNS reference variables (#916) | -| SDK async call (B5) | `Opc.Ua.Server.dll` 2.0.1 contains `ICallAsyncNodeManager`, `AsyncCustomNodeManager`, `OnCallMethod2Async` (symbols checked in the restored package); NM has no `Call` override | Async interception of imported-condition methods is likely available; X0 confirms dispatch and lock behaviour | +| SDK Call dispatch (B5) | Decompiled SDK 2.0.1: `StandardServer.CallAsync` → `MasterNodeManager.CallAsync` → `NodeManagerServiceDispatcher.CallAsync` (validation via `FindMethodState`, short `lock (Lock)`, then per-manager `IAsyncNodeManager.CallAsync`); `AsyncNodeManagerAdapter.CallAsync` forwards to `ICallAsyncNodeManager` when the wrapped manager implements it; `CustomNodeManager2` (NM's base) implements `INodeManager3` only and its sync `Call`/`GetMethodCalls` skip `Processed` items | NM implements `ICallAsyncNodeManager`; imported-condition calls are claimed and awaited with no `Lock` held (§5.6) | +| Condition subtree (N5) | `NM:2461-2475` (optional `ConfirmedState`/`Confirm`/`ShelvingState`/`MaxTimeShelved` before `Create`), `ApplicationAlarmConditions.cs:7-11` (Alarm / OffNormal / Discrete) | Counted with SDK 2.0.1: 48 / 49 / 48 nodes, ≈ 157 KiB retained each (§5.5) | +| Event delivery path (§5.4) | Decompiled SDK 2.0.1 `MonitoredItem.QueueEvent(EventFieldList)` enqueues by reference; `Subscription.ConstructMessage` moves queued lists into `EventNotificationList` by reference; a select-clause modify rebuilds queued lists via `GetEventFields` with `Handle` = the original event; `OtOpcUaSdkServer.cs:746,768` already rewrites every Publish/Republish via `ProjectedNotificationRewriter` (`WarmStandby.cs:917`), which today passes event payloads through untouched | A marked `EventFieldList` subclass survives to Publish/Republish; the rewriter is extended to events | +| Native/scripted state signals (N1) | Native `Quality = BadWaitingForInitialData` at materialise (`NM:2527`), driven Good via `WriteAlarmQuality` (`NM:1480`); `RestoreCarryOver` (`NM:2727`); scripted re-assert only for non-normal conditions (`ScriptedAlarmHostActor.cs:491`) | `_conditionStateKnown` + settle timestamp + `MarkScriptedConditionsKnown` (§5.1) | +| Alarm-bearing tags (N3, §5.2) | `AddressSpaceComposer.cs:978-985` (#896: no UNS value Variable for an alarm-bearing backing tag); `AddressSpaceComposer.cs:835-850` (alarm tags are in `RawTags`); `LocalExportCatalog.Compilation.cs:120-130` (no Alarm filter) | UNS placement address is a reserved reference id with no node; v1 exports alarm-bearing raw tags as dead Variables (pre-existing defect) | +| Galaxy ack identity (m6) | `DataConnectionAuthInterceptor.cs:19,24` (data-connection bearer = data-plane API key, `FindUsableKey` → `ApiKeyId`); `GalaxyAckIdentitySecrets.cs:30,35` (`otopcua/apikeys//galaxy-ack-user|password`); `GalaxyAckCredentialResolver.cs:75` | Remote Galaxy acks work iff those secrets exist for the service key on the origin (§6) | +| Node build reporting (M1) | `ClusterNode.cs` has no version/build column (only `LastSeenAt`); the model snapshot has none | The M1 "all nodes upgraded" check is procedural (§4.3) | | Native ack (B3) | `NM:3197` router "non-blocking … safe under Lock"; `NM:2576-2577` native AddComment has only the SDK path; `DriverHostActor` reverts on failure | The origin needs a session-less execution entry that applies and reports like the SDK path | | Server-object filtering (B4) | `NM:7155-7171` `OnConditionReportEvent`: `scopes = AclEnforced ? ConditionVisibilityScopes(node) : null` (inert with ACLs off) | Imported conditions need their own gate that does not depend on `AclEnforced` | | Method lock (B5) | `NM:3001-3009` `ReportAfterMethod` = `lock (Lock) { sdkHandler(); … }` | No remote wait may run there | @@ -324,10 +337,15 @@ X0 changes: behaviour, no new shapes without the header) is an exit gate of X0, **H2, A2 and A3** — the phases that touch v1 hot paths — so a v1 regression is attributable without a soak baseline. -AdminUI shows a deploy-time warning, and the validator a blocking error, when a connection/export/mapping carries a feature -bit while any node in `ConsumerNodeIds` (or the exporting cluster) reports a build without the feature. **(inferred: nodes -report build/feature info usable by the validator; verify in X0. If not available, the gate is procedural: "upgrade all nodes -first", in the rollout docs and the deploy checklist.)** +**The "every node is on X0" check is procedural (settled).** ConfigDb records no node build or feature level: `ClusterNode` +has only identity, ports, flags and `LastSeenAt`. The validator therefore cannot enforce it. + +- The rule lives in the rollout docs and the deploy checklist. +- AdminUI shows an informational banner on the data-connection editor whenever a feature bit is ticked. +- The consequence of breaking the rule is bounded: a pre-X0 node rejects the whole data-connection snapshot (today's + behaviour). After X0, an unknown bit is dropped fail-closed. + +Adding build reporting to `ClusterNode` is out of scope. | Consumer | Origin | Behaviour | |---|---|---| @@ -353,8 +371,14 @@ conditions re-report (`NM:5639-5651`). Some state changes never produce an event delta is either in the snapshot or after the watermark. - The snapshot includes **every** live condition in scope — inactive, acknowledged and normal-state ones too — so a complete snapshot defines the *set*, not just the retained subset. - - Cost target: ≤ 20 ms `Lock` hold at 10,000 conditions, measured in A1. If it is exceeded, slice by hub partition, each - slice with its own watermark. + - Cost (settled by measurement, revision 4): copying the snapshot fields of one SDK `OffNormalAlarmState` took + **≈ 1.7–2.9 µs**. That was 3.3–5.8 ms per 2,000 conditions over three warm runs, in a scratch harness against SDK 2.0.1 + (§9.3), outside the server. + - A snapshot is scoped to one mapping's root, and `MaxConditions` defaults to 1,000 (§5.5), so one `Lock` hold is + ≈ **2–3 ms**; at 10,000 conditions it would be ≈ 17–29 ms. + - The plan therefore never snapshots more than `MaxConditions` under one hold. Larger scopes are sliced by hub partition, + each slice with its own watermark. + - Contention inside a running server is the A1 live measurement L1 (§9.3). - **Deltas:** the SDK-free callback is raised for every condition state change, at two points: - in `ReportConditionEvent` **before** the Warm-Standby early return, so a standby's hub stays current and a promoted Primary starts correct; @@ -364,14 +388,25 @@ conditions re-report (`NM:5639-5651`). Some state changes never produce an event The callback only enqueues into a bounded `ConditionStateHub` partition: no I/O, never blocks. Overflow ⇒ that partition's epoch is invalidated ⇒ affected subscribers reset to a fresh snapshot. Teardown (`ForgetPredefinedSubtree`) raises a removal record. -- **Never a falsely empty or falsely normal snapshot.** Each record carries `state_known`. It is false for a condition that - has been materialised since the last process start or rebuild but has not yet been projected by its source: - - native: no `WriteAlarmCondition` for it since materialise, and its driver host not yet Steady (the same Stale/Steady signal - that gates `NativeAlarmAckPreflightView`, #765); - - scripted: the engine's initial evaluation not yet applied; - - a #641 carried-over condition counts as known. - - **(inferred: the per-condition "projected since materialise" flag can be kept in NM beside `_alarmConditions`; A1 task 1.)** +- **Never a falsely empty or falsely normal snapshot.** Each record carries `state_known`. **No such field exists today**: + `_alarmConditions` maps keys to `AlarmConditionState` only. A1 adds `HashSet _conditionStateKnown` in NM, + maintained under `Lock`: + - **cleared** when a condition is (re)materialised (`MaterialiseAlarmCondition`, registration at `NM:2636`) and on removal; + - **set** when `WriteAlarmCondition` applies a snapshot (`NM:1323`), whether or not the delta gate fires an event — every + native driver transition and every scripted engine projection arrives here; + - **set** by `RestoreCarryOver` (`NM:2727`): #641 carried-over state is known; + - **native, normal-state conditions:** a transition-only source (MTConnect, FOCAS) never projects a condition that stays + normal. Such a condition becomes known once its native `Quality` has been Good for `ConditionKnownSettleMilliseconds` + (default 10 s). Quality starts `BadWaitingForInitialData` at materialise (`NM:2527`) and is driven Good by the driver + connectivity path through `WriteAlarmQuality` (`NM:1480`). This only needs a timestamp beside the set, recorded when + `WriteAlarmQuality` first observes Good. The settle default is calibrated by live measurement L4 (§9.3). + - **scripted, normal-state conditions:** `ScriptedAlarmHostActor` re-asserts only **non-normal** conditions after (re)load + (`ScriptedAlarmHostActor.cs:491`), so a normal scripted condition never reaches `WriteAlarmCondition`. A1 adds a sink call, + `IOpcUaAddressSpaceSink.MarkScriptedConditionsKnown(generation)` (`Commons/OpcUa/IOpcUaAddressSpaceSink.cs`). The host + sends it, through the existing `OpcUaPublishActor` path, right after the re-assert pass completes, and it marks every + scripted condition of that generation known. + - On a Warm standby native drivers do not run, so native conditions stay unknown until promotion. That is correct, and the + stream is Primary-only by default. `snapshot_complete` is withheld until the origin's current address-space apply has completed (`CompleteAddressSpaceApply` ran for the active generation) and the serving node holds its Primary verdict. Until then the stream sends a Control `NotReady`. - **Consumer rule:** a condition is retired only when it is absent from a complete snapshot, or a removal record arrives. A @@ -397,7 +432,7 @@ addressed in that realm: | Listing export | Native condition placement address | Scripted condition placement address | |---|---|---| | Raw | `raw` namespace, identifier = RawPath (the raw tag), parent = its device/group folder | not listed (scripted conditions have no raw placement) | -| UNS | `uns` namespace, identifier = the **UNS reference variable id** of each referencing equipment (`Area/Line/Equipment/EffectiveName`, unique by the effective-name guard), parent = that equipment | `uns` namespace, its ScriptedAlarmId address under its equipment | +| UNS | `uns` namespace, identifier = the **reserved reference id** `Area/Line/Equipment/EffectiveName` of each `UnsTagReference` to the alarm-bearing tag. Per #896 no UNS node exists at that id (`AddressSpaceComposer.cs:978-985`), but the effective-name guard reserves it, so it is unique and cannot collide. The origin resolves it by reference → backing raw tag → condition. Parent = that equipment | `uns` namespace, its ScriptedAlarmId address under its equipment | - No RawPath ever reaches a UNS-only principal. - Every placement view passes the existing export realm checks: `LocalExportCatalog.cs:42-48`; and on the consumer @@ -420,8 +455,12 @@ K_p = HKDF(`DataConnections:ConditionKeySecret`, info = authenticated principal - It cannot be dictionary-reversed from guessable paths. An unkeyed hash was rejected for that reason. - If the secret is absent, the origin advertises no `conditions` capability (fail closed, with a diagnostic). -> **Pre-existing v1 finding (not fixed here; to be filed as `type:review-finding`, security):** v1 already sends -> `stable_source_id` = driver id + RawPath on **UNS reference variables** to UNS-only principals (same code path). +> **Pre-existing v1 findings (not fixed here; filed as #916 and #917):** +> 1. #916 — `type:review-finding`, security: v1 already sends `stable_source_id` = driver id + RawPath on **UNS reference variables** +> to UNS-only principals (same code path). +> 2. #917 — `type:bug`: v1 exports alarm-bearing raw tags as `Variable` (`LocalExportCatalog.Compilation.cs:120-130` has no Alarm +> filter), but `DriverHostActor` keeps them out of the value fan-out and #896 gives them no UNS variable. An imported one +> therefore reads `BadWaitingForInitialData` forever. Header-less callers keep this v1 shape (§4.1); the fix belongs in v1. **Imported condition NodeId (N4).** Keyed on **(connection, condition_key)** only — never the mapping, the home placement or stream order: @@ -488,8 +527,21 @@ Imported conditions do **not** use `MaterialiseAlarmCondition` or the `RealmKey` generation). - Event items on projected notifiers, on the Server object and on imported conditions are admitted through a verified path. This replaces the blanket deny at `DataPlaneAuthorizer.cs:184-187` for event items only; data items keep v1's path. -- Publish-time re-gating uses the v1 authority marker. **(inferred: SDK cloning of `EventFieldList` matches the data-notification - behaviour the marker relies on; X0 verifies, otherwise A3 adds a final-send filter.)** +- **Publish-time re-gating (settled from SDK 2.0.1).** Event field lists are never cloned on the way to the wire: + - `MonitoredItem.QueueEvent(EventFieldList)` enqueues the instance; + - `MonitoredItem.Publish` dequeues it; + - `Subscription.ConstructMessage` places the same instances in an `EventNotificationList`; + - Republish returns the stored message. + + So A3 uses a `ProjectedEventFieldList : EventFieldList` subclass carrying a marker: the caller, the condition id, the + authority generation and a `Func` re-check, like `ProjectedNotificationMarker` (`WarmStandby.cs:862`). + `ProjectedNotificationRewriter.Project` (`WarmStandby.cs:917`), already invoked for every Publish and Republish + (`OtOpcUaSdkServer.cs:746,768`), is extended from `DataChangeNotification` to `EventNotificationList`: + - a marked list whose check fails is **dropped**. Events have no Bad-value form, and the drop is counted. + - The one path that rebuilds queued lists is a `ModifyMonitoredItems` that changes select clauses: `GetEventFields` + creates a plain `EventFieldList` but keeps `Handle` = the original event instance. The rewriter therefore treats an + **unmarked** list whose `Handle` is an imported-condition snapshot (its `ConditionId` is in the `mapped/conditions` + namespace) as unauthorised and drops it — fail closed, counted. - **Gate A3-SEC:** with `Security:Acl:Enabled=false`, a session without the mapping grant at `i=2253` and on a projected folder receives zero imported events and zero on refresh. A positive-control session with the grant receives them, and the absence assertion follows a must-arrive sentinel. @@ -520,24 +572,47 @@ discovery and no recursive Browse: - A ConditionRefresh before the barrier answers with what exists, then emits `RefreshRequiredEventType` to authorized items when the barrier completes. -**Budget (N5).** The arithmetic that broke revision 2: `MaxProjectionNodes` defaults to 10,000 -(`RemoteNamespaceMapping.cs:29`). A condition subtree is ≈ 21 nodes (the condition plus its state-machine, property and -method children; exact count measured in X0). So 10,000 / 21 ≈ **476** conditions would exhaust the whole projection budget. +**Budget (N5) — counted, not estimated (revision 4).** Building one condition with exactly the optional children NM adds +before `Create()` — `ConfirmedState`, `Confirm`, `ShelvingState`, `MaxTimeShelved` (`NM:2461-2475`), on the three concrete +types `ApplicationAlarmConditions.Create` selects (`ApplicationAlarmConditions.cs:7-11`) — and counting the resulting tree with +SDK 2.0.1 (scratch harness, §9.3) gives: -Revision 3 gives conditions their **own** budget: +| Type | Nodes per condition | Breakdown | +|---|---|---| +| `AlarmConditionType` (default) | **48** | 2 objects, 38 variables, 8 methods | +| `OffNormalAlarmType` | **49** | 2 objects, 39 variables, 8 methods | +| `DiscreteAlarmType` | **48** | 2 objects, 38 variables, 8 methods | -- `RemoteNamespaceMapping.MaxConditions`, default **2,000** per mapping = 42,000 condition nodes at 21 each; -- host option `DataConnections:MaxImportedConditionNodes`, default **210,000** per consumer node (= 10,000 conditions × 21); -- host option `DataConnections:MaxImportedConditionBytes`, default from the X0 per-condition byte measurement × 10,000. -- Conditions are charged **once per condition_key**, not per placement, and do **not** consume `MaxProjectionNodes`. That stays - for folders and variables. Placement folders charge it as ordinary projected folders (bounded by the placement count). -- **Admission before materialising:** `total > MaxConditions`, or the connection's sum exceeding the node cap, ⇒ that mapping - is `Unavailable(ConditionCapacity)` with the observed count in diagnostics. It stays all-or-nothing per mapping, because a - partial set makes ConditionRefresh lie, but it happens at snapshot begin with an explanation rather than mid-materialisation. -- An 80% high-water diagnostic warning is raised. -- The validator warns when Σ `MaxConditions` of a node's mappings × 21 exceeds `MaxImportedConditionNodes`. -- **(inferred: realistic counts are tens to hundreds of conditions per line and low thousands per area, so 2,000 per mapping - leaves headroom; confirm against the docker-dev and one production export count in A4.)** +`Quality`, `BranchId` and `Comment` are present. The retained managed size measured **≈ 157 KiB per condition** (160,997 B +for `OffNormal`, 2,000 instances, `GC.GetTotalMemory(true)` delta, excluding NM's own indexes). **Memory, not node count, is +the binding limit.** The origin already pays the same per condition for its own local copy. + +Arithmetic: + +- with v1's `MaxProjectionNodes` default of 10,000 (`RemoteNamespaceMapping.cs:29`), 10,000 / 49 ≈ **204** conditions would + exhaust a mapping (revision 3's "≈ 476 at 21 nodes" was wrong); +- 10,000 imported conditions would retain ≈ 1.5 GiB. + +Defaults (conditions get their **own** budget; worst case is 49 nodes): + +| Setting | Default | Nodes | Memory (≈ 157 KiB each) | +|---|---|---|---| +| `RemoteNamespaceMapping.MaxConditions` | **1,000** per mapping | 49,000 | ≈ 153 MiB | +| `DataConnections:MaxImportedConditionNodes` (host) | **122,500** per consumer node (= 2,500 × 49) | 122,500 | — | +| `DataConnections:MaxImportedConditionBytes` (host) | **400 MiB** per consumer node (≈ 2,500 × 157 KiB = 384 MiB, rounded) | — | 400 MiB | + +- Conditions are charged **once per `condition_key`**, not per placement. They do **not** consume `MaxProjectionNodes`, which + stays for folders and variables; placement folders charge it as ordinary projected folders. +- **Admission before materialising:** + - `total > MaxConditions` ⇒ that mapping is `Unavailable(ConditionCapacity)` at snapshot begin, with the observed count in + diagnostics; + - when the connection's new conditions would exceed either host cap, the mappings that would cross it are rejected the same + way, in deployed order. +- It stays all-or-nothing per mapping, because a partial set makes ConditionRefresh lie. The cliff is moved to an explained, + pre-materialisation decision, with an 80% high-water warning and a validator warning when Σ `MaxConditions` × 49 of a + node's mappings exceeds `MaxImportedConditionNodes`. +- Whether 1,000 per mapping / 2,500 per node covers real exports is live measurement L5 (§9.3). The defaults are tunable and + sized from the measured memory cost, not from a guessed plant size. **Stream mechanics.** @@ -553,17 +628,47 @@ Revision 3 gives conditions their **own** budget: **Consumer:** -1. **Interception point (B5, conditional on X0).** SDK 2.0.1 ships `ICallAsyncNodeManager`, `AsyncCustomNodeManager` and - `OnCallMethod2Async` (symbols verified in `Opc.Ua.Server.dll` 2.0.1). NM has no `Call` override today. - - Preferred: NM implements `ICallAsyncNodeManager` and handles method calls whose object is an imported condition, or a - child of one, **asynchronously**, without holding `Lock` or a request thread while the remote call is in flight. Every - other call is delegated to the existing synchronous path unchanged. - - X0 must establish that `MasterNodeManager` dispatches to that interface per node manager, and that nothing in the - dispatch takes NM's `Lock` first. - - Fallback: a synchronous `Call` partition before base dispatch, plus a per-node semaphore (default 8) so request threads - cannot be exhausted. - - **If X0 finds neither path free of `Lock`, A3 is blocked and §5.6 is redesigned.** There is no fallback that applies - state locally. +1. **Interception point (B5) — settled from the SDK 2.0.1 binaries; A3 is not blocked.** The repo pins + `OPCFoundation.NetStandard.Opc.Ua.Server` 2.0.1 (`Directory.Packages.props:137`). Decompiled from + `~/.nuget/packages/opcfoundation.netstandard.opc.ua.server/2.0.1/lib/net10.0/Opc.Ua.Server.dll`: + - **The Call service is async end to end.** `StandardServer.CallAsync` awaits `ServerInternal.NodeManager.CallAsync` + (`MasterNodeManager.CallAsync` → `NodeManagerServiceDispatcher.CallAsync`). + - **Pre-dispatch validation.** The dispatcher first runs `ValidateCallRequestItemAsync` per request: `GetManagerHandleAsync`, + `FindMethodStateAsync` and `ValidatePermissionsAsync` (PermissionType.Call, 4096) on the object and the method. + - These reach NM through `CustomNodeManager2.FindMethodState`, which takes `lock (Lock)` **only for the lookup** and + returns. No NM `Lock` is held when validation ends. + - Bad items are marked `Processed`; valid ones are set `Processed = false`. + - **Node manager dispatch.** It then awaits, **sequentially, for every registered node manager**, + `IAsyncNodeManager.CallAsync(context, methodsToCall, results, errors, ct)` with `ConfigureAwait(false)`, passing the + whole batch. + - Registered managers are wrapped by `ToAsyncNodeManager()` (`MasterNodeManager`, line ≈8825 of the decompile). + - NM derives from `CustomNodeManager2`, which implements `INodeManager3` but **not** `ICallAsyncNodeManager` and not + `IAsyncNodeManager`, so NM is wrapped in `AsyncNodeManagerAdapter`. + - `AsyncNodeManagerAdapter.CallAsync` forwards to `SyncNodeManager.CallAsync` **iff the wrapped manager implements + `ICallAsyncNodeManager`**; otherwise it calls the synchronous `Call`. + - **Where the current lock comes from.** The synchronous `CustomNodeManager2.Call` → `CallSynchronousBatch` → + `GetMethodCalls` skips `Processed` requests and takes `lock (Lock)` per request it owns. NM then wraps the handler in its + own `lock (Lock)` (`ReportAfterMethod`, `NM:3001-3009`). That is the lock revision 2 had to avoid. + + **Design:** `OtOpcUaNodeManager` additionally implements + `Opc.Ua.Server.ICallAsyncNodeManager.CallAsync(OperationContext context, ArrayOf methodsToCall, + IList results, IList errors, CancellationToken cancellationToken)` (returns `ValueTask`). + Its body: + - (a) For each request with `!Processed` whose `ObjectId` is in the `mapped/conditions` namespace (a condition or a `c1.` + child id), **claim it**: set `Processed = true` and record its index. This is a pure dictionary lookup in + `ProjectedConditionRegistry` under the registry's own short lock, **never NM's `Lock`**. + - (b) Call the existing synchronous `base.Call(context, methodsToCall, results, errors)` for everything else. It skips the + claimed (`Processed`) items, so local behaviour, including `ReportAfterMethod` under `Lock`, is unchanged. + - (c) Run the local checks (step 2), then `await` the claimed remote calls concurrently, bounded by the per-node semaphore + (default 8), writing `results[i]`/`errors[i]`. + + No `Lock` is held across any `await`. The continuation runs on a pool thread (`ConfigureAwait(false)` at the dispatcher), so + no request thread is held while the remote call is in flight. The semaphore bounds upstream load, not threads. Validation's + `FindMethodState` requires the imported condition to expose instance-scoped `Acknowledge`/`AddComment`/`Confirm` method + nodes, which the shared factory creates (§5.3). + + Residual: master-level `ValidatePermissionsAsync` still checks `RolePermissions` on the object and method nodes. Imported + nodes set none, so they pass; the mapped gate in step 2 is the authority. Imported conditions get no state-applying SDK handlers and are never wrapped by `ReportAfterMethod`. 2. **Local checks** (no I/O, no `Lock`): @@ -632,9 +737,16 @@ sides; a remote native AddComment is stored. are required even with `Security:Acl:Enabled=false`, because mapped nodes always enforce the mapping gate. - **Galaxy (Q2, settled):** a separate per-export opt-in, `DataExport.AllowGalaxyServiceAck` (default false). Without it, the origin refuses remote Acknowledge/AddComment on Galaxy-sourced native conditions with `BadUserAccessDenied` before any state - change. With it, the ack runs under the service principal's Galaxy ack identity. **(inferred: a data-connection API key is - resolvable by `GalaxyAckIdentityDirectory` (`src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GalaxyAckIdentityDirectory.cs`); - X0 verifies, otherwise every such ack is refused.)** + change. With it, the ack runs under the service principal's Galaxy ack identity. This is **settled**: + - the data-connection bearer is an ordinary data-plane API key (`DataConnectionAuthInterceptor.cs:19,24`, `FindUsableKey` → + `ApiKeyId`); + - the directory and the resolver key on exactly that id (`GalaxyAckIdentitySecrets.cs:30,35`, + `GalaxyAckCredentialResolver.cs:75`); + - `TryExecuteConditionMethod` passes the service key's `ApiKeyId` into `RouteAlarmAck` (which already carries `ApiKeyId`, + `DriverHostActor.cs:2635`). + + Provisioning step: put `otopcua/apikeys//galaxy-ack-user` and `…/galaxy-ack-password` in the **origin's** + Secrets store. Without them the existing #765 preflight refuses `BadUserAccessDenied`. **Audit (M8, second pass):** @@ -654,13 +766,13 @@ NodeId: accepted under owner decision Q2, as removal + addition + RefreshRequire | Phase | Migration | Changes | |---|---|---| | H2 | `AddDataConnectionHistory` | `DataConnection.HistoryTimeoutMilliseconds` (30000); `DataExport.MaxConcurrentHistoryReads` (4), `MaxHistoryValuesPerPage` (10000), `MaxHistoryResponseBytes` (4 MiB); `RemoteNamespaceMapping.MaxHistoryAssemblyBytesPerRequest` (16 MiB) | -| A2 | `AddDataConnectionConditions` | `DataExport.MaxConditions` (2000), `AllowGalaxyServiceAck` (false); `RemoteNamespaceMapping.MaxConditions` (2000), `ConditionStaleTimeoutMilliseconds` (30000), `ConditionMethodTimeoutMilliseconds` (5000), `ConditionSnapshotTimeoutMilliseconds` (30000) | -| A2 (host options, not ConfigDb) | — | `DataConnections:MaxImportedConditionNodes` (210000), `DataConnections:MaxImportedConditionBytes` (from the X0 measurement × 10,000), `DataConnections:ConditionKeySecret` (secret) | +| A2 | `AddDataConnectionConditions` | `DataExport.MaxConditions` (1000), `AllowGalaxyServiceAck` (false); `RemoteNamespaceMapping.MaxConditions` (1000), `ConditionStaleTimeoutMilliseconds` (30000), `ConditionMethodTimeoutMilliseconds` (5000), `ConditionSnapshotTimeoutMilliseconds` (30000) | +| A2 (host options, not ConfigDb) | — | `DataConnections:MaxImportedConditionNodes` (122500), `DataConnections:MaxImportedConditionBytes` (400 MiB), `DataConnections:ConditionKnownSettleMilliseconds` (10000, origin), `DataConnections:ConditionKeySecret` (secret) | Each migration phase also adds the bits to `KnownOperations`, extends `DeploymentArtifact.DataConnections.cs`, and includes the new fields in `DataConnectionScopeRevision` (so DB-less nodes and the LocalDb artifact cache receive them). It also adds validator rules: mapping bits ⊆ connection bits, limits positive, `AllowGalaxyServiceAck` only with `AlarmAcknowledge`, and -(A2) a warning when Σ `MaxConditions` of a consumer node's mappings × the measured subtree size exceeds +(A2) a warning when Σ `MaxConditions` of a consumer node's mappings × 49 (the counted worst-case subtree) exceeds `MaxImportedConditionNodes`. Each also grows `LocalDataServices.cs:47` `Implemented(target)`. **AdminUI** (`ClusterDataConnections.razor`, editor models, `DataConnectionDiagnostics`): @@ -733,25 +845,16 @@ Deployability: X0 is a release of its own. H2, H3 and H4 each deploy and are usa history, H3 OPC UA clients, H4 the Gateway sign-off. A1 is invisible until A2/A3 negotiate it. A2 alone gives runtime consumers condition state and methods; A3 OPC UA clients. -### X0 — Tolerant readers, contract reservation, investigations (release before any new bit) +### X0 — Tolerant readers and contract reservation (release before any new bit) - **Tasks:** 1. Mask-tolerant readers at the four M1 tolerance sites (§4.3); the three grow sites stay unchanged until their phase. 2. Feature-header plumbing on every RPC: server records the per-call feature set (empty today). 3. Reserve proto fields (capabilities 16–17, metadata 14, `SubscriptionItem.condition_scope`), frame arm 9 and bits 32–512, with golden tests. The server still advertises nothing. - 4. Investigations, recorded in `docs/plans/evidence/grpc-data-ext/X0.md`: - - the method interception point (§5.6 step 1): does `MasterNodeManager` dispatch to `ICallAsyncNodeManager` per node - manager, and does any dispatch path take NM's `Lock` before an imported-condition partition? Outcome decides whether - A3 proceeds (async preferred, sync partition + semaphore fallback, otherwise A3 blocked); - - the materialised `AlarmConditionState` subtree size (nodes) and bytes per condition — sets the §5.5 defaults; - - whether NM can keep a per-condition "projected since materialise" flag for `state_known` (§5.1); - - registering a fifth namespace URI and classifying it before `RealmOf` (§5.2); - - `EventFieldList` clone and authority marker (§5.4); - - Galaxy ack-identity lookup for a data-connection key; - - node build/feature reporting for the M1 validator gate; - - native alarm source for docker-dev: the opc-plc fixture's alarm nodes via the OpcUaClient driver; - - how alarm-bearing raw tags export today (the shape §4.1 must preserve for header-less callers). + 4. Record revision 4's settled investigations in `docs/plans/evidence/grpc-data-ext/X0.md`, for review provenance: the + SDK Call dispatch trace, the condition node/byte count and the snapshot-copy timing, with the scratch harness source. + No open investigation remains in X0. 5. Manifest keys. - **Files:** `DataConnectionDeploymentRuntime.cs`, `DataContracts.cs`, `DataProtoMapper.cs`, `GrpcDataConnection.cs`, `Host/Grpc/DataConnectionGrpcService.cs`, `Commons/Protos/{data_connection.proto,DataConnectionProtoContract.cs}`, @@ -861,19 +964,25 @@ Expected: identical rows/status/timestamps to the origin; continuation followed - Tasks: - `SnapshotConditions(scope)` under a short `Lock` hold with watermark; - the delta callback in `ReportConditionEvent` (before the standby return) and in `WriteAlarmCondition` for silent applies; - - `state_known`; the `ConditionStateHub`; + - `state_known`: `_conditionStateKnown` + Good-quality settle timestamp in NM, and + `IOpcUaAddressSpaceSink.MarkScriptedConditionsKnown(generation)` sent by `ScriptedAlarmHostActor` after re-assert; + - the `ConditionStateHub`; - realm-local placement enumeration per export: Raw = RawPath; UNS = reference variable ids and ScriptedAlarmId; - the `condition_key` derivation and its secret; - `snapshot_complete` readiness (apply complete + Primary verdict); - `ProjectedDataIds`-style `c1.` identifier, child id helpers and the condition-namespace constant. -- Files: NM (snapshot + callback + `state_known` only), new `Runtime/DataConnections/ConditionStateHub.cs`, +- Files: NM (snapshot + callback + `state_known` only), `Commons/OpcUa/IOpcUaAddressSpaceSink.cs` (+ `DeferredAddressSpaceSink`, + `SdkAddressSpaceSink`, the no-op sink), `Runtime/OpcUa/OpcUaPublishActor.cs` (forwarding), + `Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs` (send after re-assert), new `Runtime/DataConnections/ConditionStateHub.cs`, `LocalExportCatalog*.cs` (placement enumeration; the catalog stays v1-shaped), `LocalCatalogCoordinator.cs`, `Abstractions/DataConnections/ProjectedDataIds.cs` (or a sibling `ImportedConditionIds.cs`). - Tests: - R/O parity cases (a)–(g) of §5.1, asserted on node state; - a **falsely-empty** negative test: an origin restart with standing alarms ⇒ `snapshot_complete` is not sent until apply completes, and no record claims "inactive" with `state_known = true` before its source projected; - - `Lock`-hold timing at 10,000 conditions ≤ 20 ms; + - a snapshot never covers more than `MaxConditions` under one `Lock` hold (structural test); the in-server hold time is L1 (§9.3); + - a normal-state scripted condition becomes known only after `MarkScriptedConditionsKnown`; a normal-state native + condition only after the quality settle window; a carried-over condition at once; - a UNS-only export lists no RawPath anywhere in the record (property test over generated topologies); - `condition_key` stable across restart and pair members, equal across a principal's Raw/UNS listings, different across principals; @@ -911,7 +1020,8 @@ Expected: identical rows/status/timestamps to the origin; continuation followed - Tasks: `ProjectedConditionRegistry` (§5.3) in the `mapped/conditions` namespace with the `MappedCondition` resolver kind classified before `RealmOf`; lazy symmetric notifier wiring (N7); primary placement from deployed config; event items on projected notifiers and the Server object (§5.4); per-connection demand, snapshot barrier and condition budget (§5.5); - method interception per the X0 outcome (§5.6); EventId re-binding (N6); RefreshRequired; `alerts` exclusion. + `ICallAsyncNodeManager` on NM with claim / `base.Call` / await (§5.6 step 1); `ProjectedEventFieldList` + rewriter + extension (§5.4); EventId re-binding (N6); RefreshRequired; `alerts` exclusion. - Files: NM, `OpcUaServer/ProjectedEventDelivery.cs`, new `OpcUaServer/ProjectedConditionRegistry.cs`, new `OpcUaServer/IProjectedConditionAccess.cs`, new `Runtime/DataConnections/ProjectedConditionAccess.cs`, `OpcUaServer/Security/DataPlaneAuthorizer.cs`, `Core/Authorization/DataOperationPolicy.cs`, `ProjectedDataAccess.cs:157`. @@ -940,7 +1050,7 @@ Expected: identical rows/status/timestamps to the origin; continuation followed | ID | Scenario | |---|---| | A01 | Scripted raise, ack, confirm via consumer; origin and consumer both show it | -| A02 | Native condition (OpcUaClient → opc-plc alarms, per X0) ack + AddComment; Confirm refused | +| A02 | Native condition: OpcUaClient driver → the opc-plc fixture, which already runs `mcr.microsoft.com/iotedge/opc-plc:2.14.10` with `--alm` (`tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.IntegrationTests/Docker/docker-compose.yml:9,29-35`). Ack + AddComment; Confirm refused | | A03 | Origin failover mid-stream with standing active alarms ⇒ resync retires nothing still active, no duplicate events, positive control; an ack with a **pre-failover** EventId succeeds after the unchanged resync (N6) | | A04 | One native alarm referenced by two equipment + a Raw mapping ⇒ one consumer condition (same `ConditionId` regardless of which mapping's subscriber came first), three notifiers, one `i=2253` event; a UNS-only principal's records carry no RawPath | | A05 | ACLs off, session without mapping grant at `i=2253` ⇒ zero imported events (with positive control) | @@ -987,9 +1097,36 @@ Use two-state id selection via `SimpleAttributeOperand(type, [X, Id])`, as the C | Partial condition sets make ConditionRefresh lie | A3 | Per-mapping all-or-nothing decided at snapshot begin from `total`; own budget sized ≈ 4× expected counts | | Failover/restart clears live alarms on the consumer | A1/A3 | Snapshot from node state, `state_known`, withheld `snapshot_complete`, retire-only-on-complete; A1 (a)–(c), A03 | | RawPath disclosure to UNS-only principals | A1 | Realm-local placements; keyed `condition_key`; property test; pre-existing `stable_source_id` disclosure is #916 | -| No lock-free interception point in the SDK | X0/A3 | X0 decides; A3 blocked rather than any local-apply fallback | +| Imported-condition method path regresses local methods | A3 | Claimed items only (`Processed`), `base.Call` unchanged for the rest; lock-freedom gate; existing `ConditionMethodEventTests` stay green | +| Imported-condition memory (≈ 157 KiB each) | A3 | Own budget sized from the counted cost; byte cap 400 MiB per consumer node; L2 confirms in-server | | v1 unsoaked in service (G0 deferred, #915) | all | Per-phase live gates; deploy notes record the risk until #915 passes | +### 9.3 Settled offline vs. needs a live run + +**Settled offline in revision 4** (no server needed): +- the SDK 2.0.1 Call dispatch trace (decompiled with `ilspycmd` from the pinned package); +- the event-delivery path; +- condition node counts (48/49/48) and retained bytes (≈ 157 KiB); +- snapshot-copy cost (≈ 1.7–2.9 µs per condition); +- the Galaxy ack-identity keying; +- the absence of node build reporting; +- the opc-plc alarm fixture; +- alarm-bearing tag export shape (#896). + +The counts, bytes and copy timing come from a scratch harness: a console project referencing `OPCFoundation.NetStandard.Opc.Ua.Server` +2.0.1 that builds each condition type with NM's optional children, walks `GetChildren`, measures a `GC.GetTotalMemory(true)` +delta over 2,000 instances, and times the snapshot field copy. It is not in the repo; X0 task 4 commits it as evidence. + +**Live measurements** — each runs on docker-dev unless stated, and each has a pass criterion: + +| ID | Phase | Measurement | Pass criterion | +|---|---|---|---| +| L1 | A1 | `SnapshotConditions` `Lock` hold inside a running origin with 1,000 conditions in scope while drivers publish | p99 ≤ 10 ms; no data Publish on the origin delayed > 50 ms during a snapshot | +| L2 | A3 | Consumer memory with 1,000 imported conditions (one mapping) | Working-set growth ≤ 200 MiB (≈ 1,000 × 157 KiB + indexes); if exceeded, lower the defaults before A4 | +| L3 | A3 | Lock-freedom: origin method handler stalled 5 s | Concurrent consumer Read/Browse/Publish < 200 ms; no local ack state before the origin record (§5.6 step 6) | +| L4 | A4 | `ConditionKnownSettleMilliseconds`: time from driver connected (quality Good) to initial alarm snapshot delivered, for the docker-dev native source (OpcUaClient → opc-plc `--alm`); Galaxy reconnect snapshot latency on the AVEVA rig when available | Default (10 s) ≥ 2× the observed p99; else raise it | +| L5 | A4 | Condition counts of the docker-dev export and of one real production export (read-only count via the origin's existing AdminUI `/alerts` or ConfigDb authoring counts) | Each mapping ≤ 80% of `MaxConditions` and each consumer node ≤ 80% of the host caps; else adjust the defaults and record why | + --- ## 10. Open questions for the owner @@ -1005,6 +1142,5 @@ build), and the owner decisions of 2026-11-23: disabling any mapping does not change them. The remaining unavoidable changes are accepted as removal + addition + RefreshRequired, never as a rejected disable: connection replaced, origin condition re-created, key-secret rotation. -Items that depend on X0 findings rather than owner input: the method interception point (§5.6 step 1 — A3 is blocked if no -lock-free path exists), `EventFieldList` re-gating, the Galaxy ack-identity lookup, the condition subtree size, and -node feature reporting for the M1 deploy check. +Nothing depends on X0 findings any more; revision 4 settled them offline. The only open items are the live measurements +L1–L5 in §9.3, each with a pass criterion. None is an owner decision. diff --git a/docs/plans/2026-11-23-grpc-data-connections-history-alarms-relay-plan-review.md b/docs/plans/2026-11-23-grpc-data-connections-history-alarms-relay-plan-review.md index 0ab805087..79f59992e 100644 --- a/docs/plans/2026-11-23-grpc-data-connections-history-alarms-relay-plan-review.md +++ b/docs/plans/2026-11-23-grpc-data-connections-history-alarms-relay-plan-review.md @@ -542,3 +542,155 @@ Nothing in X0/H becomes unsafe: features stay default-off and header-gated. Two None open at Blocker. Open Majors: **N1** hub seeding, **N2** condition subscription contract, **N3** cross-realm home, **N4** identity depends on stream order, **N5** default budgets; plus the residual part of **M1** (`LocalDataServices.cs:47`). + +--- + +## Third pass (2026-11-23) + +Reviewed: revision 4 of [`2026-11-23-grpc-data-connections-history-alarms-plan.md`](2026-11-23-grpc-data-connections-history-alarms-plan.md). +Baseline `649f2ecd2`. SDK claims were checked against `ilspycmd` decompiles of the pinned 2.0.1 packages +(`~/.nuget/packages/opcfoundation.netstandard.opc.ua.server/2.0.1/lib/net10.0/Opc.Ua.Server.dll` and +`…opc.ua.core.types/2.0.1/lib/net10.0/Opc.Ua.Core.Types.dll`); "SDK:" line numbers below refer to those decompiles +(type name given), so they are approximate but the code was read. Not run: the plan's scratch harness (node counts, +157 KiB, copy timing) is not in the repo, so those three numbers are checked for arithmetic and plausibility only. + +### Verdict per phase + +- **X0 — approve.** No open item. +- **Phase H — approve.** Unchanged since the second pass; no new defect found. +- **Phase A — approve with changes.** B5 and the publish-time re-gating are confirmed against the SDK, and N1–N8 are closed + in design. Revision 4 introduces three Majors (T1–T3), all in the new `state_known` / `expected_activation_time` + mechanisms. T1 and T2 must be fixed in the plan before A1 (which implements `state_known`); T3 before A2. + +### Second-pass items + +| Item | Status | Evidence | +|---|---|---| +| **N1** hub seeding | **Closed in shape, reopened in detail by T1/T2.** Snapshot from live nodes under one `Lock` hold, deltas before the standby return (`NM:1561-1565`) and on silent applies — correct. The `state_known` rules that make the snapshot safe are the new findings. | +| **N2** subscription contract | **Closed.** `SubscriptionItem.condition_scope`, one handle per mapping, `total`/`removed`/`snapshot_complete`; no `Condition` node kind in the catalog, so header-less callers are unaffected. | +| **N3** cross-realm home | **Closed.** Realm-local placement addresses; `condition_key` is a per-principal keyed hash. The plan's refinement is right: `stable_source_id` embeds the RawPath, so my suggested dedupe key would itself have leaked (#916 filed for the v1 exposure). One consequence to state — m-T6. | +| **N4** identity vs stream order | **Closed.** NodeId = (connection, `condition_key`) in a third mapped namespace; primary placement from deployed configuration; connection barrier before materialising. `RealmOf` folding (`NM:283-284`) is called out with a guard test. | +| **N5** budgets | **Closed.** Arithmetic checks: 10,000/49 = 204; 1,000 × 157 KiB = 153 MiB; 2,500 × 49 = 122,500; 2,500 × 157 KiB = 383 MiB; 10,000 × 157 KiB = 1.5 GiB. Optional children match `NM:2461-2475`. Conditions charged once per key, outside `MaxProjectionNodes`. See m-T7 for what the 157 KiB excludes. | +| **N6** `occurrence` across failover | **Not closed — replaced by a mechanism that is unsound (T3).** | +| **N7** lazy notifier wiring | **Closed** (wire on materialise, unwire on retirement, pin folders with event items; `EventNotifier = None` at creation confirmed). | +| **N8** G0 consequences | **Closed** (recorded-v1-client gate at X0/H2/A2/A3 exits; #915 on an X0-or-later build). | +| M1 residual (`LocalDataServices.cs:47`) | **Closed** (§4.3 grow site, H2/A2). | + +### B5 — `ICallAsyncNodeManager.CallAsync`: confirmed + +- **Dispatch.** `NodeManagerServiceDispatcher.CallAsync` validates each request (`ValidateCallRequestItemAsync`), marks bad + ones `Processed = true` and good ones `false`, then awaits `CallAsync` on every registered manager with + `ConfigureAwait(false)`, passing the whole batch (SDK: `NodeManagerServiceDispatcher` state machine, ≈1352-1455). +- **Adapter.** `AsyncNodeManagerAdapter.CallAsync` is `if (SyncNodeManager is ICallAsyncNodeManager m) return m.CallAsync(…); + SyncNodeManager.Call(…);` (SDK: `AsyncNodeManagerAdapter` ≈264-275). The check is at call time, so implementing the + interface on `OtOpcUaNodeManager` is picked up even though `CustomNodeManager2` built its adapter in its constructor + (SDK: `CustomNodeManager2` ≈1079). +- **Pre-dispatch lock.** `CustomNodeManager2.FindMethodState` takes `lock (Lock)` only around `ValidateNode` + + `FindMethod` and returns (SDK: `CustomNodeManager2` ≈4952-4990). Nothing is held when validation ends. +- **Partial claim coexists with the sync path.** `GetMethodCalls` skips `Processed` requests (`if (!val.Processed)`) and + takes `Lock` per request it owns; `CallSynchronousBatch` then invokes the handler (SDK: `CustomNodeManager2` ≈6743-6790 + and the `GetMethodCalls` iterator). So "claim ⇒ `base.Call` ⇒ await claimed" works as described. +- `ICallAsyncNodeManager.CallAsync` signature matches the plan (`ValueTask`, `ArrayOf`). + +Two points to add to §5.6, neither blocking: +1. `base.Call` runs under `BeginNodeManagerOperation()` (SDK: `CustomNodeManager2` ≈4940-4946). Keep the awaited remote + calls outside that scope — call `base.Call` to completion first, as the plan orders it. +2. The dispatcher awaits managers sequentially, so a batch that mixes an imported-condition call with calls owned by a + **later-registered** manager delays those by up to the method timeout. State the registration order or accept it. + +### Publish-time re-gating: confirmed, with one gap (m-T4) + +`MonitoredItem` rebuilds queued event lists only in `TransformQueuedEvents` on a filter modify (SDK: `MonitoredItem` +≈1347-1360), via `GetEventFields`, which creates a plain `EventFieldList` and sets `Handle = instance` (≈1880-1882). +Publish and Republish hand out the queued instances. The existing rewriter already runs on both +(`OpcUaServer/OtOpcUaSdkServer.cs:746,768`; `OpcUaServer/WarmStandby.cs:917`). The design holds. + +### New findings + +#### T1 (Major) — `state_known` flips with no delta: normal-state native conditions stay `Uncertain` on the consumer (§5.1) + +**Problem.** A native condition becomes known "once Quality has been Good for 10 s", implemented as "a timestamp beside +the set, recorded when `WriteAlarmQuality` first observes Good". That is evaluated when a snapshot is cut. Nothing raises +a delta when the window elapses: no node state changes, so neither tap point fires (`ReportConditionEvent`, +`WriteAlarmCondition`). A consumer whose snapshot was cut inside the window receives `state_known = false`, sets +`Quality = Uncertain`, and is never told otherwise — for the common case (alarm not active) until the next resync. +The same applies to `MarkScriptedConditionsKnown` unless it is specified to emit records. + +**Fix.** Make every unknown→known transition a hub delta: a per-driver one-shot timer (or the `MarkScriptedConditionsKnown` +call) raises state-only records under `Lock`. Alternatively withhold `snapshot_complete` until every in-scope condition +is known or a bounded wait expires. Add an A1 case: snapshot cut inside the window, then the consumer's condition +quality returns Good with no further origin activity. + +#### T2 (Major) — the "known" signals can declare an active alarm known-inactive (§5.1, L4) + +Two cases, same outcome: the consumer holds `Active`, receives a `state_known = true, active = false` record, and +reports a clear (losing the ack state) before the real state arrives — the false clear N1 was raised to prevent. + +- **Scripted, cold start.** `Active` is not persisted; the engine re-derives it from the predicate at load + (`src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs:445-461`), over a value cache seeded by + `ReadTag` before any driver has published. The engine already distinguishes this ("genuine cold start", + `StatusNeverPushed`, `ScriptedAlarmEngine.cs:58-67`). `MarkScriptedConditionsKnown` is sent right after the re-assert + pass, i.e. while inputs may still be never-pushed. A failover is fine (the standby's engine is warm); a restart of the + serving origin node is not. +- **Native, slow initial replay.** The 10 s window assumes a driver delivers its standing alarms within 10 s of + connecting. L4 calibrates that on OpcUaClient→opc-plc and "Galaxy when available"; the transition-only sources the + plan names (MTConnect, FOCAS) and poll-based ones are not measured, and one global default covers all drivers. + +**Fix.** Scripted: mark a condition known only when none of its inputs is `StatusNeverPushed` (the engine has +`WorstInputStatus`), and re-raise when that changes. Native: add an optional driver signal ("initial alarm state +delivered") and use the settle timer only as the fallback, configurable per driver type; L4 must cover each native alarm +source shipped, or the unmeasured ones default to a conservative value. A1 negative test: origin restart with a standing +scripted alarm whose input arrives late ⇒ no `known, inactive` record before the first real evaluation. + +#### T3 (Major) — `expected_activation_time` is not an activation time (§5.6 step 3, §4.2 field 18) + +**Problem.** `activation_time` is defined as "ActiveState transition time". The SDK sets it on every call, changed or not: +`AlarmConditionState.SetActiveState` assigns `activeState.TransitionTime.Value = DateTimeUtc.Now` unconditionally (SDK: +`AlarmConditionState` ≈912-919), and `WriteAlarmCondition` calls `SetActiveState` on **every** projection (`NM:1364`) — +a severity or message change, a same-message re-raise, the engine's re-projection after a method call, a rebuild +re-assert. So the value moves while the alarm stays active. + +Consumer EventIds are bound to "the record it was reported with", and re-binding is specified only for a resync epoch. +A state-only record inside an epoch (no consumer event, by the shared delta gate) carries a new `activation_time`; the +client's still-valid EventId then sends the old one and the origin answers `BadEventIdUnknown`. Legitimate acks fail +intermittently, most often on exactly the busy alarms. + +**Fix.** Do not derive the precondition from the SDK field. Keep an origin-owned activation marker in NM, changed only +on an inactive→active edge under `Lock` and carried through `RestoreCarryOver` (which already carries +`ActiveTransitionTime`, `NM:2670-2747`); and have the consumer always send the marker of the **latest applied record** +for the condition, deciding EventId validity locally by "same activation". A2 test: re-project an unchanged active alarm +at the origin, then ack with the pre-re-projection EventId ⇒ Good. + +#### m-T4 (Minor) — fail-closed drop loses authorised events + +The rewriter drops an unmarked list whose `Handle` is an imported-condition snapshot. That is the right default, but it +also discards events for an **authorised** caller after a `ModifyMonitoredItems` that changes select clauses, and for any +delivery that goes through the SDK's own `QueueEvent(IFilterTarget)` (when `UseProjectedEventDelivery` is off, `NM:1930`). +State that imported-condition events are always queued through the marked path regardless of that switch, and that the +rewriter re-evaluates the gate for the publishing session instead of dropping when it can; otherwise document the loss +and emit `RefreshRequired` to that item. + +#### m-T5 (Minor) — L4/L2 gate placement + +`ConditionKnownSettleMilliseconds` is implemented in A1 but calibrated in A4, and consumer memory (L2) is measured in A3 +after A2 has shipped the defaults in a migration. Move L4 to the A1 exit and L2 before the A2 defaults are frozen, or +state that A1–A3 are not deployable to a fleet before A4. + +#### m-T6 (Minor) — ConditionId across a consumer pair depends on the principal + +`condition_key` is derived per authenticated principal. If the two consumer pair members authenticate as different +principals (two exports), the same alarm has different NodeIds on each, and a client failing over between them sees a +different `ConditionId`. Require one principal per connection across its `ConsumerNodeIds` (validator rule), and assert +equal ConditionIds on both consumer nodes in A06. + +#### m-T7 (Minor) — what 157 KiB excludes + +The measurement excludes NM's indexes, the `c1./` identifier strings on 48–49 nodes per +condition, the per-condition EventId registry and placement sets. L2's allowance (200 MiB for 1,000) covers roughly 28% +overhead; keep L2 as the authority and size `MaxImportedConditionBytes` from it, not from the harness figure. + +### Open Blocker/Major items after the third pass + +No Blocker. Majors: **T1** (no delta when a condition becomes known), **T2** (known-inactive declared too early for +scripted cold start and slow native replay), **T3** (`expected_activation_time` moves on every projection). All three are +Phase A only.