Files
lmxopcua/docs/plans/evidence/grpc-data-ext/A3.md
T

164 lines
17 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# A3 evidence — PART 1 (A3a): consumer condition registry, visibility and event delivery
Phase A3 (first half) of `docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md`, 2026-11-24, branch
`a3-consumer` (from master `83c7e586`). A3b (§5.6 remote methods: `ICallAsyncNodeManager`, claim / `base.Call` / await,
lock-freedom, `BadEventIdUnknown`, native Confirm) is a separate agent's work on top of this.
## Progress log
1. Contracts (`e15bd7c9`): `OpcUaServer/IProjectedConditionAccess.cs` — `IProjectedConditionAccess` (gate, generation,
demand), `IProjectedConditionSink` (apply / remove / stale / RefreshRequired), `ImportedConditionPlacement`,
`ImportedConditionUpdate`. SDK-free except the identity type (as `IProjectedHistoryAccess`).
2. Shared helpers (`a75ea95e`, §5.3 "one refactored helper"): `CreateConditionNode` (type, optional children before
`Create()`, child ids via `New`, initial fields) is now the body of `MaterialiseAlarmCondition` AND the imported factory;
`ApplyConditionState` (state projection + the T20/#656 delta gate) is now the body of `WriteAlarmCondition` AND the
imported apply. `ApplicationAlarmConditions.Create` accepts a null parent (an imported condition has no folder parent).
3. Registry (`1ff18caa`): `OpcUaServer/ProjectedConditionRegistry.cs` (registry class + NM partial implementing
`IProjectedConditionSink`).
4. Runtime (`4f6e26dd`): `Runtime/DataConnections/ProjectedConditionAccess.cs`.
5. Host wiring (`8d6c94a3`): DI singleton + `IProjectedConditionAccess`; `OtOpcUaServerHostedService` sets
`NodeManager.ProjectedConditionAccess` and binds the node manager as the runtime's sink; host caps
`DataConnections:MaxImportedConditionNodes` (122,500) / `MaxImportedConditionBytes` (400 MiB).
6. Tests (`de381157`, `4b74ac9c`, `855f7256`, `bdc29ac2`) and the `A3` manifest entry (`762b0fa1`).
## What is implemented (A3a)
- **Namespace + classification (§5.2 N4).** `https://zb.com/otopcua/mapped/conditions` is the node manager's FIFTH
registered namespace. `IsImportedConditionId` is asked before `RealmOf` by `Permits` (read / browse / subscribe) and by
`DataPlaneAuthorizer.TryAuthorizeMapped`, which every authorizer entry point (`Authorize`, `AuthorizeIfRequired`,
`IsAllowedCached`, the alarm-command gate, history) reaches first — so the realm a caller computed with `RealmOf` (which
folds the index into Uns) is never consulted. Imported ids: Browse / Read / CreateMonitoredItems via the condition's
mapping gate; HistoryRead, writes, Call and the alarm operations refused (Call = A3b). ⚠️ **Defect found while testing:**
`OwnsNamespace` listed only indexes 0–3, so condition children kept their ns=0 TYPE ids AND `Permits` treated an
imported id as "not ours to gate" (ungated Read). Fixed; pinned by the child-Read wire test.
- **Registry (§5.3).** Keyed by full NodeId (`c1.` + base64url JSON{ConnectionId, ConditionKey}); never `_alarmConditions` /
`_eventNotifierSources` / `_nativeAlarmNodeIds`. Conditions are parentless predefined nodes with instance-scoped children
(#629). SourceNode = ConditionId = the imported id; SourceName = primary placement path; Severity verbatim (1..1000);
ConditionName / Message / Comment / ClientUserId / ConditionClass / Quality from the record. All Part 9 methods on an
imported condition answer `BadNotSupported` before the SDK touches state (no local apply; A3b replaces this).
- **Notifier wiring (N7).** Lazy and symmetric: a placement's folder (projected folder or mapping anchor, matched on
`(mappingId, local subject)`) is wired when it is materialised — at apply time, or later from `TryEnsureProjectedVariable`
/ `TryEnsureProjectedAnchor` — with `AddNotifier` both ways + `EventNotifier |= SubscribeToEvents` + `AddRootNotifier`;
unwired (`RemoveNotifier(bidirectional)`, root notifier removed, `SubscribeToEvents` cleared when the last condition
leaves) at every projected removal site (anchor removal, capacity eviction, page removal, page rollback). A folder holding
an admitted event item is **pinned**: eviction and page removal skip it; a mapping (anchor) removal still removes it,
unwiring first. The Server object is always the delivery point (`OnConditionReportEvent`).
- **Delivery + gate (§5.4).** Delivery reuses the node manager's report walk (`ReportConditionEvent` → condition's
`OnReportEvent` → Server-object items; inverse notifiers → wired folder items), so exactly-once, the #838 deferral queue
and the #854 cuts apply unchanged. The imported branch: the mapping gate per item **regardless of `AclEnforced`**
(Server object, folder hop, refresh), cached per (identity, condition, authority generation, placement version); the
folder hop also requires the folder to be currently wired. `RaiseConditionRecord` is a no-op for imported conditions
(they are not in `_alarmConditions`), so an imported condition never re-enters the origin hub.
- **`ProjectedEventFieldList : EventFieldList` + rewriter (§5.4).** Imported events ALWAYS take the marked projected path
(`EventDeliveryCache.QueueMarked`), whatever `UseProjectedEventDelivery` says; an item the projected path cannot serve
gets nothing (fail closed, counted). The marker carries identity, condition id, generation and a re-check (live condition
∧ gate). `ProjectedNotificationRewriter.Project` now also walks `EventNotificationList`: a marked list whose re-check
fails is dropped (counted); an UNMARKED list whose `Handle` is an imported-condition snapshot (a select-clause modify
rebuilt it) is re-gated for the publishing session (identity from the Publish/Republish request header's session) and
dropped only on deny (counted); anything else passes as before (v1 messages return the same instance).
- **Event items on projected notifiers.** Admitted (instead of the mapped blanket deny, which still applies to data items)
when the caller passes the gate of at least one condition wired at that folder; delivery and publish re-check per event.
- **Demand / barrier / budget (§5.5)** in `ProjectedConditionAccess`: the first admitted Server-object or projected-notifier
event item opens, per condition-bearing connection (mapping enabled ∧ Subscribe ∧ AlarmSubscribe), ONE stream under the
connection's service principal with one root-scoped item per mapping (Raw first, then mapping id ordinal); all close
together after the last item plus a 30 s linger (and the linger removes what they materialised). Snapshot begin
`total > MaxConditions` ⇒ `ConditionCapacity`, the item is REMOVED (`RemoveSubscriptionItems`), counted
(`otopcua.dataconn.conditions.capacity_rejections`); host caps (`total × 49` nodes, `total × 160,997` bytes) reject the
mappings that would cross them, in deployed order; 80% warning. Nothing is materialised until every mapping completed or
`ConditionSnapshotTimeoutMilliseconds` expired (incomplete ⇒ `Unavailable`, the rest proceed, then `RefreshRequired`).
Conditions never consume `MaxProjectionNodes`.
- **Version rule (A2 N2).** Per key per epoch; `removed` and snapshot begin bypass; a removal is applied unconditionally and
forgets the key's version.
- **Lifetime rule (A2 S1).** A stream end is re-snapshot, never removal; staleness after `ConditionStaleTimeoutMilliseconds`
⇒ `MarkConnectionStale` (Quality `BadNoCommunication` through the shared delta gate: one event each, Active/Acked
unchanged). Only a COMPLETE re-snapshot that no longer lists a key removes it (an incomplete mapping removes nothing).
T2: a `state_known = false` record never changes state; a never-known condition is `UncertainInitialValue`.
- **Primary placement / SourceName (§5.2).** From deployed config only: Raw mappings before UNS, mapping id ordinal,
placement address ordinal. SourceName = `<anchor local subject>/<placement address relative to the remote root>` (root
subject learned once per stream with `GetMetadataAsync`). ConditionId depends on (connection, key) only (N4): disabling
the primary mapping moves notifiers and SourceName, nothing else.
- **EventId re-binding seam (N6) for A3b.** `ReportImported` records each consumer-minted EventId with the activation marker
it described (32 per condition); `OtOpcUaNodeManager.TryResolveImportedEvent(conditionId, eventId, out
ImportedConditionBinding)` returns connection, condition_key, primary placement, all placements, activation marker,
native flag — everything §5.6 dispatch needs.
- **RefreshRequired.** `IProjectedConditionSink.RequireRefresh` queues `RefreshRequiredEventType` to every Server-object and
wired-folder item that may see a condition of the connection.
- **ConditionRefresh.** Imported conditions are excluded from the local replay paths (plain + cut, Server object + direct)
and replayed once by `ReplayImportedConditions` through the gated marked path, ACLs on or off.
- **§5.7.** No `alerts` publication / no consumer alarm history (imported conditions are not in `_alarmConditions`, the
condition-state sink never sees them, they are not fed to `NativeAlarmProjector`), no local shelving timers
(`OnTimedUnshelve` no-op, shelve refused).
## Tests
| Project | Class | What |
|---|---|---|
| OI | `ImportedConditionEventWireTests` (7, Phase=A3) | real SDK server + real client sessions: exactly one event per transition at a projected device folder, the mapping anchor (second placement) and `i=2253`, after a sentinel; §5.2 identity fields (SourceNode = ConditionId = `c1.` id in mapped/conditions, SourceName, Severity 777 verbatim, ConditionName); **A3-SEC** with ACLs off (no grant ⇒ folder item refused, zero events live and on ConditionRefresh, positive control + RefreshEnd sentinel; a revocation drops a queued event at publish); child Read authorized through the condition (granted Good / ungranted `BadUserAccessDenied`), Acknowledge refused and unapplied; disabling the primary mapping keeps the ConditionId and the instance (notifiers + SourceName move), a later mapping changes no NodeId; folder with an event item not retired, retirement unwires; resync of unchanged state reports nothing, then a must-arrive transition exactly once; staleness = one `BadNoCommunication` event per condition, still Active, unknown records change nothing, never-known = Uncertain |
| Runtime | `GrpcDataProjectedConditionAccessTests` (8, Phase=A3) | scripted origin stream: `total > MaxConditions` ⇒ `ConditionCapacity` + item removed before anything materialises, other mapping unaffected; 2,000 conditions with `MaxProjectionNodes = 10`; host node cap rejects at begin; version gate, removal bypass + forgotten version; stream end ⇒ no removal, staleness, complete re-snapshot removes only the missing key, incomplete removes nothing; snapshot timeout ⇒ Unavailable + RefreshRequired; primary placement Raw-first/ordinal independent of stream order + SourceName + folder subject; the gate with a REAL `DataOperationPolicy` (Subscribe grant on the folder scope; not AlarmRead; mapping needs AlarmSubscribe); demand opens, linger closes and removes |
| OpcUaServer | `ImportedConditionClassifierTests` (4, Phase=A3) | **guard test**: a condition-namespace id fed to `Authorize` / `AuthorizeIfRequired` / `IsAllowedCached` / `TryAuthorizeMapped` × {Raw, Uns} × {Read, Browse, HistoryRead, Call, CreateMonitoredItems, AlarmAcknowledge}, ACL on and off, under a Cluster-wide grant — the classifier is asked every time (48), never the realm walk; positive control on a Raw id; the node manager's classifier: Read/Subscribe through the condition, HistoryRead/Call/Ack refused, invisible ⇒ denied despite the Cluster grant; rewriter drops failed / throwing markers, re-gates unmarked, empties payloads, passes v1 messages through as the same instance |
| Host | `GrpcDataV1CompatibilityTests.A3_consumer_condition_shapes_…` (Phase=A3) | recorded-v1-client gate: the fake origin now also emits begin+`total`, an info/placement record + `snapshot_complete`, a `removed` delta; header-less (scoped or not) still the golden bytes; negotiated decodes all three. `git diff master -- '*Goldens.cs'` empty |
**Mutation record (A3-SEC, OI).** Removing only the Server-object delivery gate leaves A3-SEC green: the publish-time
marker re-check drops the event (the second layer works). Removing the delivery gate AND making the marker re-check
`true` turns it red (`deniedEvents … Count` 1). Both layers are real; no single-layer test isolates the delivery gate.
## Deviations / decisions (no questions asked; reasoning recorded)
1. **Delivery reuses the node manager's report walk** instead of a separate fan-out: imported conditions are not in the
realm-keyed maps (as the plan requires), but `ReportConditionEvent`/`DeliverConditionEventAsync`/`OnConditionReportEvent`/
`DeliverToNotifierItems`/`QueueToItem` gained an imported branch. This keeps exactly-once, #838/#854/#855 semantics
without a second implementation.
2. **Demand is global, not "per connection the caller could see"**: the first admitted event item opens every
condition-bearing connection. The per-event gate still decides visibility; the cost is opening streams a caller might not
see. Simpler and fail-safe; A4 diagnostics can reconsider.
3. **Folder event-item admission** uses the imported gate of a condition wired at that folder (not the folder's mapped
Browse proof). A folder is a notifier only while a condition is wired there (N7), so a folder-only client cannot open
demand by itself — a Server-object item (or an already-wired folder) is needed. Recorded for A4.
4. **RefreshRequired** is sent on an INCOMPLETE barrier (snapshot timeout); "a ConditionRefresh before the barrier ⇒
RefreshRequired when it completes" is not tracked separately (the timeout path covers incomplete resyncs). An UNMARKED
list dropped by the rewriter is counted but the item does NOT get a RefreshRequired (the rewriter has no item handle) —
follow-up for A3b/A4.
5. **Verdict cache** keys on `AuthorityGeneration` = (mapping-set version ≪ 32) ⊕ the policy's authority epoch, plus the
condition's placement version; the policy's own decision cache sits under it. Bounded (65,536 entries, then cleared).
6. **Removal of an imported condition emits no event** (no NodeDeleted model change for the condition namespace); clients
key on ConditionId and see it no longer refreshed. The linger close removes materialised conditions (no stale state left
when no one watches).
7. **Root-leaf replacement** of a mapping anchor (`TryApplyRootLeaf`) does not unwire an imported condition wired at that
anchor (a root-leaf mapping is a variable root; conditions there have a folder parent elsewhere). Edge case, recorded.
8. **ConditionRefresh replay of imported conditions** runs under one `Lock` hold (consistent with the synchronous events it
races); at the host cap (2,500 conditions) × items this is the longest hold A3a adds — L2/L3 live measurements should
include it. Apply is chunked at 128 updates per hold; the folder index is one scan of projected nodes per apply batch.
9. **Primary endpoint** for condition items (A2 N7: a Secondary advertises but refuses) is left to the connection source's
existing endpoint selection; a Secondary answers the item `Unavailable`, the mapping is `Unavailable` and retried on the
next stream. A3b/A4 should prefer the Primary explicitly.
10. **A3 OI tests** run outside the unit-phase runner (it accepts unit projects only), as for H1/H3.
## Gates
| Gate | Result |
|---|---|
| `dotnet build ZB.MOM.WW.OtOpcUa.slnx --no-incremental` | 0 warnings, 0 errors |
| `run-unit-phase.py A3` (Runtime + OpcUaServer + Host) | passed (`20261124T214213…`) |
| `run-unit-phase.py A2` | passed |
| `run-unit-phase.py A1`, `X0` | passed, passed |
| Host.Tests DataConnections (both v1 gates) | 207 passed |
| OI `ImportedConditionEventWireTests` | 7 passed |
| OpcUaServer.Tests full (`Category!=E2E&Category!=LiveIntegration`) | 1455 passed, 1 skipped |
| Runtime.Tests full (same filter) | 2030 passed, 3 skipped (no #920 rerun needed) |
| OI `Feature=GrpcData` + ConditionMethodEvent / NativeAlarmEventIdentityFieldDelivery / FolderConditionRefresh / ConditionRefreshDeferral | 116 passed |
| `git diff master -- '*Goldens.cs'` | empty |
Live rig: not run for A3a (no consumer-side condition demand exists until a client subscribes, and A3b + the exit gate
own the live leg); the unit + OI wire tests above use a real SDK server and real client sessions.
## Left for A3b
- §5.6: `ICallAsyncNodeManager` on the node manager (claim / `base.Call` / await, never under `Lock`), dispatch through
`TryResolveImportedEvent` → `IDataConditionMethodService` on the connection, no local apply before the origin record,
unknown EventId ⇒ `BadEventIdUnknown` unsent, native Confirm ⇒ `BadNotSupported` unsent, lock-freedom (L3), binding the
mapping's `ConditionMethodTimeoutMilliseconds`. Today every Part 9 method on an imported condition is refused
(`BadNotSupported` handlers; the classifier also refuses `Call` / alarm operations).
- RefreshRequired to an item whose UNMARKED list the rewriter dropped (deviation 4); explicit Primary endpoint for
condition items (deviation 9); the mapping-change runner hand-over (an old runner's in-flight batch can still reach the
sink until its cancellation is observed — bounded by one frame).