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 new file mode 100644 index 000000000..bb69ce2a4 --- /dev/null +++ b/docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md @@ -0,0 +1,815 @@ +# gRPC data connections: remote history and alarm/event forwarding + +Date: 2026-11-23 (revision 2, after independent review) +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 +plan/gate structure is [`2026-11-15-grpc-data-connections-implementation-plan.md`](2026-11-15-grpc-data-connections-implementation-plan.md) +("v1 plan"). Operator guide: [`docs/DataConnections.md`](../DataConnections.md) §"Feature boundary". +Independent review of revision 1: [`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/` = +`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/` = +`src/Core/ZB.MOM.WW.OtOpcUa.Core/`, `NM` = `OpcUaServer/OtOpcUaNodeManager.cs`. + +--- + +## 0. Review resolution + +Every finding was re-checked against source at `649f2ecd2` before it was accepted. None is rebutted. One extra site was +found while verifying M1 (row M1). + +| Finding | Verdict | Where addressed | +|---|---|---| +| B1 projected identity (`mapped/raw|uns` namespaces, opaque `p1.` ids, realm folding in `RealmOf`) | Accepted (verified `ProjectedDataIds.cs:8-11,47-57`, `NM:283-284`, `NM:2410`, `NM:4883-4888`) | §5.2 identity, §5.3 mapped condition registry, H3/A4 CLI recipes resolve by browsing | +| 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`) | §5.1: hub fed from `ReportConditionEvent` (`NM:1540`), A1 parity gate on reported events | +| 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`) | §5.6: projected methods intercepted before any `Lock`; no local apply before owner confirms; lock-freedom test | +| 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 a fifth site** `Runtime/DataConnections/ProjectedDataAccess.cs:157` (acquisition allowlist) | §4.3, X0 (tolerant readers ship first), rollout rule | +| 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 | +| M3 override-resident history rules | Accepted (verified `NM:8810-8817`, `:8839`, `:8854-8902`, `:10815`) | §3.1 port boundary at override level; H1 parity cases | +| M4 standing condition stream = new authority mode, outside projection budget | Accepted | §5.5 demand-driven stream, budget charge, all-or-nothing capacity | +| M5 relay loop key / both validator sites | Accepted | §8 (deferred constraints) | +| M6 bits/migration late; Gateway optional | Accepted (verified validator `:22,103,268`) | H2 carries bits+migration+artifact; Gateway leg is a required H4 gate | +| M7 duplicate conditions inside one mapping | Accepted | §5.2/§5.3: one condition per (consumer node, connection, origin condition), extra placements = notifiers | +| M8 method→permission mapping, standby, audit text | Accepted (verified `NM:3285-3290`, `NM:3118-3124`) | §4.2 bits derived from `AlarmOperationFor`; §5.6 standby; §6 sanitised separate audit field | +| M9 building on undeployed v1 | Accepted, soak deferred by owner | §1.1 — G0 is a later deploy gate (#915), not a blocker | +| m1 MAC redundant; in-memory store is a test double | Accepted (verified `HistoryContinuationStore.cs:107-123`) | §3.2: no MAC; new production `PeerHistoryContinuationStore` with idle expiry | +| m2 two release mechanisms | Accepted | §4.2: `release_continuations` flag only | +| 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 = condition version | +| m6 Galaxy ack-identity lookup unverified | Accepted | X0 task; §5.6 marked (inferred) | +| 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 | +| m10 ScadaBridge impact | Accepted | A4 exit gate | +| m11 relay hop bound | Accepted | §8: hop cap 2 until measured | +| Nits (line numbers, relay schema, phase keys, negotiation surface) | Accepted | Line refs fixed; phase keys verified free-form (`run-unit-phase.py:139` only requires a manifest key); no new protocol minors — capability fields + feature header only | +| Scope cuts 1–5 | Accepted | Relay (§8), event history and modified reads (§7), Shelve/Enable/Disable (§7), `is_restatement`/release RPC/MAC/EventId map removed | + +--- + +## 1. Summary of decisions + +| Capability | In this plan | Deferred (§7) | Out | +|---|---|---|---| +| **Remote history** | HistoryRead Raw (bounds, reverse/end-only, paging), Processed, AtTime on mapped Raw/UNS **variables**; direct `IDataConnection` history for runtime consumers | HistoryReadEvents on mapped notifiers (needs §5.2 identity); modified-value reads | **HistoryUpdate** (§2.1.1) | +| **Alarm/event forwarding** | Native + scripted Part 9 condition **state** under mapped branches; ConditionRefresh; RefreshRequired; Acknowledge, AddComment (native + scripted), Confirm (scripted) | OneShot/Timed shelve, Unshelve, Enable/Disable | Non-condition events; consumer-side alarm history or `/alerts` rows for imported conditions; replay of transitions missed in a gap | +| **Relay** | — | Separate design (§8) | — | + +Order: **history, then alarms.** History is read-only and unary and reuses v1 authority; it ships on its own. Alarms need a new +identity scheme, a stream item class and a mutation path. + +### 1.1 Deferred deploy gate G0 — v1 deployed and soaked (#915) + +v1 is merged (`95c5e484`) but **not deployed** (v1 design line 4). The review (M9) asked for v1 to be deployed and soaked +before this plan ships. **The owner deferred that soak on 2026-11-23**: the 14-day trial is tracked as a later deploy gate, +Gitea **#915** (`type:deploy-gate`, `blocked` by the wonder-box hold), and it does **not** block any phase here. + +What still holds without G0: every phase's own exit gate, including the docker-dev and cross-cluster live gates, must pass +before it merges. Deploying any phase to a production fleet before #915 passes stacks it on an unsoaked v1; record that +risk in the deploy notes when it happens. + +#915's bar, for reference: at least one real redundant pair consuming from another cluster over TLS, with a Raw and a UNS +mapping in use; 14 consecutive days with no p0/p1 grpc-data issue and no unexplained stream resets or authority/lease +failures; one planned failover of each pair during the window. + +--- + +## 2. Scope, non-goals and alternatives + +### 2.1 Remote history + +The consumer forwards HistoryRead on a projected variable over the configured `DataConnection`. The owning cluster serves it +from **its own** historian backend (`ServerHistorian:Backend` = Gateway/SqlServer/QuestDb) under its own export grants and +ACL. Part 11 results come back verbatim: status codes, timestamps and info bits. Non-goals: merging local and remote series, +caching remote history, exposing historian tagnames, making the consumer's `HistoryServerCapabilities/AggregateFunctions` +(i=11201) describe remote backends. + +#### 2.1.1 HistoryUpdate stays out (settled, Q1) + +1. **Identity:** the modified-value trail (#668) records the session principal. v1 imports use a service principal (v1 design + §8), so every remote edit would be attributed to the connection account. +2. **Authorization:** locally a **Cluster-scoped** `HistoryUpdate` grant is needed with ACLs off, and `WriteOperate` never implies + it (`.claude/rules/historian.md` §HistoryUpdate). Mapping-scoped grants have no local equivalent. +3. **Mutation ambiguity:** HistoryUpdate is Primary-only (#674), and Replace/Update/Delete are not idempotent. +4. **Backend coverage:** the Gateway answers `BadHistoryOperationUnsupported`, and QuestDB trail INSERTs can duplicate after a + timeout. + +Projected variables never set the `HistoryWrite` bit. Nothing is reserved for HistoryUpdate. + +#### 2.1.2 Alternatives + +| Approach | Decision | +|---|---| +| **A. Part 11-shaped RPC served by the origin's own pipeline, through a port extracted at override level (recommended)** | One authority for bounds, paging, tie clusters, reverse walks and aggregate status rules (#677, #680–#694, #897); one WAN round-trip per page | +| B. Remote `IHistorianDataSource` proxy | Rejected. Gateway walk-backs are 18–31 backend reads per page (#686/#693), learned ceilings would leak across the wire, and the calls are tagname-addressed | +| C. OPC UA HistoryRead tunnel | Rejected for the same reason as v1 design §1 | + +### 2.2 Alarm/event forwarding + +Conditions owned by the origin are native (`ConditionId = RawPath`, one node fanned to referencing equipment folders) or +scripted (`ConditionId = ScriptedAlarmId`). Each appears **once** on each consumer node that imports it: a real +`AlarmConditionState` in the mapped namespace, with notifiers on every projected folder that mirrors an origin placement. +Methods execute at the origin's active Primary under the origin's authorization. Nothing is applied locally before the origin +has accepted the call. + +| Approach | Decision | +|---|---| +| **A. Condition-state items on the existing Subscribe stream plus a unary method RPC (recommended)** | Reuses v1 epochs, snapshots, authority gates and recovery; state-convergent | +| B. Separate condition stream RPC | Rejected: duplicates the stream machinery hardened in v1 P04–P07 | +| C. Forward origin EventFieldLists | Rejected: origin NodeIds, no convergent resync, Retain drift under coalescing | +| D. `telemetry.proto` alarm stream | Rejected: lossy DropOldest (v1 design §2) | + +--- + +## 3. Repository evidence (verified at `649f2ecd2`) + +| Seam | File(s) | Consequence | +|---|---|---| +| Wire | `Commons/Protos/data_connection.proto` | `CapabilitiesResponse` 1–15 used; `Metadata` 1–13; `SubscriptionCommand` oneof 5–9; `SubscriptionFrame` oneof 4–7 **and field 8 = `Serving`** ⇒ new arms start at 9 | +| Operation masks (M1) | `Configuration/Validation/DataConnectionValidator.cs:12,22`; `Runtime/DataConnections/DataConnectionDeploymentRuntime.cs:151-152` (throws ⇒ aborts the whole snapshot); `Abstractions/DataConnections/DataContracts.cs:271-276` (`DataCapabilities.Validate` throws); `Commons/DataConnections/DataProtoMapper.cs:1054-1062` (masks, benign), `:284` (`Metadata.allowed_operations` cast unmasked); `Runtime/DataConnections/ProjectedDataAccess.cs:157` (acquisition allowlist) | All five change in X0 (tolerant) and H2/A2 (new bits) | +| Negotiation (M2) | `Host/Grpc/DataConnectionGrpcService.cs:26` (`Math.Max(3,…)`), `Runtime/DataConnections/LocalDataServices.cs:222` (`Math.Max(5,…)`), `GrpcDataConnection.cs:548` (`CompactCodecHeader` precedent), `:762-767` + `DataProtoMapper.cs:1207` (unknown arm ⇒ `"Expected control or acknowledgement."` ⇒ stream faults) | Per-call feature header; the server must never send unnegotiated shapes | +| History overrides (M3) | `NM:8791-9060`; modified+bounds `NM:8810-8817`; `NormalizeHistoryValues` `NM:8839`; aggregate refusals `NM:8854-8902`; `ServeNodeAsync` `NM:10083`; `ServeRawPagedAsync` `NM:10191`; `HistoryContinuationMatches` `NM:10815` (binds the NodeId string) | Port boundary = override level | +| Tagname lookup | `NM:949` public `TryGetHistorizedTagname(string, out, AddressSpaceRealm)` | Origin resolves an export view without SDK types | +| Continuation stores | `OpcUaServer/HistoryContinuationStore.cs` — `SessionHistoryContinuationStore` (production); `InMemoryHistoryContinuationStore` is a **test double** without idle expiry (`:107-123`) | A new production per-peer store is needed | +| Mapped authorization | `Core/Authorization/DataOperationPolicy.cs:80-88` (non-Browse/Read/Write/Subscribe ⇒ `None` ⇒ deny); `OpcUaServer/Security/DataPlaneAuthorizer.cs:166-178` (unknown mapped id ⇒ deny), `:184-187` (mapped `CreateMonitoredItems` denied); `NM:837` (`SecurityFilteringActive` true whenever a mapped resolver exists) | HistoryRead and alarm operations on mapped nodes are closed today and are opened deliberately | +| Projected identity (B1) | `Abstractions/DataConnections/ProjectedDataIds.cs:8-11` (`https://zb.com/otopcua/mapped/raw`, `…/mapped/uns`), `:47-57` (`p1.` + base64url(JSON{MappingId, Origin}); base64url excludes `/`); `NM:106-107` (`IsProjectedDescendant` = ns index 2/3); `NM:283-284` (`RealmOf` folds mapped 2→Raw, 3→Uns); `NM:2410` (`MaterialiseAlarmCondition` mints into the **local** realm namespace); `NM:4886-4889` (projection accepts only Folder/Variable/Tag) | Projected conditions need their own registry and id scheme | +| Condition report choke point (B2) | `NM:1540` `ReportConditionEvent` (callers `NM:1418,1505,3034,5650`); method wrapper `NM:2998-3037` under `lock (Lock)`; native SDK-applied ack `NM:3197-3202`; `DriverHostActor.cs:2612-2637` ("success sends nothing back") | The hub taps reported events, not `OpcUaPublishActor.AlarmStateUpdate` | +| 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 | +| Permissions (M8) | `NM:3285-3290` `AlarmOperationFor` (Confirm ⇒ AlarmConfirm; shelve ops ⇒ AlarmShelve; everything else, including AddComment and Enable/Disable, ⇒ AlarmAcknowledge); `NM:3118-3124` (Warm Standby refuses every method) | Wire bits derived from this one function | +| Projection budget (M4) | `NM:4909-4910` `ReserveProjectedNode`, `OpcUaServer/ProjectedNodeLifetime.cs` | Conditions are charged against it | +| Authorization vocabulary | `Configuration/Enums/NodePermissions.cs` (`AlarmRead` declared, **not enforced**), `NodeAclScopeKind.RemoteNamespaceMapping` | Visibility uses Subscribe/`CreateMonitoredItems` on the mapping scope | +| Scripted commands | `Commons/OpcUa/AlarmCommand.cs`, `Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs` | Origin path for scripted methods (as AdminUI `/alerts` uses) | +| Alarm history / alerts | `Runtime/Historian/HistorianAdapterActor.cs` (alerts topic, Primary-gated) | Imported conditions never enter the consumer's `alerts` topic | +| Config / artifact | `Configuration/Entities/{DataConnection,DataExport,RemoteNamespaceMapping}.cs`, `Runtime/Drivers/DeploymentArtifact.DataConnections.cs`, `Configuration/Validation/DataConnectionScopeRevision.cs` | New fields land in the phase that first uses them | +| Harness | `scripts/validation/grpc-data/` (`run-unit-phase.py` accepts any manifest key, `:139`; `scenarios.json` D01–D14; `cli_gate.py`; `rig.py`) | New manifest keys X0/H1–H4/A1–A4 | + +### 3.1 History port boundary (M3) + +The port sits at **override level**. Input: `(realm, identifier, HistoryReadVariant details, continuation?, budget, caller)`. +Output: a per-node outcome (status, samples, cursor). It includes everything the overrides do today: + +- aggregate refusals (unknown, `HistoryAggregateDataTypes.AppliesTo`, `SupportsAggregateFor`, + `ServerAggregateConfiguration.IsServable`); +- the modified+bounds `BadInvalidArgument` rule; +- `NormalizeHistoryValues`; +- the batch limiter and deadline; +- continuation binding, re-keyed from the SDK NodeId string to `(realm, identifier)`. + +The SDK overrides become thin adapters over the same core. HistoryRead runs outside `Lock` (`NM:8722-8725`), and the +refactor must keep it there. + +### 3.2 Continuation points and assembly (m1, m7) + +- **Origin:** a new production `PeerHistoryContinuationStore`, one instance per (authenticated principal, connection + incarnation), with a capacity equal to the export limit and an idle expiry (default 60 s, matching v1 browse continuations). + The wire token is a random 16-byte id; the stored record binds principal, serving incarnation, history epoch, view and the + hash of the details. No MAC is needed. A mismatch, another principal, an origin restart or failover, or a rebuild epoch bump + ⇒ `BadContinuationPointInvalid`. Takes are single-use: a page lost in transit makes the client's resume fail + `BadContinuationPointInvalid`, and no page is ever silently skipped. +- **Consumer:** a `HistoryCursorKind.Remote` record in the SDK session store wraps the origin token with mapping id/revision, + serving incarnation, projection generation and the caller's key. A resume re-checks the caller's grant and lease. Session close + and `releaseContinuationPoints` forward one `HistoryRead{release_continuations}` call, best effort; origin idle expiry is the + backstop. +- **Failover:** a fresh read may move endpoint within its deadline; a resumed read never moves. +- **Uncapped Raw:** the origin pages at its advertised ceiling, and the consumer returns the CP (Part 11 permits this). +- **Processed/AtTime:** these are single-shot locally. Over the wire they arrive in bounded chunks that the consumer assembles + within one **per-request** budget (`MaxHistoryAssemblyBytesPerRequest`, default 16 MiB shared across the batch). Exceeding it + ⇒ `BadTooManyOperations` for the remaining nodes. + +### 3.3 Fidelity + +- The full `uint32` status passes through, including Calculated/Interpolated/Partial bits, `Bad_BoundNotFound`, + `GoodNoData` vs `BadNoData` and `UncertainDataSubNormal`. +- Timestamps travel as ns protobuf `Timestamp`. The origin advertises `TimestampResolutionTicks` (QuestDB µs). An absent + timestamp stays absent. +- Values use the v1 `TypedValue` codec, and the origin applies AtTime type hints. A value kind that disagrees with the catalog ⇒ + `BadTypeMismatch`, never coercion. +- An unset StartTime/EndTime is sent as **absent**, not `MinValue`, because the origin's end-only logic depends on the + difference. +- Per-node deadline = min(consumer `HistoryReadDeadline` remaining, `HistoryTimeoutMilliseconds`). Expiry ⇒ `BadTimeout`. + A cancelled read is never counted as an origin backend fault. +- Consistency follows the connection: `Primary` by default. `ReadyReplica` is allowed (Q5, settled); docs note that the newest + seconds can lag while continuous-historization outboxes drain. + +--- + +## 4. Protocol, negotiation and mixed versions + +### 4.1 Negotiation (M2) + +- **No new protocol minor.** Each feature has a `CapabilitiesResponse` advertisement field plus a **per-call request header**, + `x-otopcua-data-features` (comma list: `history`, `conditions`), sent on **every** RPC. This follows the + `CompactCodecHeader` precedent (`GrpcDataConnection.cs:548`). The server keeps v1 behaviour for any call without the header: + - Browse/GetMetadata return the v1 catalog shape: no `Condition` nodes, and alarm-bearing raw tags exactly as v1 exports them; + - Subscribe never emits a condition arm; + - new RPCs answer `Unimplemented`-equivalent `FailedPrecondition("feature not negotiated")`. +- The consumer sends the header only when the selected endpoint advertised the feature. After a failover it re-derives the + header from the new endpoint's capabilities. +- **v1 clients fault on unknown frame arms.** `GrpcDataConnection.cs:762-767` hands any frame that is neither `values` nor + `compact_values` to `DecodeControlOrAck`, which throws (`DataProtoMapper.cs:1207`). This settles the revision-1 X0 + question: header gating is mandatory. Unknown `CapabilitiesResponse`/`Metadata` fields are ignored by proto3 and are safe. + +### 4.2 Contract additions (tags locked by golden tests in X0) + +```proto +// CapabilitiesResponse +HistoryCapabilities history = 16; // raw, processed, at_time; aggregates (stable HistoryAggregateType names); + // timestamp_resolution_ticks; max_values_per_page; max_concurrent_reads; continuation_idle_ticks +ConditionCapabilities conditions = 17; // state_items; methods (bitmask); max_conditions +// Metadata +HistoryInfo history = 14; // historizing +ConditionInfo condition = 15; // only when "conditions" negotiated; node_kind = "Condition" + +rpc HistoryRead(HistoryReadRequest) returns (HistoryReadResponse); +message HistoryReadRequest { repeated HistoryReadItem items = 1; Budget budget = 2; + oneof details { RawDetails raw = 3; ProcessedDetails processed = 4; AtTimeDetails at_time = 5; } + bool release_continuations = 6; } // the only release mechanism (m2) +message RawDetails { optional google.protobuf.Timestamp start = 1; optional google.protobuf.Timestamp end = 2; + uint32 num_values_per_node = 3; bool return_bounds = 4; } +message ProcessedDetails { optional google.protobuf.Timestamp start = 1; optional google.protobuf.Timestamp end = 2; + int64 interval_ticks = 3; repeated string aggregate = 4; // parallel to items + AggregateConfiguration configuration = 5; } // client values verbatim; origin IsServable decides (m8) +message AtTimeDetails { repeated google.protobuf.Timestamp times = 1; bool use_simple_bounds = 2; } +message HistoryReadResult { string correlation_id = 1; uint32 status_code = 2; repeated HistorySample samples = 3; + optional bytes continuation = 4; optional string diagnostic = 5; bool chunk_continues = 6; } +message HistorySample { TypedValue value = 1; uint32 status_code = 2; + TimestampOverride source_timestamp = 3; TimestampOverride server_timestamp = 4; } + +message ConditionInfo { string condition_type = 1; // namespace-URI qualified + string condition_name = 2; int32 source_kind = 3; // NATIVE / SCRIPTED + View home = 4; // the one origin condition address + repeated View notifiers = 5; // origin placements (raw device folder + referencing equipment) + uint32 supported_methods = 6; string origin_source_name = 7; } +message ConditionState { // SubscriptionFrame oneof arm 9 (wrapped in ConditionStates) + Handle handle = 1; int64 version = 2; int64 occurrence = 3; // occurrence increments on each new activation + bool active = 4; bool acknowledged = 5; bool confirmed = 6; bool enabled = 7; int32 shelving = 8; + uint32 severity = 9; string message = 10; uint32 quality = 11; google.protobuf.Timestamp unshelve_at = 12; + int32 condition_class = 13; google.protobuf.Timestamp time = 14; bool retain = 15; + optional string comment = 16; optional string client_user_id = 17; } +message ConditionStates { bool is_snapshot = 1; repeated ConditionState items = 2; bool snapshot_complete = 3; } + +rpc CallConditionMethod(ConditionMethodRequest) returns (ConditionMethodResponse); +message ConditionMethodRequest { string operation_id = 1; View condition = 2; int32 method = 3; + int64 expected_occurrence = 4; optional string comment = 5; + string expected_serving_incarnation = 6; int64 remaining_budget_ticks = 7; + optional string on_behalf_of = 8; } // untrusted audit text; capped and sanitised at the origin (§6) +message ConditionMethodResponse { int32 state = 1; uint32 status_code = 2; optional string diagnostic = 3; Serving serving = 4; } +``` + +New `DataOperations` bits (M8: derived from `AlarmOperationFor`, one authority shared in code): + +| Bit | Name | Covers | +|---|---|---| +| 32 | `HistoryRead` | Raw/Processed/AtTime | +| 64 | `AlarmSubscribe` | condition state items and condition metadata (the **origin-side** grant; local visibility uses Subscribe, §5.4) | +| 128 | `AlarmAcknowledge` | Acknowledge, AddComment (Enable/Disable later, same bit — `AlarmOperationFor` `_` arm) | +| 256 | `AlarmConfirm` | Confirm | +| 512 | `AlarmShelve` | reserved for the deferred shelve methods | + +### 4.3 Mixed versions and the masks (M1) + +**Rule:** a new bit is only ever authored after the **X0 release** (tolerant readers) runs on every node of both clusters. +X0 changes: + +- `DataConnectionDeploymentRuntime.cs:151-152`: unknown bits on a row are **dropped** (fail closed: an unknown grant is no + grant) and counted in diagnostics. They no longer throw for the whole snapshot. +- `DataContracts.cs:271-276`: `DataCapabilities.Validate` masks to the known set instead of throwing. +- `DataProtoMapper.cs:284`: `Metadata.allowed_operations` masked on decode. `:1054-1062` is already masking (kept). +- `DataConnectionValidator.cs:12`: still rejects unknown bits. The known set grows only in the phase that adds the feature + (H2, A2), so authoring cannot get ahead of the code. +- `ProjectedDataAccess.cs:157`: extended in the phase that acquires with a new operation (H3, A3). + +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.)** + +| Consumer | Origin | Behaviour | +|---|---|---| +| new | v1 | Features not advertised ⇒ no header ⇒ v1 behaviour. Projected variables keep `Historizing=false` and no HistoryRead bit; HistoryRead ⇒ `BadHistoryOperationUnsupported`; no conditions. Diagnostics: "origin lacks feature" | +| v1 | new | No header ⇒ unchanged v1 catalog, frames and RPCs (C/H test with a recorded v1 client covering Browse, GetMetadata, Read, Subscribe) | +| new | new, grant missing | Per-item `BadUserAccessDenied` / condition items not admitted | +| pair mid-upgrade | — | Cluster selection re-probes capabilities per endpoint; history CPs and condition streams are incarnation-bound, so a failover onto an older binary drops the feature (`BadContinuationPointInvalid`; condition quality Bad, then RefreshRequired) | + +--- + +## 5. Alarm/event forwarding — redesigned semantics + +### 5.1 Origin condition hub (B2) + +- **Tap:** a new SDK-free callback raised from `ReportConditionEvent` (`NM:1540`), the single point where every + condition event is reported: driver/engine projections (`NM:1418`, `:1505`), method wrappers including SDK-applied native acks + and comment-only reports (`NM:3034`), rebuild carry-over (`NM:5650`). It is invoked under `Lock` with an immutable record: + - snapshot fields, Retain, comment, ClientUserId, Time, condition class and quality; + - a per-condition `version` (monotonic within the serving incarnation) and `occurrence`. + + The callback only enqueues into a bounded `ConditionStateHub` partition (no I/O, never blocks; overflow ⇒ that partition's + epoch is invalidated ⇒ subscribers reset). Teardown (`ForgetPredefinedSubtree`) raises a removal record. +- `OpcUaPublishActor.AlarmStateUpdate` is **not** used as the tap: native acks applied by the SDK never pass through it + (`DriverHostActor.cs:2612-2637`). +- **A1 gate:** parity on **reported events**. For every reported condition event the hub must hold an identical record. A + local-client native ack on the origin is a required case; so are AddComment, scripted Confirm, ack-revert (#760), quality-only + updates and rebuild carry-over. + +### 5.2 Identity (B1, M7) + +- **One condition per (consumer node, connection, origin condition address)**, materialised in a **home mapping**: the first + mapping on that consumer node with the feature that catalogues the condition, ordered Raw realm before UNS, then mapping id + ordinal. +- Every other placement becomes **notifier wiring only**: other origin notifier folders in the same mapping, and the same + condition reached through another mapping. This covers both the within-mapping case (one native alarm referenced by two + equipment) and the cross-mapping case (Raw + UNS). It preserves the local model: one condition, extra notifiers, one + Server-object copy (Q4, settled). +- **NodeId:** mapped namespace of the home realm (`ProjectedDataIds.NamespaceUri(realm)`), identifier + `ProjectedDataIds.Identifier(homeMappingId, originConditionAddress)`. +- **Children (#629):** `/`, added as `ProjectedDataIds.ChildIdentifier`. Decoding splits at + the first `/`; the base64url alphabet has none, so the split is unambiguous. The mapped resolver classifies a child as + belonging to its condition's subject, so child Reads and method Calls are authorized like the condition + (`DataPlaneAuthorizer.cs:166-178` would otherwise deny them). +- **If the home mapping is disabled or loses the feature,** the condition is re-homed deterministically. That is a new NodeId, + so clients see a removal then an addition, and a RefreshRequired is emitted. Documented. +- **Fields:** + + | Field | Value | + |---|---| + | `ConditionId` / `SourceNode` | the projected condition NodeId (opaque) | + | `SourceName` | `/`, e.g. `Plant/remote-a` + `/` + `Plant/Modbus/dev1/HR200` | + | `ConditionName`, `Severity` (verbatim), `ConditionClassId/Name`, `Message`, `Time`, `Comment`, `ClientUserId` | from the origin record | + | `EventId` | consumer-minted | + + `SourceName` is human-meaningful and unique per consumer: anchor paths are unique locally, and origin SourceNames are unique + per origin cluster. **The local invariant "SourceName = ConditionId identifier" does not hold for imported conditions.** + Clients must key on `ConditionId`, which is what ScadaBridge's documented guidance already says. The ScadaBridge impact is + checked in the A4 exit gate. + +### 5.3 Mapped condition registry (B1) + +Projected conditions do **not** go through `MaterialiseAlarmCondition` or the `RealmKey`-keyed maps (`_alarmConditions`, +`_eventNotifierSources`, `_nativeAlarmNodeIds`), because `RealmOf` folds mapped namespaces into Raw/Uns. A new +`ProjectedConditionRegistry` keyed by full NodeId (namespace index included) does three things: + +- creates the `AlarmConditionState` through a factory that shares the field/child-id assignment code with + `MaterialiseAlarmCondition` (refactored into a common helper — no duplicate identity rules); +- wires notifiers symmetrically (the `WireAlarmNotifiers` pattern); +- applies stream records through a state-apply helper shared with `WriteAlarmCondition`, so the delta gate (#656 no-op re-statements) is the same code. + +### 5.4 Visibility and authorization (B4) + +- **Local permission:** an imported condition's events reach an item only if the item's caller passes the mapping gate for + `CreateMonitoredItems` (`DataOperations.Subscribe`) on **any** placement mapping that wires the condition. That is the same + permission local alarm visibility uses (`NM:6437-6442`). `NodePermissions.AlarmRead` is not used; it is not enforced + anywhere today. +- **The gate runs regardless of `AclEnforced`** in all three delivery paths: `OnConditionReportEvent` (Server object), folder + notifier delivery (`ProjectedEventDelivery`'s per-(session, identity) verdict cache) and `ConditionRefresh`. It is cached per + (session, identity, condition, authority generation). +- Event monitored items on projected notifiers and on the Server object are admitted through a verified path instead of the + blanket deny at `DataPlaneAuthorizer.cs:184-187` (event items only; data items keep v1's path). +- Queued event notifications carry the v1 publish-time authority marker so they are re-gated at Publish/Republish. **(inferred: + the SDK clones `EventFieldList` notifications the same way the v1 marker relies on for data notifications; X0 verifies, and if + not, A3 adds a final-send filter in the event queue.)** +- **Gate A3-SEC:** with `Security:Acl:Enabled=false`, a session without the mapping grant subscribed at `i=2253` and on a + projected folder receives **zero** imported events and zero on ConditionRefresh. A positive-control session with the grant + receives them, and an absence assertion follows a must-arrive sentinel. + +### 5.5 Stream demand, authority and budget (M4) + +- **Demand-driven:** a mapping's condition stream opens on the first admitted local event item that could see its conditions + (a projected notifier under the mapping, or the Server object when the caller holds the mapping's Subscribe grant). It closes + when the last such item goes, after a short linger (default 30 s) to absorb churn. + - Upstream it runs under the **connection service principal** (as v1 value demand does). Downstream delivery is re-gated per + local caller (§5.4). This item goes to the security review. + - A ConditionRefresh issued before the mapping's first `snapshot_complete` answers with what is materialised, then emits + `RefreshRequiredEventType` on the mapping's notifiers and to authorized Server-object items once the snapshot completes. +- **Budget:** each condition charges itself, its children (about 20 nodes) and any not-yet-materialised ancestor folders + against `MaxProjectionNodes`/bytes (`ReserveProjectedNode`) and against `MaxConditions`. Ancestors of a materialised condition + are pinned while it is. + - If the snapshot's set cannot be charged **in full**, the mapping's conditions go `Unavailable(ConditionCapacity)`: no + partial set (a partial set would make ConditionRefresh lie), a diagnostic, and RefreshRequired. +- **Queue class:** conditions use a non-coalescing bounded class inside the stream (priority control > condition > value). + Overflow ⇒ reset ⇒ fresh snapshot; a condition state is never silently dropped or merged. +- **Duplicates:** records with `version ≤` the last applied in an epoch are dropped. Across epochs the shared delta gate + suppresses unchanged re-statements. +- **Gaps:** intermediate transitions during an interruption are lost; state converges. Origin alarm history is the record (event + history over the wire is deferred, §7). +- **Disconnect:** after `ConditionStaleTimeoutMilliseconds`, every condition of the mapping gets `Quality = BadNoCommunication` + (an annotation only, #477) with one event; methods answer `BadNoCommunication`. +- **Resync:** a new epoch ⇒ full snapshot ⇒ reconcile. Conditions missing from a **complete** snapshot get Retain=false and are + retired; changed ones produce one event. If the resync is incomplete ⇒ RefreshRequired. + +### 5.6 Methods: no `Lock`, no local apply before the owner confirms (B3, B5, m5, M8) + +**Consumer** (option 1 of the review): + +1. The node manager's `Call` handling **partitions projected-condition method requests** (object = a registry condition, method = + an Acknowledge/AddComment/Confirm declaration id) **before any node-manager `Lock` is taken and before base dispatch**. + Projected conditions get no SDK `OnAcknowledge`/`OnConfirm`/`OnAddComment` handlers that apply state, and are never wrapped + by `ReportAfterMethod`. **(inferred: the override point. `CustomNodeManager2.Call` is virtual, and the SDK 2.0 line may offer + an async call path that X0 must check first; X0 also records whether the base takes `Lock` before our partition, in which case + the partition moves into an `INodeManager`-level `Call` override.)** +2. Local checks, no I/O and no `Lock`: + - mapping gate with `AlarmOperationFor(method)` on a placement mapping; + - per-call key re-check (`AuthorizeKeyUsable`, #563); + - method in `supported_methods` (native Confirm ⇒ `BadNotSupported`, unsent); + - Warm Standby refusal (same rule as `NM:3122-3124`); + - **EventId:** must be one this consumer minted for that condition within its last N (default 8) events — a small registry + with its own short lock. Unknown ⇒ `BadEventIdUnknown`. The matching record's `occurrence` becomes `expected_occurrence`. + No origin EventId exists on the wire (m5). +3. A bounded remote `CallConditionMethod` on the request thread. Timeout = min(request deadline, `ConditionMethodTimeout`, + default 5 s). A per-node semaphore (default 8 concurrent) stops these calls exhausting SDK request threads; excess ⇒ + `BadTooManyOperations`. +4. The consumer returns the origin's status and **does not touch local condition state**. The origin applies and reports the + change, the hub streams it, and the consumer applies it through §5.3 and reports one consumer event. A later revert at the + origin (#760/#869) arrives the same way. + - Outcome mapping: scripted applied ⇒ Good; native ⇒ Good (`AcceptedUnconfirmed` in diagnostics); `RejectedBeforeDispatch` + ⇒ the origin's status; transport loss after send ⇒ `BadCommunicationError` with `OutcomeUnknown` in diagnostics. + - **No retry anywhere.** Duplicate `operation_id`s join in the origin's operation registry. + - The client may see Good before the confirming event arrives. Documented, as for v1 writes. +5. **Lock-freedom gate (A3):** stall the origin's method handler for 5 s. A concurrent Read, Browse and data Publish on the + consumer must complete in under 200 ms. A local client must observe no acknowledged state before the origin's record arrives + (positive control: the state does arrive after release). + +**Origin:** a new session-less node-manager entry point, `TryExecuteConditionMethod(realm, conditionId, method, comment, +expectedOccurrence, principal, audit)`. Both it and the SDK path are factored out of `HandleNativeAlarmAck` + +`ReportAfterMethod`, so neither goes around the other. It: + +- takes `Lock`; +- runs the same gate: the export bit (checked at ingress), the origin ACL via `EvaluateAlarmCommandGate` semantics for the + service principal, the Primary gate (`NativeAlarmAckPrimaryGate`), Warm Standby refusal, native preflight + (`NativeAlarmAckPreflight`); +- checks the occurrence precondition (moved ⇒ `BadEventIdUnknown`); +- for **native**: applies Ack + the Confirmed/Retain re-assert + the comment to the `AlarmConditionState`, reports once, then + invokes the existing non-blocking `NativeAlarmAckRouter`, so `DriverHostActor`'s "already acknowledged / revert on failure" + contract holds unchanged; +- for **scripted**: publishes `AlarmCommand` (the AdminUI `/alerts` path) and returns Good on admission; +- releases `Lock` and returns. + +Remote condition methods are additionally **Primary-only for scripted conditions**: `DataCapabilitiesProvider` strips the alarm +method bits off-Primary, and ingress re-checks before dispatch. Condition state streaming is Primary-only by default (a Warm +standby runs no native drivers). + +**A2 gate:** the **origin's own** OPC UA subscribers see exactly one ack event for a remote native ack. A driver failure +reverts it on both origin and consumer. A remote AddComment on a native condition stores the comment. + +### 5.7 What the consumer does not do with imported conditions (Q3, settled) + +- no publication to the `alerts` topic (so no consumer alarm history and no `/alerts` rows; counts and stream state appear in + data-connection diagnostics only); +- not fed to `NativeAlarmProjector`; +- no local shelving timers; +- only nodes in the mapping's `ConsumerNodeIds` mirror state, each independently (consumer redundancy is covered in A4). + +--- + +## 6. Security, configuration and authoring + +**Grants (all default OFF):** + +- Connection, export and mapping `AllowedOperations` gain the §4.2 bits. +- Local visibility uses the existing Subscribe grant on the `RemoteNamespaceMapping` scope; local methods use + `NodePermissions.AlarmAcknowledge`/`AlarmConfirm` on that scope; history uses `NodePermissions.HistoryRead` on that scope. All + 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.)** + +**Audit (M8):** + +- `on_behalf_of` is capped at 128 characters, stripped of control and format characters, and stored in a **separate** audit + field: a new optional `AlarmCommand.RemoteAuditText`, plus the origin's data-connection audit log. +- `AlarmCommand.User` / ClientUserId is the service principal only, never concatenated with remote text. +- AdminUI and alarm-history renderers display `RemoteAuditText` as plain text. + +**Schema** — each migration lands in the first phase that needs it (M6). Columns are non-null with defaults; no backfill. + +| Phase | Migration | Changes | +|---|---|---| +| H2 | `AddDataConnectionHistory` | `DataConnection.HistoryTimeoutMilliseconds` (30000); `DataExport.MaxConcurrentHistoryReads` (4), `MaxHistoryValuesPerPage` (10000), `MaxHistoryResponseBytes` (4 MiB); `RemoteNamespaceMapping.MaxHistoryAssemblyBytesPerRequest` (16 MiB) | +| A2 | `AddDataConnectionConditions` | `DataExport.MaxConditions` (10000), `AllowGalaxyServiceAck` (false); `RemoteNamespaceMapping.MaxConditions` (10000), `ConditionStaleTimeoutMilliseconds` (30000), `ConditionMethodTimeoutMilliseconds` (5000) | + +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`. + +**AdminUI** (`ClusterDataConnections.razor`, editor models, `DataConnectionDiagnostics`): + +- operation checkboxes and limit fields arrive in the phase that adds the bits (H2, A2); +- diagnostics follow in H4/A4: negotiated features; history counts by status class; open remote continuations; condition + stream state, snapshot time, count, capacity state, RefreshRequired count; method outcomes; dropped-unknown-bit count; +- every AdminUI task ends with a docker-dev `/run` drive (no bUnit; login disabled on the rig). + +**Metrics** (no ids in labels): `otopcua.dataconn.history.reads{variant,status_class}`, `…history.continuations.active`, +`…conditions.items`, `…conditions.resyncs`, `…conditions.refresh_required`, `…conditions.capacity_rejections`, +`…condition_methods{method,outcome}`, `…operations.unknown_bits_dropped`. + +--- + +## 7. Deferred within these capabilities (not planned here) + +- **HistoryReadEvents on mapped notifiers.** It needs §5.2 identity first. The wire row is defined from + `HistoricalEvent(EventId, SourceName, EventTimeUtc, ReceivedTimeUtc, Message, Severity, EventTypeName, ConditionName, AlarmId, + ConditionReference)` (`HistoryReadContracts.cs:194-204`), not invented fields. Where-clauses: only `OfType` conjunctions are + forwarded. Plan it after A4. +- **Modified-value reads:** a niche read once HistoryUpdate is out remotely. +- **Shelve/Unshelve/Enable/Disable:** after A4 has proven §5.6. The bit layout is already reserved. + +--- + +## 8. Relay — deferred to a separate design + +Relay (re-export of imported branches, multi-hop, read-distribution nodes) is **out of this plan**. A separate design may start +only after G0 (#915) and after this plan's A phase. It must resolve, at least: + +1. **Origin == expected-cluster binding.** v1 binds an address's origin cluster to the serving/expected cluster at: + - export side: `Runtime/DataConnections/LocalExportCatalog.cs:42-48` (rejects a non-local or projected node) and `:53` + (forces the local cluster id); + - consumer side: `RemoteNamespaceResolver.cs:193,251,334`, `GrpcDataConnection.cs:302` (browse provenance) and `:251-256` + (`Verify` serving identity), `ConfiguredProjectionDiscovery.cs:31`. + + Recommended starting point (from the review): **re-addressing**. For a downstream consumer the relay is the origin of its + relay export, and the true origin appears only in a provenance chain. That keeps every site above intact. Relaxing the binding + instead touches all of them and needs its own security review. +2. **Loop key.** Same-cluster node-to-node hops are legal in v1, so a chain may contain one cluster id twice. The loop key must be + `(cluster, export id)` or `(cluster, node, mapping)`, never the cluster alone. Use static cycle detection across every cluster + present in a draft (the validator already reads other clusters' mappings, `DataConnectionValidator.cs:246`), plus a runtime + check for fleets with separate ConfigDbs. Both validator sites change: the consumer-mapping ban (`:246-247`) and export + ownership (`:265-266`, `KindInRealm`). +3. **Hop cap 2** (default 1) until the partitioned-revocation bound (Σ per-hop lease bounds) has been measured. Writes and + condition methods still execute only at the origin's active Primary, with no replay at any hop. + +--- + +## 9. Phases + +### 9.1 Execution model + +Mirror the v1 plan: + +- the coordinator owns contracts, shared files, test runs and commits; +- at most two disjoint implementers plus an independent reviewer, with review at each contract freeze and at each + security/mutation boundary; +- red/green per task, and phase gates via `scripts/validation/grpc-data/run-unit-phase.py ` with new manifest keys + (X0, H1–H4, A1–A4) and traits `[Trait("Feature","GrpcData")] [Trait("Phase","H1")]`; +- no timing widening or skips; +- commit explicit owned paths only, and leave the unrelated AB CIP fixture edits alone; +- serialize edits to the proto, `DataContracts.cs`, NM, `DataConnectionValidator.cs`, the model snapshot and `unit-phases.json`. + +Project keys are the v1 plan's (A, C, F, K, R, O, H, P, U, L), plus `OpcUaServer.IntegrationTests` (OI). + +Deployability: X0 is a release of its own. H2, H3 and H4 each deploy and are usable alone: H2 gives runtime consumers direct +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) + +- **Tasks:** + 1. Mask-tolerant readers at the five M1 sites (§4.3). + 2. Feature-header plumbing on every RPC: server records the per-call feature set (empty today). + 3. Reserve proto fields 14–17 / 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 `Call` override point and lock behaviour (§5.6); + - `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). + 5. Manifest keys. +- **Files:** `DataConnectionDeploymentRuntime.cs`, `DataContracts.cs`, `DataProtoMapper.cs`, `GrpcDataConnection.cs`, + `Host/Grpc/DataConnectionGrpcService.cs`, `Commons/Protos/{data_connection.proto,DataConnectionProtoContract.cs}`, + `scripts/validation/grpc-data/unit-phases.json`. +- **Tests:** + - R: an artifact with an unknown bit on one row ⇒ that row loses the bit, other connections unaffected (old code threw for + the whole snapshot); + - A: capabilities with unknown bits ⇒ masked; + - C/H: a recorded v1 client vs the X0 server, all RPCs byte-identical behaviour; header absent ⇒ no new shapes. +- **Exit gate:** X0 manifest green; existing GrpcData P01–P09 manifest green; X0 evidence filed; contract review. Rollout note: + X0 must run on every node of both clusters before H2/A2 bits are authored. + +### Phase H — Remote history + +**H1 — Origin history port at override level.** +- Tasks: the port (§3.1); overrides become adapters; `PeerHistoryContinuationStore`; continuation re-keyed to + `(realm, identifier)`; `IDataHistoryService` in Abstractions. +- Files: NM, new `OpcUaServer/HistoryReadPort.cs`, `HistoryContinuationStore.cs`, `HistoryPaging.cs`, + `Abstractions/DataConnections/IDataServices.cs`. +- Tests: + - O: all existing history classes unchanged and green; + - `HistoryReadPortParityTests` (port vs override, same fake backend) with **required cases**: aggregate refused for the + node's type (#897), `SupportsAggregateFor` refusal, non-default aggregate configuration, modified+bounds ⇒ + `BadInvalidArgument`, value normalisation, end-only and reverse raw, bounds placeholders, uncapped raw, epoch bump ⇒ CP + invalid; + - paged-vs-unpaged fuzz over random tie series through the port (≥ 10k seeded cases); + - store tests for idle expiry, capacity eviction, principal/incarnation mismatch and single-use take. +- Exit gate: zero diffs in existing outcomes; fuzz clean; refactor review. +- Risk: regression in a tuned file. Mitigation: wrap, don't rewrite; nothing moves under `Lock`. + +**H2 — Wire, ingress, client, schema (first deployable increment).** +- Tasks: + - the `HistoryRead` RPC; `HistoryCapabilities` from `IHistorianDataSource`; `HistoryInfo` in catalog compilation (header-gated); + - codecs; + - ingress: `Ready(…, HistoryRead)`, then export grant, then origin ACL `HistoryRead` on the view (always on the ingress), then + tagname. Denied and unhistorized are indistinguishable. Per-principal admission and the response-byte cap; + - client: header gating, deadlines, `FailedPrecondition`/`Unimplemented` ⇒ unsupported; + - `LocalDataConnection` history for direct runtime consumers; + - **validator bit + `AddDataConnectionHistory` + artifact projection + AdminUI checkboxes/limits**. +- Files: proto/mapper, `Host/Grpc/DataConnectionGrpcService.cs`, + `Runtime/DataConnections/{LocalDataServices,LocalDataConnection,GrpcDataConnection,DataCapabilitiesProvider,LocalExportCatalog.Compilation}.cs`, + `Core/Authorization/DataOperationPolicy.cs`, `Configuration/{Entities/*,Validation/DataConnectionValidator.cs,Migrations/*}`, + `Runtime/Drivers/DeploymentArtifact.DataConnections.cs`, `AdminUI/DataConnections/*`. +- Tests: + - C codecs: status bits, absent timestamps, ns precision, absent start/end, aggregate configuration passthrough; + - H wire: denied vs unhistorized, admission ⇒ `BadTooManyOperations`, v1 peer and header-less caller, cancel not a backend + fault, lost page ⇒ `BadContinuationPointInvalid`; + - F validator + migration up/down; P artifact; U editor models. +- Exit gate: H2 manifest; Host wire suite; docker-dev smoke of a direct runtime-consumer read (harness probe). + +**H3 — Consumer OPC UA projection.** +- Tasks: projected `Historizing`/AccessLevel; `IProjectedHistoryAccess` (`ProjectedDataAccess.cs:157` allowlist extended); + overrides split local and projected handles; `HistoryCursorKind.Remote`; release forwarding on `releaseContinuationPoints` + and session close; mapping gate `HistoryRead`; per-request assembly budget. +- Files: NM, new `OpcUaServer/IProjectedHistoryAccess.cs`, new `Runtime/DataConnections/ProjectedHistoryAccess.cs`, + `OpcUaServer/Security/DataPlaneAuthorizer.cs`. +- Tests: O for allow/deny with ACLs on and off, resume after mapping revision change / lease expiry / failover / origin rebuild + epoch bump, consumer session close ⇒ origin continuations released (origin store count returns to 0), uncapped CP, assembly cap, + and `BadAggregateNotSupported` both ways. +- Exit gate: H3 manifest; OI end to end; docker-dev scenarios H01–H06 (below) on the **SqlServer and QuestDB** origin backends. + +**H4 — Gateway gate, diagnostics, docs (capability "supported").** +- Tasks: diagnostics; docs (`DataConnections.md`, `Historian.md` remote section, `Client.CLI.md` note); **required Gateway + leg**: an origin with `ServerHistorian:Backend=Gateway` against a local **read-only** HistorianGateway (`historian.md` + read-only gate recipe: `ApiKeys__Mode=Disabled`, `Historian__LiveWritesEnabled=false`) reading the real AVEVA Historian over + VPN. That needs no wonder-box remote command; SQL/historian access is allowed. Run H01–H04 on it, with the reverse/end-only and + ceiling-bounded cases. +- If the Gateway leg cannot run: file a `type:deploy-gate`, `blocked` issue. Remote history is then documented as supported + on SqlServer/QuestDB only, and the Gateway is listed as unverified. +- Exit gate: Gateway leg passed (or the issue filed and docs scoped accordingly); reviewer approval; docs; umbrella history + entry. + +**Scenarios** (`scenarios.json` rows, each restores baseline): + +| ID | Scenario | +|---|---| +| H01 | Raw paging with a tie cluster at a page boundary, Raw and UNS mappings | +| H02 | Processed with an aggregate the origin backend refuses for the node type | +| H03 | AtTime, integer node | +| H04 | Continuation across origin failover ⇒ `BadContinuationPointInvalid`, fresh read succeeds | +| H05 | v1 origin (pinned old image) ⇒ unsupported | +| H06 | Denied vs unhistorized indistinguishable; consumer session close releases origin continuations; origin rebuild mid-page | + +**Client CLI live gate.** Projected NodeIds are opaque `p1.` ids in `https://zb.com/otopcua/mapped/raw|uns`. Never type them; +resolve them by browsing from the mapping anchor (a local parent path + branch name): + +```bash +# 1. find the anchor under the local parent, then the projected leaf (NodeIds printed by browse) +otopcua-cli browse -u opc.tcp://localhost:4841/OtOpcUa -U apikey -P "$KEY" -n "ns=;s=Plant" -d 1 +otopcua-cli browse -u opc.tcp://localhost:4841/OtOpcUa -U apikey -P "$KEY" -n "" -r -d 4 +# 2. read history on the printed projected NodeId (ns index = mapped/raw's index in this server's NamespaceArray) +P='' +otopcua-cli historyread -u opc.tcp://localhost:4841/OtOpcUa -U apikey -P "$KEY" -n "$P" --start --end --max 7 +otopcua-cli historyread ... -n "$P" --aggregate TimeAverage --interval 60000 +# 3. the same window on the ORIGIN node (ns=;s=Plant/Modbus/dev1/Speed on the origin server) must match row-for-row +``` + +The harness (`cli_gate.py`) automates step 1 by BrowseName walk, as the D-series scenarios already resolve projected ids. +Expected: identical rows/status/timestamps to the origin; continuation followed to completion; a denied key ⇒ +`BadUserAccessDenied`; unhistorized ⇒ `BadHistoryOperationUnsupported`. + +### Phase A — Alarm/event forwarding + +**A1 — Origin hub, identity primitives, catalog (header-gated).** +- Tasks: the `ReportConditionEvent` callback and `ConditionStateHub` (§5.1); `occurrence`; condition catalogue entries emitted + **once** at their home address with `notifiers` (§5.2), only for callers that negotiated `conditions` **and** hold + `AlarmSubscribe` on the export (header-less callers keep the v1 shape); `ProjectedDataIds.ChildIdentifier` + decode. +- Files: NM (callback only), new `Runtime/DataConnections/ConditionStateHub.cs`, `LocalExportCatalog*.cs`, + `LocalCatalogCoordinator.cs`, `Abstractions/DataConnections/ProjectedDataIds.cs`. +- Tests: + - R/O reported-event parity (§5.1 cases, the local-client native ack required); + - version/occurrence monotonicity; + - catalogue: one native condition referenced by two equipment ⇒ one entry with three notifiers; + - A: child id round-trip; ids with `/` in the origin path still decode. +- Exit gate: A1 manifest; reviewer sign-off on the source inventory. + +**A2 — Wire and origin execution.** +- Tasks: condition items on Subscribe (arm 9, non-coalescing class, `snapshot_complete`); `CallConditionMethod`; + `TryExecuteConditionMethod` (§5.6 origin); Primary/standby; operation registry; audit sanitising; + `AllowGalaxyServiceAck`; **validator bits + `AddDataConnectionConditions` + artifact + AdminUI checkboxes**. +- Files: proto/mapper, `Runtime/DataConnections/{DataSubscriptionSession,DeliveryScheduler,LocalSubscriptionService,LocalDataServices,WriteOperationRegistry,DataCapabilitiesProvider}.cs`, + `Host/Grpc/DataConnectionGrpcService.cs`, NM (entry point factored from `HandleNativeAlarmAck`/`ReportAfterMethod`), + `OpcUaServer/NativeAlarmAck.cs`, `Commons/OpcUa/AlarmCommand.cs` (`RemoteAuditText`), + `Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs`, Configuration and AdminUI files. +- Tests: + - H wire: + - remote native ack ⇒ the **origin's own** subscribers see exactly one ack event; + - driver failure ⇒ revert seen on origin and in the stream; + - native AddComment stored; + - off-Primary / Warm Standby ⇒ `RejectedBeforeDispatch`; + - Galaxy without opt-in ⇒ `BadUserAccessDenied`, no state change; + - occurrence moved ⇒ `BadEventIdUnknown`; + - duplicate operation id joins; + - transport drop ⇒ `OutcomeUnknown`, no retry; + - audit text sanitised and separate; + - R: stream priority, overflow ⇒ reset, revocation mid-snapshot, header-less stream never receives arm 9; + - F/P/U as in H2. +- Exit gate: A2 manifest; security/mutation review (includes the standing-principal question in §5.5). + +**A3 — Consumer registry, visibility and methods.** +- Tasks: `ProjectedConditionRegistry` (§5.3); home mapping and notifier wiring (§5.2); event items on projected notifiers and + the Server object (§5.4); demand-driven streams and budget (§5.5); method interception (§5.6 consumer); 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`. +- Tests (O over the wire, `ConditionMethodEventTests` / `NativeAlarmEventIdentityFieldDeliveryTests` patterns): + - exactly one event per origin transition at the folder and at `i=2253`, also when the condition has two placements; + - identity fields per §5.2; + - child Read/Call authorized via the condition; + - **A3-SEC** (§5.4); + - **lock-freedom** (§5.6 step 5); + - no local apply before origin confirmation; + - unknown EventId ⇒ `BadEventIdUnknown` unsent; + - native Confirm ⇒ `BadNotSupported` unsent; + - capacity ⇒ `Unavailable(ConditionCapacity)`, no partial set; + - home-mapping disable ⇒ re-home + RefreshRequired; + - resync with no event for unchanged state, followed by a must-arrive real transition (#656 positive control). +- Exit gate: A3 manifest; SDK/security review. + +**A4 — Diagnostics, docs, docker-dev and live gates.** +- Tasks: diagnostics; docs (`DataConnections.md`, `AlarmTracking.md` "Imported conditions", `ScriptedAlarms.md`, + `security.md`); scenarios A01–A08. + +| 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 | +| A03 | Origin failover mid-stream ⇒ resync, no duplicate events, positive control | +| A04 | One native alarm referenced by two equipment + a Raw mapping ⇒ one consumer condition, three notifiers, one `i=2253` event | +| A05 | ACLs off, session without mapping grant at `i=2253` ⇒ zero imported events (with positive control) | +| A06 | Consumer Primary change with clients connected to both consumer nodes ⇒ both converge, no duplicates | +| A07 | Consumer node restart ⇒ ConditionRefresh correct after snapshot; RefreshRequired observed if refresh preceded snapshot | +| A08 | Revoke `AlarmAcknowledge` at origin ⇒ method denied, state still streams; no consumer `alerts`/alarm-history rows | + +**Client CLI live gate** (resolve ids by browsing; projected ids are opaque): + +```bash +# 1. browse from the UNS anchor to the projected equipment folder (mapped/uns namespace) +otopcua-cli browse -u opc.tcp://localhost:4841/OtOpcUa -U apikey -P "$KEY" -n "ns=;s=assembly" -d 1 +otopcua-cli browse -u ... -n "" -r -d 3 # note the projected equipment folder NodeId F +# 2. subscribe to its events with refresh; each notification prints ConditionId (projected) and EventId +otopcua-cli alarms -u ... -U apikey -P "$KEY" -n "$F" --refresh +# 3. act on the printed ConditionId / EventId +otopcua-cli ack -u ... -n "" -e -c "remote ack" +otopcua-cli comment -u ... -n "" -e -c "note" +otopcua-cli confirm -u ... -n "" -e +# 4. concurrently `otopcua-cli alarms` on the ORIGIN shows the same transition once (origin ConditionId = RawPath / ScriptedAlarmId) +``` + +Use two-state id selection via `SimpleAttributeOperand(type, [X, Id])`, as the CLI does; never `"X/Id"`. + +- **Exit gate:** A01–A08 pass with baseline restoration; reviewer approval; docs; **ScadaBridge consumer-impact check** + recorded in `sister-project-history/otopcua.md`: + - `SourceName` shape `/`; + - `ConditionId` opaque and stable while the home mapping is unchanged; + - native `ConfirmedState = true` re-assert preserved; + - severity verbatim; + - RefreshRequired handling. + +### 9.2 Risk register + +| Risk | Phase | Mitigation | +|---|---|---| +| History refactor regresses local HistoryRead | H1 | Override-level port, parity cases from M3, fuzz | +| Old nodes reject artifacts with new bits | X0 | Tolerant readers ship first; author bits only after X0 is everywhere | +| v1 clients fault on new shapes | X0/A1 | Per-call feature header; header-less = v1 shape | +| Imported alarms leak with ACLs off | A3 | Gate independent of `AclEnforced`, A3-SEC + A05 | +| Remote wait freezes the address space | A3 | Interception before `Lock`, semaphore, lock-freedom gate | +| Remote ack is a no-op at origin | A2 | Session-less entry factored from the SDK path; origin-subscriber assertion | +| Partial condition sets make ConditionRefresh lie | A3 | All-or-nothing capacity, RefreshRequired | +| v1 unsoaked in service (G0 deferred, #915) | all | Per-phase live gates; deploy notes record the risk until #915 passes | + +--- + +## 10. Open questions for the owner + +Settled by this revision: Q1 (HistoryUpdate out), Q3 (no consumer `/alerts`/alarm history), Q5 (ReadyReplica history +allowed, Primary default), Q2 (service-principal attribution, with a separate Galaxy opt-in and sanitised audit text), Q4 (one +condition with extra notifiers), Q6 (relay deferred, §8), and G0 (the 14-day soak is deferred to #915, not a blocker). + +Remaining: + +1. **Standing upstream authority for condition streams (§5.5).** Do you accept that a condition stream, once opened by a local + subscriber, runs upstream under the connection's service principal (re-gated per local caller on delivery)? The alternative + is to make condition visibility per local caller end to end, which needs delegated identity. +2. **Re-home behaviour (§5.2).** When the home mapping is disabled, do you accept a NodeId change (removal + addition + + RefreshRequired)? The alternative is to reject disabling a home mapping while another mapping still places its conditions. 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 new file mode 100644 index 000000000..0ab805087 --- /dev/null +++ b/docs/plans/2026-11-23-grpc-data-connections-history-alarms-relay-plan-review.md @@ -0,0 +1,544 @@ +# Review: gRPC data connections — remote history, alarm/event forwarding and relay plan + +Date: 2026-11-23 +Reviewed: [`2026-11-23-grpc-data-connections-history-alarms-relay-plan.md`](2026-11-23-grpc-data-connections-history-alarms-relay-plan.md) ("the plan") +Baseline: `649f2ecd2` (same commit the plan cites). Independent review; every claim below was checked against `src/`, +not against the plan's §3 evidence table. No code, plan or issue was changed. + +Path shorthand follows the plan: `OpcUaServer/` = `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/`, +`Runtime/` = `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/`, `Host/` = `src/Server/ZB.MOM.WW.OtOpcUa.Host/`, +`Commons/` = `src/Core/ZB.MOM.WW.OtOpcUa.Commons/`, `Abstractions/` = `src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/`, +`Configuration/` = `src/Core/ZB.MOM.WW.OtOpcUa.Configuration/`, `Core/` = `src/Core/ZB.MOM.WW.OtOpcUa.Core/`. +`NM` = `OpcUaServer/OtOpcUaNodeManager.cs`. + +## Verdict + +**Rework** for Phase A (alarms) and Phase R (relay); **approve with changes** for Phase H (history). + +The history design is sound in shape (origin serves through its own pipeline, opaque origin-bound continuation) and most +of its evidence is accurate. The alarm design rests on a tap point and an execution path that do not carry what the plan +says they carry, reuses an SDK seam that holds the node-manager `Lock`, and inherits a delivery path that is unfiltered +with ACLs off. The relay design contradicts an identity invariant that v1 enforces in at least six places and that the +plan does not inventory. Separately, the plan's projected-identity model (§6.2, both live-gate recipes) is wrong about +how v1 names projected nodes. + +Recommended split: ship H as its own approved plan after fixing M1–M6; return A and R for redesign of the sections named +in B1–B6. + +## What was verified as correct + +So the findings below are read in proportion — these plan claims hold at `649f2ecd2`: + +- `DataOperations` bits and the `int` columns (`Abstractions/DataConnections/DataContracts.cs:229`; migration lines 42/77/118). +- `AllowsMappedOperation` fails closed for everything but Browse/Read/Write*/Subscribe (`Core/Authorization/DataOperationPolicy.cs:80-88`). +- Blanket mapped `CreateMonitoredItems` deny (`OpcUaServer/Security/DataPlaneAuthorizer.cs:184-187`). +- HistoryRead on mapped nodes is authorized even with ACLs off: `SecurityFilteringActive` is true whenever a mapped + resolver is installed (`NM:837`), so `AuthorizeHistoryRead` (`NM:8757-8787`) does reach the mapped gate. +- History runs outside `Lock` (`NM:8722-8725` comment); history line references (8791/8842/8916/9001/10083/10191) are accurate. +- `TryGetHistorizedTagname(string, out, AddressSpaceRealm)` is public at `NM:949`. +- `Write` is stripped off-Primary (`Runtime/DataConnections/DataCapabilitiesProvider.cs:28`). +- Native ack Primary gate wiring (`OpcUaServer/OtOpcUaSdkServer.cs:141`, `Host/OpcUa/OtOpcUaServerHostedService.cs:352`). +- Every file the plan names exists; the Client.CLI options used in the recipes exist + (`HistoryReadCommand.cs` `--modified/--events/--of-type/--aggregate/--interval`, `AcknowledgeCommand.cs -e`, `ShelveCommand.cs --kind/--duration`). +- Harness: `unit-phases.json` has P00–P12, `scenarios.json` has D01–D14. + +--- + +## Blockers + +### B1 — Projected identity is not what the plan says (§6.2, §5.4, H5 and A4 live gates) + +**Problem.** The plan says a projected condition's NodeId is "the projected local identity in the mapping's realm +namespace (mapping prefix + origin-relative path), like projected variables", sets `SourceName` to "the projected local +identifier string", and writes live gates against `ns=;s=Plant/remote-a/Modbus/dev1/Speed` and +`ns=;s=assembly/remote-line-2/filler`. + +**Evidence.** Projected nodes do not live in the Raw/UNS namespaces and are not path-shaped: + +- `Abstractions/DataConnections/ProjectedDataIds.cs:8-11,47-57` — two dedicated namespaces + (`https://zb.com/otopcua/mapped/raw`, `…/mapped/uns`) and identifier = `"p1." + base64url(JSON{MappingId, Origin})`. +- `NM:106-107` — `IsProjectedDescendant` = namespace index `NamespaceIndexes[2]` / `[3]`. +- `NM:4883-4885` — `TryEnsureProjectedVariable` rejects any definition whose identifier does not decode to + (mapping, origin address). + +Consequences the plan does not address: + +1. `SourceName` = an opaque base64 blob on every imported alarm. ScadaBridge and operators key on `SourceName`. +2. Condition children are `{ConditionId}/{browse path}` (#629, `.claude/rules/alarms.md`). `p1./ShelvingState/…` + does not decode, and the mapped authorizer denies any mapped-namespace id its resolver cannot classify + (`DataPlaneAuthorizer.cs:168-178`), so every child Read/Call would be denied. +3. `MaterialiseAlarmCondition(…, AddressSpaceRealm realm, …)` mints in `NamespaceIndexForRealm(realm)` (`NM:2410`) — the + **local** Raw/UNS namespace. `AddressSpaceRealm` has only `Raw`/`Uns`, and `RealmOf` folds mapped index 2 into `Raw` + and 3 into `Uns` (`NM:283-284`), so the `RealmKey`-keyed maps (`_alarmConditions`, `_eventNotifierSources`, + `_nativeAlarmNodeIds`) cannot tell a local id from a mapped one. A3's "materialise via the existing + `MaterialiseAlarmCondition`/`New`" is therefore not available as written. +4. Both CLI recipes fail at the first command. + +**Fix.** Add an explicit identity section before any A work: (a) the mapped-namespace encoding for a condition and its +children (extend `ProjectedDataIds` with a child-path component and teach the mapped resolver to scope children to their +condition); (b) a human-meaningful `SourceName` rule (recommend `/`, not the +NodeId string — the "SourceName = ConditionId identifier" invariant cannot survive opaque ids and the plan should say +so and record the ScadaBridge impact); (c) a mapped-aware condition registry instead of reusing the realm-keyed maps; +(d) rewrite both live-gate recipes to resolve NodeIds by browsing from the mapping anchor. + +### B2 — The condition hub's tap point misses real transitions and cannot supply half the wire fields (§6.1, §4.2 `ConditionState`, A1) + +**Problem.** The plan taps `OpcUaPublishActor.AlarmStateUpdate` and says the hub holds "the latest +`AlarmConditionSnapshot` + event metadata (time, message, origin EventId, last comment/user)". + +**Evidence.** + +- A **native acknowledge made by a local OPC UA client on the origin never produces an `AlarmStateUpdate`.** The SDK + handler applies the state on the node (`NM:3198-3202`, "Good ⇒ the SDK applies the node-state change") and + `DriverHostActor` only tells the projector and routes to the driver — "success sends nothing back" + (`Runtime/Drivers/DriverHostActor.cs:2612-2637`). The hub would keep showing the condition unacknowledged; a remote + consumer would never see a local operator's ack. +- Method-driven transitions are reported from `ReportAfterMethod` inside the node manager (`NM:3003-3037`), including + comment-only reports (`alwaysReport`). None of that passes through `OpcUaPublishActor`. +- `AlarmConditionSnapshot` (`Commons/OpcUa/AlarmConditionSnapshot.cs`) has no Retain, EventId, comment, user, time or + restatement flag. Retain is computed in the node manager (`NM:3024`), the EventId is minted by the SDK at report time + and suppressed by the delta gate. Proto fields `origin_event_id`, `retain`, `last_comment`, `last_user`, + `is_restatement` cannot be populated from the chosen tap. + +A1's inventory ("native, scripted, ack-revert, quality-only, deferred replay, rebuild, teardown") omits the +SDK-applied method path entirely, and its parity test ("every `AlarmStateUpdate` reaches the hub") would pass while the +defect ships. + +**Fix.** Tap the node manager's single report choke point (`ReportConditionEvent` / the per-condition `OnReportEvent` +hook at `NM:7158`) through an SDK-free callback carrying the post-report state, Retain, comment and EventId. Gate A1 on +a parity test of *reported events*, not of `AlarmStateUpdate` messages, with a local-client native ack as a required case. + +### B3 — Remote native ack "through the same route" does not acknowledge anything at the origin (§6.5, A2) + +**Problem.** "native ⇒ the same route the node manager's native ack uses (`NativeAlarmAckPreflight` → `RouteAlarmAck`)". + +**Evidence.** In the local path the *SDK* is what changes the condition (`NM:3200-3202`), writes the comment and causes +the one event; `HandleNativeAlarmAck` only gates and routes. `DriverHostActor` assumes the node is already acknowledged +(`DriverHostActor.cs:2612`, "The node is already acknowledged (the SDK applies the client's ack)") and on failure +*reverts* it. Driving only preflight + route from the data-connection ingress leaves the origin node unacknowledged, emits +no origin event, stores no comment, and makes a later driver failure "revert" a state that never changed. +`AddComment` on a native condition has no non-SDK path at all (`NM:2577`). + +Scripted is fine: `AlarmCommand` → engine → re-projection is the path AdminUI `/alerts` already uses. + +**Fix.** Add a session-less node-manager entry point (`TryAcknowledgeNative(conditionId, comment, principal)`) that takes +`Lock`, runs the same gate/Primary/standby/preflight sequence, applies Ack + Confirmed/Retain re-assert + comment to the +`AlarmConditionState`, reports once, then routes — i.e. factor `HandleNativeAlarmAck` + `ReportAfterMethod`, do not go +around them. A2 needs a wire test asserting the **origin's own** OPC UA subscribers see the ack event. + +### B4 — Imported conditions leak to every Server-object subscriber when ACLs are off; `AlarmRead` is not an enforced permission (§8.1, §6.5, A3) + +**Problem.** The plan requires a local `AlarmRead` grant on the mapping scope "even with `Security:Acl:Enabled=false`". + +**Evidence.** + +- `NodePermissions.AlarmRead` is declared (`Configuration/Enums/NodePermissions.cs:24`) and used only in the `ReadOnly` + bundle (`:38`). There is no `OpcUaOperation.AlarmRead` (`Abstractions/OpcUaOperation.cs`) and no enforcement site in `src/`. + Local event visibility is gated by `CreateMonitoredItems` on the notifier (`NM:6437-6442`). +- Server-object (`i=2253`) condition delivery is filtered only when ACLs are enforced: + `scopes = AclEnforced ? ConditionVisibilityScopes(node) : null` (`NM:7171`), documented as "Inert while + `Security:Acl:Enabled` is false — every item receives every condition" (`NM:7155-7156`). + +Reusing this path for projected conditions delivers every imported alarm (message, source, severity) to every session +subscribed at the Server object on an ACL-off consumer, with no mapping gate at all. `ConditionRefresh` has the same +shape. This breaks the v1 rule the plan itself cites (mapped nodes enforce the mapping gate regardless of the ACL switch). + +**Fix.** (a) Decide the local permission honestly: either reuse `CreateMonitoredItems`/`Subscribe` on the mapping scope +(what local alarms do) or introduce `OpcUaOperation.AlarmRead` with enforcement — do not cite an unenforced bit. +(b) Add a mapped-condition visibility check that runs **independently of `AclEnforced`** in `OnConditionReportEvent`, +folder delivery and `ConditionRefresh`. (c) A3 gate: with `Security:Acl:Enabled=false`, a session without the mapping +grant subscribed at `i=2253` receives zero imported events and zero on refresh (with a positive-control session that does). + +### B5 — Part 9 method handlers run under the node-manager `Lock`; the recommended "await bounded remote acceptance" would freeze the address space (§6.5, A3 risk) + +**Problem.** The plan recommends awaiting the remote call (≤ 5 s) because "the call runs outside the node-manager `Lock` +on the SDK's request thread". + +**Evidence.** The seam A3 reuses wraps every condition method in `lock (Lock) { … sdkHandler() … }` +(`NM:3003-3009`); `.claude/rules/alarms.md` states the pre-check "runs under the SDK `Lock`" and forbids I/O there; the +existing routers are explicitly "non-blocking by contract … safe to call under Lock" (`NM:3134`, `NM:3197`). A 5 s +network wait there blocks every read, write, browse and publish on the consumer. It is also semantically wrong: the SDK +handler would apply the ack **locally** and report a consumer event before the origin has agreed, contradicting "the +result event is reported only from the origin's state stream". + +**Fix.** Projected conditions need their own method handlers that never call the SDK's state-applying handler. Options, +in order of preference: (1) intercept `Call` for projected condition methods in the node manager's `Call` override before +any `Lock` is taken, run the bounded remote call there, return its status, and let the stream apply state; (2) +Good-on-acceptance with a consumer-side revert, mirroring #760. The plan must pick one and prove lock-freedom with a +test that holds a concurrent Read during a stalled method call. This is a design decision, not an A3 implementation detail. + +### B6 — Relay's "origin address unchanged end to end" contradicts an identity binding v1 enforces everywhere (§7.2) + +**Problem.** A relayed `View` keeps `origin_cluster_id = A` while consumer C's connection targets cluster B. + +**Evidence.** v1 binds the address's origin cluster to the serving/expected cluster on both sides: + +- Export side: `Runtime/DataConnections/LocalExportCatalog.cs:42` rejects a view whose `OriginClusterId` is not the local + cluster, `:53` forces it to the local cluster, `:48` does the same for the backing source key. +- Consumer side: `RemoteNamespaceResolver.cs:193`, `:251`, `:334` (`connection.Target.ExpectedClusterId` must equal the + address's origin cluster), `GrpcDataConnection.cs:302`, `ConfiguredProjectionDiscovery.cs:31`. +- Response serving identity must equal the selected endpoint's (`GrpcDataConnection.cs:251-256` `Verify`). + +None of this appears in the plan's evidence table or R1 file list. "Sharing keys include the full chain" and "hops +describe custody, not ownership" cannot be implemented without deciding which cluster an address names at each hop. + +**Fix.** Choose explicitly and re-derive §7: **re-addressing** (recommended) — for C, B *is* the origin of B's relay +export; B's export nodes are addressed by B's cluster id and a relay-export identifier, and A appears only in +`Provenance`. This keeps every v1 invariant above intact and makes relay a new export *source*, not a new trust model. +The alternative (relax the binding) touches all seven sites and needs its own security review before R1. + +--- + +## Major + +### M1 — Four hard-coded "known operations" masks; an old-binary consumer node rejects its whole data-connection snapshot (§3, §4.3, §8.2) + +**Evidence.** The plan lists only `DataConnectionValidator.cs:12,22`. Also: + +- `Runtime/DataConnections/DataConnectionDeploymentRuntime.cs:151-152` — `throw new ArgumentException("Unknown operation.")` + for **any** connection in the artifact carrying an unknown bit; the throw aborts the snapshot, not the row. +- `Abstractions/DataConnections/DataContracts.cs:271-276` — `DataCapabilities.Validate` throws on unknown bits. +- `Commons/DataConnections/DataProtoMapper.cs:1054-1062` — capability decode silently masks to the five v1 bits (benign). +- `DataProtoMapper.cs:284` — `Metadata.allowed_operations` is cast unmasked. + +So in a mixed-version consumer pair, deploying one connection with `HistoryRead` takes **all** data connections down on +the not-yet-upgraded node. §4.3's "rolling restart inside a pair" row covers the wire, not the artifact. + +**Fix.** Add a deploy gate: new bits may be authored only when every node in the connection's `ConsumerNodeIds` (and the +exporting cluster's nodes) reports a binary that understands them — or ship the mask-tolerant readers one release ahead +(X0) and document "upgrade all nodes before enabling". Add the three sites to H2/X0 file lists and a test that an +old-shape reader ignores rather than throws. + +### M2 — Unary RPCs have no negotiated feature set; catalog changes reach v1 consumers (§4.1, §4.3, §6.1) + +**Evidence.** `GetCapabilities` ignores the requested minor: the ingress returns `Math.Max(3, …)` +(`Host/Grpc/DataConnectionGrpcService.cs:26`), `LocalDataServices.cs:222` returns `Math.Max(5, …)`, and +`IDataConnection.GetCapabilitiesAsync(budget, ct)` has no minor parameter. Browse/GetMetadata carry only auth and target +headers (`GrpcDataConnection.cs:214-221`). The plan's "records the negotiated feature set per call" has nothing to record +from for unary calls. + +Effect: A1 emits `node_kind = "Condition"` and **stops exporting alarm-bearing raw tags as variables** for every +caller. A v1 consumer's `TryEnsureProjectedVariable` returns false for any kind other than Folder/Variable/Tag +(`NM:4887`); and a node it previously projected disappears. §4.3 row "v1 | new ⇒ Unchanged v1 traffic" is false for the catalog. + +The X0 "inferred" question is already answerable: a v1 client that receives a frame with neither `values` nor +`compact_values` calls `DecodeControlOrAck`, which throws `"Expected control or acknowledgement."` +(`GrpcDataConnection.cs:762-767`, `DataProtoMapper.cs:1207`) — the stream faults. Negotiated gating is mandatory. + +**Fix.** Negotiate by request header on every RPC, following the existing precedent (`CompactCodecHeader`, +`GrpcDataConnection.cs:548`) rather than a new `Open.features` field; emit Condition nodes and the variable removal only +to callers that declared the feature **and** hold `AlarmRead` on the export. Keep alarm-bearing raw tags in their v1 +shape for everyone else. Add a C/H test with a recorded v1 client against the new server for Browse, not only for frames. + +### M3 — H1's extraction list misses logic that lives in the SDK overrides (§5.1.2, H1) + +**Evidence.** The plan extracts "per-node cores of `ServeRawPagedAsync`/`ServeModifiedPagedAsync`/`ServeNodeAsync`/`ServeEventsAsync`". But: + +- All aggregate refusals — unknown aggregate, `HistoryAggregateDataTypes.AppliesTo`, `SupportsAggregateFor`, + `ServerAggregateConfiguration.IsServable` — are in the `HistoryReadProcessed` override body (`NM:8854-8902`), before + `ServeNodeAsync` is called. §5.1.4 promises exactly these at the origin. +- `NormalizeHistoryValues(nodesToProcess, results)` is a post-pass in the override (`NM:8839`, `:10826`). +- The modified-read `ReturnBounds` ⇒ `BadInvalidArgument` rule is in the override (`NM:8810-8817`). +- The batch limiter and deadline (`WithHistoryReadBatchLimiter`, `CreateDeadline(context)`) take SDK context. +- The serve functions take `NodeHandle`, `ISession`, `ArrayOf`, `IList` + (`NM:10191-10201`); `HistoryContinuationMatches` binds to `nodeId.ToString()` (`NM:10814-10815`), an SDK NodeId string. + +**Fix.** Define the port boundary at the override level (details in → per-node outcome out), not at the `Serve*` level, +and list the override-resident rules explicitly as parity cases. `HistoryReadPortParityTests` must include: an aggregate +the backend refuses for the node's type, non-default aggregate configuration, modified+bounds, and value normalisation. + +### M4 — An always-on condition stream is a new authority mode, and conflicts with the lazy, budgeted projection (§6.3, A3 risk) + +**Evidence.** v1 stream demand is derived from an authorized local caller and is withdrawn with it +(`docs/DataConnections.md` §"Subscription freshness and exact-item renewal"; `DataPlaneAuthorizer` mapped proof needs a +caller identity, `:180`). Projected nodes are created on demand under a node budget and retired when idle +(`NM:4909-4910` `ReserveProjectedNode`, `OpcUaServer/ProjectedNodeLifetime.cs`). The plan opens one stream per mapping +with no local caller and pins up to 10,000 conditions (plus ~20 children each, plus every ancestor folder) per mapping +outside that budget, mentioning it only as an A3 risk line. + +**Fix.** Specify: whose authority the standing stream runs under (the service principal alone — say so and have it +security-reviewed); the node charge of a condition subtree against `MaxProjectionNodes`; what happens when the charge is +refused (recommend: mapping `Unavailable(ConditionCapacity)`, never a partial set, because a partial set makes +ConditionRefresh lie); and whether ancestors of a pinned condition are pinned. Consider demand-driven instead: open the +condition stream on the first local event subscription under the mapping or at `i=2253`, close on last. + +### M5 — Relay loop rule rejects legitimate same-cluster hops; cross-cluster cycles are often visible at deploy time (§7.3, R4) + +**Evidence.** §7.3 rejects any item "whose provenance already contains its own cluster id". But same-cluster node-to-node +connections are a supported v1 mode (`docs/DataConnections.md` §"Routing and availability") and R4 proposes to "reuse a +same-cluster Node target as one hop" — that chain contains the cluster id twice by construction. Conversely the plan +says no single ConfigDb sees a cross-cluster cycle, yet the existing rule already reads other clusters' mappings from the +same draft (`DataConnectionValidator.cs:246`: `other.ClusterId == connection.ExpectedClusterId`). + +Also: the rule that actually blocks re-export is on the **consumer's mapping** (`:246-247`), and export validation +requires a local owner (`:265-266`, `KindInRealm` at `:141-146`). The plan describes relaxing the ban "for `RelayEnabled` +exports" only; both sites change. (The plan's citation `:110` is an unrelated comment line.) + +**Fix.** Loop key = `(cluster id, export id)` (or `(cluster, node, mapping)`), never cluster alone. Do static cycle +detection across every cluster present in the draft, and keep the runtime check for fleets with separate ConfigDbs. Name +both validator sites in R1. + +### M6 — History phasing: bits and limits are unusable until H5; the default backend is an optional gate (§9 H2–H5) + +**Evidence.** The validator rejects unknown bits (`DataConnectionValidator.cs:22,103,254,268`) and the migration plus +limits land in H5, so nothing from H2–H4 can be deployed on docker-dev until H5; the "independently shippable" H2/H3/H4 +gates are in-process only. The Gateway backend — the default, and the one with walk-backs, learned ceilings and missing +reverse support (`.claude/rules/historian.md` #686/#693/#694) — is "optional (needs the user)". Those are exactly the +behaviours argued in §2.1.2 for choosing design A. + +**Fix.** Move validator bits, migration and artifact projection into H2. Make a Gateway-backed origin leg a required gate +before the capability is documented as supported (the local read-only HistorianGateway recipe needs no wonder-box +command); if it cannot run, file it as a `type:deploy-gate` `blocked` issue rather than leaving it optional in prose. +Add scenarios: consumer session close ⇒ origin continuations released; origin rebuild (epoch bump) mid-page; a page +response lost in transit (origin `TryTake` is single-use, so the resume must fail `BadContinuationPointInvalid`, never +silently skip a page). + +### M7 — Duplicate conditions arise inside one mapping, not only across two (§6.1, §6.2, Q4) + +**Evidence.** §6.1 emits a native condition "under their raw tag's parent folder and (UNS) under each referencing +equipment". Locally that is **one** `AlarmConditionState` with extra notifiers and one Server-object copy (CLAUDE.md +"Native alarms"; `WireAlarmNotifiers` `NM:2782`). The plan's catalog turns it into N independent catalog nodes, hence N +projected conditions and N Server-object events per transition on the consumer whenever two equipment reference the tag — +with a single UNS mapping. Q4 frames this as a two-mapping corner case. + +**Fix.** Catalogue each condition once, in its home realm (native ⇒ Raw at its RawPath, scripted ⇒ UNS), and carry the +other placements only as `ConditionInfo.notifiers`. The consumer materialises one condition per (connection, origin +condition address) and wires notifiers to whichever projected folders exist — the local model, preserved. + +### M8 — Method/permission mapping and standby rules diverge from the origin's own (§4.1 bit table, §6.5) + +**Evidence.** Locally Enable/Disable and AddComment require `AlarmAcknowledge` (`NM:3285-3290`, the `_ =>` arm); the +plan places Enable/Disable under `AlarmShelve`. "The owner's ACL decides" then cannot hold: an export bit and the origin +ACL check name different permissions for the same call. The origin also refuses every condition method on a Warm Standby +(`NM:3122-3124`, `:3168`); the plan covers Primary but should state the standby refusal is reached too. The +`AlarmCommand.User` string is free text built from `on_behalf_of` — untrusted remote text concatenated into an audit +field that AdminUI and the alarm historian render. + +**Fix.** Derive the wire bit from `AlarmOperationFor` (one authority, shared code). Cap and sanitise `on_behalf_of` +(length, control characters) and keep it in a separate audit field rather than inside `User`. + +### M9 — Building on an undeployed v1 + +**Evidence.** `docs/plans/2026-11-15-grpc-data-connections-design.md:4` — "Not yet deployed" (merged today, `95c5e484`). +The plan adds three protocol minors, a new stream class and a relaxed safety invariant on a protocol with no production +soak, while wonder-box remote access is on hold. + +**Fix.** Make "v1 deployed and soaked on at least one real pair" an X0 entry criterion, or state explicitly that the +owner accepts stacking. If v1 is not deployed anywhere, the mixed-version matrix can also be simplified — say which. + +--- + +## Minor + +- **m1 — MAC'd tokens over a server-side store are redundant (§5.2).** State is held in a per-(principal, incarnation) + store keyed by a random id; binding principal/view/details-hash in the stored record does the same job. Either go + fully stateless (sealed token) or drop the MAC. Note `InMemoryHistoryContinuationStore` is a test double + (`OpcUaServer/HistoryContinuationStore.cs:108-123`, "production uses the SDK's own per-session store") with no idle + expiry — the evidence table reads as if it were ready for per-peer use. +- **m2 — Two release mechanisms (§4.2).** `ReleaseHistoryContinuations` RPC and `HistoryReadRequest.release_continuations`. Keep one. +- **m3 — `HistoryEventRow` lists fields `HistoricalEvent` does not have.** No Acked/Active flags, no ConditionId; it has + `EventTypeName`, `AlarmId`, `ConditionReference` (`Abstractions/Historian/HistoryReadContracts.cs:194-204`). + Define the row from the record. +- **m4 — `SubscriptionFrame` field 8 is taken** by `Serving` (`data_connection.proto`, `SubscriptionFrame`); new arms + start at 9, not "after 4–7". +- **m5 — Origin EventId round-trip is unnecessary (§6.1, §6.2).** The origin's non-SDK execution paths carry no EventId + (`AlarmCommand` has none). Let the consumer's own SDK condition validate the client's EventId locally, and send an + expected condition `version` as the staleness precondition. This deletes the bounded local→origin EventId map. +- **m6 — Galaxy attribution claim is stated as fact but unverified (§6.5).** The service principal does carry an + `ApiKeyId` (`Abstractions/DataConnections/IDataConnection.cs:19`), so the lookup is plausible, but whether a + data-connection credential is listable by `GalaxyAckIdentityDirectory` was not shown. Mark **(inferred)** and add to X0. +- **m7 — Processed/AtTime assembly (§5.2).** 16 MiB per node × batch parallelism per request is an unbudgeted consumer + allocation; bound it per request, not per node. +- **m8 — `ProcessedDetails.default_configuration` is computed by the consumer** against the consumer's server defaults; + the origin's `IsServable` is the authority. Send the configuration fields, or refuse at the consumer and never send. +- **m9 — Consumer redundancy is not gated in A.** A03 covers origin failover only. Add: consumer Primary change with + clients on both consumer nodes; and the #656 no-duplicate rule asserted with a positive control (a real transition + after the resync must arrive). +- **m10 — ScadaBridge is a consumer of these events** but appears only as a docs task in A4. Add a consumer-impact check + (SourceName shape, ConfirmedState on native, severity) to the A4 exit gate. +- **m11 — R2's revocation bound "Σ per-hop lease bounds"** grows linearly with hops while the hard cap is 4; state the + resulting worst-case number in the plan and let the owner accept it, or cap hops at 2 until measured. + +## Nits + +- §3 "≈ 11k lines": 10,951. Fine. +- §3 `DataPlaneAuthorizer.cs:183-187` is `:184-187`. +- `AddDataConnectionRelay` lists "`RootKind` accepts `RemoteNamespaceMapping`" as a schema change; the column is + `nvarchar(32)` with no check constraint (migration line 74) — validator-only. +- §9.2 traits `[Trait("Phase","H1")]`: confirm `run-unit-phase.py` accepts non-`Pnn` keys before adding them. +- Three minors (6/7/8) plus three capability messages plus per-RPC features is more negotiation surface than needed; the + capability messages alone suffice. + +## Scope to cut + +1. **Relay (all of Phase R)** — move to its own design after B6 is resolved and v1 has soaked. R3 (relayed writes, + history, condition methods) should not be planned until R1/R2 exist. +2. **H4 event history** — defer until alarm identity (B1) is settled; its `SourceName`/`ConditionId` rules depend on it. +3. **Modified-value reads over the wire** — HistoryUpdate is out of scope remotely, so the trail is a niche read; cut from H. +4. **Enable/Disable and Shelve for remote callers** in the first alarm cut — ship state + Acknowledge/AddComment/Confirm, + add the rest once B3/B5 are proven. +5. `is_restatement`, `ReleaseHistoryContinuations` RPC, token MAC, origin EventId map (see m1/m2/m5). + +## Open questions Q1–Q6 + +- **Q1 (HistoryUpdate / delegated identity).** Agree: keep out. The plan's four reasons are accurate against + `.claude/rules/historian.md`. Do not reserve anything for it. +- **Q2 (remote ack attribution).** Agree with service-principal attribution, with two conditions: it must be an explicit + per-export opt-in separate from `AlarmAcknowledge` for exports that contain Galaxy conditions (an ack account bound to + a machine credential is an operator-identity decision), and `on_behalf_of` must be sanitised and stored apart from + `User` (M8). Verify the directory lookup first (m6). +- **Q3 (consumer `/alerts`).** Agree: keep imported conditions off the `alerts` topic and the consumer's alarm historian. + Show counts and stream state in data-connection diagnostics only. +- **Q4 (same condition through two mappings).** Disagree with "allow with a warning". Materialise one condition per + origin condition per consumer node and wire additional placements as notifiers (M7). If that is deferred, reject + overlapping `AlarmRead` mappings at deploy — double Server-object events are not a warning-grade outcome for ScadaBridge. +- **Q5 (history from a ready replica).** Agree to allow it; it follows the connection's existing `Consistency`, and local + reads are ungated by role. Document the outbox-lag caveat and keep `Primary` the default. +- **Q6 (relay ordering and default).** Keep relay last and out of this plan. If it returns: default `MaxHops = 1`, hard + cap 2 until R2's partitioned-revocation bound has been measured. + +## Suggested path forward + +1. Approve Phase H after M1, M2 (header negotiation), M3, M6 and the cuts above; H1 can start immediately — it is a pure + refactor with a strong parity gate. +2. Return Phase A for a revised §6 covering B1–B5 and M4/M7/M8, with an X0 that also answers m6. +3. Drop Phase R from this document; reopen as a separate design once B6/M5 are decided and v1 is deployed (M9). + +--- + +## Second pass (2026-11-23) + +Reviewed: revision 2, [`2026-11-23-grpc-data-connections-history-alarms-plan.md`](2026-11-23-grpc-data-connections-history-alarms-plan.md) +(relay moved to its §8; G0 soak deferred by the owner to #915 — not re-raised here). Baseline still `649f2ecd2`. +Each closure below was checked against `src/`, not against the plan's §0 table. "Closed" means the design now matches the +code's constraints; nothing is implemented, so every closure still depends on the gate the plan names. + +### Updated verdict + +**Phase H: approve** (X0 + H1–H4 can start). **Phase A: approve with changes** — the six blockers are closed or reduced to +X0 investigations, but the rewrite introduced four Majors (N1–N4) that must be resolved in the plan before A1 starts. +No Blocker remains open. + +### Status of first-pass findings + +| Finding | Status | Evidence / remaining gap | +|---|---|---| +| **B1** projected identity | **Closed** for NodeIds, children, registry, SourceName and CLI recipes (§5.2, §5.3, H/A recipes browse from the anchor). `p1.` ids are base64url with `/`→`_` (`Abstractions/DataConnections/ProjectedDataIds.cs:57`), so the child split at the first `/` is sound. Two residual identity gaps are new findings N3 (cross-realm home) and N4 (home depends on stream order). | +| **B2** hub tap point | **Partially closed.** `ReportConditionEvent` (`NM:1540`) is the right choke point and its four callers are as listed (`NM:1418,1505,3034,5650`). But a hub fed only by reported events is not a complete state source — see **N1**. | +| **B3** origin native ack | **Closed.** `TryExecuteConditionMethod` applies + reports under `Lock`, then calls the non-blocking router, which is what `DriverHostActor.cs:2612-2637` assumes. A2 gate asserts the origin's own subscribers see the event. | +| **B4** ACL-off leak / `AlarmRead` | **Closed** in design: gate independent of `AclEnforced` in all three delivery paths, permission = `CreateMonitoredItems` (matches `NM:6437-6442`), A3-SEC + A05 with positive control. Publish-time re-gating is correctly left as an X0 item. | +| **B5** methods under `Lock` | **Closed, conditional on X0.** No SDK handlers, no `ReportAfterMethod`, no local apply. Supporting evidence the plan can cite: SDK 2.0.1 ships `ICallAsyncNodeManager`, `AsyncCustomNodeManager` and `OnCallMethod2Async` (symbols in `Opc.Ua.Server.dll` 2.0.1), so an async interception that does not hold a request thread is likely available; NM has no `Call` override today. If X0 finds the base takes `Lock` first, §5.6 is not implementable as written — keep the lock-freedom test as a hard A3 gate. | +| **B6** relay binding | **Closed by removal** (§8 records the seven sites correctly). | +| **M1** operation masks | **Closed**, one omission: `Runtime/DataConnections/LocalDataServices.cs:47` `Implemented(target)` is a sixth hard-coded set (used at `:81,204,216`); a bit absent from it is never advertised nor put in metadata. It is an origin-side "grow in H2/A2" site, not a tolerance site; add it to the H2/A2 task lists. `ProjectedDataAccess.cs:157` verified (enum pattern `Browse or Read or Write or Subscribe`). | +| **M2** unary negotiation | **Closed.** Per-call header follows the `CompactCodecHeader` precedent; header-less callers keep the v1 catalog; recorded-v1-client test covers Browse/GetMetadata/Read/Subscribe. | +| **M3** override-resident rules | **Closed** (§3.1; required parity cases listed in H1). | +| **M4** standing stream / budget | **Partially closed.** Demand-driven and charged against the budget, but see **N2** (no wire mechanism to subscribe) and **N5** (defaults make all-or-nothing fail). | +| **M5** relay loop key | **Closed by removal** (§8). | +| **M6** history phasing | **Closed.** Bits, migration, artifact and AdminUI in H2; Gateway leg required in H4 or an explicit `blocked` deploy-gate issue with docs scoped to SqlServer/QuestDB. | +| **M7** duplicate placements | **Closed** as a model (one condition, extra notifiers, A04). Its mechanics raise N3/N4. | +| **M8** permission mapping / audit | **Closed** (bits from `AlarmOperationFor` `NM:3285-3290`; separate sanitised audit field). Note `AlarmCommand` (`Commons/OpcUa/AlarmCommand.cs:49-54`) crosses the mesh on `alarm-commands`: adding `RemoteAuditText` must be shown to deserialize on a not-yet-upgraded pair member (add to A2 tests). | +| **M9** v1 soak | Owner decision (#915). See "Consequences of deferring G0" below. | +| m1–m11, nits, scope cuts | **Closed** as stated in §0; spot-checked m1 (`HistoryContinuationStore.cs:114`), m3 (`HistoryReadContracts.cs:194-204`), m4 (arm 9), m5 (no origin EventId on the wire). | + +### New findings + +#### N1 (Major) — An event-fed hub is not a state source: failover or restart can clear every imported alarm (§5.1, §5.5 resync) + +**Problem.** §5.5 retires any consumer condition "missing from a **complete** snapshot". The snapshot comes from a hub that +only learns a condition when `ReportConditionEvent` fires for it. + +**Evidence.** +- On a Warm Standby `ReportConditionEvent` returns before delivery (`NM:1561-1565`, `_standby.AlarmsSuppressed`); the plan + does not say whether the callback sits before or after that return. If after, a just-promoted Primary has an empty hub + while its nodes hold active alarms, and nothing re-reports unchanged state. +- After an origin restart or rebuild, only conditions carried over in an off-normal state report + (`CompleteAddressSpaceApply`, `NM:5639-5651`); a snapshot requested before drivers re-project sees a partial hub. +- State that changes without an event never reaches the hub: `WriteAlarmCondition` applies everything and reports only + when the delta gate fires (`NM:1363-1418`); ConditionClass "never fires an event on its own" (`NM:1386-1388`). + +Result: origin failover ⇒ new epoch ⇒ "complete" but empty snapshot ⇒ the consumer emits Retain=false for alarms that are +still active. A03 would catch it only if the standby had been demoted-then-promoted with standing alarms; make that explicit. + +**Fix.** The node is the source of truth. Build the snapshot by enumerating the node manager's live conditions under +`Lock` (an SDK-free `SnapshotConditions()` beside the callback) and use the callback only for deltas after the snapshot's +version watermark. Raise the callback before the standby early-return. A1 parity gate: hub snapshot == node state for +every condition after (a) cold start before any driver publish, (b) standby promotion with standing alarms, (c) rebuild. + +#### N2 (Major) — No contract for subscribing to conditions (§4.2, §5.5) + +**Problem.** `ConditionState` carries a per-item `Handle`, so conditions are stream items, but the revised proto adds no +command or item kind to request them. v1 items are named by `View` in `Open.items`/`ItemChanges` +(`data_connection.proto` `SubscriptionItem`), i.e. the consumer must already know each condition. The plan never says how +it learns them: a full recursive Browse of the mapped branch contradicts the lazy, depth- and node-budgeted projection +(`RemoteNamespaceMapping.MaxProjectionNodes`/`MaxProjectionDepth`), and conditions added by a later origin deploy have no +discovery path at all. + +**Fix.** Add one root-scoped item kind ("all conditions under this export root", one handle per mapping; each +`ConditionState` carries its own `View` + `ConditionInfo` on first appearance or in the snapshot). That removes the +catalogue walk, makes additions/removals ordinary stream records, and makes "snapshot complete" well defined. Lock it in +X0 with the other tags. + +#### N3 (Major) — A native condition imported through a UNS-only mapping has a Raw-realm home (§5.2, A1) + +**Problem.** Native conditions are homed at their Raw address (`ConditionInfo.home`), and the consumer mints the NodeId in +"the mapped namespace of the home realm" under the home mapping's id. With only a UNS export/mapping: +- the UNS export must hand a Raw address to a principal that holds no Raw grant (the origin's RawPath is disclosed, and + the export check is realm-bound — `Runtime/DataConnections/LocalExportCatalog.cs:42-48`); +- the consumer's id pairs a UNS mapping with a Raw-realm view, which the v1 invariants reject + (`NM:4885` `View.Realm != definition.Realm`; `OpcUaServer/Security/DataPlaneAuthorizer.cs:182` realm must match the namespace). + +**Fix.** Address a condition **within the realm of the export that lists it** (for UNS: under the referencing equipment), +and dedupe across placements by an opaque stable key — `Metadata.stable_source_id` already exists for this +(`LocalExportCatalog.Compilation.cs:92`). The consumer keys its registry on `(connection, stable key)`; no cross-realm +address ever crosses the wire. + +#### N4 (Major) — Home mapping, and therefore ConditionId, depends on which stream opened first (§5.2 vs §5.5) + +**Problem.** Home = "the first mapping … that catalogues the condition, Raw before UNS". Streams are demand-driven per +mapping. A client subscribing under the UNS mapping first gets a UNS-homed NodeId; when another client later opens the Raw +mapping's stream, the rule re-homes the condition: removal + addition + RefreshRequired for every imported alarm, caused +only by subscription order. ScadaBridge is told to key on `ConditionId`. + +**Fix.** Make the home a function of deployed configuration only (e.g. lowest-ordered enabled mapping of the connection +whose root covers the condition's stable key, regardless of demand), or drop the mapping id from the condition NodeId and +key it on `(connection, stable key)` so placements never affect identity. The second also removes owner question 2. + +#### N5 (Major) — Default budgets make all-or-nothing fail on ordinary plants (§5.5, §6 schema) + +**Evidence.** `MaxConditions` default 10000; each condition charges itself plus ~20 children against +`MaxProjectionNodes`, whose default is 10000 (`Configuration/Entities/RemoteNamespaceMapping.cs:29`). About 470 conditions +exhaust the whole node budget before any variable is projected, and the rule is then `Unavailable(ConditionCapacity)` for +the entire mapping. + +**Fix.** Give conditions their own node budget (`MaxConditions` × measured subtree size), or charge a condition as one +unit. Measure the real child count in X0 and state the default that results. Add a validator warning when +`MaxConditions` cannot fit. + +#### N6 (Minor) — `occurrence` across an origin restart or failover (§5.6) + +`version` is "monotonic within the serving incarnation"; `occurrence` has no stated lifetime, and +`expected_serving_incarnation` rejects calls bound to the old incarnation. After a failover the resync emits no event for +unchanged alarms (#656), so a client holds only pre-failover EventIds and every ack fails until it issues ConditionRefresh. +Specify that the consumer re-binds its retained EventIds to the new incarnation when the resynced state is unchanged, or +document the refresh requirement and gate it in A03. + +#### N7 (Minor) — Notifier wiring versus lazy projection (§5.2, §5.5) + +Non-home placements are wired to "every projected folder that mirrors an origin placement", but those folders exist only +once browsed and can be retired when idle (`OpcUaServer/ProjectedNodeLifetime.cs`); projected folders are created with +`EventNotifier = None` (`NM:4914`). State: wiring is applied when a placement folder materialises, removed symmetrically +on retirement, and a folder with an event item is pinned. + +#### N8 (Minor) — Consequences of deferring G0 + +Nothing in X0/H becomes unsafe: features stay default-off and header-gated. Two things to hold: +1. X0 and A3 change v1 hot paths (the five readers, the mapped `CreateMonitoredItems` deny for event items, `Call` + partitioning). The "recorded v1 client, byte-identical" test is an X0 gate only — repeat it as an exit gate of H2, A2 + and A3, so a v1 regression is attributable without a soak baseline. +2. State in #915 which build the soak runs on. A soak on pre-X0 v1 says nothing about the X0 readers that every later + phase depends on. + +### Open or new Blocker/Major items + +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`).