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

438 lines
47 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 — consumer condition registry, visibility, event delivery (A3a) and remote methods (A3b)
Phase A3 (first half) of `docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md`, 2026-11-24, branch
`a3-consumer` (from master `83c7e586`). A3b (§5.6 remote methods: `ICallAsyncNodeManager`, claim / `base.Call` / await,
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).
---
# A3 — PART 2 (A3b): methods on imported conditions, no `Lock` waits; A3 exit (L2, L3, live)
2026-11-24, branch `a3-consumer`, on top of A3a (`b5ab6e7c`). Not merged, not pushed.
## Progress log
1. `c1be5725` NM: `ICallAsyncNodeManager` (`OpcUaServer/ImportedConditionMethods.cs`), EventId registry gate, N6 re-binding.
2. `28098a8d` Runtime/Host: `ProjectedConditionAccess : IProjectedConditionMethods` (`ProjectedConditionAccess.Methods.cs`), the
runner's stream serving identity, `DataConnectionDeploymentLease : IDataConditionMethodService`, host wiring.
3. `de51886d` OI wire tests; `2d0147f9` Runtime tests + `A3` manifest; `fecb178e` L2 harness + byte cap.
4. `4e6535ee` live smoke (`conditions_a3_smoke.py`, seeder conditions profile makes the CONSUMER condition-bearing).
5. Live `a3b-cond-1` / `-2` FAILED and found two A3a integration defects, fixed in `404a664c` (logger) and `82ecc116` (root view);
live `a3b-cond-3` PASS.
## What is implemented (A3b, plan §5.6)
- **Interception (step 1).** Verified against the pinned SDK 2.0.1 (ilspy): `CustomNodeManager2` has a public virtual
`CallAsync(OperationContext, ArrayOf<CallMethodRequest>, IList<CallMethodResult>, IList<ServiceResult>, CancellationToken)` but
does NOT declare `ICallAsyncNodeManager`, so `AsyncNodeManagerAdapter.CallAsync` ran the synchronous `Call`. NM now declares
`ICallAsyncNodeManager` and overrides `CallAsync`: (a) claims every unprocessed request whose ObjectId is in the
`mapped/conditions` namespace — a namespace-index test, **no lock at all** — and marks it `Processed`; (b) calls
`base.Call(...)` unchanged (it skips the claimed ones; local behaviour incl. `ReportAfterMethod` under `Lock` is unchanged),
completed before any remote await; (c) runs the claimed calls concurrently and awaits them. No `Lock` is held at any point;
the SDK pre-validation `FindMethodState` takes `Lock` only for its lookup (plan's residual).
- **Local checks (step 2), no I/O, no NM `Lock`:** condition resolved from the ObjectId (`TryParse`, lock-free registry
`Find`) else `BadNodeIdUnknown`; method from the MethodId — the type declarations (`AcknowledgeableConditionType_Acknowledge`
/ `_Confirm`, `ConditionType_AddComment`) or this condition's instance child (`c1.…/Acknowledge` etc.); anything else
(shelve, enable/disable) `BadNotSupported`; no port ⇒ `BadNotSupported`; **per-caller mapping gate**
`IProjectedConditionMethods.AuthorizeMethod(local caller, placements, method)` ⇒ `BadUserAccessDenied` unsent; native
Confirm ⇒ `BadNotSupported`; the origin's `supported_methods` (kept from the listing) lacks the method ⇒ `BadNotSupported`;
Warm Standby ⇒ the standby refusal; argument shape (`BadArgumentsMissing` / `BadTooManyArguments` / `BadTypeMismatch`);
**EventId**: must be one this consumer minted for that condition AND bound to the CURRENT marker, else `BadEventIdUnknown`
unsent. The EventId registry (`RecentEvents`, 32 per condition) and `Activation` are now read/written under a per-condition
`MethodGate` (the plan's "small registry with its own lock"); `TryResolveImportedEvent` also uses it instead of `Lock`.
- **The gate** (`ProjectedConditionAccess.AuthorizeMethod`, real `DataOperationPolicy`): for a placement in primary order whose
mapping is current, condition-bearing, of the placement's realm and itself grants the method's bit (AlarmAcknowledge for
Acknowledge/AddComment, AlarmConfirm for Confirm): `AuthorizeLocal(caller, AlarmAcknowledge|AlarmConfirm, folder scope)`,
which re-checks the caller's key (#563); regardless of `Security:Acl:Enabled` (as the A3a visibility gate). Returns the
placement to dispatch through and that mapping's `ConditionMethodTimeoutMilliseconds`.
- **Dispatch (steps 4–5).** Bounded by a per-node semaphore (8; waiting counts against the budget, exhausted ⇒
`BadTooManyOperations` unsent). Budget = min(request `OperationDeadline`, the mapping's method timeout). A fresh operation id
(`a3-<guid>`) per dispatch; **an identical call already in flight** (same caller, condition, EventId, method, comment) **joins**
it — one dispatch, the same answer. The port call is bounded by budget + 250 ms (`WaitAsync` + `CancelAfter`). The Runtime
addresses the origin with the placement, `expected_activation` = the latest applied marker, `expected_serving_incarnation` =
the serving identity of the CURRENT condition stream (`IDataSubscriptionProvenance`), `on_behalf_of` = the local principal,
through the deployed lease (`DataConnectionDeploymentLease` now implements `IDataConditionMethodService`: the row's
AlarmAcknowledge/AlarmConfirm bit else `UnauthorizedAccessException` ⇒ `BadUserAccessDenied`, unsent). No open condition stream
(connection down / never opened) ⇒ `BadNoCommunication`, nothing leased or sent.
- **No local apply.** Imported conditions keep their A3a `BadNotSupported` SDK handlers; nothing in the claimed path touches
node state. The node changes only when the origin's record arrives on the condition stream.
- **Outcome mapping (documented choice).** `DriverConfirmedSuccess` (scripted) / `AcceptedUnconfirmed` (native) ⇒ `Good` (the
client may see Good before the confirming event); `RejectedBeforeDispatch` ⇒ the origin's status (+ its diagnostic);
**`OutcomeUnknown` ⇒ `BadTimeout` when the budget elapsed, otherwise `BadCommunicationError`**, always with
"OutcomeUnknown: …" in the diagnostic and a Warning log. Chosen over an Uncertain code: Part 4 gives a Call result no
"maybe applied" Uncertain meaning, and an Uncertain-family status reads as success to most clients; a Bad status plus the
confirming (or absent) condition event is the honest answer. Never retried.
- **N6 re-binding** (`RebindImportedEventIds`). After a record that changed no state: a moved marker re-binds retained EventIds
only when the record's `time` equals the time they were bound under (F6); otherwise a fresh EventId bound to the new marker is
stamped on the node (what a ConditionRefresh now returns) and `RequireRefresh(connection)` is queued after the apply
(outside `Lock`). A condition whose first record reported no event gets one bound EventId.
## A3a defects found by the live gate (fixed)
1. **`ProjectedConditionAccess` logged to `NullLogger` in production** (DI passed no logger): the first live failure
(`a3b-cond-1`, nothing imported) left no trace. Now the host logger; plus Information logs for stream open (serving), a
refused item (Warning, status + diagnostic) and each snapshot barrier (statuses, record count, timeout).
2. **The UNS root item was refused `Denied`** (`a3b-cond-2`: `map-uns item refused by the origin (Denied)`, `map-raw` Complete,
0 records). The item view was built from the anchor address with subject = the address identifier (an opaque EquipmentId);
the origin requires its own subject (`area/line/plc`). Now metadata is asked exactly as `RemoteNamespaceResolver` asks it
(subject = `RemoteRootEntityId`) and the item carries the origin's canonical view from the metadata answer. Pinned by
`The_condition_item_carries_the_origins_canonical_root_view_learned_from_metadata` (red with the item view reverted).
The A3a unit tests could not see either: their fake origin accepted any view.
## Tests (A3b)
| Project | Class | What |
|---|---|---|
| OI | `ImportedConditionMethodWireTests` (7, Phase=A3) | real SDK server + client sessions; the port fakes the origin: **once + join** (duplicate in-flight call joins, one dispatch, both Good; still unacked until the origin record; record ⇒ acked; a later call = new dispatch, fresh op id); **child Call** via the instance method id, denied caller `BadUserAccessDenied` unsent, re-gated per local caller, Acknowledge grant ≠ Confirm; **unknown / superseded EventId** `BadEventIdUnknown`, native Confirm + OneShotShelve `BadNotSupported`, all unsent, positive control carries the current marker; **N6** same-time resync re-binds, other-time resync ⇒ old EventId unknown + fresh ackable EventId; **L3 lock-freedom**; **mixed batch** (local native Ack through `base.Call` = Good + routed once + one local ack event, imported Ack dispatched, imported unchanged); **timeout** (300 ms mapping timeout ⇒ `BadTimeout` < 3 s, port cancelled, one dispatch), OutcomeUnknown ⇒ `BadCommunicationError`, refusal statuses passed through (`BadInvalidState`, `BadNoCommunication`), nothing applied |
| Runtime | `GrpcDataProjectedConditionMethodTests` (5, Phase=A3, manifest `A3`) | gate with a real `DataOperationPolicy` (AlarmAcknowledge ⇒ Ack/AddComment not Confirm; Subscribe-only ⇒ denied; mapping lacking the bit ⇒ denied; mapping timeout 4321 ms carried; unknown mapping/caller/null denied); no open stream ⇒ `BadNoCommunication`, never leased, nothing sent; call carries the stream's serving incarnation, placement, marker, op id, budget, on-behalf-of; OutcomeUnknown passed through; connection down after a stream end ⇒ `BadNoCommunication`, nothing sent; lease refusal ⇒ `BadUserAccessDenied` unsent; canonical root view |
| OI | `ImportedConditionMemoryMeasurementTests` (opt-in `OTOPCUA_A3_L2=1`, Category=Perf) | L2 harness |
OI suites run outside the unit-phase runner (it accepts unit projects only), as for A3a.
**Red-on-revert (each mutation built, run, restored; `git status` clean after):**
| Mutation | Test | Result |
|---|---|---|
| M1: port call waited synchronously under `lock (Lock)` | L3 lock-freedom | **red** (the first Read/Browse waited out the 5 s stall: `ack.IsCompleted` already true) |
| M2: in-flight join disabled | once + join | **red** (joined count never 1) |
| M3: `AuthorizeMethod` verdict ignored | child Call gate | **red** (denied caller got Good) |
| M4: EventId marker check ignored | unknown/superseded EventId | **red** (superseded EventId accepted) |
| M5: mapping timeout ignored (30 s budget) | timeout | **red** (elapsed > 3 s) |
| M6: N6 re-bind disabled | re-binding | **red** (same-time resync EventId refused) |
| M7: `base.Call` skipped when anything is claimed | mixed batch | **red** (local Ack not Good) |
| R1: no-stream check removed (Runtime) | connection down | **red** |
| R2: mapping-bit check removed (Runtime) | gate | **red** |
| R3: item view reverted to the address-only view | canonical root view | **red** |
| native-Confirm check removed (not run) | — | expected **masked**: `supported_methods` of a native condition (Native = 3) lacks Confirm, a second layer refusing the same call `BadNotSupported` unsent |
## L3 — lock-freedom (§9.3, hard gate) — PASS
Measured by the OI wire test (in-process, real SDK server; the origin's method handler is stalled 5 s at the consumer's
`IProjectedConditionMethods` port — the consumer-side boundary, below which everything is the remote origin). 10 rounds of
concurrent Read (raw variable), Browse (Plant folder) and a data Publish (value write → client notification, publishing interval
20 ms) while the call is in flight, plus `Monitor.TryEnter(Lock)` from the test thread; `AckedState` asserted false after every
round; the origin record applied after release flips it (positive control). Three runs:
| Run | Stall | Read max | Browse max | Data Publish max | `Lock` acquire max | Baseline (no stall) read / browse / publish |
|---|---|---|---|---|---|---|
| 1 | 5003 ms | 1.8 ms | 1.2 ms | 99.7 ms | 0.01 ms | 1.3 / 5.0 / 105.8 ms |
| 2 | 5003 ms | 1.9 ms | 6.3 ms | 98.6 ms | 0.01 ms | 1.3 / 4.6 / 107.7 ms |
| 3 | 5002 ms | 2.6 ms | 1.1 ms | 99.7 ms | 0.01 ms | 1.2 / 5.4 / 105.9 ms |
All < 200 ms. The ~100 ms publish figure is the server's minimum publishing interval (identical without a stall), not a delay.
Deviation: the plan lists L3 as a docker-dev measurement; the live rig has no hook to stall the origin's handler, so the gate is
this deterministic in-process measurement (its mutation M1 proves it detects a `Lock` wait).
## L2 — consumer memory, 1,000 imported conditions in one mapping (§9.3) — PASS
In-process harness (`ImportedConditionMemoryMeasurementTests`, opt-in): a running SDK server, 1,000 conditions materialised through
the real `IProjectedConditionSink` (nodes + instance-scoped children, ids, registry + folder/notifier indexes, one more transition
each so every N6 EventId slot is used, the verdict cache exercised once per condition) plus the update records the runtime keeps per
key. Forced compacting GCs before/after. Three runs:
| Run | Working-set growth | Managed heap growth | per condition (heap) | materialise / transition |
|---|---|---|---|---|
| 1 | +107.1 MiB | +197.4 MiB | 207,036 B | 605 / 80 ms |
| 2 | +106.2 MiB | +197.4 MiB | 207,029 B | 704 / 91 ms |
| 3 | +112.2 MiB | +197.4 MiB | 207,029 B | 747 / 77 ms |
| 4 (after-materialise split) | +106.8 MiB | +196.1 MiB | 205,665 B (204,612 after materialise alone) | 602 / 83 ms |
Working-set growth ≤ 200 MiB: **PASS** (the heap grows more than the working set because the process had already committed GC
regions at baseline). Per the plan, `MaxImportedConditionBytes` is now set from the measurement: `BytesPerCondition` 160,997 →
**205,665** (the managed-heap figure, the larger of the two) and the default `DataConnections:MaxImportedConditionBytes` =
205,665 × 2,500 = **514,162,500 B (≈ 490 MiB)** (was 400 MiB). `MaxConditions` (1,000 per mapping) needs no lowering.
Nearly all of it is the SDK condition node + children (X0's node-only figure was 160,997); the A3b EventId registry adds ~1 KB.
## Live — run `a3b-cond-3` (build `82ecc116`, clean tree) — PASS
```bash
python3 scripts/validation/grpc-data/rig.py up --run-id a3b-cond-3 --conditions --timeout 1200
python3 scripts/validation/grpc-data/rig.py seed --run-id a3b-cond-3
# ~90 s for CONTROL's ClusterNode contact refresh
python3 scripts/validation/grpc-data/rig.py deploy --run-id a3b-cond-3 --timeout 300
python3 scripts/validation/grpc-data/conditions_a3_smoke.py --run-id a3b-cond-3
python3 scripts/validation/grpc-data/rig.py down --run-id a3b-cond-3
```
The conditions profile now also makes the CONSUMER condition-bearing (connection + both mappings carry 64|128|256; ConfigDb
showed 479 on both). `conditions_a3_smoke.py` raises ScalarHigh, runs CLI `alarms --refresh` on the SOURCE Primary (origin's own
subscriber) and the CONSUMER Primary, acks through the consumer with CLI `ack`, then clears.
| Item | Observed | Result |
|---|---|---|
| Consumer import | `stream 1 … opened (2 mapping(s), serving source-1:4053)`; barrier `map-raw=Complete, map-uns=Complete; 1 record(s)`; consumer CLI shows ScalarHigh Active/Unacknowledged with ConditionNodeId `ns=6;s=c1.…` (mapped/conditions) and a consumer EventId | PASS |
| Bogus EventId via the consumer | `Acknowledge failed: BadEventIdUnknown [0x809A0000]`; origin shows no ack | PASS |
| Ack via the consumer (CLI `ack`) | `Acknowledge successful` in 580 ms | PASS |
| Origin audit (source-1) | `Data-connection condition method Acknowledge by fixture-consumer (key …) on Uns:…:source-scalar-high op a3-1eabf280…: DriverConfirmedSuccess 0x00000000; on behalf of fixture-cli` — the service principal, the consumer's fresh op id, the local caller as on-behalf-of | PASS |
| Origin's own subscriber | ScalarHigh: Active/Unacknowledged, **exactly one Active/Acknowledged** | PASS |
| Consumer subscriber | Active/Unacknowledged, **exactly one Active/Acknowledged** (the origin's record re-imported) | PASS |
| Teardown | no run-labelled containers / networks left | — |
Failed attempts (history): `a3b-cond-1` — nothing imported, no log (A3a defect 1); `a3b-cond-2` — map-uns Denied (A3a defect 2).
Each fix changed the image inputs, so each run was torn down and a fresh run id brought up.
## Deviations / decisions (A3b)
1. **EventIds retained: 32** (A3a's `RecentEventIds`), not the plan's "last N (default 8)"; validity is "minted for this condition
under the current marker", as §5.6 step 3 specifies.
2. **Consumer-side join of identical in-flight calls** (the brief's "duplicate call joins"): each dispatch has a fresh operation id
(the origin's own registry joins duplicates of an id); two identical local calls in flight share one dispatch. A repeat after
completion is a new dispatch (no retry, no stale join).
3. **Dispatch placement** = the first placement (primary order) the CALLER passes the method gate on, not unconditionally the
primary placement: a caller authorized only via a second mapping is addressed through that mapping's placement.
4. **`expected_serving_incarnation`** = the serving identity of the condition stream the records arrived on (no stream ⇒
`BadNoCommunication`, unsent). A stream that does not expose provenance cannot be called through (production streams do).
5. **OutcomeUnknown ⇒ Bad** (`BadTimeout` / `BadCommunicationError`), see "Outcome mapping".
6. **The node manager enforces the mapping timeout itself** (budget + 250 ms grace around the port), so a port that never answers
cannot hold a request past it; the Runtime passes the budget to `GrpcDataConnection`, whose own ceiling still applies.
7. **L3 measured in-process** (see L3). **L2 measured in-process** (allowed by the brief).
8. Defaults changed at the A3 exit: `BytesPerCondition` 205,665, `MaxImportedConditionBytes` ≈ 490 MiB (L2).
9. Two A3a files were edited beyond A3b's seams because the live gate required it: the ProjectedConditionAccess DI logger and the
condition item root view (defects above); plus the per-condition `MethodGate` and N6 re-binding hook in `ApplyImported` /
`ReportImported` / `TryResolveImportedEvent`.
## Open / follow-ups
- RefreshRequired after an un-re-bindable resync goes to every item that may see the connection's conditions (A3a's
`RequireRefresh`), not only the affected mapping's notifiers.
- The A3a deviation 9 (explicit Primary endpoint for condition items) is still open; the live run happened to stream from the
Primary (source-1).
## Gates (A3b, at `82ecc116`)
| Gate | Result |
|---|---|
| `dotnet build ZB.MOM.WW.OtOpcUa.slnx --no-incremental` | 0 warnings, 0 errors |
| `run-unit-phase.py A3` (Runtime + OpcUaServer + Host) | passed (`20261124T225624…`) |
| `run-unit-phase.py A2` | passed (`20261124T225724…`) |
| `run-unit-phase.py A1` | passed (`20261124T225845…`) |
| `run-unit-phase.py X0` | passed (`20261124T230234…`) |
| Host.Tests `.DataConnections.` (both v1 gates) | 207 passed |
| Runtime.Tests full (`Category!=E2E&Category!=LiveIntegration`) | 2035 passed, 3 skipped (no #920 rerun needed) |
| OpcUaServer.Tests full (same filter) | 1455 passed, 1 skipped |
| OI `Feature=GrpcData` + ConditionMethodEvent / NativeAlarmEventIdentityFieldDelivery / FolderConditionRefresh / ConditionRefreshDeferral | 123 passed, 1 skipped (the opt-in L2 harness) |
| OI `ImportedConditionMethodWireTests` ×3 | 7/7 each |
| `git diff master -- '*Goldens.cs'` | empty |
| Live `a3b-cond-3` | PASS (above) |
---
# A3 — Review round 1 (A3a adversarial review, `a3a-review-round1.md`, written against `b5ab6e7c`)
2026-11-24, branch `a3-consumer`, on top of A3b (`3c941458`). Not merged, not pushed. Commits: `69aeeb77` (runner + NM fixes,
Runtime tests), `14343bf0` (folder promotion for folder-only demand, NM tests).
"Red on revert": the test was run with the fix removed (Runtime: the whole HEAD runner restored with interface stubs; NM: the
single fix line(s) removed by a scripted mutation) and failed; the fix was then restored and the test passed.
| Finding | Resolution | Test(s) | Red on revert |
|---|---|---|---|
| **B1** in-stream re-snapshot removes conditions | `ProjectedConditionAccess.Runner.cs`: a begin opens a per-mapping `Buffer`; snapshot records fill it; the committed `Live` set (and every node) is untouched until `snapshot_complete`, which swaps and re-merges old ∪ new keys — only a key the complete set no longer lists (and no other mapping lists) is removed. Deltas apply to `Live` and the buffer. An in-stream capacity refusal removes the mapping's keys once (keys another mapping lists survive) and requires refresh | `B1_an_in_stream_multi_frame_re_snapshot…` (begin + 2 record frames + positive control on map-b, then complete); `B1_an_in_stream_re_snapshot_over_capacity…` | yes / yes (refresh assertion; the removal shape itself was already right) |
| **B2** timed-out / non-Good mapping frozen Good | frames of a timed-out mapping keep being processed: a late `snapshot_complete` swaps in and re-runs the merge (full re-diff); at an incomplete barrier the keys no contributing mapping lists are `MarkConditionsStale` (new sink method, `BadNoCommunication`, one event each, never removed); after the barrier a still-`Unavailable` mapping ends the stream after a bounded wait (`ConditionSnapshotTimeout` × 1,2,4,8 backoff), cancelled by a late completion | `B2_a_snapshot_completing_after_the_timeout…`; `B2_an_incomplete_barrier_marks…`; `B2_S7_a_refused_item…` (new stream within 5 s) | yes / yes / yes |
| **Deviation 9** Primary endpoint | new `IDataPrimarySubscriptionSource.SubscribePrimaryAsync` (Abstractions) on `GrpcDataConnection` (skips a non-Primary endpoint; a role-only miss is not a discovery failure, no probe backoff) and the deployment lease; the runner uses it and also drops any stream whose provenance role is not Primary | `Deviation9_a_condition_stream_served_by_a_Secondary…` | yes (hangs: the old runner keeps the Secondary stream) |
| **B3** revalidation stands down folder items; demand leak | `RevalidateEventItems` asks `ImportedNotifierAdmits` for a projected notifier; the unsubscribe arm releases demand before both early returns; `_authorizer?.LogFiltered` (a rig without an authorizer NRE'd once an item was stood down) | `B3_revalidation_keeps_an_admitted_folder_item_and_deleting_a_stood_down_item_releases_its_demand` (real `RevalidateMonitoredItems()`, lease counter) | yes (revalidation mutation) / yes (demand-order mutation) |
| **B4** host caps per connection / order / trust `total` | one node-wide `ConditionLedger`: connection charge = max(materialised keys, Σ mapping claims); a claim is the admitted `total` while snapshotting, the record count after (growth is charged); admission is against everything charged or claimed, order-independent. Records past `total`, `Live` past `MaxConditions`, or growth past the node caps ⇒ `ConditionCapacity` (item removed, keys removed, refresh). `ChargedConditions` observation | `B4_the_host_caps_are_node_wide_across_connections`; `B4_admission_is_order_independent…`; `B4_records_past_the_snapshot_total…`; `B4_post_snapshot_delta_growth…` | yes ×4 |
| **S1** rebuild leaves stale wiring | `RebuildAddressSpace` calls `UnwireAllImportedFolders()` before clearing; `WiredByFolder` keeps the promoted folder INSTANCE — a re-created folder with the same NodeId unwires the dead instance and is promoted afresh | `S1_a_full_rebuild_unwires_and_the_re_created_folder_is_promoted_and_delivers_again` | yes (rebuild-unwire removed), yes (both removed) |
| **S2** verdict cache outlives expiry / IsActive | `Verdict` stores `ValidUntil` = min(credential expiry, now + 5 s) for a positive verdict; `AuthorityGeneration` folds every current mapping's `Authority.IsActive` | `S2_a_cached_positive_verdict_is_re_proved…` (OpcUaServer.Tests); `S2_an_authority_deactivation_moves_the_authority_generation…` (Runtime) | yes / yes (by construction: the old formula ignores IsActive) |
| **S3** removal races a new runner | a new runner of a connection awaits its predecessor's `Stopped` (loop end + removal) before opening a stream; stopped runners are kept per connection in `_stopping` | `S3_a_new_runner_waits_for_the_old_runners_removal…` (the sink holds the old removal open 400 ms) | yes |
| **S4** `TakeMaterialised` cross-thread | the materialised set is handed over inside the new runner's loop after the predecessor stopped (no concurrent mutation, no orphaned key) | `S4_a_mapping_change_hands_the_materialised_set_over…` | **no** — the race window is one in-flight frame; the test pins the hand-over, it cannot force the interleaving |
| **S5** Lock-hold bounds | `ProjectedFolderIndex()` scan replaced by the incremental `FolderIds`/`FolderKeys` index (maintained in `OnProjectedFolderMaterialised`/`Removing`, cleared on rebuild, resolved against the live projected maps); refresh targets gathered 128 conditions per hold, visibility decided off Lock | covered by every OI wiring test (index correctness); no timing test | n/a (not behaviour-observable) |
| **S6** metadata failure swallowed | a root whose metadata is not Good (or a failed call) is `Unavailable` (logged), its item is not opened; all roots failing ends the stream | `S6_a_root_whose_metadata_fails…` | yes |
| **S7** RefreshRequired only on timeout | any incomplete barrier (a mapping not `Known`: timed out, refused, metadata) requires refresh | `B2_S7_a_refused_item…` (`RefreshRequired == 1`) | yes |
| **Deviation 3** folder-only demand | event items on any projected folder are admitted through `ImportedNotifierAdmits` = a wired condition the caller sees, OR the mapping gate on the folder's own (mapping, subject) key (`IProjectedConditionAccess.CanSubscribeFolder`); projected folders of a condition-bearing mapping (`IsConditionBearingMapping`) are `SubscribeToEvents` from materialisation (the SDK answers `BadNotSupported` before `SubscribeToEvents` otherwise) and never demoted by an unwire | `Deviation3_a_folder_only_client_opens_demand…` (granted Good + demand + the condition then delivered; anonymous denied) | yes (promotion removed ⇒ `BadNotSupported`) |
| **Deviation 6** removal tells nobody | `RemoveConditions` captures the items that may see the conditions BEFORE unwiring, removes, then queues `RefreshRequired` (off Lock) to those passing the gate. `RequireRefresh`'s early return on a connection with no conditions stays: nothing of it can be held any more — the removal itself now notifies | `Deviation6_removing_an_imported_condition_sends_RefreshRequired_only_to_the_items_that_could_see_it` (Server + folder get it; a map-b folder item does not, after a must-arrive control) | yes |
| **Deviation 8** one-hold replay | `ReplayImportedConditions` runs 128 conditions per Lock hold; each condition's snapshot and its queueing share a hold (ordering vs. live events kept) and one `EventDeliveryCache` per snapshot is shared across items | `Deviation8_ConditionRefresh_replays_hundreds…` (300 conditions inside RefreshStart/End) | **no** — chunking is not observable; the test guards correctness of the chunked replay |
| **A3b open item** RefreshRequired scope after an EventId-invalidating resync | `ApplyConditions` collects the un-re-bindable CONDITIONS and refreshes only the items that may see one of them (shared `QueueImportedRefresh`) | via the shared targeting in `Deviation6_…` (a folder item of another mapping is not refreshed); the A3b re-binding test still passes | not separately reverted |
| NIT `IsWiredTo` reads `Folders` off Lock | `ImportedCondition.WiredFolders` immutable array, replaced under Lock on wire/unwire | — | n/a |
| NIT `Infos` never pruned | `ConditionSet.Apply` drops the info with a removed key; a swap discards the old set | — | n/a |
| NIT stale callback after a fresh barrier | stale mark and barrier serialize on the runner's stale gate + generation | — | n/a (race) |
| Test adequacy: vacuous absence assertions | `Applied.ShouldBeEmpty` / `Removed.ShouldBeEmpty` now follow a must-arrive control (a later frame's item removal; the barrier) | the three original tests rewritten | — |
| Test adequacy: delivery gate not isolated | `ImportedConditionDeliveryGateTests` (non-parallel collection): the denied Server-object session gets nothing AND `ProjectedEventFieldList.DroppedOnPublish` does not move | `A3_SEC_the_delivery_gate_alone_withholds…` | yes — removing only the Server-object delivery gate turns it red while the original A3-SEC test stays green |
Residual / recorded:
- A projected folder materialised while its mapping was NOT condition-bearing (or before `ProjectedConditionAccess` is bound) is
not promoted until it re-materialises; the host binds access before any projection deploys.
- The B2 retry ends the whole stream (complete mappings re-snapshot too), bounded by the backoff; a per-item re-add is A4 material.
- In-stream capacity refusal removes the mapping's keys (all-or-nothing, §5.5) rather than keeping them stale.
## Gates (review round 1, at `14343bf0`)
| Gate | Result |
|---|---|
| `dotnet build ZB.MOM.WW.OtOpcUa.slnx --no-incremental` | 0 warnings, 0 errors |
| `run-unit-phase.py A3` | passed (`20261124T234716…`) |
| `run-unit-phase.py A2` | passed (`20261124T234814…`) |
| `run-unit-phase.py A1` | passed (`20261124T234927…`) |
| `run-unit-phase.py X0` | passed (`20261124T235258…`) |
| Host.Tests `.DataConnections.` (both v1 gates) | 207 passed |
| Runtime.Tests full (`Category!=E2E&Category!=LiveIntegration`) | 2049 passed, 3 skipped (no #920 rerun needed) |
| OpcUaServer.Tests full (same filter) | 1456 passed, 1 skipped |
| OI `Feature=GrpcData` + ConditionMethodEvent / NativeAlarmEventIdentityFieldDelivery / FolderConditionRefresh / ConditionRefreshDeferral | 129 passed, 1 skipped in 2 of 4 runs; the other 2 runs failed 2 and 6 of the #854 deferral stress tests (`ConditionRefreshDeferralWireTests` / `FolderConditionRefreshWireTests` `Deferred_events_older_than_a_refresh…`, `A_condition_removed_during_a_plain_refresh…`) — **pre-existing**: the same suite at the unchanged base `3c941458` failed 2 of them in 1 of 3 runs; the classes pass 3/3 in isolation on this branch; no imported-condition code is reached in those rigs (no `ProjectedConditionAccess`). Root cause not established (load-sensitive local-condition deferral) — to be filed as an issue, not closed as a flake |
| `git diff master -- '*Goldens.cs'` | empty |
## Live — run `a3r1-cond-1` (build `14343bf0` + docs) — PASS
Same procedure as `a3b-cond-3` (`rig.py up --conditions`, seed, ~88 s, deploy, `conditions_a3_smoke.py`, `rig.py down`).
Consumer: `stream 1 for connection consumer-source opened (2 mapping(s), serving source-1:4053)` (the Primary, now via
`SubscribePrimaryAsync`); barrier `map-raw=Complete, map-uns=Complete; 1 record(s)`. Bogus EventId ⇒ `BadEventIdUnknown`; ack
through the consumer `Acknowledge successful` (608 ms); origin subscriber and consumer subscriber each saw exactly one
Active/Acknowledged. Teardown: no run-labelled containers or networks left.