diff --git a/.claude/rules/drivers.md b/.claude/rules/drivers.md index 24094d6b7..c20978143 100644 --- a/.claude/rules/drivers.md +++ b/.claude/rules/drivers.md @@ -294,6 +294,15 @@ host logger factory (wired in `DriverFactoryBootstrap`; the FOCAS and TwinCAT fa AFTER configured ones; more than one discovered server without `discoveryServerUri` fails the connect. Session events are the OTel counter `otopcua.driver.opcuaclient.events`. `HistoryAggregateType` carries the full Part 13 set; an aggregate the gateway can't serve is `BadAggregateNotSupported` per node. +- **OpcUaClient RefreshEnd = A1 known-state signal, lossless brackets only (#926):** no RefreshStart, an + `EventQueueOverflowEventType` (matched by EventType BEFORE the source filter — it comes from the Server object), a + RefreshRequired, or a publish-sequence gap (`EventFieldList.Message.SequenceNumber`; SDK 2.0.1's `Republish` publish-state + never fires for a gap that blocks delivery — do not rely on it) inside the bracket ⇒ no signal + bounded re-refresh + (3 per episode, 2/4/8 s; a new budget only after a 5-min + cool-down). A loss OUTSIDE a bracket (overflow, gap) re-refreshes too, and any loss after a signal raises + `AlarmInitialStateEventArgs.Withdrawn` (host ⇒ `Known: false`, F5 re-armed, out of the backstop). A Start while a + bracket is open is a loss. Exhausted ⇒ stays unknown; never fall back to `Unsignalable` (that starts the backstop that + marks known). - **OpcUaClient server host-name check (#816):** the SDK checks the server certificate's host only with `checkDomain: true`; its 8-arg `DefaultSessionFactory.CreateAsync` hard-codes `false`, so driver, AdminUI browser and Client.Shared never checked before #816. Now `certificateValidation.validateServerHostName` (tri-state, unset = off = diff --git a/docs/Client.CLI.md b/docs/Client.CLI.md index ee488d32e..24cbe420f 100644 --- a/docs/Client.CLI.md +++ b/docs/Client.CLI.md @@ -121,6 +121,8 @@ otopcua-cli read -u opc.tcp://localhost:4840/OtOpcUa -n "ns=3;s=DEV.ScanState" - | Flag | Description | |------|-------------| | `-n` / `--node` | Node ID to read (required) | +| `--max-age` | Maximum cached value age in milliseconds (0–2147483647; default 0). Value attribute only | +| `-a` / `--attribute` | Attribute to read instead of the value (case-insensitive): `Value` (default), `Historizing`, `AccessLevel`, `UserAccessLevel`, `DataType`, `ValueRank`, `ArrayDimensions`, `MinimumSamplingInterval`, `NodeClass`, `BrowseName`, `DisplayName`, `EventNotifier`. The output gains an `Attribute:` line. Used by the #921 gate to show a projected variable's `Historizing` is False when its origin lacks the history feature | Output: diff --git a/docs/DataConnections.md b/docs/DataConnections.md index aca10c1fc..7b509e8b7 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -90,6 +90,40 @@ reply cannot lengthen it. Renewal grants no parent or sibling visibility, Browse local Browse privilege. Missing capability, denied Metadata or an invalid lease leaves the item unavailable until valid authority can be established. +**A lapsed lease is not an access denial (#922).** A projected node idle longer than its mapping's +`MetadataLeaseMilliseconds` keeps its retained proof; the lease is only *lapsed* when its time ran +out or its route was replaced while the local catalog authority, mapping binding and cache +generation are all still current and nothing revoked it. On a refused value Read / attribute Read / +HistoryRead of such a node, the consumer first authorizes the caller against the lapsed subject +(local grant + mapping bit, everything but the lease). A caller without the grant is still +`BadUserAccessDenied` and nothing is sent to the origin. A granted caller gets the same exact +`GetMetadata` renewal as above, for the operation it is performing (Read / HistoryRead bit, not +Subscribe), one per node and operation at a time, with a 250 ms back-off after a failure. On-demand +renewals never touch the unary budget (cold reads, writes) or the browse/subscription-renewal fetch +slots: they queue (at most 64) for their own pool of `max(1, maxConcurrentFetches / 2)` origin calls, +reserve 256 KiB each, and have 3 s end to end, so a batch of N lapsed nodes renews all N: + +- **Value Read** answers `BadWaitingForInitialData` (as a cold read does) while the renewal runs off + the request thread; once it commits, a read is scheduled so the client's retry is served from the + fresh sample. `BadResourceUnavailable` while a renewal cannot be started (capacity, back-off). + A non-Value attribute of a lapsed node answers `BadResourceUnavailable` while it renews. +- **HistoryRead** renews within the request and is then served. The wait (one per batch, at most 4 s + and never past `HistoryReadDeadline`, no node-manager `Lock` held, the request's cancellation + honoured) takes one of the non-local history batch slots first. A batch that finds none free does + not wait. A renewal that cannot complete (origin unreachable or silent, no slot) answers + `BadResourceUnavailable`. A renewal that succeeded while the node manager's ACL veto still refuses + answers `BadUserAccessDenied`. +- **Browse:** a cached page past half its lease is served as is *and* refreshed in the background + (one refresh per page key), so a re-browse renews the leases of the nodes it lists. + +An origin that stopped granting the operation fails the renewal; the consumer then keeps answering +the retryable status (it cannot tell that from an unreachable origin). + +Not covered yet: a **Write** or **CreateMonitoredItems** on a lapsed node is still refused +`BadUserAccessDenied` (neither starts a renewal; a re-browse, a Read or a HistoryRead of the node +renews it, after which they succeed). A lease that was revoked (`Invalidate`), a removed mapping and a +retired node are refusals, not lapses, and are never renewed. + An authorized logical monitored-item request can survive a physical stream expiry and seek a new pinned binding with bounded retries. The old binding and any queued sample evidence remain tied to their original authority and serving generation. The same item needs a fresh, complete baseline @@ -170,11 +204,35 @@ advertisement and a per-call request header, `x-otopcua-data-features`, whose va - The new RPCs (`HistoryRead`, `CallConditionMethod`) answer `FailedPrecondition("feature not negotiated")`. A history-only call is also refused `CallConditionMethod`. - Header-less goldens (`*Goldens.cs`) and the recorded-v1-client gates (`GrpcDataV1CompatibilityTests`, - `GrpcDataV1RealOriginCompatibilityTests`) pin the v1 bytes. Every phase ran them with an empty goldens diff. + `GrpcDataV1RealOriginCompatibilityTests`) pin the v1 bytes. Every phase ran them with an empty goldens diff. The two + pre-deploy corrections below are the only deliberate differences. The real-origin gate applies them to the recorded + goldens in `GrpcDataV1RealOriginCorrections`; the goldens are never re-recorded. -Fix two v1 defects before any v1 deploy. #916: `stable_source_id` leaks the driver id and RawPath to UNS-only peers. -#917: v1 exports alarm-bearing raw tags as variables that never get a value. G0, the v1 deploy and soak (#915), is still -open; see the plan's §1.1. +### What an origin exports (v1 corrections #916, #917) + +v1 was merged but not deployed (#915), so two defects were fixed in v1 itself. Header-less callers get the fix too. +Neither change alters the wire shape: one drops an optional field, the other drops a page item. Evidence: `docs/plans/evidence/grpc-data-ext/V1-916-917.md`. + +- **No `Metadata.stable_source_id` (#916).** The origin never sends field 10. It used to carry the internal acquisition key, + which for a driver tag is `:`. That disclosed driver ids and RawPaths to peers holding + only a UNS export. + - No consumer used the field except for byte accounting, so it was dropped rather than replaced by an opaque id. A + stable opaque id would only let a peer correlate Raw and UNS nodes. + - The field is `optional`. Old consumers decode its absence as null, so every version mix works. + - Conditions dedupe on the keyed `condition_key` instead. + - Internally the origin still keys acquisition on the unchanged `BackingSourceKey`. +- **Alarm-bearing raw tags are not exported as values (#917).** A tag with an alarm config never gets a value: the driver + host keeps it out of the value fan-out, and #896 gives it no UNS variable. + - The origin compiles it as an unsupported value node. GetMetadata, Read, Subscribe and HistoryRead on it answer + `Unsupported`, and writes are refused. + - **Browse does not list it**, and the same holds for any unsupported value node, such as a data type v1 cannot carry. + Every consumer build applies a browse page all or nothing and cannot materialise an `UnsupportedVariable`. Listing one + made the whole folder unbrowsable on the consumer (`BadNoCommunication`); the live gate found this. + - The node stays in the catalog, so an export rooted at it still compiles. Such a root grants nothing: the values are unsupported, and the condition sits under the tag's folder, not under the tag. + - The alarm itself is forwarded as a **condition** (A1–A4, see "Condition forwarding end to end"). Condition placements + do not depend on the value node. + +G0, the v1 deploy and soak (#915), is still open; see the plan's §1.1. ## Remote history (runtime consumers) @@ -200,6 +258,10 @@ the bit (see "Mixed versions" below); the AdminUI editor shows a reminder. **Negotiation.** The capabilities probe always asks for `history`; an origin advertises it only when a historian backend is configured. Other calls carry the header only toward an endpoint that advertised it. An origin without a historian, a pre-H2 origin, or a call without the header answers unsupported — the v1 responses are unchanged. +Live-gated against a real pre-H2 origin (#921, `docs/plans/evidence/grpc-data-ext/H05-v1-origin.md`): a pre-H2 origin +ignores the probe's header (capabilities byte-identical with and without it), so the consumer's projected variables have +`Historizing` False, HistoryRead answers `BadHistoryOperationUnsupported` locally, and no HistoryRead or feature-headed data +call is sent. (Sent anyway, a HistoryRead is refused `PERMISSION_DENIED` by the old data listener's v1 method allowlist.) **Limits.** @@ -479,8 +541,14 @@ refresh, EventIds) is documented in [Alarm tracking § Imported conditions](Alar is raised on the hub. - `DataConnections:ConditionKnownSettle:OpcUaClient` (default 60 s) is the only backstop timer. It exists for upstreams without ConditionRefresh. - - Open gaps: #924 (L4 latency for Galaxy, Heidenhain and real Logix ALMD), #925 (Galaxy deploy-added conditions stay - unknown) and #926 (an OpcUaClient RefreshEnd can signal known over lost events). + - Open gaps: #924 (L4 latency for Galaxy, Heidenhain and real Logix ALMD) and #925 (Galaxy deploy-added conditions stay + unknown). + - An OpcUaClient RefreshEnd signals only for a lossless refresh bracket (#926). Loss inside the bracket — queue + overflow, RefreshRequired, a skipped publish gap, or a missing RefreshStart — suppresses the signal and re-runs + ConditionRefresh, at most 3 times per episode. If every retry is lossy, the conditions stay unknown and the timeout + diagnostic reports them. A loss after the signal **withdraws** "known" for that subscription's conditions + (`AlarmInitialStateEventArgs.Withdrawn` ⇒ `MarkConditionsKnown(Known: false)`, F5 re-armed, no backstop) until a + clean refresh signals again. See `docs/drivers/OpcUaClient.md`. ### Condition key (`DataConnections:ConditionKeySecret`) diff --git a/docs/drivers/Galaxy.md b/docs/drivers/Galaxy.md index 7a6f4a014..97038e80a 100644 --- a/docs/drivers/Galaxy.md +++ b/docs/drivers/Galaxy.md @@ -206,6 +206,17 @@ The session-less alarm feed (`GatewayGalaxyAlarmFeed`) and alarm acknowledger (` Every (re)open of `StreamAlarms` replays the gateway's active-alarm snapshot. `GatewayGalaxyAlarmFeed` maps each entry to a transition flagged `IsRestatement` (#656): `Active` → `Retrigger` (upstream's unack is authoritative), `ActiveAcked` → `ActiveAcknowledged` (one atomic active+acked projection — the old `Acknowledge` mapping projected an acked alarm **inactive** on a cold host), `Inactive` → `Clear`. The host writes no `/alerts` row for a replayed entry that changes nothing the condition shows, so a gateway reconnect no longer duplicates history; live `Transition` messages are never flagged. The gateway folds UnackRtn and AckRtn into `Inactive`, so an inactive-unacked alarm cannot be distinguished at reconnect (gateway contract limit). +**Establishing a changed alarm subscription without a stream reopen (#925).** The driver turns each `snapshot_complete` sentinel into `IAlarmInitialStateSignal.InitialAlarmStateDelivered` (grpc-data A1) for the live alarm subscription, but a sentinel only comes when `StreamAlarms` opens. A subscription that becomes live while the stream is already past its sentinel (a re-subscribe with a changed alarm set, a reconnect that kept the session-less feed, or a change during the snapshot phase, which the sentinel cannot vouch for) would otherwise stay "unknown" (Uncertain on gRPC-data consumers) until the stream happened to reopen. The driver now re-reads the active-alarm set with the gateway's `QueryActiveAlarms` RPC instead. That RPC serves the same monitor cache as the stream's opening snapshot and needs the same `EventsRead` scope. +- **How a re-read is applied.** The entries are replayed exactly like snapshot entries: as restatements, with the same kind mapping. The signal follows the replay, and only if the subscription the re-read was made under is still the live one. +- **Why there are no phantom transitions.** The stream stays open. Live dispatch and the replay are serialised, so each check below and its replay happen as one step. + - An entry is skipped when the live stream delivered a full-state message for the same alarm after the query was issued (a snapshot entry, `Raise`, `Retrigger` or `Clear`), because that message is at least as new as the query's view of it (counter `galaxy.alarm_feed.snapshot_refresh.superseded`). + - An `Acknowledge` carries only the ack, so it is merged, not treated as superseding: an `Active` entry replays as `ActiveAcked`. Skipping it would have marked a cold condition known while it still showed inactive. + - If a stream (re)opened while the query was in flight, the whole re-read is discarded and does not signal. An alarm that cleared in the reopen gap is simply absent from the new snapshot, so the query's entry for it would be a phantom `Active`. The reopened stream's own sentinel covers the subscription. + - A re-read is not started while the current stream has not yet delivered its sentinel. +- **Bounded.** One re-read runs at a time. Requests that arrive while it runs collapse into one follow-up run. A failure is retried 3 times, 5 s apart. A gateway without the RPC (`Unimplemented`) is not retried. A re-read that fails never signals: the conditions stay unknown, F5 diagnoses them, and the next stream sentinel signals as before. +- **Residuals.** The query can be *ahead* of the stream: it can show a raise whose live `Raise` is still queued. That `Raise` then lands on an already-active condition, and the host treats it as the re-statement it is. Like every snapshot replay, the query lists active alarms only. An alarm that cleared while no subscription was live, so that its live `Clear` was dropped, is not cleared by it. This is a pre-existing limit of every snapshot replay. +- **In practice.** A deploy that changes a Galaxy driver's alarm tags also changes its config, so the driver respawns and its fresh feed's first sentinel covers the new set (#665: there is no in-place path). The re-read is the safety net for the paths where the feed outlives the subscription. + ## Testing - **Unit tests**: `tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/` — fakes the gateway gRPC surface; covers Browse, Runtime, Health, and Config in isolation. diff --git a/docs/drivers/OpcUaClient.md b/docs/drivers/OpcUaClient.md index 27fe1c400..9441a47c8 100644 --- a/docs/drivers/OpcUaClient.md +++ b/docs/drivers/OpcUaClient.md @@ -449,8 +449,33 @@ initialise (the AdminUI form drops them on the next save). Pinned by > `Unspecified` the host wrote as "Activated", and a retained-Active host condition stayed Active). So the host writes no > duplicate row when its condition already shows that state (see `docs/AlarmTracking.md`). Condition **branch** events (non-null `BranchId`) are ignored. > **`ConditionRefresh`** is called after the event item is created, after a keep-alive outage the session survived, and on a -> `RefreshRequired` event, so a condition already active upstream is reported at subscribe; `RefreshStart`/`RefreshEnd` -> markers are dropped. A server without it (`BadNotSupported`/`BadMethodInvalid`/…) is logged once and tolerated. +> `RefreshRequired` event, so a condition already active upstream is reported at subscribe. The `RefreshStart`/`RefreshEnd` +> markers are never projected as alarms. A server without ConditionRefresh (`BadNotSupported`/`BadMethodInvalid`/…) is logged once and tolerated. +> +> **A RefreshEnd signals "initial alarm state delivered" only for a lossless bracket (#926).** That signal is grpc-data +> A1's known-state signal. The driver tracks RefreshStart…RefreshEnd per alarm subscription, and the RefreshEnd does +> not signal when any of these happened: +> +> - no RefreshStart was seen; +> - the server sent an `EventQueueOverflowEventType`. That notice comes from the Server object, so it is matched before +> the source filter, and it is never projected as an alarm; +> - a `RefreshRequired` arrived; +> - a delivered publish message skipped a sequence number. This catches the gap the SDK gives up on after a failed +> republish, which the SDK reports nowhere else. +> +> A RefreshStart that arrives while a bracket is still open is a loss too. +> +> Any loss logs a Warning and re-runs ConditionRefresh on that subscription. That includes an overflow or sequence gap +> outside a bracket, which can hold a lost live transition, and a failed ConditionRefresh call. +> +> - **Withdraw on a later loss:** a loss after the subscription signalled also **withdraws "known"** +> (`AlarmInitialStateEventArgs.Withdrawn`). The host takes known back for those conditions (`Uncertain` on a +> consumer), keeps them out of the backstop, and diagnoses them if no signal follows. +> - **Retry bounds:** at most 3 re-refreshes run per episode, backing off 2 s, 4 s and 8 s. A clean RefreshEnd resets +> the budget. Once the budget is spent, a further loss gets a new budget only after a 5-minute cool-down. +> - **RefreshRequired:** its sweeps are coalesced while one is queued. The alarm event item asks for a +> queue of 10,000 (previously 1,000); the server may revise it down. Counters on `otopcua.driver.opcuaclient.events`: +> `alarm_event_queue_overflow` and `alarm_refresh_lossy`. > Last-told state survives a re-initialise (the host re-subscribes the same set over nodes it did not rebuild) and is > forgotten when the subscribed set changes (the host rebuilt, recreating the nodes inactive). Index keys are server-stable (`nsu=`), so a namespace reorder across a re-initialise keeps > matching. docker-dev seeds an opc-plc driver (`MAIN-opcua`); the alarm tag is diff --git a/docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md b/docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md index 9c518385b..30102c1b5 100644 --- a/docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md +++ b/docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md @@ -65,7 +65,7 @@ found while verifying M1 (row M1). | N8 G0 deferral consequences | Accepted | Recorded-v1-client gate repeated at H2, A2 and A3 exits; §1.1: #915's soak should run on an X0-or-later build | | **Revision 4 (settled offline)** | | | | B5 interception point | Settled: works | §5.6 step 1 — NM implements `ICallAsyncNodeManager`; SDK 2.0.1 dispatch traced (validation's `FindMethodState` holds `Lock` only for the lookup; per-manager `CallAsync` awaited with `ConfigureAwait(false)`); A3 not blocked | -| N5 node count | Settled: 48–49 nodes, ≈ 157 KiB each (was "~21") | §5.5 recomputed: 10,000 / 49 ≈ 204; `MaxConditions` 1,000; host caps 122,500 nodes / 400 MiB | +| N5 node count | Settled: 48–49 nodes, ≈ 157 KiB each (was "~21"; the bytes were a `GC.GetTotalMemory` artifact — #929 re-measured ≈ 77 KiB node-only, see §5.5) | §5.5 recomputed: 10,000 / 49 ≈ 204; `MaxConditions` 1,000; host caps 122,500 nodes / 400 MiB | | `state_known` field | Settled: does not exist; named additions (revised in revision 5 by T1/T2) | §5.1: `_conditionStateKnown`, `MarkConditionsKnown`, driver signal / per-driver timer, scripted inputs-established | | Event re-gating, Galaxy keying, build reporting, opc-plc alarms, alarm-tag export | Settled from code/SDK | §5.4, §6, §4.3, A02, §5.2 (+ second pre-existing v1 defect) | | Remaining live items | Listed | §9.3 L1–L5 with pass criteria | @@ -88,7 +88,7 @@ found while verifying M1 (row M1). | Galaxy one-shot signal per feed instance | Accepted (verified `GatewayGalaxyAlarmFeed.cs:69,140-152,168`) | §5.1: signal raised on **every** sentinel (not the one-shot task), and drivers re-signal each complete cycle, so conditions become known again after a reopen or a deploy that adds them; A1 test (vii) | | **Fifth pass (revision 7)** | | | | G1 driver-wide signal scope | Accepted (verified `FocasAlarmProjection.cs:253-276`, `AbCipAlarmProjection.cs:211`, `HeidenhainAlarmProjection.cs:214`) | §5.1: `AlarmInitialStateEventArgs.ConditionIds`; `MarkConditionsKnown` takes a condition-id set; per-host / per-node hooks in the driver table; MTConnect excludes `Unavailable`; A1 test (viii) | -| G2 RefreshEnd ordering across publish responses | Accepted; **settled by decompiling** `Opc.Ua.Client` 2.0.1: not ordered by default (`SequentialPublishing` false; parallel workers) | §5.1: `SequentialPublishing = true` on the alarm subscription (`OpcUaClientDriver.cs:2445`); gap ⇒ no signal; A1 test (ix) | +| G2 RefreshEnd ordering across publish responses | Accepted; **settled by decompiling** `Opc.Ua.Client` 2.0.1: not ordered by default (`SequentialPublishing` false; parallel workers) | §5.1: `SequentialPublishing = true` on the alarm subscription (`OpcUaClientDriver.cs:2445`); A1 test (ix). Loss inside the refresh bracket (EventQueueOverflow, RefreshRequired, a publish-sequence gap the SDK skipped, or a missing RefreshStart) ⇒ that RefreshEnd does not signal and ConditionRefresh is re-run, bounded (#926) | | G3 deferred signal outliving a dropped alarm | Accepted (verified `OpcUaPublishActor.cs:1048-1051`, `:1106-1112`) | §5.1 loss rule: a drop or skip discards that source's deferred `MarkConditionsKnown`; A1 test (x) | | G4 re-bind rarely holds across failover | Accepted | §5.6 step 3: client-visible behaviour stated (`BadEventIdUnknown` → `RefreshRequired` → ConditionRefresh → Good); A03 corrected | | G5 suppression gate | Accepted (verified `DriverInstanceActor.cs:184-188,1144-1148,2536-2541`) | §5.1: signal attached/gated with `OnAlarmEvent`; A1 test (xi) | @@ -191,7 +191,7 @@ has accepted the call. | Namespaces (N4) | `NM:117-118` `RegisteredNamespaceUris` (Raw, UNS, mapped/raw, mapped/uns); `NM:283-284` `RealmOf` folds every index but 0/2 into Uns | A fifth URI `mapped/conditions` is a registration change; it must be classified before `RealmOf` | | Stable source id (N3) | `SourceSamplePublisher.cs:32-33` (`":"`), emitted in `Metadata.stable_source_id` at `LocalExportCatalog.Compilation.cs:92,123` | Not usable as a condition dedupe key (discloses RawPath); pre-existing disclosure on UNS reference variables (#916) | | SDK Call dispatch (B5) | Decompiled SDK 2.0.1: `StandardServer.CallAsync` → `MasterNodeManager.CallAsync` → `NodeManagerServiceDispatcher.CallAsync` (validation via `FindMethodState`, short `lock (Lock)`, then per-manager `IAsyncNodeManager.CallAsync`); `AsyncNodeManagerAdapter.CallAsync` forwards to `ICallAsyncNodeManager` when the wrapped manager implements it; `CustomNodeManager2` (NM's base) implements `INodeManager3` only and its sync `Call`/`GetMethodCalls` skip `Processed` items | NM implements `ICallAsyncNodeManager`; imported-condition calls are claimed and awaited with no `Lock` held (§5.6) | -| Condition subtree (N5) | `NM:2461-2475` (optional `ConfirmedState`/`Confirm`/`ShelvingState`/`MaxTimeShelved` before `Create`), `ApplicationAlarmConditions.cs:7-11` (Alarm / OffNormal / Discrete) | Counted with SDK 2.0.1: 48 / 49 / 48 nodes, ≈ 157 KiB retained each (§5.5) | +| Condition subtree (N5) | `NM:2461-2475` (optional `ConfirmedState`/`Confirm`/`ShelvingState`/`MaxTimeShelved` before `Create`), `ApplicationAlarmConditions.cs:7-11` (Alarm / OffNormal / Discrete) | Counted with SDK 2.0.1: 48 / 49 / 48 nodes, ≈ 157 KiB retained each (§5.5; corrected by #929 to ≈ 77 KiB node-only) | | Event delivery path (§5.4) | Decompiled SDK 2.0.1 `MonitoredItem.QueueEvent(EventFieldList)` enqueues by reference; `Subscription.ConstructMessage` moves queued lists into `EventNotificationList` by reference; a select-clause modify rebuilds queued lists via `GetEventFields` with `Handle` = the original event; `OtOpcUaSdkServer.cs:746,768` already rewrites every Publish/Republish via `ProjectedNotificationRewriter` (`WarmStandby.cs:917`), which today passes event payloads through untouched | A marked `EventFieldList` subclass survives to Publish/Republish; the rewriter is extended to events | | Native/scripted state signals (N1) | Native `Quality = BadWaitingForInitialData` at materialise (`NM:2527`), driven Good via `WriteAlarmQuality` (`NM:1480`); `RestoreCarryOver` (`NM:2727`); scripted re-assert only for non-normal conditions (`ScriptedAlarmHostActor.cs:491`); scripted cold start re-derives Active from a `ReadTag`-seeded cache (`ScriptedAlarmEngine.cs:440-461`, `StatusNeverPushed` `:58-67`, `WorstInputStatus` `:1325`); existing driver signals: Galaxy `IGalaxyAlarmFeed.InitialSnapshotCompleted` (`:38`), OpcUaClient ConditionRefresh sweep (`OpcUaClientDriver.cs:2552`); `IAlarmSource` implementers: Galaxy, OpcUaClient, MTConnect, FOCAS, AbCip, Heidenhain; SDK `SetActiveState` stamps `TransitionTime = Now` on every call (`NM:1364` calls it per projection) | `_conditionStateKnown` + `MarkConditionsKnown` deltas + driver signal / per-driver timer + inputs-established; origin-owned activation marker (§5.1, §5.6) | | Alarm-bearing tags (N3, §5.2) | `AddressSpaceComposer.cs:978-985` (#896: no UNS value Variable for an alarm-bearing backing tag); `AddressSpaceComposer.cs:835-850` (alarm tags are in `RawTags`); `LocalExportCatalog.Compilation.cs:120-130` (no Alarm filter) | UNS placement address is a reserved reference id with no node; v1 exports alarm-bearing raw tags as dead Variables (pre-existing defect) | @@ -476,7 +476,7 @@ conditions re-report (`NM:5639-5651`). Some state changes never produce an event | Driver | Exact hook | Signal raised | |---|---|---| - | Galaxy | `GatewayGalaxyAlarmFeed.cs:168`, where the gateway's `snapshot_complete` sentinel is handled in `Dispatch` on the feed thread after the snapshot entries (`:155-169`) | On **every** sentinel, covering every condition of the feed's current subscription. The existing `InitialSnapshotCompleted` task (`:69`) stays for its current users but is not the signal: it is one-shot per feed instance (the reopen loop `:140-152` does not reset it), and its `RunContinuationsAsynchronously` continuation could overtake queued transitions. After a gateway stream reopen, the reopened stream's sentinel signals again | + | Galaxy | `GatewayGalaxyAlarmFeed.cs:168`, where the gateway's `snapshot_complete` sentinel is handled in `Dispatch` on the feed thread after the snapshot entries (`:155-169`) | On **every** sentinel, covering every condition of the feed's current subscription. The existing `InitialSnapshotCompleted` task (`:69`) stays for its current users but is not the signal: it is one-shot per feed instance (the reopen loop `:140-152` does not reset it), and its `RunContinuationsAsynchronously` continuation could overtake queued transitions. After a gateway stream reopen, the reopened stream's sentinel signals again. **#925:** a subscription that becomes live after the current stream's sentinel (or changes during its snapshot phase) is established by a `QueryActiveAlarms` re-read instead: the entries are replayed as restatements, except where a newer live message already arrived, and then the signal is raised (`docs/drivers/Galaxy.md`) | | OpcUaClient (**F1**, **G2**) | The per-event route that today drops `RefreshEndEventType` as a marker (`OpcUaClientDriver.cs:3066-3067`, `IsRefreshMarker` `:2860-2864`), reached from `OnEventNotification` (`:2749-2762`) | On receipt of `RefreshEndEventType`, covering every condition of that alarm subscription, after the refreshed events delivered before it were projected. **Not** when `TryConditionRefreshAsync` returns (`:2881-2900`). See G2 below for ordering across publish responses | | FOCAS | `FocasAlarmProjection.PollOnceAsync` per-host loop (`:243-276`): after `NoteAlarmReadSucceeded(host)` (`:273`) and that host's `Tick` (`:274`). The `continue` path for a failed host (`:253-272`) raises nothing | **Per host**: the condition ids of that host's alarm tags, after its read succeeded and its transitions were emitted. Raised again on each later successful read | | AbCip ALMD/ALMA | `AbCipAlarmProjection.Tick` (`:195`), called from `RunPollLoopAsync` (`:251`); a node whose `InAlarm` read is non-Good is skipped (`:211`) | **Per node**: at the end of each `Tick`, the condition ids of the nodes whose `InAlarm` (and, for ALMA, all plan refs) read Good in that tick. Skipped nodes are excluded | @@ -492,11 +492,39 @@ conditions re-report (`NM:5639-5651`). Some state changes never produce an event - So the RefreshEnd of a multi-response replay could be processed before an earlier response. A1 therefore sets **`SequentialPublishing = true` on the alarm subscription** (`OpcUaClientDriver.cs:2445`). The data subscriptions are unchanged. - - **As implemented (A1):** there is no gap-based suppression. The SDK 2.0.1 surface the driver sees (the per-item - `Notification` callback) exposes no per-message gap or republish failure. With `SequentialPublishing` the worker - waits for a missing sequence number (republish) before it delivers later ones, so an ordinary gap still orders the - RefreshEnd last. **Residual:** a gap the SDK gives up on could let a RefreshEnd signal over a lost refreshed event. - The mitigation for notification-queue overflow and abandoned gaps is tracked in #926. + - With `SequentialPublishing` the worker waits for a missing sequence number (republish) before it delivers later + ones, so an ordinary (recovered) gap still orders the RefreshEnd last. + - **As implemented (#926): a RefreshEnd signals only for a lossless RefreshStart…RefreshEnd bracket.** The driver + tracks the bracket per alarm subscription. It does **not** signal when: + - no RefreshStart opened the bracket (the head of the replay was discarded); + - an `EventQueueOverflowEventType` arrived since the RefreshStart. That notice comes from the Server object, so it + is matched by EventType **before** the source filter; + - a `RefreshRequired` arrived since the RefreshStart; + - a **publish-sequence gap** was seen inside the bracket. That is a delivered message whose sequence number is + neither the previous one nor its successor; the SDK sets `EventFieldList.Message`, and the alarm subscription has + one monitored item. This is how a gap the SDK gave up on is detected. SDK 2.0.1 reports that skip to nothing + else: its `PublishStateChangedMask.Republish` callback fires only in a worker pass that also delivers a message, + which the blocking gap prevents (verified by decompiling, and pinned by a real-SDK test). + - A RefreshStart that arrives while a bracket is still open is itself a loss. It never erases the open bracket's + loss. + - **A loss after the signal withdraws "known"** (review r1). This covers an overflow or sequence gap outside a + bracket, which can hold a live Raise. The driver raises `AlarmInitialStateEventArgs.Withdrawn` once per signalled + episode, ordered like the signal. The host sends `MarkConditionsKnown(Known: false)` for exactly those + conditions, removes them from the backstop, and puts them back in the F5 window. A clean RefreshEnd, or a + transition, makes them known again. + - Every loss, inside or outside a bracket, re-runs ConditionRefresh on that subscription. A failed ConditionRefresh + call is retried the same way. The retries are bounded: + - at most 3 per lossy episode, backing off 2 s, 4 s and 8 s; + - a clean RefreshEnd ends the episode and resets the budget; + - once the budget is spent, a further loss gets a new budget only after a 5-minute cool-down. So the driver + never storms the upstream and never gives up permanently. + - A RefreshRequired keeps its own sweep, now coalesced while one is queued. + - With no signal, the conditions stay unknown (`Uncertain`) and F5's `ConditionKnownSignalTimeout` diagnostic + reports them. They are never declared known-inactive, and the `Unsignalable` backstop is not used for this. + - The alarm event item's queue is now 10,000 (it was 1,000), so overflow is rarer. The detection above is the fix. + - Live on `opc-plc --alm` with a test-sized queue: the overflow notices reach the driver. With `DiscardOldest` + false the RefreshEnd is itself dropped. With `DiscardOldest` true the RefreshEnd arrives over a lossy replay and + is refused. Before the fix it signalled. Evidence: `docs/plans/evidence/grpc-data-ext/926-refresh-bracket.md`. - **OpcUaClient upstream without ConditionRefresh** (`:2887-2893`, "conditions already active are reported only on their next transition"). This is the one case with no signal at all. The driver reports `InitialStateUnsignalable` for that subscription, and the per-driver-type **backstop timer** (`DataConnections:ConditionKnownSettle:OpcUaClient`, default @@ -517,8 +545,13 @@ conditions re-report (`NM:5639-5651`). Some state changes never produce an event - `DriverHostActor` turns it into `MarkConditionsKnown(driverInstanceId, conditionIds)` and sends it to `OpcUaPublishActor` **after** the `AlarmStateUpdate`s it already forwarded (Akka preserves per-sender-pair order). - `OpcUaPublishActor` treats it as an alarm message. While a plan apply is in progress (`PlanPipelineBusy`) it is - deferred beside the `AlarmStateUpdate`s (`HandleAlarmUpdate`/`DeferAlarm`) and replayed **after** the deferred - alarms. + deferred beside the `AlarmStateUpdate`s (`HandleAlarmUpdate`/`DeferAlarm`). **As implemented after #926 review + r2:** the deferred alarm states, alarm qualities and marks are replayed in **arrival order** (one list, per-entry + sequence). Marks are held per condition, so a later mark of the same condition replaces an earlier one, and + withdrawals are bounded by the number of conditions. + - A "known" mark still lands after the projections it summarises, because it arrived after them. + - A withdrawal followed by a re-establishing transition now ends known, as the live path leaves it. Replaying all + marks last had ended it unknown. - **Loss rule (G3).** The deferral is a bounded keyed store, not a queue. An `AlarmStateUpdate` that does not fit is dropped (`DeferAlarm` → `WarnDeferredOverflow`, `OpcUaPublishActor.cs:1048-1051`), and replay skips alarms outside the applied scope (`:1106-1112`). @@ -614,7 +647,9 @@ per-origin-cluster `${secret:}` of at least 32 UTF-8 bytes, identical on both pa - It cannot be dictionary-reversed from guessable paths. An unkeyed hash was rejected for that reason. - If the secret is absent, the origin advertises no `conditions` capability (fail closed, with a diagnostic). -> **Pre-existing v1 findings (not fixed here; filed as #916 and #917):** +> **Pre-existing v1 findings (not fixed here; filed as #916 and #917).** *Update 2026-11-28: both are fixed in v1 before +> deploy. `stable_source_id` is no longer sent, and alarm-bearing raw tags are no longer value nodes (not listed by Browse, `Unsupported` on every value operation). See +> `docs/plans/evidence/grpc-data-ext/V1-916-917.md`.* > 1. #916 — `type:review-finding`, security: v1 already sends `stable_source_id` = driver id + RawPath on **UNS reference variables** > to UNS-only principals (same code path). > 2. #917 — `type:bug`: v1 exports alarm-bearing raw tags as `Variable` (`LocalExportCatalog.Compilation.cs:120-130` has no Alarm @@ -758,23 +793,28 @@ SDK 2.0.1 (scratch harness, §9.3) gives: | `OffNormalAlarmType` | **49** | 2 objects, 39 variables, 8 methods | | `DiscreteAlarmType` | **48** | 2 objects, 38 variables, 8 methods | -`Quality`, `BranchId` and `Comment` are present. The retained managed size measured **≈ 157 KiB per condition** (160,997 B -for `OffNormal`, 2,000 instances, `GC.GetTotalMemory(true)` delta, excluding NM's own indexes). **Memory, not node count, is -the binding limit.** The origin already pays the same per condition for its own local copy. +`Quality`, `BranchId` and `Comment` are present. The retained managed size of the node tree alone is **≈ 77 KiB per +condition** (79,085 B for `OffNormal`, 2,000 instances, retained heap `HeapSizeBytes − FragmentedBytes` after a full blocking +GC; ≈ 90 KB of settled working set; excluding NM's own indexes; re-measured for #929, X0 evidence). Revision 4's +"≈ 157 KiB (160,997 B)" was a `GC.GetTotalMemory(true)` delta, which on .NET 10 also counts committed-but-free GC regions +(the same harness still reports 158,169 B that way) — it was inflated ≈ 2×. The in-server worst case measured by L2 +(node tree + NM indexes + identifiers + EventId registry + placements + runner records) is **111,715 B heap / 158,629 B working +set**, and `BytesPerCondition` = **160,000 B** is set from that (A3 evidence, "L2 worst-case memory"). **Memory, not node +count, is the binding limit.** The origin already pays the same node-tree cost per condition for its own local copy. Arithmetic: - with v1's `MaxProjectionNodes` default of 10,000 (`RemoteNamespaceMapping.cs:29`), 10,000 / 49 ≈ **204** conditions would exhaust a mapping (revision 3's "≈ 476 at 21 nodes" was wrong); -- 10,000 imported conditions would retain ≈ 1.5 GiB. +- 10,000 imported conditions would retain ≈ 1.5 GiB (at the L2 160,000 B each). Defaults (conditions get their **own** budget; worst case is 49 nodes): -| Setting | Default | Nodes | Memory (≈ 157 KiB each) | +| Setting | Default | Nodes | Memory (L2 `BytesPerCondition` 160,000 B each) | |---|---|---|---| | `RemoteNamespaceMapping.MaxConditions` | **1,000** per mapping | 49,000 | ≈ 153 MiB | | `DataConnections:MaxImportedConditionNodes` (host) | **122,500** per consumer node (= 2,500 × 49) | 122,500 | — | -| `DataConnections:MaxImportedConditionBytes` (host) | **400 MiB** per consumer node (≈ 2,500 × 157 KiB = 384 MiB, rounded) | — | 400 MiB | +| `DataConnections:MaxImportedConditionBytes` (host) | **400,000,000 B** per consumer node (= 2,500 × 160,000 B ≈ 381 MiB) | — | ≈ 381 MiB | - Conditions are charged **once per `condition_key`**, not per placement. They do **not** consume `MaxProjectionNodes`, which stays for folders and variables; placement folders charge it as ordinary projected folders. @@ -790,14 +830,16 @@ Defaults (conditions get their **own** budget; worst case is 49 nodes): node's mappings exceeds `MaxImportedConditionNodes`. - Whether 1,000 per mapping / 2,500 per node covers real exports is live measurement L5 (§9.3). The defaults are tunable and sized from the measured memory cost, not from a guessed plant size. -- **What the 157 KiB excludes (m-T7):** +- **What the node-only figure (≈ 77 KiB; "157 KiB" before #929) excludes (m-T7):** - NM's indexes; - the `c1./` identifier strings on 48–49 nodes; - the per-condition EventId registry; - placement sets. - **L2 is the authority:** `MaxImportedConditionBytes` is set from the L2 measurement (per-condition in-server bytes × 2,500), - and the 400 MiB above is a provisional default until L2 passes. + **L2 is the authority:** `MaxImportedConditionBytes` is set from the L2 measurement (per-condition in-server bytes × 2,500). + L2 passed at the A3 exit: the larger of its heap and settled-working-set figures, max of three runs, rounded up, is + 160,000 B, so the default is 400,000,000 B. The ≈ 40 KiB gap between the node-only heap (≈ 77 KiB) and L2's heap + (≈ 109 KiB) is the excluded state above plus the worst-case placements, EventId slots and event-queue entries. **Stream mechanics.** @@ -1385,7 +1427,7 @@ Use two-state id selection via `SimpleAttributeOperand(type, [X, Id])`, as the C | Acks fail on busy alarms because the precondition moves | A2 | Origin-owned activation marker, bumped only on a new occurrence (T3) | | RawPath disclosure to UNS-only principals | A1 | Realm-local placements; keyed `condition_key`; property test; pre-existing `stable_source_id` disclosure is #916 | | Imported-condition method path regresses local methods | A3 | Claimed items only (`Processed`), `base.Call` unchanged for the rest; lock-freedom gate; existing `ConditionMethodEventTests` stay green | -| Imported-condition memory (≈ 157 KiB each) | A3 | Own budget sized from the counted cost; byte cap 400 MiB per consumer node; L2 confirms in-server | +| Imported-condition memory (≈ 77 KiB node-only, 160,000 B in-server worst case) | A3 | Own budget sized from the counted cost; byte cap 400,000,000 B (≈ 381 MiB) per consumer node; L2 confirmed in-server | | v1 unsoaked in service (G0 deferred, #915) | all | Per-phase live gates; deploy notes record the risk until #915 passes | ### 9.3 Settled offline vs. needs a live run @@ -1393,7 +1435,7 @@ Use two-state id selection via `SimpleAttributeOperand(type, [X, Id])`, as the C **Settled offline in revision 4** (no server needed): - the SDK 2.0.1 Call dispatch trace (decompiled with `ilspycmd` from the pinned package); - the event-delivery path; -- condition node counts (48/49/48) and retained bytes (≈ 157 KiB); +- condition node counts (48/49/48) and retained bytes (≈ 157 KiB in revision 4; ≈ 77 KiB after the #929 re-measure); - snapshot-copy cost (≈ 1.7–2.9 µs per condition); - the Galaxy ack-identity keying; - the absence of node build reporting; @@ -1401,8 +1443,10 @@ Use two-state id selection via `SimpleAttributeOperand(type, [X, Id])`, as the C - alarm-bearing tag export shape (#896). The counts, bytes and copy timing come from a scratch harness: a console project referencing `OPCFoundation.NetStandard.Opc.Ua.Server` -2.0.1 that builds each condition type with NM's optional children, walks `GetChildren`, measures a `GC.GetTotalMemory(true)` -delta over 2,000 instances, and times the snapshot field copy. It is not in the repo; X0 task 4 commits it as evidence. +2.0.1 that builds each condition type with NM's optional children, walks `GetChildren`, measures the retained heap over +2,000 instances, and times the snapshot field copy. X0 task 4 committed it as evidence (`docs/plans/evidence/grpc-data-ext/harness/`). +It first measured a `GC.GetTotalMemory(true)` delta; #929 switched it to the L2 method (full blocking GC, +`HeapSizeBytes − FragmentedBytes`, settled working set) and the figure halved. **Live measurements** — each runs on docker-dev unless stated, and each has a pass criterion: diff --git a/docs/plans/evidence/grpc-data-ext/920.md b/docs/plans/evidence/grpc-data-ext/920.md new file mode 100644 index 000000000..451df9563 --- /dev/null +++ b/docs/plans/evidence/grpc-data-ext/920.md @@ -0,0 +1,77 @@ +# #920 — `GrpcDataConfiguredDiscoveryWireTests` flake: root causes + +2026-11-28. Two unrelated causes, one in production and one in a test. Neither is a timeout, and nothing was widened or +skipped. + +## 1. `Failed_sdk_item_construction_releases_candidate_and_fanout_ownership` — production race (fixed) + +**Symptom.** The node manager's shared `ProjectedCandidateBudget` held 1 entry, expected 0. + +**Cause.** Trace instrumentation (temporary, removed) showed that the extra entry was not the failed item's. It was a +proof candidate on the *existing* item 1, for the acquisition it had already delivered (`v=1 complete=True`, same proof). +The sequence: + +1. Item 2's `CreateMonitoredItems` acquires a demand. Its stream registration gets the fake origin's snapshot, which + repeats item 1's acquisition (same version, still fresh). +2. The test's injected proof throws, so construction fails. The catch disposes the demand on the SDK thread. +3. That disposal raced the stream pump's `Publish` for the registration. The pump had passed the top check + (`!registration.Demand.IsValid`). The duplicate-baseline check `HasFreshCachedLocked(registration.Demand)` then read the + dying demand's `IsValid == false` as "the cache is not fresh". The trace shows `Publish v=1 complete=True last=1 + fresh=False`. +4. So the same acquisition was published again as a new complete baseline to every item on the node. Item 1 kept a + candidate that no SDK notification will ever consume, because the node's value did not change. The candidate also + kept its shared budget charge. + +In production this applies to any subscription whose demand is disposed while its snapshot is being published: a failed +item construction, a client deleting an item, or a session closing. Each such event re-baselines every other item on +the node and leaves one orphan candidate on each, until that item's binding changes. + +**Fix** (`ProjectedDataAccess`): + +- `HasFreshCachedLocked` no longer depends on the demand's validity. Whether the cached acquisition is fresh does not + depend on it. +- After the duplicate check, `Publish` re-checks the demand. A demand disposed since the top check publishes nothing + (`PublishDemand`). +- `AfterPublishDemandCheckForTests` is an internal seam on the pump. + +**Regression test.** `A_demand_disposed_mid_publish_does_not_republish_a_fresh_baseline`: + +- It disposes the second item's demand at the seam. +- Its positive control is a third item whose snapshot carries a new acquisition (v2) through the same in-order publisher. +- It asserts that no v1 baseline arrived before v2, and that item 1 holds exactly one candidate. +- **Red** with the two production lines reverted: `seen.Count(x => x.SourceVersion == 1) should be 0 but was 1`. +- **Green** with the fix. + +## 2. `Bad_null_sdk_notification_cannot_borrow_unproven_sample_evidence("different_timestamp")` — test race (fixed) + +**Symptom.** `BadNoCommunication` was delivered where `BadUserAccessDenied` was expected. + +**Cause.** SDK 2.0.1 delivers a node change to its items asynchronously, from `MonitoredNode2.ProcessChannelAsync`. A +`QueueValue` stack trace confirmed this. Under load, the change for the sample the test had just published reached the +item *after* the test's `Disabled → Reporting` cycle and after its injected notification. At queue size 1 it overwrote +the injected notification (source timestamp T+1). The proven sample (T) that took its place correctly matched its +candidate and was correctly delivered. + +So the production fence held, and the test's assumption that delivery is synchronous was wrong. The `different_status` +case already tolerates this ordering. + +**Fix.** Before the mode cycle, the test waits until the SDK has queued the published sample. It checks the item's +`m_lastValue` for source timestamp T and `BadNoCommunication`, with a 10 s bounded wait that fails with a message. + +The other scenarios were already robust: + +- `ambiguous` and `missing_timestamp`: a late second sample is ambiguous against both candidates, so it is denied anyway. +- `expired_proof`: the proof is invalid, so the notification is denied anyway. + +## Numbers (macOS, Release, shared host, load average 25–100 from parallel agents) + +| | Before | After | +|---|---|---| +| Class runs (`--filter FullyQualifiedName~GrpcDataConfiguredDiscoveryWireTests`) | **5 / 16 failed** (4 × failed-construction, 1 × different_timestamp) | **30 / 30 consecutive passed** (111 tests each, incl. the new one) | +| `different_timestamp` stressed in-process (100 ×) | 16 / 100, 6 / 40 | 0 / 100 | +| failed-construction stressed in-process | 2 / 150 | 0 / 100 | +| New regression test (25 ×) | red, deterministic | 0 / 25 | + +Other gates at `4cf06261`: `dotnet build ZB.MOM.WW.OtOpcUa.slnx -c Release` 0 warnings / 0 errors; Runtime.Tests (rest of the +suite, `Category!=E2E&Category!=LiveIntegration`) 1982 passed, 3 skipped; Host.Tests `.DataConnections.` (incl. the v1 +compatibility gate) 207 passed. diff --git a/docs/plans/evidence/grpc-data-ext/926-refresh-bracket.md b/docs/plans/evidence/grpc-data-ext/926-refresh-bracket.md new file mode 100644 index 000000000..27073486b --- /dev/null +++ b/docs/plans/evidence/grpc-data-ext/926-refresh-bracket.md @@ -0,0 +1,177 @@ +# #926 — OpcUaClient RefreshEnd signals only for a lossless refresh bracket + +2026-11-28. Follow-up to A1 (plan §5.1, OpcUaClient row, G2). + +## Defect + +A1 takes the alarm subscription's `RefreshEndEventType` as `InitialAlarmStateDelivered`. That signal declares the +conditions it covers state-known. The driver raised it on every RefreshEnd, including one that closed a replay that had +lost events. A condition that was active upstream could then be declared known-inactive. + +## Ways a replay can lose events + +- **Event-queue overflow.** The upstream inserts an `EventQueueOverflowEventType` notice. Its SourceNode is the Server + object, so the driver's source filter dropped it, and in pass-through mode it would have been projected as an alarm. + Where the notice lands depends on `DiscardOldest`: + - With `DiscardOldest` false (production), the newest events, often the RefreshEnd itself, are dropped. + - With `DiscardOldest` true, or on a server that refreshes asynchronously, the RefreshStart and the head of the + replay are dropped, but the RefreshEnd still arrives. +- **RefreshRequired** arriving during the replay. +- **A publish gap the SDK gives up on.** With `SequentialPublishing` the SDK holds later messages while it republishes + the missing one. If that republish fails (`BadMessageNotAvailable`), it skips the gap and delivers the next message. + - Decompiling SDK 2.0.1 (`Subscription` message worker) shows that `PublishStateChangedMask.Republish` is raised only + inside `if (messagesToDeliver != null)`. + - So when the gap is holding every later message back, which is exactly this case, no callback fires. Verified with a + real `Subscription`: the order was `live:1, start:2, end:4` and no Republish state was raised. + +## Fix (`OpcUaClientDriver`) + +**Per-subscription bracket state.** Each `RemoteAlarmSubscription` has an `AlarmRefreshBracket`, guarded by +`_alarmStateLock`. + +**Bracket events are matched by EventType before projection** (`RouteBracketEvent`): +- RefreshStart opens the bracket. +- EventQueueOverflow records a loss and requests a re-refresh. +- RefreshRequired records a loss; its existing sweep is the re-refresh. +- RefreshEnd signals only if the bracket was opened and saw no loss. Otherwise it logs a Warning, increments + `alarm_refresh_lossy`, and requests a re-refresh unless one was already requested. + +**Publish-sequence check.** `RouteAlarmEventFieldList` reads `NoteAlarmMessageSequence(efl.Message.SequenceNumber)` +before it routes the event. The alarm subscription has one monitored item, so every message that carries data +consumes one sequence number. Inside a bracket, a number that is neither the same as the last nor its successor +(wrap-aware) is a loss. + +**Bounded re-refresh.** `ScheduleAlarmRefreshRetryLocked` → `RetryAlarmRefreshAsync`: +- At most 3 re-refreshes per episode, backing off 2 s, 4 s, then 8 s. A clean RefreshEnd resets the budget. +- Requests are coalesced while one is pending. +- The retry is cancelled with the session's work token, and skipped if the subscription is no longer the one + registered. +- When the budget is spent, one Warning is logged (it includes the revised queue size) and nothing signals. The + conditions stay unknown (`Uncertain`) and F5's `ConditionKnownSignalTimeout` diagnostic reports them. + `Unsignalable` is deliberately not used: it starts the backstop that marks the conditions known. + +**Queue size.** The alarm event item's queue is now 10,000 (it was 1,000), so overflow is rarer. The detection above is +the actual fix. + +**New counters.** `otopcua.driver.opcuaclient.events{event=alarm_event_queue_overflow|alarm_refresh_lossy}`. + +## Tests + +### Unit: `OpcUaClientRefreshBracketLossTests` + +11 tests: + +- an overflow inside the bracket, a RefreshEnd with no RefreshStart, and a RefreshRequired inside the bracket each + suppress the signal, and each has a positive control; +- an overflow outside a bracket requests a re-refresh; +- the retry bound, and the budget reset after a clean bracket; +- a re-refresh whose own RefreshStart is lost can request the next one; +- sequence gap, repeat, wrap and gap-outside-bracket; +- the overflow notice is never projected; +- queue-size pin; +- the real-SDK abandoned gap, plus a lossless real-SDK positive control. + +`OpcUaClientInitialAlarmStateSignalTests`: the two tests that routed a RefreshEnd with no RefreshStart now route the +RefreshStart first. A real server always sends one, and the live latency test below passes with the new requirement. + +### Red + +These mutations were run as red checks: + +- **RefreshEnd always signals:** 6 of 10 bracket tests fail. +- **Sequence check removed:** the real-SDK gap test fails. +- **Live:** the same always-signal mutation gives `signals=3` over lossy replays (run `discardOldest=True`, below). + +### Live: `OpcUaClientRefreshOverflowLiveTests` + +Run against the shared `opc-plc --alm` at `opc.tcp://10.100.0.35:50000`, read-only, using test seams for the item's queue +size and `DiscardOldest`. No local docker, so the rig lock was not needed. + +| Case | Overflow notices seen | Lossy RefreshEnds refused | Signals | +|---|---|---|---| +| `DiscardOldest=false`, queue 1 | 25 | 0 (the RefreshEnd was dropped by the server) | 0 | +| `DiscardOldest=true`, queue 2 | 11–20 across runs | 1–3 across runs (≤ 1 + 3, bounded) | 0 | +| Production queue (control) | 0 | 0 | signalled | +| Mutation (always signal), `DiscardOldest=true` | 15 | — | **3** | + +The lossy-RefreshEnd count varies because opc-plc keeps firing live alarms, which can push a RefreshEnd out of a +2-entry queue. + +Two observations from the runs: + +- `DiscardOldest=false` with queue 2 produced no overflow notice and no RefreshEnd on this opc-plc. It still never + signalled, so the outcome was safe. +- A `MeterListener` filtered by `ReferenceEquals` on `OtOpcUaTelemetry.OpcUaClientEvents` never enabled the counter + when that class ran alone. The instrument is published inside the type's static initializer, where the field still + reads null. The test now reads the field before calling `Start()`. + +`OpcUaClientAlarmSignalLatencyTests` (L4) still passes 20 out of 20 samples, which means opc-plc sends RefreshStart. + +## Residuals + +- **False positives.** A StatusChange-only message on the alarm subscription consumes a sequence number and reads as a + gap. So can an SDK sequence resync after a transfer. Either costs one bounded re-refresh and is never a wrong signal. +- **Stale RefreshEnd.** If the previous replay's lossy RefreshEnd is still in flight when a re-refresh starts, it can + request one extra refresh. That stays inside the bound. +- ~~**Live losses after the conditions are known.** An overflow outside a bracket is repaired by a re-refresh. A gap + outside a bracket is not detected, but the next bracket replays the full state. In both cases conditions that are + already known are not taken back to unknown.~~ Superseded by review round 1 (below): both are losses, re-refreshed, + and they withdraw "known". + +## Review round 1 (2026-11-28) + +| # | Finding | Outcome | +|---|---|---| +| 1 | A sequence gap outside a bracket was detected and ignored, although it can hold a live Raise. | **Fixed.** Every newer, non-successor sequence number is a loss, inside or outside a bracket. It withdraws "known" if the subscription signalled, and requests a re-refresh from the same budget. | +| 2 | A loss after the signal never withdrew "known". The budget was shared across episodes. | **Fixed with a new host contract.** `AlarmInitialStateEventArgs.Withdrawn` is an additive constructor flag, exclusive with `Unsignalable`. The driver raises it once per signalled episode, on the first loss, ordered like the signal. `DriverHostActor` turns it into `MarkConditionsKnown(Known: false)` for exactly those conditions (the existing withdraw primitive), removes them from the backstop, and re-adds them to the F5 pending set. The budget was already per episode, because a clean RefreshEnd resets it. A spent budget now also renews after a 5-minute cool-down (`AlarmRefreshRetryCooldown`). While spent, a loss leaves the request open (`ScheduleAlarmRefreshRetryLocked` returns false), so the post-cool-down loss can start a retry. | +| 3 | A nested RefreshStart erased the outer bracket's loss. | **Fixed.** A Start while a bracket is open is recorded as a loss with `??=`, so it never clears the existing one. A depth counter was rejected: in the serial case a lost RefreshEnd would keep the depth above zero forever, so nothing would ever signal. | +| 4 | A failed ConditionRefresh (at subscribe, in a sweep, or in a retry) was never retried. | **Fixed.** The catch in `TryConditionRefreshAsync` calls `NoteConditionRefreshFailed`, which uses the same bounded retry. | +| 5 | A retry's `finally` cleared a `RetryPending` that a newer retry had set. | **Fixed** with a generation token (`RetryGeneration`). | +| 6 | Backward sequence numbers were written back, which produced a second, false gap. | **Fixed.** A repeated or older number (wrap-aware, forward distance ≥ 2³¹) is ignored and not recorded. | +| 7 | The RefreshRequired sweep was unbounded. | **Coalesced**: a RefreshRequired is a no-op while a sweep is queued and not yet started. It is not rate-limited, so a server that sends RefreshRequired continuously still gets back-to-back sweeps. That limit existed before this change and is reported as a follow-up. | + +**Red checks.** One mutation per fix, each run against the new tests: + +- M1 (gap outside a bracket ignored): `Sequence_gap_outside_a_bracket_withdraws_known_and_re_refreshes` fails. +- M2 (no withdraw): the 3 withdraw tests fail. +- M3 (a nested Start erases the loss): `An_overlapping_RefreshStart_does_not_erase_the_loss` fails. +- M4 (no generation token): `A_retry_scheduled_during_a_refresh_call_keeps_coalescing` fails. +- M5 (older numbers recorded): `An_older_sequence_number_is_ignored_and_not_recorded` fails. +- M6 (a failed refresh is not retried): `A_failed_ConditionRefresh_is_retried_bounded` fails. +- M7 (host ignores `Withdrawn`): Runtime `A_withdrawn_signal_takes_known_back_and_rearms_F5_until_the_next_signal` and + `A_withdrawal_cancels_the_backstop_for_its_conditions` fail. + +M6 goes through the `ReportRefreshFailedForTest` seam. The catch that calls it is covered by review. + +**Residual.** If a subscription never signalled (its initial refresh is still pending), a loss withdraws nothing, +because nothing was known. + +## Review round 2 (2026-11-28) + +| # | Finding | Outcome | +|---|---|---| +| 1 | `OpcUaPublishActor` replayed every deferred alarm first and every mark last. So a withdrawal followed by a transition, both deferred by a plan, ended **unknown** although the transition had re-established the condition, and the host no longer counted it in F5. | **Fixed.** Deferred alarm states, alarm qualities and marks replay as **one list in arrival order**. Each entry carries a sequence number, and consecutive marks of the same (source, realm, known) are batched into one sink call. The G3 out-of-scope check is a pre-pass, so a source's known marks are still discarded wherever they sit in the list. Pinned by `Deferred_alarms_and_marks_replay_in_arrival_order`, which also checks the mirror order (transition then withdrawal ends unknown). That test is red against the previous actor. | +| 5 | The deferred-withdrawal list was "bounded by connectivity edges", which stopped being true once #926 made withdrawals routine. | **Fixed.** Deferred marks are now held **per (realm, condition)**, and the latest mark wins. Withdrawals are never dropped, and are bounded by the number of conditions. Known marks for a new condition beyond `Capacity` still overflow, as before. `A_withdrawal_beyond_the_deferral_capacity_is_never_dropped` now expects one coalesced replay instead of three (it is red against the old list). | +| 2 | The driver looked up the subscription outside `_alarmStateLock`, so a stale record could signal or withdraw. | **Fixed.** `IsRegisteredLocked` is re-checked under the lock before a RefreshEnd signals and before a withdrawal, and both removals (`UnsubscribeAlarmsAsync`, the shutdown loop) now take the lock. There is no deterministic unit test for this race; the lock is the guarantee. | +| 3 | A withdrawal after F5 had already raised its diagnostic did not update the diagnostic's count. | **Fixed.** The host calls `Hub.UpdateUnsignalled` when the pending set grows under a raised diagnostic. Covered by `A_withdrawal_after_the_diagnostic_updates_its_count`, which is red with the call removed. | +| 4 | Conditions on unsignalable subscriptions never withdraw. | **Documented** in `IAlarmInitialStateSignal`. Only a source that signalled withdraws; conditions made known by the backstop stay known through a later loss. That is the backstop's own residual. | +| 6 | The backstop test had no positive control. | **Fixed.** The sibling condition that was not withdrawn is marked known by the same backstop. | +| — | `AlarmInitialStatePublished` serialization | A comment now says it must stay in-process: a serialized copy that lost `Withdrawn` would default it to false and turn a withdrawal into a known mark. | + +**Found, not mine.** `OpcUaPublishActorWarmTests.A_deployed_cluster_mode_that_disagrees_with_the_local_mode_is_logged_and_counted` +fails when run in isolation. It has the same `MeterListener` and static-initializer trap fixed in the live test above: +it matches `ReferenceEquals(instrument, OtOpcUaTelemetry.RedundancyModeMismatch)` before that field has been initialized. +Reported as a follow-up. + +**Round 2 gates:** + +- Full Release build: 0 warnings. +- OpcUaClient.Tests: 430/430. +- OpcUaClient.IntegrationTests: 13/13, live against opc-plc. +- `GrpcDataV1CompatibilityTests`: 49/49. +- Runtime.Tests: 2095 of 2100 passed and 3 were skipped. + - The 2 failures are pre-existing; neither is caused by #926. + - `DriverHostActorApplyingStashTests.ACompletedApply_NeverReportsAWedge` fails every time on base `05f431f5d` too. I + confirmed this in a clean worktree at that commit. + - `GrpcDataConfiguredDiscoveryWireTests.Bad_null_sdk_notification_cannot_borrow_unproven_sample_evidence(different_timestamp)` + fails only under full-suite load. It passes in isolation, both on this branch and on base. diff --git a/docs/plans/evidence/grpc-data-ext/A1-core.md b/docs/plans/evidence/grpc-data-ext/A1-core.md index fc3f22541..92ccf20df 100644 --- a/docs/plans/evidence/grpc-data-ext/A1-core.md +++ b/docs/plans/evidence/grpc-data-ext/A1-core.md @@ -215,6 +215,26 @@ Heidenhain legs are **blocked**: Galaxy needs the VPN and mxaccessgw, and Heiden sentinel, which comes only on a stream reopen. Until then F5 diagnoses it. - This is by design (vii): the snapshot that preceded the subscribe may have carried that alarm while it was unroutable. - Open question: should the driver ask the gateway for a fresh snapshot on a changed subscription set? + **Answered by #925 (2026-11-28):** yes. mxaccessgw already serves `QueryActiveAlarms` from the same monitor cache as the + stream snapshot, so no gateway change was needed. A subscribe on a stream that is past its sentinel, and a sentinel for + a stream opened under an earlier subscription (F4), both trigger a re-read. The re-read is replayed as restatements; an + entry is skipped when the live stream already delivered a newer message for that alarm. Then the live subscription is + signalled. Re-reads are coalesced: one in flight plus one follow-up. A failed re-read is retried 3 times and never + signals. Tests: `GalaxyAlarmSnapshotRefreshTests` (6). Each of these mutations turns a test red: no re-read on subscribe + (5 red), no supersede check, no handle check at the signal, Unimplemented retried, no re-read at a mismatched sentinel, + no coalescing. The F5 re-arm for deploy-added refs was already in place (`RearmConditionSignalsAfterReindex`, review + round 1). **Not live-gated:** no Galaxy or mxaccessgw is reachable (wonder-box hold). + **#925 review round 1:** + - *Ack-only supersede:* a live `Acknowledge` no longer supersedes an entry. It is merged instead (Active ⇒ ActiveAcked). + Test `An_acknowledge_during_the_reread_merges_into_its_entry_instead_of_superseding_it`. Red on the original code, and + on either mutation: ack counted as full state, or no merge. + - *Reopen during the query:* a stream epoch is bumped before `StreamOpened`. A changed epoch at replay time drops the + re-read and its signal. No re-read starts before the current stream's sentinel. Test + `A_stream_reopen_during_the_reread_drops_its_replay_and_its_signal`. Red on the original code (phantom Tank2 + Retrigger plus a second signal), and with the epoch check removed. + - *Lows:* a dispose race returns false instead of throwing `ObjectDisposedException`. The retry wait and the RPC observe + a teardown token, which every runtime teardown cancels. An unexpected failure no longer discards a queued follow-up. + - Galaxy.Tests: 645 passed, 13 skipped. The 13 alarm-signal tests passed 15 runs out of 15. - **OpcUaClient: no signal suppression on an SDK-reported sequence gap during a refresh.** Plan G2 says such a `RefreshEnd` "does not signal". - The SDK 2.0.1 surface the driver sees (the per-item `Notification` callback) exposes no per-message gap or republish @@ -222,6 +242,9 @@ Heidenhain legs are **blocked**: Galaxy needs the VPN and mxaccessgw, and Heiden - With `SequentialPublishing` the worker waits for the missing sequence number (republish) before delivering later ones. - Residual: a gap the SDK gives up on could let a `RefreshEnd` signal over a lost refreshed event. **Resolved in review round 2:** the plan's G2 text now states what is implemented, and the overflow and gap mitigation is tracked in #926. + - **#926 (2026-11-28) closes the residual.** The driver now detects the skipped gap itself, from the delivered message's + sequence number. It also detects queue overflow, RefreshRequired and a missing RefreshStart inside the refresh + bracket, and re-runs ConditionRefresh, bounded. See `926-refresh-bracket.md`. - **MTConnect also signals on a mid-stream `/current` re-baseline** (OUT_OF_RANGE / Agent restart), not only on the subscribe resync and the pump's first act. A re-baseline is a complete re-read, and without the signal a restarted Agent's conditions would wait for the next reconnect. diff --git a/docs/plans/evidence/grpc-data-ext/A3-927.md b/docs/plans/evidence/grpc-data-ext/A3-927.md new file mode 100644 index 000000000..0c8ba5279 --- /dev/null +++ b/docs/plans/evidence/grpc-data-ext/A3-927.md @@ -0,0 +1,49 @@ +# #927 — live gate: driver-failure ack revert through DriverHostActor under the connection service principal + +A2b (remote `CallConditionMethod`) had been gated live only for a scripted condition. The path where a remote ack of a +**native** condition reaches a driver that fails it, and DriverHostActor reverts the node (`RevertNativeAlarmAck`, +`AlarmStateUpdate(EstablishesState: false)`), was unit-tested only (`ConditionMethodNodeManagerTests`, A2.md "Driver failure +revert seen in the stream"). This adds scenario **A09** to `scripts/validation/grpc-data/conditions_scenarios.py` and runs it. + +## How the driver is made to fail (a real failure, no seam) + +The conditions profile's SOURCE `OpcUaClient` driver `source-opcua` watches the run-owned `opc-plc:2.14.10 --alm` native alarm +`EastTankYellow`. A09 `docker compose pause`s the `opcplc` container immediately before the consumer's ack. The driver is still +`Connected` (its keep-alive has not yet noticed), so `OpcUaClientDriver.AcknowledgeAsync` sends the upstream +`AcknowledgeableConditionType.Acknowledge` call and gets **no reply**; the SDK call fails with a `ServiceResultException` +(request timeout) inside the 5 s ack window, `DriverInstanceActor.HandleAcknowledgeAsync` reports `AlarmAckFailed`, and +DriverHostActor reverts. The container is unpaused in the scenario's `finally` (and again by the per-scenario restore if it +was left paused). Pausing also freezes opc-plc's own alarm cycling, so no upstream transition can explain the +Unacknowledged that follows the ack. + +**Why not an upstream refusal.** The option the issue suggests — an upstream that answers the Acknowledge with a Bad status +(stale EventId, already acked) — does **not** revert today: `OpcUaClientDriver.AcknowledgeAsync` only logs a per-ack Bad +result (and an ack whose condition id resolves to nothing), by design (`docs/drivers/OpcUaClient.md`: "a reply still returns +normally, including per-ack refusals … a refusal is the server answering"), to keep refusals off the AlarmAcknowledge breaker. +`DriverOperationRefusedException` now exists for exactly that (breaker-exempt, reverts), so an upstream refusal leaving the +node Acknowledged is a gap — reported as a follow-up, not changed here (it reverses a documented driver decision). A +no-reply transport failure is the failure class the driver does surface, and it exercises the whole revert path. + +## Result — run `a927-1`, 2026-11-28, HEAD `cdbbe22a9`: A09 **PASS** (12/12) + +`rig.py up --conditions` → `seed` → 85 s → `deploy --timeout 300` → `conditions_scenarios.py --only A09` → `rig.py down` +(0 run containers, 0 run volumes). + +| Check | Evidence | +|---|---| +| native condition present on both sides, Unacknowledged | consumer `EastTankYellow` `Inactive, Unacknowledged` (opaque `ns=6;s=c1.…` id), origin `ns=2;s=opcua/opcplc/EastTankYellow` same record time | +| caller gets Good | 15:13:40 `opcplc` paused; consumer CLI `ack` ⇒ `Acknowledge successful` (plan §5.6 step 5: native ⇒ Good, `AcceptedUnconfirmed`; the failure reaches the caller as the revert) | +| audit records the remote call | origin `source-1`: `Data-connection condition method Acknowledge by fixture-consumer (key …) on Raw:…:opcua/opcplc/EastTankYellow op a3-…: AcceptedUnconfirmed 0x00000000; on behalf of fixture-cli` — the connection's **service principal** (`fixture-consumer`) on behalf of the end user | +| the driver really failed | 15:13:46 `DriverInstance source-opcua: native-alarm acknowledge of opcua/opcplc/EastTankYellow failed` | +| DriverHostActor reverted (EstablishesState: false) | 15:13:46 `DriverHost source-1:4053: … did not reach the alarm system (the upstream acknowledge failed (ServiceResultException)); reverting the condition to unacknowledged` — `RevertNativeAlarmAck` is the only producer of that line and of an `EstablishesState: false` update | +| origin node applied, then reverted | origin Server-object events after the ack: `Inactive, Acknowledged` → `Inactive, Unacknowledged` (nothing else: upstream frozen) | +| consumer saw the reverted delta | consumer events after the ack: `Inactive, Acknowledged` → `Inactive, Unacknowledged`; same ConditionId, a new EventId | +| positive control | 15:13:48 unpaused; 30 s later the condition was `Active, Unacknowledged` (opc-plc had re-activated it; whether the paused call was later applied upstream is not observable from this state); a second consumer ack of the current EventId ⇒ Good and **no** new revert line in the next 15 s | + +Evidence files (removed with the run folder; copies taken before `down`): `evidence/A4S-A09.json`, `A4S-results.md`, the CLI +`*.process.json` logs. + +## Not covered + +- The upstream-refusal flavour (Bad per-ack status) — it does not revert; follow-up above. +- `/alerts` (alarm-history) rows for the ack and its revert were not asserted. diff --git a/docs/plans/evidence/grpc-data-ext/A3.md b/docs/plans/evidence/grpc-data-ext/A3.md index ccac46fab..8b49f81a4 100644 --- a/docs/plans/evidence/grpc-data-ext/A3.md +++ b/docs/plans/evidence/grpc-data-ext/A3.md @@ -300,6 +300,8 @@ regions at baseline). Per the plan, `MaxImportedConditionBytes` is now set from **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. +(Superseded: these figures and X0's were `GC.GetTotalMemory` deltas — see round 2's L2 below and #929, which re-measured the +node-only retained heap at 79,085 B.) ## Live — run `a3b-cond-3` (build `82ecc116`, clean tree) — PASS @@ -658,7 +660,7 @@ Worst case (2 placements per condition, all 8 EventId slots filled, 3 event item **L2: PASS** (both ≤ 200 MiB in every run). `BytesPerCondition` = the larger of the two per-condition figures, max of three runs, rounded up: 158,629 → **160,000** (was 230,000); `MaxImportedConditionBytes` default = 160,000 × 2,500 = **400,000,000 B (≈ 381 MiB)** (was ≈ 548 MiB). The X0 node-only figure (160,997) and A3b's 197.4 MiB were taken with `GetTotalMemory` too and are -likely inflated the same way (not re-measured here). +likely inflated the same way (not re-measured here; #929 re-measured X0: 79,085 B node-only heap, X0 evidence). ## Gates (round 2, at `b884db5f`) @@ -693,7 +695,8 @@ Active/Acknowledged; `passed: true`. Teardown: no run-labelled containers or net - File: the `GrpcDataConditionStreamTests.Overflow_before_the_snapshot_is_drained_resets_the_stream` load sensitivity (above). - The plan's L2 / X0 figures (≈ 157–161 KiB per condition node, §5.5 table) came from `GC.GetTotalMemory` and are likely - inflated by the same region accounting; the plan's §5.5 table was not edited (evidence only). + inflated by the same region accounting; the plan's §5.5 table was not edited (evidence only). Done in #929: the X0 harness + now uses the L2 method (79,085 B node-only heap vs 158,169 B by `GetTotalMemory`), and §5.5 cites L2's 160,000 B. # A3 — Verification review round 2 diff --git a/docs/plans/evidence/grpc-data-ext/A4-docs.md b/docs/plans/evidence/grpc-data-ext/A4-docs.md index a547cb2d8..6936cb541 100644 --- a/docs/plans/evidence/grpc-data-ext/A4-docs.md +++ b/docs/plans/evidence/grpc-data-ext/A4-docs.md @@ -32,7 +32,7 @@ The sources were the code at `91438049` and the evidence logs X0–A3. The plan | # | Plan says | Code does (evidence) | |---|---|---| | D1 | §5.6 step 2(c): one per-node semaphore (default 8) bounds remote method calls. | 8 per node **and** 4 per connection inside them. A dispatch with < 250 ms of budget left is `BadTimeout`, unsent (`ImportedConditionMethods.cs:63-79`, `:247`, `:270`; A3b review S4). | -| D2 | §5.5 / §6: `MaxImportedConditionBytes` 400 MiB, ≈ 157 KiB (160,997 B) per condition. | `BytesPerCondition` = 160,000. The default is 400,000,000 B ≈ 381 MiB (`ProjectedConditionAccess.cs:58-61`, `DataConnectionOptions.cs:25`; A3 round-2 L2 measured the retained heap, not `GC.GetTotalMemory`). #929 re-measures the plan's figures. | +| D2 | §5.5 / §6: `MaxImportedConditionBytes` 400 MiB, ≈ 157 KiB (160,997 B) per condition. | `BytesPerCondition` = 160,000. The default is 400,000,000 B ≈ 381 MiB (`ProjectedConditionAccess.cs:58-61`, `DataConnectionOptions.cs:25`; A3 round-2 L2 measured the retained heap, not `GC.GetTotalMemory`). #929 re-measured the plan's figures: node-only 79,085 B heap (X0 harness, now on the L2 method); §5.5 corrected, default unchanged. | | D3 | §6 metrics list `…conditions.refresh_required`. | Not present (`OtOpcUaTelemetry.cs:233-265` has `unsignalled`, `partition_overflows`, `items`, `resyncs`, `capacity_rejections`, `condition_methods`, `marks_discarded`). A4 diagnostics work; TODO 2. | | D4 | §5.4/§5.5: demand per connection the caller could see. | Demand is node-wide: the first admitted event item opens every condition-bearing connection, and the per-event gate still decides visibility (A3a deviation 2). | | D5 | §6: local visibility uses "the Subscribe grant on the `RemoteNamespaceMapping` scope". | `Subscribe` on the **placement folder's** scope, within a current mapping of the placement's realm that grants `AlarmSubscribe`, not `AlarmRead` (`ProjectedConditionAccess.cs:170-190`; A3 Runtime gate tests). Narrower than the mapping scope, and consistent with it. | diff --git a/docs/plans/evidence/grpc-data-ext/H05-v1-origin.md b/docs/plans/evidence/grpc-data-ext/H05-v1-origin.md new file mode 100644 index 000000000..9df80a922 --- /dev/null +++ b/docs/plans/evidence/grpc-data-ext/H05-v1-origin.md @@ -0,0 +1,59 @@ +# #921 — H05 live gate against a real pre-H2 (v1) origin + +The H3 gate replaced H05 ("v1 origin ⇒ unsupported") with an origin export that drops HistoryRead (H3.md "Not verified / +substitutions"). That removes `Historizing` before any wire call, so the plan §4.3 mixed-version row "new consumer → v1 origin" +was never exercised live. This gate runs it against a SOURCE pair built from a pinned pre-H2 commit. + +## Rig additions (`scripts/validation/grpc-data/`, README "Pinned pre-H2 SOURCE") + +- `rig.py up --source-revision `: `resolve_pinned_source_revision` requires X0 `a15912539` to be an ancestor (a pre-X0 + node rejects the whole snapshot once a newer bit is authored), H2 `ef938b435` **not** to be one, and no `rpc HistoryRead` in + that revision's `data_connection.proto`. **`0c86edc19`** (the #918 merge, between H1 and H2 on master's first-parent line) + passes; it is post-X0 (tolerant readers, feature header parsed with `SupportedFeatures = None`), its + `LocalDataServices.Implemented()` has no HistoryRead and its proto has no HistoryRead RPC — a genuine v1 origin. +- The rig `git archive`s it into the run folder, adds one rig file (`node-probe/WireTap.cs`, ASP.NET Core only, compiled + unchanged against the pinned tree) and builds the pinned tree's own Dockerfile (`compose.source-pinned.yml`). CONTROL and + CONSUMER run this checkout. `verify_candidate` checks SOURCE stamps against the pinned revision and export hash, the other + four against this checkout. Unit tests: `PinnedSourceRevisionTests` (6, incl. the real `0c86edc1` / H2 commits). +- **Wire tap** (`GRPC_DATA_WIRE_TAP=1`, only on the pinned SOURCE): per data-listener request, one line at arrival (gRPC path, + `x-otopcua-data-features` value, remote address — before authentication) and one at completion (gRPC status). No credential + or body. +- `Client.CLI read --attribute ` (new; `Historizing`, `AccessLevel`, …) for a real OPC UA attribute read. +- `history_v1_origin_gate.py` (H05V1) and probe `--scenario history-v1-origin`. + +## Result — run `h05v1-1`, 2026-11-28 15:20–15:26 UTC: **PASS, 25/25 checks** + +`rig.py up --history --source-revision 0c86edc1 --timeout 1500` → `seed` → 80 s → `deploy --timeout 300` (all six nodes +applied the HEAD-built artifact, including the pinned SOURCE pair) → `history_v1_origin_gate.py` → `down` (0 containers, +0 volumes, 0 images left). SOURCE has a SqlServer historian and historizes `counter` (the `--history` overlay). + +| Assertion | Observed | +|---|---| +| builds | `source-1/2` stamp `0c86edc194bf…` (pinned export hash `1111f654…`); `control-*`, `consumer-*` stamp HEAD `cdbbe22a9` | +| projected Raw + UNS `counter` `Historizing` | `False` (Good) on both; `AccessLevel` = 1 (CurrentRead, no HistoryRead bit) | +| control: origin's own `counter` | `Historizing` `True`, `AccessLevel` = 13 (HistoryRead bit set); projected value Read Good on both realms | +| `historyread` on projected Raw / UNS `counter` | `HistoryRead of ns=4;s=p1.… failed: BadHistoryOperationUnsupported (0x80720000).` (UNS `ns=5` same) | +| control: `historyread` on the origin's node | Good, 30–31 rows in the window | +| diagnostics (CONSUMER page, prerendered) | `Negotiated features none (v1 behaviour) · origin history not advertised · projected history reads good 0 · uncertain 0 · bad 0` | +| diagnostics (SOURCE page) | `Exports with dropped unknown operation bits: export-raw: HistoryRead; export-uns: HistoryRead — this node's build is older than a feature authored here; the dropped bits grant nothing until the node is upgraded.` | +| tap, consumer window (12 arrivals, all from the two consumer containers, no other remote) | methods `GetCapabilities, Browse, GetMetadata, Read` (control: the consumer's v1 traffic is there); **no** `HistoryRead` / `CallConditionMethod`; the only arrivals carrying the feature header are the capability probes (`history,conditions`, plan §4.1: the probe always asks) | +| tap positive control (probe `history-v1-origin`, both origins) | capabilities with `history,conditions` byte-identical to capabilities without (operations 31, no `history`, no `conditions`); a HistoryRead with header `history` arrives at the tap with that header and completes **`grpc-status 7` (PERMISSION_DENIED)** | + +**Finding (harness expectation, not a product defect).** The first pass (same run) failed two expectations of mine, both +corrected in the harness and re-run green: +1. A sent HistoryRead is refused **PERMISSION_DENIED**, not the UNIMPLEMENTED the issue/plan text guessed. At `0c86edc1`, + `DataConnectionEndpoints` admits only its six v1 methods (`GetCapabilities, Browse, GetMetadata, Read, Write, Subscribe`) on + the data listener and refuses any other path before gRPC routing. A current consumer never sends one (the tap shows it), so + this only affects a hand-rolled caller; documented in `DataConnections.md`. +2. The first projected value Read answered `BadWaitingForInitialData`; the gate now retries only that status (bounded 60 s), + as every mapped positive read on this rig does (README). + +The re-run used `--pinned-build` (harness and probe source edited after `up`; images unchanged, probe republished). + +Evidence (run folder removed by `down`; copies taken before): `evidence/H05V1-results.json`, `probe/source-1/wire-tap.jsonl`. + +## Not covered + +- Subscribe / Write from the consumer to the v1 origin did not occur in the window (the gate reads via the CLI); the H2/A2 + recorded-v1-client gates cover the header-less shapes of those calls. +- Conditions against a v1 origin (`--conditions` with a pinned SOURCE) were not run. diff --git a/docs/plans/evidence/grpc-data-ext/H3.md b/docs/plans/evidence/grpc-data-ext/H3.md index f27bfbe42..ff0b95cd9 100644 --- a/docs/plans/evidence/grpc-data-ext/H3.md +++ b/docs/plans/evidence/grpc-data-ext/H3.md @@ -139,7 +139,7 @@ while held, 0 after the session closed; `down` ⇒ 0/0/0/0 for both runs. **Found on the re-run (pre-existing v1 projection behaviour, not an H3 defect — for a follow-up):** an idle projected node's authority lapses with its 15 s `MetadataLeaseMilliseconds`; any read after that is `BadUserAccessDenied` — a value Read exactly as a HistoryRead (reproduced in the Runtime harness) — and a re-browse served from the still-cached browse page does not renew it -(live: the H06 rebuild leg denied right after a re-browse). The gate now starts each held leg right after a deploy + re-browse. +(live: the H06 rebuild leg denied right after a re-browse). The gate now starts each held leg right after a deploy + re-browse. **Fixed by #922** (`fu922.md`): a lapsed lease now renews on demand. The gate no longer re-browses before H04's resume, and H06(c) idles past the lease on purpose. ## Review round 3 (approve-with-changes) — fixes @@ -173,7 +173,7 @@ Round 3 was itself an independent (Fable) verification of the round-2 commits - **H05**: the rig builds no pinned v1 image, so "v1 origin" is substituted by an origin that does not advertise history for the principal (export without bit 32). The v1 wire shape itself is covered by the H2 recorded-v1-client gates; the live v1-origin - path is follow-up **#921**. + path is follow-up **#921** — since run live against a pinned pre-H2 origin (`0c86edc1`), PASS 25/25: `H05-v1-origin.md`. - **H01 tie clusters**: not representable live on either backend — SqlServer `hist.Sample` PK `(TagId, SourceTimeUtc)`, QuestDB `DEDUP UPSERT KEYS(ts, tag)` keep one sample per timestamp. Tie paging is proven by the H1 port fuzz (10k seeds). - **ReadyReplica consistency** on projected history and the Gateway backend (H4) were not run. diff --git a/docs/plans/evidence/grpc-data-ext/V1-916-917.md b/docs/plans/evidence/grpc-data-ext/V1-916-917.md new file mode 100644 index 000000000..dbed3e40e --- /dev/null +++ b/docs/plans/evidence/grpc-data-ext/V1-916-917.md @@ -0,0 +1,180 @@ +# v1 pre-deploy corrections: #916 and #917 + +Two defects in gRPC data connections v1 (merged `95c5e484`, never deployed, #915), found while planning remote history and +alarm forwarding (plan §5.2, "Pre-existing v1 findings"; N3). Both are fixed in the v1 origin catalog +(`LocalExportCatalog.Compilation.cs`), so header-less v1 callers get the fix too. Neither changes the wire shape. + +## #916: `Metadata.stable_source_id` disclosed driver ids and RawPaths + +**Defect.** `Compile` put `BackingSourceKey.StableSourceId` into `Metadata.stable_source_id` (proto field 10) on every value +node, in every realm. For a driver source that key is `SourceKey.ForDriver`'s `:`, +and the reference is the RawPath. So a peer holding only a UNS export learned the origin's driver instance ids and RawPaths. +The recorded real-origin golden shows the leak: `Browse/uns` carries `8:driver-1Plant/Modbus/dev1/Speed` on the UNS Speed +reference. + +**Consumer-side uses of the field (all of them).** Every read of `DataMetadata.StableSourceId` / `Metadata.stable_source_id` +in `src/`: + +| Site | Use | +|---|---| +| `DataProtoMapper.EncodeMetadata` / `DecodeMetadata` | Copies it when present. Decodes absence as `null` (`HasStableSourceId`). | +| `ProjectedProofSize.cs:21` | Byte accounting of a proof. | +| `OtOpcUaNodeManager.cs:4439` | Byte accounting of a projected definition. | + +Nothing dedupes on it, compares it, keys on it, or exposes it to the consumer's own OPC UA clients. It is not an OPC UA +property, not shown in the AdminUI and not logged. `DataSourceIdentity.StableSourceId` (Core.Abstractions) has no users. +A1–A4 dedupe conditions by the keyed `condition_key` (`ConditionKeys`), never by this field. + +**Decision: omit the field on every export, in every realm.** We considered two alternatives: + +- *A keyed opaque id* (HMAC like `condition_key`). Rejected. No consumer uses the field, so an opaque value would only be a + stable cross-realm correlator: it would tell a peer holding both a Raw and a UNS export that two nodes share a source. + It would also depend on `DataConnections:ConditionKeySecret`, which is optional, so the field would come and go with an + unrelated setting. +- *Omit only where the realm differs.* Rejected. A Raw export also does not need the internal key, and keeping one rule + is simpler to audit. + +**Mixed versions.** Field 10 is `optional`. An old consumer decodes its absence as `null` and uses it for nothing but size +accounting, so an upgraded origin works with old consumers, and a new consumer works with an old origin (it ignores +the value). + +One effect to know about: consumers compare whole `DataMetadata` records, field 10 included, when they renew a +projection (`ProjectedCatalogCache.SameMetadata`, `OtOpcUaNodeManager` projected-variable reuse). An origin pair running a +pre-fix build on one member and this build on the other would therefore look like a metadata change at failover, and the +node would be re-projected once. No pre-fix build was ever deployed (#915), so this cannot happen in the field. + +The internal `BackingSourceKey` (on `LocalDataNode.Source`) is unchanged: acquisition, sample routing, +partitioning, write routes and `SourceKey.TryDriver` still use it. + +## #917: alarm-bearing raw tags were exported as Variables that never get a value + +**Defect.** `Compile` added every raw tag plan as a `Variable` with Read/Subscribe/HistoryRead. An alarm-bearing tag +(`RawTagPlan.Alarm != null`) never receives a value, because `DriverHostActor` keeps it out of the value fan-out and #896 +gives it no UNS variable. So a consumer that imported one read `BadWaitingForInitialData` forever. + +**Are these tags now forwarded as conditions?** Yes. Since A1–A4, every alarm-bearing raw tag gets a native condition +placement at its RawPath in Raw (parented at its device or group folder). Every UNS reference to one gets a placement at +the reserved `Area/Line/Equipment/EffectiveName` id, parented at the equipment. Both are listed through root-scoped +condition items and keyed by `condition_key`, and the consumer materialises them in its `mapped/conditions` namespace. +The alarm is therefore served as a condition, never as a value. + +**Decision: compile the tag as an unsupported value node, and do not list it in Browse.** The rule is +`supported = plan.Alarm is null && …` in `Compile`. In `LocalDataServices.BrowseAsync`, a child with a `Source` and +`!Supported` is skipped. + +- **Value operations.** Every value gate already keys on `LocalDataNode.Supported`: GetMetadata, Read and Subscribe + answer `Unsupported`, history requires `Supported`, and `DataWriteDispatchGate` refuses writes. +- **The node stays in the catalog.** Removing it would turn a deployable `DataExport` rooted at that tag + (`RootKind = RawTag` is valid) into a catalog compile failure ("Export has no valid origin root") for the whole cluster. +- **Browse hides it. The live gate forced this.** The first attempt listed the tag as the existing v1 + `UnsupportedVariable` kind, on the assumption that consumers skip that kind. They do not. `ProjectedNamespaceApplier` + hands a whole page to `IProjectedNamespacePageSink.TryApply`, and `OtOpcUaNodeManager.TryEnsureProjectedVariable` + rejects anything that is not a Folder, Variable or Tag (`OtOpcUaNodeManager.cs:4988`). So **one** `UnsupportedVariable` + child failed the whole page. + - On run `fu916-1`, browsing the consumer's `remote-opc` branch (the A4 Raw mapping of the opc-plc device, which holds + the alarm tag `EastTankYellow`) answered `BadNoCommunication`. + - The rig's `resolve` walk hit the same status, and `deploy` timed out on "deployed catalog and OPC UA namespace + identity". + - Every consumer build behaves this way, including the merged v1 consumers. Listing the node would therefore break any + mixed-version consumer. Not listing it works for all of them, because a page simply has one item fewer. +- **The same holds for any unsupported value node**, for example a data type v1 cannot carry. A pre-existing v1 origin + already broke consumer browse of a folder holding one, and the browse filter fixes that too. + +Condition placements are independent of the value node. They need only their parent folder or equipment, so condition +forwarding is unchanged. The live gate below re-proves it on the alarm tag itself. + +## The v1 gate: goldens not re-recorded + +`GrpcDataV1RealOriginGoldens` (recorded on `1086593a`) captured both defects. The goldens stay as recorded. The new +`GrpcDataV1RealOriginCorrections.Expected(scenario)` applies exactly two edits to the parsed golden message and +re-serialises it: + +- it clears `stable_source_id` on every Metadata; +- it removes HighTemp from the device Browse page, and makes its GetMetadata item `status = Unsupported` with no value + and no lease. + +The test then compares the real origin's header-less bytes with the result. Only Browse, Browse/uns and GetMetadata are +corrected. GetCapabilities, Read, Write, Write/no-write-grant and Subscribe are compared with the raw goldens, unchanged. +`V1_corrections_916_917_are_exact_and_the_recorded_leak_was_real` pins the method: + +- an unedited golden re-serialises byte-identically, so an edit is the only possible difference; +- the corrected scenarios really differ from the goldens, and the others really do not; +- the recorded UNS browse really contains the leaked `driver-1Plant/Modbus/dev1/`, and no corrected scenario does; +- HighTemp is the single Unsupported item in GetMetadata, and the only item dropped from the recorded device page. + +The fake-origin gate `GrpcDataV1CompatibilityTests` is untouched and green. + +Before the fix, the decoded diff of real-origin output against the goldens was exactly these edits: field 10 on every +value node of Browse, Browse/uns and GetMetadata, plus the HighTemp entries. + +## Red/green + +| Test | Before the fix (master behaviour) | After | +|---|---|---| +| `GrpcDataConditionPlacementTests.No_exported_metadata_carries_the_internal_source_key_916` (60 generated topologies; encoded metadata of every node; UNS bytes searched for every driver id and RawPath; positive control: the internal key still contains them) | **Failed**: `node.Metadata.StableSourceId should be null` | Pass | +| `GrpcDataConditionPlacementTests.An_alarm_bearing_raw_tag_is_an_UnsupportedVariable_and_keeps_its_condition_placements_917` (positive controls: a plain tag, and the same tag without its alarm config, stay supported `Variable`s; 3 placements and the Raw listing intact; an export rooted at the alarm tag compiles) | **Failed**: alarm tag `Supported` was true | Pass | +| `GrpcDataV1RealOriginCompatibilityTests` header-less + feature-header Browse, Browse/uns, GetMetadata vs the raw goldens | Pass on master; fail with the fix | Compared with `Expected(...)`: pass | + +Control run: with master's `src` restored over this branch's tests, the full Runtime.Tests `Feature=GrpcData` run failed +exactly the two new tests (#916, #917). All other tests passed (1021/1023). + +The browse filter has its own red/green. With the `LocalDataServices` skip commented out, the real-origin Browse scenario +fails, both header-less and with the feature header (2 failures). With the skip restored, it passes. + +## Gate runs (Release, on `70539999` + docs) + +- Runtime.Tests `Feature=GrpcData`: **1023/1023 passed in 3 of 3 consecutive full runs.** + - Two earlier full runs each failed one test, + `GrpcDataConfiguredDiscoveryWireTests.Bad_null_sdk_notification_cannot_borrow_unproven_sample_evidence(different_timestamp)`: + it expected `BadUserAccessDenied` and got `BadNoCommunication`. + - This is the pre-existing intermittent **#920**, which reproduces on master and is being fixed separately. It passed + 40/40 in isolation here. + - It is not touched by this change. Its fixture's nodes are all `Supported`, so the browse skip is a no-op there, and + the test exercises SDK notification queueing, not catalog metadata. + - The new 60-seed property test takes about 125 ms, the same order as the existing 60-seed UNS-only property test, so + it is not a load source. +- Host.Tests `Feature=GrpcData`: 210/210 passed. This includes `GrpcDataV1CompatibilityTests` (fake origin, untouched), + `GrpcDataV1RealOriginCompatibilityTests` and `GrpcDataHistoryWireTests`. +- `dotnet build -c Release` (whole solution): 0 warnings, 0 errors. + +## Live gate (local grpc-data rig, `--conditions` profile, under the shared rig lock) + +| Run | Build | Result | +|---|---|---| +| `fu916-1` | `b7ca71f1`: alarm tag listed as `UnsupportedVariable` | **Failed**, which is how the browse defect above was found. `deploy` timed out on "deployed catalog and OPC UA namespace identity". The seeder `resolve` got `BadNoCommunication`. The consumer's `remote-opc` folder answered `BadNoCommunication` to a Client.CLI browse, while the SOURCE leaves read Good on both pair members | +| `fu916-2` | interim | Discarded. The image was built while the source tree was being edited, so `verify_candidate` refused it ("running manifest does not match current image build inputs") | +| `fu916-3` | `70539999`: Browse skips unsupported value nodes | **PASS**, details below | + +`fu916-3` ran `up --conditions` → `seed` → 85 s → `deploy --timeout 300` (ready) → `conditions_a3_smoke.py` → `conditions_scenarios.py` → `down`: + +- `deploy --timeout 300` reached ready; +- `conditions_a3_smoke.py` reported `passed: true` (origin and consumer subscribers each saw Active/Unacknowledged → Active/Acknowledged); +- `conditions_scenarios.py` passed **A01–A08, 8/8**, `source_revision` `70539999`. A04 is the three placements of the alarm tag `EastTankYellow` (Raw `map-opc`, UNS `map-pumpa`/`map-pumpb`) and the UNS-only principal's records; +- `down` left 0 run containers. + +A Client.CLI browse of consumer-1 then showed `remote-opc` → `FastUInt1` only, with the alarm tag not listed. Evidence is in +`artifacts/grpc-data/runs/fu916-3/evidence/` (`A4S-results.{json,md}`). + +The live run does not separately probe `stable_source_id` over gRPC. #916 is pinned by the wire-level real-origin gate and +the 60-seed property test above. + +## Review round 1 (2026-11-28) + +| Finding | Fix | Red/green | +|---|---|---| +| #916 defence in depth: the mapper still encoded field 10 if anything set it | `DataProtoMapper.EncodeMetadata` never writes field 10. `DecodeMetadata` drops it, so a consumer of a pre-fix origin never retains it in `OriginMetadata`. The proto marks field 10 deprecated in a comment (not renumbered or removed) | `GrpcDataCodecTests.Stable_source_id_is_never_encoded_and_is_dropped_on_decode_916`: red with master's mapper, green with the fix. Engineering units (field 11) are the positive control | +| The fake-origin gate's goldens carry field 10 from its fake metadata, so the mapper change moves them | `GrpcDataV1Corrections.Expected` clears field 10 on the parsed Browse/GetMetadata goldens. That is the only edit, and the goldens are not re-recorded | `V1_correction_916_clears_only_stable_source_id`: the recording really carried field 10, an unedited golden re-serialises identically, and the other RPCs compare raw | +| Browse page boundaries | A skipped unsupported node no longer counts against the page's scan bound. The budget timeout still bounds the call. The skip therefore never yields an empty `Complete=false` page | `GrpcDataLocalConnectionTests.Browse_skips_unsupported_value_nodes_across_page_boundaries_917`, page size 2 over `[Speed, u, u, u, v, u, v]`. Red before the fix (an empty first-continuation page). Green after: `Speed, c3, c5` each exactly once, 2 non-empty pages, completes. Positive control: the skipped nodes are addressable (`Unsupported`) | +| Internal metadata still said an unsupported node was writable | `Add` compiles `writable &= supported` (raw tags, UNS references, virtual tags) | The #917 test fixture's alarm tag is now `ReadWrite`. `alarm.Metadata.Writable.ShouldBeFalse()` was red before the change and green after. Positive control: the same tag without its alarm is writable | +| Stale "browsable" test doc; "an export may still be rooted at it" | Both reworded. Such a root compiles, but grants nothing: the values are unsupported, and the condition placement sits under the tag's folder, not under the tag | — | + +A consumer receiving an empty `Complete=false` page is no longer produced by this change. It can still come from the +pre-existing name filter. Whether the consumer resolver tolerates one was not tested end to end; it is suggested as a +follow-up. + +Gates after the review, Release: + +- Commons.Tests: 513/513. +- Runtime.Tests `Feature=GrpcData`: 1024/1024. +- Host.Tests `Feature=GrpcData`: 211/211. This includes both v1 gates. +- `dotnet build -c Release`: 0 warnings, 0 errors. diff --git a/docs/plans/evidence/grpc-data-ext/X0.md b/docs/plans/evidence/grpc-data-ext/X0.md index 2c4d0035a..08c3d6bdc 100644 --- a/docs/plans/evidence/grpc-data-ext/X0.md +++ b/docs/plans/evidence/grpc-data-ext/X0.md @@ -51,8 +51,16 @@ optional children NM adds before `Create()`: `ConfirmedState`, `Confirm`, `Shelv `Quality`, `BranchId` and `Comment` are present. -Retained size is ≈ 157 KiB per condition (160,997 B). It was measured on 2,000 `OffNormal` instances as a -`GC.GetTotalMemory(true)` delta. +Retained size is ≈ 77 KiB per condition: **79,085 B** managed heap, ≈ 90 KB settled working set (re-measured 2026-11-28 for +#929, three runs: heap 79,085 / 79,085 / 79,085 B, working set 90,284 / 90,144 / 90,038 B). It is measured on 2,000 +`OffNormal` instances as the change in `HeapSizeBytes − FragmentedBytes` of the last full blocking GC (after forced +compacting collections), with the working set sampled until it settles — the same `Measure()` as the L2 harness. + +- **Correction (#929).** X0 originally reported ≈ 157 KiB (160,997 B), a `GC.GetTotalMemory(true)` delta. On .NET 10 (GC + regions) that call also counts committed-but-free region space (A3 round 2 showed +92 vs +218 MiB for the same state); the + harness still logs it for comparison and it reads 158,169 B, i.e. ≈ 2× the retained heap. +- `BytesPerCondition` (160,000 B) is unaffected: it comes from the L2 in-server worst case (111,715 B heap / 158,629 B + working set, A3 round 2), which already used this method. Node-only ≈ 77 KiB of L2's ≈ 109 KiB heap is the SDK node tree. - It excludes NM's indexes, the `c1.` identifier strings, the EventId registry and placement sets (m-T7). - L2 (A3 exit) is the authority for `MaxImportedConditionBytes`. @@ -220,6 +228,10 @@ pre-H2 master `1086593a`. 2. Still expect these exact bytes **without** the header. 3. Expect them **with** the header too, until the server advertises the feature in `SupportedFeatures`. 4. Never re-record. +- **Pre-deploy corrections (#916, #917; 2026-11-28).** Two deliberate v1 fixes change real-origin Browse, Browse/uns and + GetMetadata. `GrpcDataV1RealOriginCorrections.Expected` applies exactly those edits to the parsed, unre-recorded golden: + it clears `stable_source_id`, drops the alarm-bearing HighTemp from the device Browse page, and makes its GetMetadata + item `Unsupported`. A test pins that the edits are the only difference. See `V1-916-917.md`. ## 3. Gate runs diff --git a/docs/plans/evidence/grpc-data-ext/fu922.md b/docs/plans/evidence/grpc-data-ext/fu922.md new file mode 100644 index 000000000..e7a24916c --- /dev/null +++ b/docs/plans/evidence/grpc-data-ext/fu922.md @@ -0,0 +1,88 @@ +# #922 — a lapsed projected metadata lease is not an access denial + +Found in the H3 live gate (`H3.md` §"Found on the re-run"). Pre-existing v1 projection behaviour (95c5e484). + +## Root cause + +A projected node's authority is its catalog proof, bound to a `BoundProjectionLease` whose remote `MetadataAuthorityLease` lasts +`MetadataLeaseMilliseconds` (15 s on the rig) from the browse that fetched it. Only a **subscription** ever renewed it +(`RemoteNamespaceResolver.RenewExactAsync`, Subscribe only). After the lease lapsed: + +- `ProjectedCatalogCache.TryResolveProjected` / `Valid` required `Lease.IsValid`, so `ProjectedDataAccess.TryAcquire` returned + `false`, and the node manager's Read pre-loop mapped **every** `false` to `BadUserAccessDenied`. A lapse looked the same as an + ACL denial. +- HistoryRead: `AuthorizeHistoryRead` → `DataPlaneAuthorizer` → `MappedSubjectResolver` (`TryResolveProjected`) returned + `Deny` ⇒ `BadUserAccessDenied`. +- Re-browse: a cached parent page is served while its own lease holds, and nothing renews on a cache hit. A re-browse just + before the page's lease ran out therefore renewed nothing, and the nodes lapsed seconds later (the H06 observation). + +## Fix + +| Piece | Change | +|---|---| +| `BoundProjectionLease.Renewable` | the lease is invalid ONLY because it is transient: the remote time ran out or the route was replaced, while the local catalog authority, mapping binding and cache generation are current and nothing called `Invalidate` | +| `ProjectedCatalogCache.TryResolveForRenewal` | the retained, non-retired proof that is valid or `Renewable` (every `ValidCore` fence except the lease) | +| `OtOpcUaNodeManager.TryResolveForRenewal` (+ `IProjectedNodeLookup`, sinks) | the committed live definition without the authority check (lock-free snapshot), so the renewal commits against the exact SDK node | +| `DataOperationPolicy.AuthorizeMappedSubject` | `AuthorizeMapped` minus the lease checks. Classifies a refusal only and serves nothing | +| `IProjectedDataAccess.RenewLapsed` → `ProjectedLapseOutcome {Denied, Renewing, Unavailable}` | `Denied` unless the node is lapsed-renewable AND the caller holds the grant for the operation (local grant + mapping bit + op-specific checks). Otherwise starts ONE exact renewal per node (`RenewExactAsync` generalised to `authorizeAs`/`required` = Read or HistoryRead; the subscription default is unchanged), off the request thread, inside the unary budget, with a 250 ms back-off after a failure. A successful Read renewal then schedules a read so the retry is served from cache | +| Read pre-loop | `Denied` ⇒ `BadUserAccessDenied` (unchanged); `Renewing` ⇒ `BadWaitingForInitialData` (as for a cold read); `Unavailable` ⇒ `BadResourceUnavailable`. A non-Value attribute of a lapsed node ⇒ `BadResourceUnavailable` | +| `AuthorizeHistoryRead` | renews lapsed projected handles within the request (one block-bridged wait per batch, ≤ 5 s, no `Lock` held — the SDK released it before dispatching, as H3 recorded), re-authorizes, then serves. A renewal that does not complete ⇒ `BadResourceUnavailable` | +| `ProjectedBrowseAccess` | an initial cached page past half its lease is served AND refreshed in the background (one in flight per page key) | + +The node-manager `Lock` is never held across a network renewal. The Read path only starts the task. The renewal commits +through `IProjectedNamespacePageSink.TryRenewExact`, which takes `Lock` briefly and performs no I/O. + +## Red / green (Runtime harness, `GrpcDataLeaseLapseWireTests`, `Trait Issue=922`, real consumer SDK session + projection stack) + +| Test | master (`05f431f5d` src) | fix | +|---|---|---| +| value Read after the lease lapses ⇒ retryable, renews on demand without a browse (twice), attribute read not denied | **FAIL** (`BadUserAccessDenied`) | pass | +| no local Read grant ⇒ still `BadUserAccessDenied` after the lapse; no metadata/read call; renewal counter 0 (counted synchronously at admission) | pass | pass | +| HistoryRead after the lapse ⇒ renewed in the request, Good, 3 values | **FAIL** (`BadUserAccessDenied`) | pass | +| lapsed HistoryRead with the origin unreachable ⇒ `BadResourceUnavailable`, nothing read; Good after recovery | **FAIL** (`BadUserAccessDenied`) | pass | +| no local HistoryRead grant ⇒ still `BadUserAccessDenied` after the lapse, unsent | pass | pass | +| re-browse of a cached page past half its lease renews (origin browse call, lease holds at t0+20 s) | **FAIL** (no origin call) | pass | + +Real ACL denial and lease lapse are tested both ways. The lapse cases are red on master and the ACL-denial controls are green on +both. 8 consecutive green runs of the six tests after the final assertion fix. +Harness note: the fixture origin observes its single sample once, so the sample's origin age grows with the manual clock. The +value tests use a stale timeout and client maxAge longer than the idle gaps, so that age stays out of the result under test. + +## Gates + +`dotnet build -c Release` (solution) 0 errors. Runtime.Tests 2096 passed / 3 skipped / **2 failed** under machine load average +100–150: `VirtualTagActorTimerTests.Ticks_during_a_slow_run_coalesce_instead_of_piling_up` and +`GrpcDataConfiguredDiscoveryWireTests.Failed_sdk_item_construction_releases_candidate_and_fanout_ownership` (its first +subscription publish was not Good, and it calls no code path changed here). Once load dropped, both passed 12/12 on master `src` +and 12/12 on the fix. Cause not established, so this is recorded as load-correlated, not as a flake. OpcUaServer.Tests 1460 passed +(+2 skips). Host.Tests 497 passed, including `GrpcDataV1CompatibilityTests` (goldens untouched). Core.Tests 385 passed (+1 skip). + +## Live (grpc-data rig, OrbStack, run `f922a-sqlserver`, `--history --history-backend sqlserver`) + +`history_gate.py` with the workaround removed: H04 no longer re-browses before its resume, and H06(c) now deliberately idles +`LEASE_LAPSE_SECONDS = 20` (> the 15 s lease) after its restore before the held read. **H01–H06 all PASS** (47/34/35/44/58/238 +assertions). + +Value-Read probe (one browse, then never again; Client CLI `read --max-age 10000` on CONSUMER, raw/counter and uns/scalar): +the fresh-lease control and both idle legs (20 s and 40 s, i.e. past the lease) answer `BadWaitingForInitialData` then Good on +the next read, with **no `BadUserAccessDenied` anywhere**. With the CLI's default `--max-age 0`, every projected read (lapsed or +not) stays `BadWaitingForInitialData`, because the v1 Read path never serves `maxAge = 0` from cache. That is separate from this +fix and is filed as a follow-up. `rig.py down` ⇒ 0 containers / volumes / networks / images. + +## Security review round 1 (no auth bypass; two availability findings + lows) — fixes + +Merged local master first (incl. #916/#917, DataConnections), clean, build 0 errors. + +| # | Finding | Resolution | Red/green | +|---|---|---|---| +| 1 | A renewal reserved `MaxUnaryBytes` in the unary budget: (A) a batch of N lapsed nodes renewed only the first, (B) while one ran, every cold read / write / subscription renewal was refused | renewals left the unary budget: own resolver pool `max(1, maxConcurrentFetches/2)` (never `_fetchSlots`), a bounded queue (64), 256 KiB each, 3 s end to end including the pool wait | `A_read_batch_of_several_lapsed_nodes_renews_every_node…`, `A_history_batch_of_several_lapsed_nodes…`, `A_renewal_in_flight_does_not_crowd_out_a_cold_read…`: all **red** on the pre-review fix, green now | +| 2 | `AuthorizeHistoryRead` waited 5 s before the history batch limiter and ignored the request token, so concurrent HistoryReads against a slow origin pinned SDK threads past the 16-batch cap. The wait also equalled the renewal budget | the wait first takes a non-local history slot with `Wait(0)` (none free ⇒ no wait, retryable), honours `OperationContext.CancellationToken`, and lasts 4 s (≤ `HistoryReadDeadline`) against a 3 s renewal | `Concurrent_history_reads_against_a_slow_origin…`: 24 reads against a silent origin, ≥ 24 − RemoteSlots answer in < 2.5 s, all `BadResourceUnavailable`, origin untouched, Good after release. **Red** on the pre-review fix (all 24 waited ~5 s) | +| 3 | Two authorities (policy classifies, `DataPlaneAuthorizer` vetoes) | a renewal that completed `true` and is still vetoed ⇒ `BadUserAccessDenied` | by construction; the grant-revoked test below covers the revoked case | +| 4 | Renewals keyed by node only, though each requests its operation's bit | keyed by (realm, id, operation), back-off too | — | +| 5 | Back-off map cleared wholesale at 4096; browse refresh deduped per (caller, MaxResults) | expired entries are evicted first, otherwise the one expiring first; one background refresh per parent node | — | +| 6 | Write / CreateMonitoredItems on a lapsed node | documented in `docs/DataConnections.md` as not covered (still `BadUserAccessDenied` until a read/browse renews); reported as a follow-up | — | + +New safety controls, green on both the pre-review fix and now: an `Invalidate`d lease ⇒ `BadUserAccessDenied`, no renewal, no origin +call. A grant revoked while the renewal is parked at the origin ⇒ nothing served, the renewal never commits, then +`BadUserAccessDenied`. A mapping removed while renewing ⇒ not revived, not answered as a lapse. 13 #922 tests, 5 consecutive green +runs. diff --git a/docs/plans/evidence/grpc-data-ext/harness/Program.cs b/docs/plans/evidence/grpc-data-ext/harness/Program.cs index 28605d4b2..34c475dc0 100644 --- a/docs/plans/evidence/grpc-data-ext/harness/Program.cs +++ b/docs/plans/evidence/grpc-data-ext/harness/Program.cs @@ -18,18 +18,33 @@ static class P { int total = Count(ctx, alarm, kinds); Console.WriteLine($"{name}: total={total} ({string.Join(", ", kinds.Select(k => k.Key + "=" + k.Value))}); Quality={(alarm.Quality!=null)} BranchId={(alarm.BranchId!=null)} Comment={(alarm.Comment!=null)}"); } + // #929: GC.GetTotalMemory counts committed-but-free regions on .NET 10. Use the last full blocking GC's + // HeapSizeBytes - FragmentedBytes plus a settled working set: the same method as the L2 harness's Measure() + // (tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMemoryMeasurementTests.cs). + static (long Heap, long WorkingSet) Measure() { + for (int i = 0; i < 3; i++) { GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true, true); GC.WaitForPendingFinalizers(); } + GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true, true); + var info = GC.GetGCMemoryInfo(GCKind.FullBlocking); + using var p = System.Diagnostics.Process.GetCurrentProcess(); p.Refresh(); long ws = p.WorkingSet64; + var settle = System.Diagnostics.Stopwatch.StartNew(); + while (settle.Elapsed < TimeSpan.FromSeconds(10)) { + Thread.Sleep(500); p.Refresh(); long next = p.WorkingSet64; bool stable = Math.Abs(next - ws) < 1024 * 1024; ws = next; if (stable) break; } + return (info.HeapSizeBytes - info.FragmentedBytes, ws); + } static void Main() { var ctx = new SystemContext((ITelemetryContext)null) { NodeIdFactory = new Ids(), NamespaceUris = new NamespaceTable() }; ctx.NamespaceUris.Append("urn:a"); ctx.NamespaceUris.Append("urn:b"); Run("AlarmConditionState", p => new AlarmConditionState(p), ctx); Run("OffNormalAlarmState", p => new OffNormalAlarmState(p), ctx); Run("DiscreteAlarmState", p => new DiscreteAlarmState(p), ctx); - var keep = new List(); long before = GC.GetTotalMemory(true); + var keep = new List(); var (heap0, ws0) = Measure(); long before = GC.GetTotalMemory(true); for (int i = 0; i < 2000; i++) { var parent = new FolderState(null); var a = new OffNormalAlarmState(parent); a.ConfirmedState = new TwoStateVariableState(a); a.Confirm = new AddCommentMethodState(a); a.ShelvingState = new ShelvedStateMachineState(a); a.MaxTimeShelved = new PropertyState.Implementation(a); a.Create(ctx, new NodeId("c"+i, 2), new QualifiedName("c"+i, 2), new LocalizedText("c"+i), true); keep.Add(a); } - long after = GC.GetTotalMemory(true); Console.WriteLine($"retained bytes/condition (2000, OffNormal, no address-space indexes): {(after-before)/2000}"); GC.KeepAlive(keep); + var (heap1, ws1) = Measure(); long after = GC.GetTotalMemory(true); + Console.WriteLine($"retained bytes/condition (2000, OffNormal, no address-space indexes): heap {(heap1-heap0)/2000} (GCMemoryInfo), " + + $"working set {(ws1-ws0)/2000} (settled); GC.GetTotalMemory delta {(after-before)/2000} (not used, #929)"); GC.KeepAlive(keep); var conds = keep.Cast().ToArray(); var recs = new object[conds.Length]; for (int w = 0; w < 3; w++) { var sw = System.Diagnostics.Stopwatch.StartNew(); for (int i = 0; i < conds.Length; i++) { var c = conds[i]; recs[i] = (c.NodeId, c.ActiveState?.Id?.Value, c.AckedState?.Id?.Value, c.ConfirmedState?.Id?.Value, diff --git a/scripts/validation/grpc-data/README.md b/scripts/validation/grpc-data/README.md index 8b94ee0b9..e23196ba4 100644 --- a/scripts/validation/grpc-data/README.md +++ b/scripts/validation/grpc-data/README.md @@ -112,6 +112,9 @@ used) and seeds a SOURCE `OpcUaClient` driver `opcua` → device `opcplc` with a principal `fixture-cli-nogrant` has no NodeAcl row. `python3 scripts/validation/grpc-data/conditions_scenarios.py --run-id [--only A01,A02,A04,A05,A08]` runs the scenarios (results `evidence/A4S-.json`, `A4S-results.{json,md}`); see `docs/plans/evidence/grpc-data-ext/A4.md` "Live scenarios (part 1)". `conditions_a3_smoke.py` still passes on this profile. +`--only A09` (#927) is the driver-failure ack revert: it `docker compose pause`s the run-owned `opcplc` just before a remote ack of +`EastTankYellow`, so the OpcUaClient driver's upstream Acknowledge times out and DriverHostActor reverts the condition; it +unpauses in its own `finally` (and again in the per-scenario restore). See `docs/plans/evidence/grpc-data-ext/A3-927.md`. ## H3 projected-history gate (opt-in) @@ -139,6 +142,38 @@ primary. The continuation scenarios use the CLI's hand-paged mode (`--page-size` (`originAccounting.historyOpenContinuations`). Every scenario restores the baseline. Results: `evidence/H3-history--results.json`. +## Pinned pre-H2 SOURCE — H05 against a real v1 origin (#921, opt-in) + +`rig.py up --run-id --history --source-revision 0c86edc1` builds the SOURCE pair from a pinned commit; CONTROL and +CONSUMER stay on this checkout. The revision must contain X0 (`a15912539`, tolerant readers — a pre-X0 node rejects the whole +data-connection snapshot once a newer bit is authored) and must not contain H2 (`ef938b435`); its `data_connection.proto` must +have no `HistoryRead` RPC. `0c86edc1` (the #918 merge, between H1 and H2) passes. The rig `git archive`s that commit into the +run folder (`pinned-source/`), copies in one rig file — `node-probe/WireTap.cs`, ASP.NET Core only — and builds it with the +pinned tree's own Dockerfile (`compose.source-pinned.yml`, image `otopcua-grpc-data-source-pinned:`, run-labelled, removed +by `down`). The manifest records `source_pinned` (revision, export hash); `verify_candidate` checks the SOURCE stamps against it +and the export against its recorded hash, and everything else against this checkout. + +The wire tap (`GRPC_DATA_WIRE_TAP=1`, set only by that overlay) appends to the node's restricted probe directory +(`probe/source-N/wire-tap.jsonl`) one line per data-listener request at arrival (gRPC path, `x-otopcua-data-features` value, +remote address) and one at completion (gRPC status). No credential or body is recorded. + +```bash +python3 scripts/validation/grpc-data/rig.py up --run-id h05v1 --history --source-revision 0c86edc1 --timeout 1500 +python3 scripts/validation/grpc-data/rig.py seed --run-id h05v1 +sleep 75 +python3 scripts/validation/grpc-data/rig.py deploy --run-id h05v1 --timeout 300 +python3 scripts/validation/grpc-data/history_v1_origin_gate.py --run-id h05v1 # evidence/H05V1-results.json +python3 scripts/validation/grpc-data/rig.py down --run-id h05v1 +``` + +`history_v1_origin_gate.py` asserts the plan §4.3 row "new consumer → v1 origin": projected `counter` (Raw and UNS) +`Historizing` False and no HistoryRead `AccessLevel` bit (`Client.CLI read --attribute`), `historyread` ⇒ +`BadHistoryOperationUnsupported`, the consumer page "Negotiated features none (v1 behaviour) · origin history not advertised", +and — from the tap — no consumer call but the capability probe carries the feature header and no HistoryRead/CallConditionMethod +reaches the origin. Controls: the origin's own `counter` is historizing and its `historyread` returns rows; the consumer's v1 calls +are in the same tap window; the probe's `--scenario history-v1-origin` sends new-shape calls (capabilities with the header are +byte-identical to without; HistoryRead ⇒ `PERMISSION_DENIED`: a pre-H2 data listener admits only its six v1 methods) and the tap records them. + ## Scenario authoring and node probes The seeder is available through `LocalRig.seed_helper(action, *arguments)`. Its diff --git a/scripts/validation/grpc-data/compose.source-pinned.yml b/scripts/validation/grpc-data/compose.source-pinned.yml new file mode 100644 index 000000000..5cff40f53 --- /dev/null +++ b/scripts/validation/grpc-data/compose.source-pinned.yml @@ -0,0 +1,25 @@ +# lmxopcua#921 pinned-origin overlay (opt-in: `rig.py up --source-revision `). The SOURCE pair runs a Host image built +# from a pinned post-X0, pre-H2 commit (a "v1 origin": no HistoryRead RPC, no `history` feature), exported by the rig into the +# run folder; CONTROL and CONSUMER keep the current checkout's image. The only file the rig adds to the pinned tree is the +# self-contained node-probe wire tap (node-probe/WireTap.cs), enabled here with GRPC_DATA_WIRE_TAP: it records, per request +# on the data listener, the gRPC path and the x-otopcua-data-features header value into the node's restricted probe +# directory (wire-tap.jsonl) — never a credential or a body. Without this file the rig is unchanged. + +x-pinned-env: &pinned-env + GRPC_DATA_WIRE_TAP: "1" + +services: + source-1: + build: + context: ${GRPC_DATA_SOURCE_PINNED_CONTEXT:?pinned SOURCE export required} + dockerfile: scripts/validation/grpc-data/Dockerfile + target: runtime + labels: + otopcua.grpc-data.run: ${GRPC_DATA_RUN_ID} + com.docker.compose.project: ${GRPC_DATA_PROJECT} + args: {SOURCE_REVISION: "${GRPC_DATA_SOURCE_PINNED_REVISION:?pinned revision required}", SOURCE_TREE_HASH: "${GRPC_DATA_SOURCE_PINNED_TREE_HASH:?pinned tree hash required}"} + image: ${GRPC_DATA_SOURCE_IMAGE:?run-scoped pinned SOURCE image required} + environment: *pinned-env + source-2: + image: ${GRPC_DATA_SOURCE_IMAGE:?run-scoped pinned SOURCE image required} + environment: *pinned-env diff --git a/scripts/validation/grpc-data/conditions_scenarios.py b/scripts/validation/grpc-data/conditions_scenarios.py index 23c8769e7..899860156 100644 --- a/scripts/validation/grpc-data/conditions_scenarios.py +++ b/scripts/validation/grpc-data/conditions_scenarios.py @@ -4,7 +4,7 @@ Part 1 implemented A01, A02, A04, A05 and A08; part 2 adds A03 (origin failover + EventId re-binding), A06 (consumer Primary change, both consumer nodes, two principals) and A07 (consumer node restart, ConditionRefresh vs the first -snapshot barrier). Everything else (watchers, browse-resolved ids, per-scenario restore + JSON/markdown result) is shared. +snapshot barrier). A09 (lmxopcua#927) is the driver-failure ack revert through DriverHostActor for a remote native ack. Everything else (watchers, browse-resolved ids, per-scenario restore + JSON/markdown result) is shared. Rules every scenario follows: - ids are RESOLVED, never constructed: projected folders by browsing the consumer's address space, imported ConditionIds @@ -30,8 +30,9 @@ from pathlib import Path import rig import scenarios -SCENARIOS = ("A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "F937") -TIMEOUTS = {"A01": 420, "A02": 360, "A03": 1200, "A04": 480, "A05": 720, "A06": 1200, "A07": 900, "A08": 720, "F937": 900} +SCENARIOS = ("A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "A09", "F937") +TIMEOUTS = {"A01": 420, "A02": 360, "A03": 1200, "A04": 480, "A05": 720, "A06": 1200, "A07": 900, "A08": 720, "A09": 600, "F937": 900} +REVERT_LOG = "did not reach the alarm system" REFRESH_REQUIRED = "RefreshRequiredEventType" _LOG_TIME = re.compile(r"(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?)") NO_ACK = int(0b111111111111) & ~(1 << 8) # NodePermissions.Admin (4095) without AlarmAcknowledge (1 << 8) @@ -570,6 +571,88 @@ class ConditionScenarios: self.raise_scripted(0) time.sleep(4) + # ---- lmxopcua#927 ------------------------------------------------------------------------------------------------- + def scenario_A09(self): + """A remote (A2b CallConditionMethod) ack of the NATIVE EastTankYellow, under the connection's service principal, that + the OpcUaClient driver genuinely fails: the run-owned opc-plc is `docker pause`d just before the ack, so the driver's + upstream Acknowledge call gets no reply and times out (no test seam). Asserts: the caller gets Good (plan §5.6 step 5: + native ⇒ Good, `AcceptedUnconfirmed`; the failure reaches it as the revert); the origin applies the ack then REVERTS it + (DriverHostActor `RevertNativeAlarmAck` ⇒ `EstablishesState: false`, logged "did not reach the alarm system … reverting"); + the consumer sees the reverted delta; the origin audit records the call on behalf of the end user. The upstream is frozen, + so no driver transition can explain the Unacknowledged that follows the ack (control: no upstream event while paused). + After unpausing, a second ack of the then-current EventId is not reverted (positive control for the failure).""" + source, consumer = self.r.primary("source"), self.r.primary("consumer") + name = self.fixture["conditions"]["native"]["condition"] + since = self.utc(-2) + origin = self.watch(source, "origin") + imported = self.watch(consumer, "consumer") + unacked = lambda b: b.get("State", "").endswith("Unacknowledged") + event = wait_for(lambda: self.latest(imported, name, unacked), 300) + origin_event = wait_for(lambda: self.latest(origin, name, unacked), 30) + if not self.check("consumer_has_unacknowledged_native_condition", event) or not self.check("origin_has_it_too", origin_event): + return + condition = event["ConditionNodeId"] + self.report["condition_id"] = condition + self.report["before"] = {"consumer": event, "origin": origin_event} + paused = False + try: + self.r.rig.compose("pause", "opcplc", timeout=60) + paused = True + self.report["paused_utc"] = self.utc() + origin_mark, consumer_mark = len(origin.blocks(name)), len(imported.blocks(name)) + result = self.ack(consumer, condition, event["EventId"], "ack-driver-fails") + self.report["ack"] = result + self.check("caller_gets_good_accepted_unconfirmed", result["good"]) + + def reverted(watcher, mark): + tail = states(watcher.blocks(name)[mark:]) + acked = next((i for i, state in enumerate(tail) if state and state.endswith(", Acknowledged")), None) + return tail if acked is not None and any(state and state.endswith("Unacknowledged") for state in tail[acked + 1:]) else None + + origin_tail = wait_for(lambda: reverted(origin, origin_mark), 60) + consumer_tail = wait_for(lambda: reverted(imported, consumer_mark), 30) + self.report["origin_after_ack"] = states(origin.blocks(name)[origin_mark:]) + self.report["consumer_after_ack"] = states(imported.blocks(name)[consumer_mark:]) + self.check("origin_applied_then_reverted", origin_tail) + self.check("consumer_saw_the_reverted_delta", consumer_tail) + latest = self.latest(imported, name) + self.check("consumer_reverted_event_is_a_new_event_id", latest and latest.get("EventId") != event["EventId"]) + self.check("consumer_reverted_condition_id_unchanged", latest and latest.get("ConditionNodeId") == condition) + reverts = self.log_lines(source, since, REVERT_LOG) + failures = self.log_lines(source, since, "native-alarm acknowledge of") + self.report["origin_revert_log"] = reverts[-5:] + self.report["origin_driver_failure_log"] = failures[-5:] + self.check("origin_logged_the_driver_failure_and_revert", + any("reverting the condition to unacknowledged" in line for line in reverts)) + self.check("driver_instance_logged_the_failed_upstream_ack", any("failed" in line or "refused" in line for line in failures)) + audit = self.audit(source, since) + self.report["origin_audit"] = audit[-10:] + self.check("origin_audited_the_remote_ack", + any(re.search(r"condition method \W?Acknowledge\b", line) and "AcceptedUnconfirmed" in line and "fixture-cli" in line + for line in audit)) + # Control: the upstream is frozen, so the Unacknowledged after the ack cannot be an upstream transition. Every + # origin event after the ack is either the ack itself or the revert (plus comms-loss quality, which has no state). + self.report["origin_tail_states"] = sorted(set(filter(None, self.report["origin_after_ack"]))) + finally: + if paused: + self.r.rig.compose("unpause", "opcplc", timeout=60) + self.report["unpaused_utc"] = self.utc() + # Positive control: once opc-plc answers again, an ack of the current EventId is not reverted. (The paused call may + # still be applied upstream when the container resumes; then the condition is already acknowledged, also recorded.) + time.sleep(30) + current = self.latest(imported, name) + self.report["after_unpause"] = current + if current and current.get("State", "").endswith("Unacknowledged"): + mark = len(self.log_lines(source, since, REVERT_LOG)) + result = self.ack(consumer, condition, current["EventId"], "ack-after-unpause") + self.report["control_ack"] = result + self.check("control_ack_good", result["good"]) + time.sleep(15) + self.check("control_ack_not_reverted", len(self.log_lines(source, since, REVERT_LOG)) == mark) + else: + self.report["control_note"] = "the upstream applied the paused acknowledge after unpause (condition already acknowledged)" + self.check("control_upstream_acknowledged_after_unpause", current and current.get("State", "").endswith(", Acknowledged")) + # ---- part 2 scenarios ------------------------------------------------------------------------------------------- def scenario_A03(self): """Origin failover mid-stream with standing active alarms. Phase 1: a consumer stream reset against the SAME origin @@ -860,6 +943,9 @@ class ConditionScenarios: finally: self.stop_watchers() try: + # A09 unpauses in its own finally; this covers a failure between its pause and that block. + if scenario == "A09" and "paused" in self.r.rig.compose("ps", "--all", "--format", "{{.State}}", "opcplc", timeout=30): + self.r.rig.compose("unpause", "opcplc", timeout=60) self.r.device("set", address=20, value=0) if scenario in ("A03", "A08"): self.r.deadline = time.monotonic() + 600 diff --git a/scripts/validation/grpc-data/history_gate.py b/scripts/validation/grpc-data/history_gate.py index 5a5dc2587..d3c975463 100644 --- a/scripts/validation/grpc-data/history_gate.py +++ b/scripts/validation/grpc-data/history_gate.py @@ -24,6 +24,8 @@ NODE_PERMISSIONS_ADMIN = 4095 # NodePermissions.Admin = bits 0..11 (HistoryUpda NODE_PERMISSIONS_HISTORY_READ = 1 << 3 NODE_PERMISSIONS_BROWSE = 1 << 0 EXPORT_WITHOUT_HISTORY = 31 # Browse | Metadata | Read | Write | Subscribe +# #922: longer than the rig mappings' 15 s MetadataLeaseMilliseconds, so a projected node idles past its lease. +LEASE_LAPSE_SECONDS = 20 def _iso(moment): @@ -266,9 +268,8 @@ class HistoryGate: with self.runner.stopped(source): observed["new_primary"] = self.runner.wait_primary("source", exclude=source) self.runner.wait_connection_ready(consumer, "raw") - # Resume INSIDE the stop window: the issuing endpoint is down, the pinned resume cannot move. Re-browse first so - # the node's projection authority is current (it lapses with the 15 s metadata lease, as for a value Read). - self.rebrowse() + # Resume INSIDE the stop window: the issuing endpoint is down, the pinned resume cannot move. No re-browse: a + # projected node whose 15 s metadata lease lapsed renews on demand within the HistoryRead (#922). self.held_resume_now() self.runner.wait_pair_topology("source") @@ -374,10 +375,11 @@ class HistoryGate: self.runner.check(any(l.startswith("Page 2: BadContinuationPointInvalid") for l in lines), "resume after the origin rebuild is invalid") self.runner.check(any(l.startswith("Fresh: Good") for l in lines), "a fresh read after the rebuild succeeds") report["rebuild"] = lines - # (c) a consumer session close releases the origin continuation. Each held read starts right after a deploy + re-browse: - # an idle projected node's authority lapses with its 15 s metadata lease and a re-browse served from the cached page - # does not renew it (a value Read is refused the same way — pre-existing v1 projection behaviour, reported). + # (c) a consumer session close releases the origin continuation. The restore's deploy retires cold projected nodes, so it + # re-browses; the held read then deliberately starts only after the node's 15 s metadata lease has LAPSED (#922: it + # renews on demand within the HistoryRead instead of answering BadUserAccessDenied). self.restore() + time.sleep(LEASE_LAPSE_SECONDS) consumer = self.runner.primary("consumer") self.runner.check(self.origin_state() == 0, "no origin continuation open before") counts = {} diff --git a/scripts/validation/grpc-data/history_v1_origin_gate.py b/scripts/validation/grpc-data/history_v1_origin_gate.py new file mode 100644 index 000000000..d53945a80 --- /dev/null +++ b/scripts/validation/grpc-data/history_v1_origin_gate.py @@ -0,0 +1,268 @@ +"""lmxopcua#921 live gate: H05 (plan §4.3 mixed versions, row "new consumer → v1 origin") against a PINNED pre-H2 origin. + + python3 scripts/validation/grpc-data/rig.py up --run-id --history --source-revision 0c86edc1 --timeout 1500 + python3 scripts/validation/grpc-data/rig.py seed --run-id + sleep 75 # CONTROL's ClusterNode contact refresh before the first deploy + python3 scripts/validation/grpc-data/rig.py deploy --run-id --timeout 300 + python3 scripts/validation/grpc-data/history_v1_origin_gate.py --run-id + python3 scripts/validation/grpc-data/rig.py down --run-id + +The SOURCE pair runs a Host built from the pinned commit (post-X0, pre-H2: no HistoryRead RPC, no `history` feature); +CONTROL and CONSUMER run this checkout. SOURCE still has a historian (the `--history` overlay) and historizes `counter`, so +the origin's OWN HistoryRead is the positive control for "the origin has history, the wire does not carry it". + +What is asserted (results: the run's restricted `evidence/H05V1-results.json`): +1. the running build stamps — SOURCE = the pinned revision, CONTROL/CONSUMER = this checkout; +2. projected Raw and UNS `counter` variables: `Historizing` False and no HistoryRead bit in `AccessLevel`, while the + origin's own `counter` is `Historizing` True (control); a projected value Read is Good (control: the projection is live); +3. a CLI `historyread` on each projected variable ⇒ `BadHistoryOperationUnsupported`; on the origin's own node ⇒ Good rows; +4. diagnostics say the origin lacks the feature: the CONSUMER data-connections page shows "Negotiated features none (v1 + behaviour)" and "origin history not advertised"; the SOURCE page names the HistoryRead bit the older build dropped; +5. no new-shape call reaches the v1 origin from the consumer: in the pinned origins' wire tap (node-probe/WireTap.cs) for + the consumer's window, no HistoryRead / CallConditionMethod arrival, and no data call (anything but the capability + probe) carries `x-otopcua-data-features` — with the consumer's v1 calls (GetCapabilities/Browse/GetMetadata/Read/ + Subscribe) present in the same window (control). The capability probe itself always carries the client's features + (plan §4.1); a v1 origin ignores the header, which (6) shows byte-for-byte; +6. tap positive control: the probe's `history-v1-origin` scenario sends new-shape calls to both pinned origins — capabilities + with the feature header answer byte-identically to capabilities without it, a HistoryRead with the header is refused + PERMISSION_DENIED (a pre-H2 data listener admits only its six v1 methods and refuses any other path before routing — not + the UNIMPLEMENTED the plan's table guessed) — and the tap records those arrivals with the header and that status. +""" +import argparse +import html +import json +import re +import sys +import time +import urllib.request +import uuid +from pathlib import Path + +import history_gate +import rig +import scenarios + +ACCESS_LEVEL_HISTORY_READ = 0x04 +V1_PATHS = ("GetCapabilities", "Browse", "GetMetadata", "Read", "Subscribe", "Write") +NEW_SHAPE_PATHS = ("HistoryRead", "CallConditionMethod") + + +class V1OriginGate(history_gate.HistoryGate): + def __init__(self, run_id, *, pinned_build=False): + super().__init__(run_id, pinned_build=pinned_build) + self.pinned = self.runner.manifest.get("source_pinned") + if not self.pinned: + raise SystemExit("run was not brought up with --source-revision (no pinned SOURCE)") + self.checks = {} + self.detail = {} + + def check(self, name, condition): + self.checks[name] = bool(condition) + return bool(condition) + + # ------------------------------------------------------------------------------------------------------------ tools + + def tap(self, node): + path = self.runner.rig.folder / "probe" / node / "wire-tap.jsonl" + if not path.is_file() or path.is_symlink(): + return [] + rows = [] + for line in path.read_text(errors="replace").splitlines(): + try: + rows.append(json.loads(line)) + except ValueError: + continue + return rows + + def taps(self): + return {node: self.tap(node) for node in ("source-1", "source-2")} + + @staticmethod + def method(row): + return (row.get("path") or "").rsplit("/", 1)[-1] + + def stamp(self, node): + return json.loads(self.runner.rig.compose("exec", "--no-TTY", node, "cat", "/app/grpc-data-source.json", timeout=15)) + + def container_addresses(self, node): + ids = self.runner.rig.compose("ps", "--quiet", node).split() + if len(ids) != 1: + return [] + row = json.loads(rig.run_command([*self.runner.rig.docker, "container", "inspect", ids[0]]))[0] + return [network.get("IPAddress") for network in row["NetworkSettings"]["Networks"].values() if network.get("IPAddress")] + + def attribute(self, node, node_id, attribute, name): + argv = ["dotnet", str(self.runner.cli_dll), "read", "-u", self.runner.endpoint(node), "-U", "apikey", "-P", self.runner.key, + "-n", node_id, "-a", attribute] + result = self.runner.process(argv, self.runner.active + "-" + name + "-" + uuid.uuid4().hex[:6], timeout=60) + value = re.search(r"^Value:\s*(.*)$", result.stdout, re.M) + status = re.search(r"^Status:\s*(\S+)", result.stdout, re.M) + return {"exit": result.returncode, "value": value[1].strip() if value else None, "status": status[1] if status else None} + + def value_read(self, node, node_id, name): + argv = ["dotnet", str(self.runner.cli_dll), "read", "-u", self.runner.endpoint(node), "-U", "apikey", "-P", self.runner.key, + "-n", node_id, "--max-age", "5000"] + # As every mapped positive read on this rig: retry only an explicit BadWaitingForInitialData (README), bounded. + end = time.monotonic() + 60 + while True: + result = self.runner.process(argv, self.runner.active + "-" + name + "-" + uuid.uuid4().hex[:6], timeout=60) + status = re.search(r"^Status:\s*(\S+)", result.stdout, re.M) + observed = status[1] if status else None + if observed != "BadWaitingForInitialData" or time.monotonic() >= end: + return observed + time.sleep(2) + + def history(self, node, node_id, name): + result = self.cli(node, ["-n", node_id, *self.window_args(), "--max", "50"], name) + returned = re.search(r"^(\d+) values returned\.", result.stdout, re.M) + rows = int(returned[1]) if returned else 0 + return {"exit": result.returncode, "status": "Good" if result.returncode == 0 else self.error_status(result), "rows": rows, + "tail": (result.stdout + result.stderr)[-400:]} + + def page(self, cluster): + """The AdminUI data-connections page of `cluster`, served by the CONTROL primary (login disabled on the rig).""" + control = self.runner.primary("control") + url = self.runner.endpoint(control, "admin") + f"/clusters/{cluster}/data-connections" + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + with opener.open(urllib.request.Request(url), timeout=15) as response: + text = response.read(8 * 1024 * 1024).decode("utf-8", errors="replace") + return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", text))) + + # ------------------------------------------------------------------------------------------------------------- run + + def run(self): + self.runner.publish() + self.runner.active, self.runner.deadline = "H05V1", time.monotonic() + 1500 + started = time.monotonic() + error = None + try: + self.scenario() + except Exception as failure: # recorded with every check made so far + error = type(failure).__name__ + ": " + str(failure)[:400] + passed = error is None and bool(self.checks) and all(self.checks.values()) + result = {"id": "H05V1", "pinned": self.pinned, "consumer_revision": self.runner.manifest.get("source_revision"), + "passed": passed, "error": error, "failed_checks": [k for k, v in self.checks.items() if not v], + "checks": self.checks, "detail": self.detail, "duration_seconds": round(time.monotonic() - started, 1), + "window": [history_gate._iso(w) for w in self.window] if self.window else None} + self.runner.save("H05V1-results.json", result) + print(json.dumps({k: result[k] for k in ("id", "passed", "error", "failed_checks", "duration_seconds")}), flush=True) + return result + + def scenario(self): + # 1. Which build is actually running where. + stamps = {node: self.stamp(node) for node in self.runner.manifest["nodes"]} + self.detail["stamps"] = stamps + self.check("source_nodes_run_the_pinned_pre_h2_build", + all(stamps[n].get("revision") == self.pinned["revision"] and stamps[n].get("tree_hash") == self.pinned["tree_hash"] + for n in ("source-1", "source-2"))) + self.check("control_and_consumer_run_this_checkout", + all(stamps[n].get("revision") == self.runner.manifest["source_revision"] for n in stamps if not n.startswith("source-"))) + + self.accumulate() + tap_start = {node: len(rows) for node, rows in self.taps().items()} + consumer = self.resolve_projected() + source, origin_counter = self.origin_node("raw", "counter") + + # 2. Historizing / AccessLevel: projected false, origin true (control); projected value Read Good (control). + attributes = {} + for realm in ("raw", "uns"): + node_id = self.projected[(realm, "counter")] + attributes[realm] = {"historizing": self.attribute(consumer, node_id, "Historizing", f"{realm}-historizing"), + "access_level": self.attribute(consumer, node_id, "AccessLevel", f"{realm}-access"), + "value_status": self.value_read(consumer, node_id, f"{realm}-value")} + attributes["origin"] = {"node": origin_counter, + "historizing": self.attribute(source, origin_counter, "Historizing", "origin-historizing"), + "access_level": self.attribute(source, origin_counter, "AccessLevel", "origin-access")} + self.detail["attributes"] = attributes + + def access(entry): + try: + return int(entry["value"]) + except (TypeError, ValueError): + return None + + for realm in ("raw", "uns"): + row = attributes[realm] + self.check(f"projected_{realm}_counter_historizing_false", row["historizing"]["value"] == "False" and row["historizing"]["status"] == "Good") + level = access(row["access_level"]) + self.check(f"projected_{realm}_counter_access_level_has_no_history_read", level is not None and level & ACCESS_LEVEL_HISTORY_READ == 0) + self.check(f"projected_{realm}_counter_value_read_good", row["value_status"] == "Good") + self.check("origin_counter_historizing_true_control", attributes["origin"]["historizing"]["value"] == "True") + origin_level = access(attributes["origin"]["access_level"]) + self.check("origin_counter_access_level_has_history_read_control", + origin_level is not None and origin_level & ACCESS_LEVEL_HISTORY_READ != 0) + + # 3. HistoryRead: projected ⇒ unsupported, origin's own node ⇒ Good rows (control). + reads = {realm: self.history(consumer, self.projected[(realm, "counter")], f"{realm}-historyread") for realm in ("raw", "uns")} + reads["origin"] = self.history(source, origin_counter, "origin-historyread") + self.detail["history_reads"] = reads + for realm in ("raw", "uns"): + self.check(f"projected_{realm}_historyread_bad_history_operation_unsupported", + reads[realm]["status"] == "BadHistoryOperationUnsupported") + self.check("origin_own_historyread_good_with_rows_control", reads["origin"]["status"] == "Good" and reads["origin"]["rows"] > 0) + + # 4. Diagnostics: the consumer negotiated nothing and the origin advertised no history; the origin names the drop. + consumer_page = self.page("CONSUMER") + source_page = self.page("SOURCE") + line = re.search(r"Negotiated features .{0,400}?open remote continuations", consumer_page) + dropped = re.search(r"Exports with dropped unknown operation bits: .{0,400}?upgraded\.", source_page) + self.detail["diagnostics"] = {"consumer_history_line": line[0] if line else None, "source_dropped_line": dropped[0] if dropped else None} + self.check("consumer_diagnostics_negotiated_features_none_v1", + line is not None and "Negotiated features none (v1 behaviour)" in line[0]) + self.check("consumer_diagnostics_origin_history_not_advertised", line is not None and "origin history not advertised" in line[0]) + self.check("source_diagnostics_older_build_dropped_history_read", dropped is not None and "HistoryRead" in dropped[0]) + + # 5. The consumer's window on the pinned origins' wire tap. + consumer_ips = {address for node in ("consumer-1", "consumer-2") for address in self.container_addresses(node)} + window = {node: rows[tap_start[node]:] for node, rows in self.taps().items()} + arrivals = [dict(row, origin=node) for node, rows in window.items() for row in rows if row.get("phase") == "arrival"] + from_consumer = [row for row in arrivals if row.get("remote") in consumer_ips] + methods = sorted({self.method(row) for row in from_consumer}) + featured = [row for row in from_consumer if row.get("features")] + self.detail["tap_window"] = {"consumer_addresses": sorted(consumer_ips), "arrivals": len(arrivals), "from_consumer": len(from_consumer), + "methods": methods, "featured_methods": sorted({self.method(row) for row in featured}), + "featured_values": sorted({row["features"] for row in featured}), + "other_remotes": sorted({row.get("remote") for row in arrivals if row.get("remote") not in consumer_ips})} + self.check("tap_saw_consumer_v1_calls_control", len({"Read", "Browse", "GetMetadata"} & set(methods)) >= 2) + self.check("tap_no_history_read_or_condition_method_from_consumer", not set(NEW_SHAPE_PATHS) & set(methods)) + self.check("tap_no_data_call_from_consumer_carries_the_feature_header", + all(self.method(row) == "GetCapabilities" for row in featured)) + self.check("tap_all_consumer_calls_are_v1_methods", set(methods) <= set(V1_PATHS)) + + # 6. Positive control for the tap (and the Unimplemented wire path): new-shape calls the probe sends on purpose. + before = {node: len(rows) for node, rows in self.taps().items()} + output = self.runner.folder / ("H05V1-probe-" + uuid.uuid4().hex[:6] + ".json") + argv = ["dotnet", str(self.runner.probe_dll), "--manifest", str(self.runner.manifest_path), "--scenario", "history-v1-origin", + "--output", str(output)] + self.runner.process(argv, "H05V1-probe", timeout=120) + report = scenarios.restricted_json(output) if output.exists() else {"passed": False} + self.detail["probe"] = report + self.check("probe_v1_origin_capabilities_identical_and_history_read_refused", report.get("passed") is True) + time.sleep(1) + after = {node: rows[before[node]:] for node, rows in self.taps().items()} + control = {} + for node, rows in after.items(): + history_arrivals = [row for row in rows if row.get("phase") == "arrival" and self.method(row) == "HistoryRead"] + completions = [row for row in rows if row.get("phase") == "completion" and self.method(row) == "HistoryRead"] + control[node] = {"history_read_arrivals": len(history_arrivals), + "history_read_features": sorted({row.get("features") or "" for row in history_arrivals}), + "history_read_grpc_status": sorted({row.get("grpcStatus") or "" for row in completions}), + "featured_capabilities": sum(1 for row in rows if row.get("phase") == "arrival" + and self.method(row) == "GetCapabilities" and row.get("features"))} + self.check(f"tap_recorded_probe_history_read_with_header_{node}", + history_arrivals and all(row.get("features") == "history" for row in history_arrivals)) + self.check(f"tap_recorded_permission_denied_status_{node}", completions and all(row.get("grpcStatus") == "7" for row in completions)) + self.detail["tap_control"] = control + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--run-id", required=True) + parser.add_argument("--pinned-build", action="store_true", help="keep the recorded checkout hash (harness edits during a run)") + arguments = parser.parse_args(argv) + result = V1OriginGate(arguments.run_id, pinned_build=arguments.pinned_build).run() + return 0 if result["passed"] else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/validation/grpc-data/node-probe/WireTap.cs b/scripts/validation/grpc-data/node-probe/WireTap.cs new file mode 100644 index 000000000..b7340c43d --- /dev/null +++ b/scripts/validation/grpc-data/node-probe/WireTap.cs @@ -0,0 +1,104 @@ +using System.Text.Json; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using Microsoft.Extensions.DependencyInjection; + +[assembly: HostingStartup(typeof(GrpcDataNodeProbe.WireTapStartup))] + +namespace GrpcDataNodeProbe; + +/// +/// Rig-only data-listener wire tap (lmxopcua#921). Off unless GRPC_DATA_WIRE_TAP=1; the rig sets it only on a +/// pinned-origin SOURCE (rig.py up --source-revision). It writes one JSON line when each request arrives on the +/// data listener (port 4057) and one when it completes: the UTC time, the gRPC path, the value of the +/// x-otopcua-data-features request header (null when absent), the remote address and, at completion, the +/// gRPC status. It records no credential, header other than the feature header, or message body. +/// +/// +/// Self-contained on purpose: it uses ASP.NET Core only, so the rig copies this one file into a pinned older tree's +/// node probe and the same tap runs on a Host built from that revision. The arrival line is written before the gRPC +/// pipeline runs, so a call the older Host refuses (an unimplemented method, an unauthenticated caller) is recorded +/// too. The file is bounded (); past it, a single truncation line is written. +/// +public sealed class WireTapStartup : IHostingStartup +{ + /// The tap's output file name inside the node's probe directory. + public const string FileName = "wire-tap.jsonl"; + + /// + public void Configure(IWebHostBuilder builder) + { + if (Environment.GetEnvironmentVariable("GRPC_DATA_WIRE_TAP") != "1") return; + var directory = Environment.GetEnvironmentVariable("GRPC_DATA_NODE_PROBE_DIR"); + if (string.IsNullOrWhiteSpace(directory) || !Directory.Exists(directory)) return; + var tap = new WireTapLog(Path.Combine(directory, FileName)); + builder.ConfigureServices(services => services.AddSingleton(new WireTapStartupFilter(tap))); + } +} + +/// The bounded append-only line log behind the tap. +public sealed class WireTapLog(string path) +{ + /// Lines written before the log stops (a soak would otherwise fill the probe directory). + public const int MaximumLines = 50_000; + + private readonly object _gate = new(); + private int _lines; + + /// Appends one record as a JSON line; never throws into the request pipeline. + public void Write(object record) + { + try + { + lock (_gate) + { + if (_lines > MaximumLines) return; + var line = _lines++ == MaximumLines ? JsonSerializer.Serialize(new { truncated = true }) : JsonSerializer.Serialize(record); + File.AppendAllText(path, line + "\n"); + } + } + catch (IOException) { } + catch (UnauthorizedAccessException) { } + } +} + +/// Records each data-listener request at arrival (before authentication) and at completion. +public sealed class WireTapStartupFilter(WireTapLog log) : IStartupFilter +{ + private const int DataListenerPort = 4057; + private const string FeaturesHeader = "x-otopcua-data-features"; + private static long _sequence; + + /// + public Action Configure(Action next) => app => + { + app.Use(nextMiddleware => async context => + { + if (context.Connection.LocalPort != DataListenerPort) + { + await nextMiddleware(context); + return; + } + var sequence = Interlocked.Increment(ref _sequence); + var path = context.Request.Path.Value; + string? features = context.Request.Headers.TryGetValue(FeaturesHeader, out var value) ? value.ToString() : null; + var remote = context.Connection.RemoteIpAddress?.ToString(); + log.Write(new { phase = "arrival", sequence, utc = DateTime.UtcNow.ToString("O"), path, features, remote, protocol = context.Request.Protocol }); + try + { + await nextMiddleware(context); + } + finally + { + // A trailers-only answer (e.g. Unimplemented) carries grpc-status in the headers; a normal one in the trailers. + var trailers = context.Features.Get()?.Trailers; + string? status = trailers is not null && trailers.TryGetValue("grpc-status", out var t) ? t.ToString() + : context.Response.Headers.TryGetValue("grpc-status", out var h) ? h.ToString() : null; + log.Write(new { phase = "completion", sequence, utc = DateTime.UtcNow.ToString("O"), path, grpcStatus = status, httpStatus = context.Response.StatusCode }); + } + }); + next(app); + }; +} diff --git a/scripts/validation/grpc-data/probe/Program.cs b/scripts/validation/grpc-data/probe/Program.cs index dd51120dd..ad4aeb54c 100644 --- a/scripts/validation/grpc-data/probe/Program.cs +++ b/scripts/validation/grpc-data/probe/Program.cs @@ -26,7 +26,7 @@ try using var manifest = JsonDocument.Parse(await File.ReadAllTextAsync(manifestPath)); var root = manifest.RootElement; var scenario = arguments.GetValueOrDefault("--scenario", "all"); - if (scenario is not ("all" or "D13" or "wire" or "history" or "conditions" or "condition-records")) throw new ArgumentException("Unsupported wire scenario."); + if (scenario is not ("all" or "D13" or "wire" or "history" or "history-v1-origin" or "conditions" or "condition-records")) throw new ArgumentException("Unsupported wire scenario."); var nodes = root.GetProperty("nodes"); var endpoints = root.GetProperty("endpoints"); var keyPath = root.GetProperty("credentials").GetProperty("data_key_files").GetProperty("source").GetString()!; @@ -462,7 +462,72 @@ try ["expect"] = expect, ["expectedFound"] = expected, })); } - if (scenario is not ("D13" or "history" or "conditions" or "condition-records")) + if (scenario == "history-v1-origin") + { + // lmxopcua#921 (H05 against a pinned pre-H2 origin): what a NEW caller sees from a v1 origin when it asks for the + // features. Capabilities with the full feature header are byte-identical to those without it (no history, no + // conditions, no HistoryRead bit), and a HistoryRead with the header is refused PERMISSION_DENIED: a pre-H2 data + // listener admits only its six v1 methods (DataConnectionEndpoints.Methods at that revision) and refuses any other + // path before gRPC routing, so the call never reaches a handler (observed live, #921). This deliberately sends new-shape calls, so on a wire-tapped origin it is also the tap's + // positive control (the tap must record them). + failurePhase = ProbeFailurePhase.WireOperation; + var fixture = root.GetProperty("fixture"); + var rawUri = fixture.GetProperty("namespace_uris").GetProperty("raw").GetString()!; + var historized = fixture.GetProperty("history").GetProperty("historized").GetProperty("raw").GetString()!; + foreach (var node in sourceNodes) + { + var name = node.Name; + failureTarget = name; + var nodeId = node.Value.GetProperty("node_id").GetString()!; + Metadata With(string? features) + { + var headers = Headers(key, "Node", nodeId); + if (features is not null) headers.Add("x-otopcua-data-features", features); + return headers; + } + using var handler = security.Handler(name); + using var channel = GrpcChannel.ForAddress($"https://{name}:4057", new() { HttpHandler = handler }); + var client = new W.DataConnectionService.DataConnectionServiceClient(channel); + var deadline = () => DateTime.UtcNow.AddSeconds(20); + var plain = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, With(null), deadline()); + var featured = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, With("history,conditions"), deadline()); + static byte[] Shape(W.CapabilitiesResponse response) + { + // The serving identity aside, the two answers must be the same bytes. + var copy = response.Clone(); + copy.Serving = null; + return copy.ToByteArray(); + } + var v1Shape = plain.History is null && featured.History is null && plain.Conditions is null && featured.Conditions is null + && (plain.Operations & 32) == 0 && (featured.Operations & 32) == 0; + var identical = Shape(plain).AsSpan().SequenceEqual(Shape(featured)); + string historyRead; + try + { + var request = new W.HistoryReadRequest + { + Budget = new() { TimeoutTicks = TimeSpan.FromSeconds(10).Ticks, MaxItems = 1, MaxBytes = 1024 * 1024 }, + Raw = new() { NumValuesPerNode = 5, End = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTimeOffset(DateTimeOffset.UtcNow) }, + }; + request.Items.Add(new W.HistoryReadItem { CorrelationId = "one", View = new() { Address = new() { OriginClusterId = "SOURCE", + NamespaceUri = rawUri, IdentifierKind = "string", Identifier = historized }, Realm = (int)DataRealm.Raw, Subject = historized } }); + await client.HistoryReadAsync(request, With("history"), deadline()); + historyRead = "OK"; + } + catch (RpcException error) { historyRead = error.StatusCode.ToString(); } + results.Add(new("history-v1-origin-" + name, "history-v1-origin", v1Shape && identical && historyRead == "PermissionDenied", 3, new() + { + ["withoutHeader"] = new { operations = plain.Operations, historyPresent = plain.History is not null, conditionsPresent = plain.Conditions is not null, + protocolMinor = plain.ProtocolMinor, bytes = plain.CalculateSize() }, + ["withHeader"] = new { operations = featured.Operations, historyPresent = featured.History is not null, conditionsPresent = featured.Conditions is not null, + protocolMinor = featured.ProtocolMinor, bytes = featured.CalculateSize() }, + ["byteIdentical"] = identical, + ["historyReadWithHeader"] = historyRead, + ["serving"] = featured.Serving.ToString(), + })); + } + } + if (scenario is not ("D13" or "history" or "history-v1-origin" or "conditions" or "condition-records")) { var fixture = root.GetProperty("fixture"); var rawUri = fixture.GetProperty("namespace_uris").GetProperty("raw").GetString()!; diff --git a/scripts/validation/grpc-data/rig.py b/scripts/validation/grpc-data/rig.py index 7d28ac4b2..54224c7bd 100644 --- a/scripts/validation/grpc-data/rig.py +++ b/scripts/validation/grpc-data/rig.py @@ -517,26 +517,91 @@ def run_command(argv, *, timeout=120, environment=None): return result.stdout +def _image_input(name): + """Whether repository-relative `name` is an image build input (the filter both tree hashes share).""" + suffix = Path(name).suffix + return not name.startswith(("docs/", "tests/", ".playwright-mcp/")) and ( + suffix in {".cs", ".csproj", ".props", ".targets", ".slnx", ".resx", ".razor", ".css", ".js", ".proto"} + or name in {"global.json", "NuGet.Config", "nuget.config", "Directory.Build.rsp", ".dockerignore", "scripts/validation/grpc-data/Dockerfile"} + or name.startswith("src/") and suffix == ".json") + + +def _tree_hash(root, names): + import hashlib + digest = hashlib.sha256() + for name in sorted(set(filter(None, names))): + path = root / name + if not _image_input(name): + continue + if path.is_file() and not path.is_symlink(): + digest.update(name.encode() + b"\0") + digest.update(hashlib.sha256(path.read_bytes()).digest()) + return digest.hexdigest() + + def source_tree_hash(): """Hash image build inputs, including pending/new code, excluding review evidence. Harness Python and test sources have their own evidence and do not enter the Host/seeder/probe binaries. Notes can change without invalidating an image. """ - import hashlib paths = run_command(["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"]).split("\0") - digest = hashlib.sha256() - for name in sorted(set(filter(None, paths))): - path = ROOT / name - if (name.startswith(("docs/", "tests/", ".playwright-mcp/")) or - not (path.suffix in {".cs", ".csproj", ".props", ".targets", ".slnx", ".resx", ".razor", ".css", ".js", ".proto"} - or name in {"global.json", "NuGet.Config", "nuget.config", "Directory.Build.rsp", ".dockerignore", "scripts/validation/grpc-data/Dockerfile"} - or name.startswith("src/") and path.suffix == ".json")): - continue - if path.is_file() and not path.is_symlink(): - digest.update(name.encode() + b"\0") - digest.update(hashlib.sha256(path.read_bytes()).digest()) - return digest.hexdigest() + return _tree_hash(ROOT, paths) + + +# lmxopcua#921: a pinned pre-H2 SOURCE pair (plan §4.3 mixed versions, row "new consumer → v1 origin"). A pinned revision must +# CONTAIN X0 (a pre-X0 node rejects the whole data-connection snapshot once any newer bit is authored, so it is not the v1 origin +# the row describes) and must NOT contain H2 (whose merge adds the origin HistoryRead RPC and the `history` feature). +X0_MERGE = "a15912539f8a48804c31e74b2558994a50a338e6" +H2_MERGE = "ef938b435bbad2862bcd4b8e1f39e0b1ef2089b2" +PINNED_DATA_PROTO = "src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto" +# The only rig file added to a pinned tree: the self-contained data-listener wire tap (ASP.NET Core only, compiles at any revision). +PINNED_OVERLAY_FILES = ("scripts/validation/grpc-data/node-probe/WireTap.cs",) + + +def resolve_pinned_source_revision(revision, *, git=None): + """The full SHA of `revision` once it is proven a post-X0, pre-H2 commit; RigError otherwise.""" + git = git or (lambda *arguments: run_command(["git", *arguments])) + if not isinstance(revision, str) or not re.fullmatch(r"[0-9a-f]{7,40}", revision): + raise RigError("a pinned SOURCE revision must be a hexadecimal commit id") + full = git("rev-parse", "--verify", "--quiet", revision + "^{commit}").strip() + if not re.fullmatch(r"[0-9a-f]{40}", full): + raise RigError("the pinned SOURCE revision does not name a commit") + if git("merge-base", X0_MERGE, full).strip() != X0_MERGE: + raise RigError("the pinned SOURCE revision predates X0 (tolerant readers); it would reject the whole snapshot") + if git("merge-base", H2_MERGE, full).strip() == H2_MERGE: + raise RigError("the pinned SOURCE revision contains H2; it is not a v1 (pre-history) origin") + if re.search(r"^\s*rpc\s+HistoryRead\b", git("show", f"{full}:{PINNED_DATA_PROTO}"), re.M): + raise RigError("the pinned SOURCE revision's data contract already has HistoryRead") + return full + + +def export_pinned_source(revision, directory): + """Extract `revision`'s committed tree into a new restricted `directory` and add the rig's wire tap.""" + import shutil + import subprocess + if directory.exists(): + raise RigError("pinned SOURCE export directory already exists") + directory.mkdir(mode=0o700) + archive = subprocess.Popen(["git", "archive", "--format=tar", revision], cwd=ROOT, stdout=subprocess.PIPE) + try: + extract = subprocess.run(["tar", "-x", "-C", str(directory)], stdin=archive.stdout, timeout=600, check=False) + finally: + archive.stdout.close() + if archive.wait(timeout=600) != 0 or extract.returncode != 0: + raise RigError("could not export the pinned SOURCE revision") + for name in PINNED_OVERLAY_FILES: + target = directory / name + if target.exists(): + raise RigError("the pinned SOURCE tree already has a rig overlay file") + shutil.copyfile(ROOT / name, target) + return pinned_tree_hash(directory) + + +def pinned_tree_hash(directory): + """The image-input hash of an exported pinned tree (same filter as `source_tree_hash`).""" + names = [str(path.relative_to(directory)) for path in directory.rglob("*") if path.is_file() and not path.is_symlink()] + return _tree_hash(directory, [name.replace(os.sep, "/") for name in names]) def device_tree_hash(): @@ -678,6 +743,8 @@ class LocalRig: files.extend(["--file", str(HERE / "compose.history.questdb.yml")]) if self.environment.get("GRPC_DATA_CONDITIONS") == "1": files.extend(["--file", str(HERE / "compose.conditions.yml")]) + if self.environment.get("GRPC_DATA_SOURCE_PINNED") == "1": + files.extend(["--file", str(HERE / "compose.source-pinned.yml")]) return files def compose(self, *args, timeout=120): @@ -749,10 +816,18 @@ class LocalRig: expected = source_tree_hash() if manifest.get("source_tree_hash") != expected: raise RigError("running manifest does not match current image build inputs") + pinned = manifest.get("source_pinned") + if pinned is not None: + # lmxopcua#921: the SOURCE pair runs the pinned revision; its export must still hash to what was built. + if (not isinstance(pinned, dict) or pinned_tree_hash(self.folder / "pinned-source") != pinned.get("tree_hash") + or pinned.get("revision") != self.environment.get("GRPC_DATA_SOURCE_PINNED_REVISION")): + raise RigError("pinned SOURCE export does not match the recorded pinned build") for node in NODES: raw = self.compose("exec", "--no-TTY", node, "cat", "/app/grpc-data-source.json", timeout=15) stamp = json.loads(raw) - if stamp.get("tree_hash") != expected or stamp.get("revision") != manifest.get("source_revision"): + want = ((pinned["tree_hash"], pinned["revision"]) if pinned is not None and node.startswith("source-") + else (expected, manifest.get("source_revision"))) + if stamp.get("tree_hash") != want[0] or stamp.get("revision") != want[1]: raise RigError("running Host build stamp does not match the candidate") device_hash = device_tree_hash() if manifest.get("device_source_hash") != device_hash: @@ -848,7 +923,7 @@ class LocalRig: self.save(manifest) return manifest - def up(self, timeout=600, history=False, history_backend="sqlserver", conditions=False): + def up(self, timeout=600, history=False, history_backend="sqlserver", conditions=False, source_revision=None): import secrets import credentials if self.folder.exists(): @@ -875,6 +950,16 @@ class LocalRig: settings["GRPC_DATA_HISTORY_BACKEND"] = history_backend if conditions: settings["GRPC_DATA_CONDITIONS"] = "1" + pinned = None + if source_revision is not None: + # lmxopcua#921: the SOURCE pair is built from a pinned post-X0, pre-H2 revision (the "v1 origin"); CONTROL and + # CONSUMER stay on this checkout. Only the wire tap is added to the pinned tree. + full = resolve_pinned_source_revision(source_revision) + pinned = {"revision": full, "tree_hash": export_pinned_source(full, self.folder / "pinned-source"), + "x0_merge": X0_MERGE, "h2_merge_absent": H2_MERGE, "overlay_files": list(PINNED_OVERLAY_FILES)} + settings.update({"GRPC_DATA_SOURCE_PINNED": "1", "GRPC_DATA_SOURCE_PINNED_REVISION": full, + "GRPC_DATA_SOURCE_PINNED_TREE_HASH": pinned["tree_hash"], "GRPC_DATA_SOURCE_PINNED_CONTEXT": str(self.folder / "pinned-source"), + "GRPC_DATA_SOURCE_IMAGE": f"otopcua-grpc-data-source-pinned:{self.run_id}"}) atomic_write_secret(self.folder / "environment.json", json.dumps(settings)) self.environment.update(settings) credentials.provision_tls(self.folder / "security", NODES[2:]) @@ -891,12 +976,15 @@ class LocalRig: resolved = json.loads(self.compose("config", "--format", "json")) validate_fixture_endpoints(resolved, local_services=SERVICES) try: - self.compose("build", "--pull", "migrator", "device", "control-1", "seeder", timeout=1800) + self.compose("build", "--pull", "migrator", "device", "control-1", "seeder", *(["source-1"] if pinned else []), + timeout=2400 if pinned else 1800) # a pinned run builds a second Host image self.compose("up", "--detach", "sql", "device", "migrator", *NODES, timeout=timeout) manifest = self.allocate_manifest() manifest["source_revision"] = revision manifest["source_tree_hash"] = tree_hash manifest["device_source_hash"] = settings["DEVICE_TREE_HASH"] + if pinned is not None: + manifest["source_pinned"] = pinned self.capture(manifest) wait_until(lambda: self.health(manifest, require_catalog=False), timeout=timeout, description="six node health and independent pair roles") manifest["state"] = "up" @@ -1347,6 +1435,8 @@ def main(argv=None): parser.add_argument("action", choices=("preflight", "up", "seed", "deploy", "status", "down")) parser.add_argument("--run-id") parser.add_argument("--timeout", type=float, default=None) + parser.add_argument("--source-revision", default=None, + help="up only (#921): build the SOURCE pair from this pinned post-X0, pre-H2 commit (a v1 origin), e.g. 0c86edc1") parser.add_argument("--conditions", action="store_true", help="up only: add the A2a conditions overlay (AlarmSubscribe exports + one scripted alarm)") parser.add_argument("--history", action="store_true", help="up only: add the H2 history overlay (SOURCE historian + history seed profile)") parser.add_argument("--history-backend", choices=HISTORY_BACKENDS, default=None, @@ -1381,6 +1471,10 @@ def main(argv=None): if arguments.action != "up": raise RigError("--conditions applies to up only; the run remembers it") options["conditions"] = True + if arguments.source_revision is not None: + if arguments.action != "up": + raise RigError("--source-revision applies to up only; the run remembers it") + options["source_revision"] = arguments.source_revision result = action(**options) print(json.dumps({"run_id": result["run_id"], "state": result.get("state"), "manifest": str(rig.path), "healthy": result.get("healthy")})) return 0 diff --git a/scripts/validation/grpc-data/tests/test_rig.py b/scripts/validation/grpc-data/tests/test_rig.py index fe00cf21a..224a3a480 100644 --- a/scripts/validation/grpc-data/tests/test_rig.py +++ b/scripts/validation/grpc-data/tests/test_rig.py @@ -569,3 +569,85 @@ class AkkaSeedEndpointTests(unittest.TestCase): for row in variants: with self.subTest(row=row), self.assertRaises(rig.RigError): rig.validate_fixture_endpoints(row, local_services={"source-1"}) + + +class PinnedSourceRevisionTests(unittest.TestCase): + """lmxopcua#921: a pinned SOURCE must be a post-X0, pre-H2 commit; no Docker or real git.""" + + PINNED = "0c86edc194bf50c2a902a081959333097e0b3bb5" + PROTO_V1 = "service DataConnectionService {\n rpc Read(ReadRequest) returns (ReadResponse);\n}\n" + + def git(self, *, x0=True, h2=False, proto=None): + def run(*arguments): + if arguments[0] == "rev-parse": + return self.PINNED + "\n" + if arguments[0] == "merge-base": + if arguments[1] == rig.X0_MERGE: + return (rig.X0_MERGE if x0 else "1" * 40) + "\n" + return (rig.H2_MERGE if h2 else "2" * 40) + "\n" + if arguments[0] == "show": + return proto if proto is not None else self.PROTO_V1 + raise AssertionError(arguments) + return run + + def test_a_post_x0_pre_h2_commit_resolves_to_its_full_sha(self): + self.assertEqual(rig.resolve_pinned_source_revision("0c86edc1", git=self.git()), self.PINNED) + + def test_pre_x0_h2_or_a_history_rpc_is_refused(self): + history = self.PROTO_V1 + " rpc HistoryRead(HistoryReadRequest) returns (HistoryReadResponse);\n" + for options in ({"x0": False}, {"h2": True}, {"proto": history}): + with self.subTest(options=options), self.assertRaises(rig.RigError): + rig.resolve_pinned_source_revision("0c86edc1", git=self.git(**options)) + + def test_only_hexadecimal_commit_ids_are_accepted(self): + for value in ("HEAD", "master", "0c86edc1;rm", "abc", None, "--all"): + with self.subTest(value=value), self.assertRaises(rig.RigError): + rig.resolve_pinned_source_revision(value, git=self.git()) + + def test_the_real_pin_0c86edc1_is_post_x0_and_pre_h2(self): + """The committed history itself (read-only git): the issue's suggested pin passes the guard.""" + self.assertEqual(rig.resolve_pinned_source_revision("0c86edc1"), self.PINNED) + with self.assertRaises(rig.RigError): + rig.resolve_pinned_source_revision(rig.H2_MERGE[:12]) + + def test_pinned_tree_hash_uses_the_image_input_filter(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) + (root / "src").mkdir() + (root / "docs").mkdir() + (root / "src" / "A.cs").write_text("class A {}") + (root / "docs" / "note.cs").write_text("ignored") + first = rig.pinned_tree_hash(root) + (root / "docs" / "note.cs").write_text("still ignored") + self.assertEqual(rig.pinned_tree_hash(root), first) + (root / "src" / "A.cs").write_text("class A { int x; }") + self.assertNotEqual(rig.pinned_tree_hash(root), first) + + def test_candidate_expects_the_pinned_stamp_on_source_nodes_only(self): + instance = object.__new__(rig.LocalRig) + instance.folder = Path("/nonexistent") + instance.environment = {"GRPC_DATA_SOURCE_PINNED_REVISION": "pinned-rev"} + instance.load = Mock(return_value={"source_tree_hash": "code", "source_revision": "revision", "device_source_hash": "device", + "source_pinned": {"revision": "pinned-rev", "tree_hash": "pinned-code"}}) + + def stamp(*args, **kwargs): + if "device" in args: + return "device\n" + pinned = args[2].startswith("source-") + return json.dumps({"tree_hash": "pinned-code" if pinned else "code", "revision": "pinned-rev" if pinned else "revision"}) + + def current_everywhere(*args, **kwargs): + return "device\n" if "device" in args else json.dumps({"tree_hash": "code", "revision": "revision"}) + + instance.compose = Mock(side_effect=stamp) + with patch.object(rig, "source_tree_hash", return_value="code"), patch.object(rig, "device_tree_hash", return_value="device"): + with patch.object(rig, "pinned_tree_hash", return_value="pinned-code"): + self.assertEqual(instance.verify_candidate(), "code") + # A current-checkout stamp on a SOURCE node (the pinned image is not what runs) is refused. + instance.compose.side_effect = current_everywhere + with self.assertRaises(rig.RigError): + instance.verify_candidate() + # The export edited after the build is refused before any stamp is read. + instance.compose.side_effect = stamp + with patch.object(rig, "pinned_tree_hash", return_value="edited-export"), self.assertRaises(rig.RigError): + instance.verify_candidate() diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/ReadCommand.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/ReadCommand.cs index aac885270..de8b94e31 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/ReadCommand.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/ReadCommand.cs @@ -29,11 +29,29 @@ public class ReadCommand : CommandBase [CommandOption("max-age", Description = "Maximum cached value age in milliseconds (0 to 2147483647; default 0)")] public double MaxAgeMilliseconds { get; init; } + /// Gets the attribute to read; Value (the default) is the current value. + [CommandOption("attribute", 'a', Description = "Attribute to read: Value (default), Historizing, AccessLevel, UserAccessLevel, DataType, ValueRank, ArrayDimensions, MinimumSamplingInterval, NodeClass, BrowseName, DisplayName, EventNotifier")] + public string Attribute { get; init; } = "Value"; + + /// The attributes --attribute accepts (case-insensitive), by name. + internal static readonly IReadOnlyDictionary AttributeIds = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["Value"] = Attributes.Value, ["Historizing"] = Attributes.Historizing, ["AccessLevel"] = Attributes.AccessLevel, + ["UserAccessLevel"] = Attributes.UserAccessLevel, ["DataType"] = Attributes.DataType, ["ValueRank"] = Attributes.ValueRank, + ["ArrayDimensions"] = Attributes.ArrayDimensions, ["MinimumSamplingInterval"] = Attributes.MinimumSamplingInterval, + ["NodeClass"] = Attributes.NodeClass, ["BrowseName"] = Attributes.BrowseName, ["DisplayName"] = Attributes.DisplayName, + ["EventNotifier"] = Attributes.EventNotifier, + }; + /// public override async ValueTask ExecuteAsync(IConsole console) { if (!double.IsFinite(MaxAgeMilliseconds) || MaxAgeMilliseconds < 0 || MaxAgeMilliseconds > int.MaxValue) throw new CommandException("Invalid --max-age value: expected a finite number from 0 to 2147483647 milliseconds."); + if (!AttributeIds.TryGetValue(Attribute ?? "", out var attributeId)) + throw new CommandException($"Invalid --attribute value: expected one of {string.Join(", ", AttributeIds.Keys)}."); + if (attributeId != Attributes.Value && MaxAgeMilliseconds != 0) + throw new CommandException("--max-age applies to the Value attribute only."); ConfigureLogging(); @@ -56,9 +74,11 @@ public class ReadCommand : CommandBase DataValue value; try { - value = MaxAgeMilliseconds == 0 - ? await service.ReadValueAsync(nodeId, ct) - : await service.ReadValueAsync(nodeId, TimeSpan.FromMilliseconds(MaxAgeMilliseconds), ct); + value = attributeId != Attributes.Value + ? await service.ReadAttributeAsync(nodeId, attributeId, ct) + : MaxAgeMilliseconds == 0 + ? await service.ReadValueAsync(nodeId, ct) + : await service.ReadValueAsync(nodeId, TimeSpan.FromMilliseconds(MaxAgeMilliseconds), ct); } catch (ServiceResultException ex) when (ex.StatusCode != StatusCodes.BadSessionIdInvalid && ex.StatusCode != StatusCodes.BadConnectionClosed @@ -68,12 +88,14 @@ public class ReadCommand : CommandBase // BadUserAccessDenied, ...) as an exception. A read command's job is to REPORT that status, // not crash with a stack trace — session-level failures still propagate. await console.Output.WriteLineAsync($"Node: {NodeId}"); + if (attributeId != Attributes.Value) await console.Output.WriteLineAsync($"Attribute: {Attribute}"); await console.Output.WriteLineAsync($"Value: "); await console.Output.WriteLineAsync($"Status: {(StatusCode)ex.StatusCode} ({ex.StatusCode.SymbolicId})"); return; } await console.Output.WriteLineAsync($"Node: {NodeId}"); + if (attributeId != Attributes.Value) await console.Output.WriteLineAsync($"Attribute: {Attribute}"); await console.Output.WriteLineAsync($"Value: {ValueFormatter.Format(ValueConverter.ToClrObject(value.WrappedValue))}"); await console.Output.WriteLineAsync($"Status: {value.StatusCode}"); await console.Output.WriteLineAsync($"Source Time: {value.SourceTimestamp.ToString("O")}"); diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSessionAdapter.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSessionAdapter.cs index f086ab4bb..aa9e82589 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSessionAdapter.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSessionAdapter.cs @@ -76,6 +76,14 @@ internal sealed class DefaultSessionAdapter : ISessionAdapter return ValidateReadResult(response.ResponseHeader, response.Results, nodeId); } + /// + public async Task ReadAttributeAsync(NodeId nodeId, uint attributeId, CancellationToken ct) + { + ArrayOf nodes = [new ReadValueId { NodeId = nodeId, AttributeId = attributeId }]; + var response = await _session.ReadAsync(null, 0, TimestampsToReturn.Both, nodes, ct); + return ValidateReadResult(response.ResponseHeader, response.Results, nodeId); + } + internal static DataValue ValidateReadResult(ResponseHeader? header, ArrayOf results, NodeId nodeId) { var serviceStatus = header?.ServiceResult.Code ?? StatusCodes.BadUnexpectedError; diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISessionAdapter.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISessionAdapter.cs index e59ddb9fb..70e6c0b4b 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISessionAdapter.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISessionAdapter.cs @@ -64,6 +64,17 @@ internal interface ISessionAdapter : IDisposable /// Reads a value using the supplied maximum cache age. Task ReadValueAsync(NodeId nodeId, TimeSpan maximumAge, CancellationToken ct = default); + /// + /// Reads one attribute of a node (for example ). A Bad result throws + /// with its status, like . + /// + /// The node to read. + /// The attribute id (). + /// The cancellation token that aborts the read. + /// The attribute's data value. + Task ReadAttributeAsync(NodeId nodeId, uint attributeId, CancellationToken ct = default) => + throw new NotSupportedException("This session adapter does not read node attributes."); + /// /// Writes a typed value to a node on the connected OPC UA server. /// diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs index c19f3210b..02b7aa453 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs @@ -56,6 +56,14 @@ public interface IOpcUaClientService : IDisposable return ReadValueAsync(nodeId, ct); } + /// Reads one attribute of a node (for example ). + /// The node to read. + /// The attribute id (). + /// The cancellation token that aborts the read. + /// The attribute's data value; a Bad result throws . + Task ReadAttributeAsync(NodeId nodeId, uint attributeId, CancellationToken ct = default) => + throw new NotSupportedException("This client does not read node attributes."); + /// /// Writes an operator-supplied value to an OPC UA node after applying client-side type conversion when needed. /// diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/OpcUaClientService.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/OpcUaClientService.cs index 402fdcc1a..026d48030 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/OpcUaClientService.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/OpcUaClientService.cs @@ -223,6 +223,14 @@ public sealed class OpcUaClientService : IOpcUaClientService return await _session!.ReadValueAsync(nodeId, maximumAge, ct); } + /// + public async Task ReadAttributeAsync(NodeId nodeId, uint attributeId, CancellationToken ct = default) + { + ThrowIfDisposed(); + ThrowIfNotConnected(); + return await _session!.ReadAttributeAsync(nodeId, attributeId, ct); + } + /// public async Task WriteValueAsync(NodeId nodeId, object value, CancellationToken ct = default) { diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs index ba7a6bc84..8d1e7b39a 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs @@ -258,8 +258,8 @@ public static class DataProtoMapper v.Dimensions.AddRange(x.Dimensions); if (x.ArrayElementKind is { } elementKind) v.ArrayElementKind = (W.ValueKind)elementKind; - if (x.StableSourceId is not null) - v.StableSourceId = x.StableSourceId; + // #916: field 10 (stable_source_id) is never encoded, whatever the caller set. It carried the origin's internal + // acquisition key (driver instance id + RawPath), and no consumer needs it. if (x.EngineeringUnits is not null) v.EngineeringUnits = x.EngineeringUnits; // H2: the service strips this (and the HistoryRead bit) from every response of a call that did not negotiate history. @@ -288,7 +288,8 @@ public static class DataProtoMapper // A2b method bits are condition grants, never node operations, so a metadata item carrying them is masked too. (DataOperations)(x.AllowedOperations & (uint)DataOperationSets.Understood & ~(uint)DataOperationSets.ConditionGrants), x.CatalogRevision, - x.HasStableSourceId ? x.StableSourceId : null, + // #916: dropped on decode too, so a consumer of a pre-fix origin never retains it in OriginMetadata. + null, x.HasEngineeringUnits ? x.EngineeringUnits : null, x.IsStale, x.HasArrayElementKind ? (DataValueKind)x.ArrayElementKind : null, diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto index 188c4416f..de130c405 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto @@ -161,6 +161,8 @@ message Metadata { bool writable = 7; uint32 allowed_operations = 8; int64 catalog_revision = 9; + // DEPRECATED (#916): never sent and ignored on receipt. It carried the origin's internal acquisition key (driver + // instance id + RawPath). Kept so the field number is never reused. optional string stable_source_id = 10; optional string engineering_units = 11; bool is_stale = 12; diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAlarmInitialStateSignal.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAlarmInitialStateSignal.cs index 00c5af02d..c7f059d06 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAlarmInitialStateSignal.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAlarmInitialStateSignal.cs @@ -34,6 +34,15 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions; /// once with set: the host then applies its /// per-driver-type backstop timer to those conditions instead. No other shipped source should use it. /// +/// +/// Withdrawing (#926). A source that signalled and then LOSES events for those conditions (an OPC UA +/// event-queue overflow, a publish gap) raises the event with +/// set: the host takes "known" back from them (Uncertain on a consumer) until the source signals again or a +/// transition re-establishes one. Same ordering rule: after every alarm event raised before it. Only a source +/// that SIGNALLED withdraws: conditions that became known through the +/// backstop are not withdrawn by a later loss (the OPC UA client has no refresh bracket there, and its loss +/// detection never re-arms the backstop) — that residual is the backstop's own. +/// /// public interface IAlarmInitialStateSignal { @@ -50,11 +59,18 @@ public sealed class AlarmInitialStateEventArgs : EventArgs /// when the source can never signal for these conditions (no refresh upstream); /// the host's backstop timer applies instead of an immediate mark. /// - public AlarmInitialStateEventArgs(IReadOnlyList conditionIds, bool unsignalable = false) + /// + /// (#926) when the source can no longer vouch for these conditions' state (it lost events + /// after establishing them): the host withdraws "known". Exclusive with . + /// + public AlarmInitialStateEventArgs(IReadOnlyList conditionIds, bool unsignalable = false, bool withdrawn = false) { ArgumentNullException.ThrowIfNull(conditionIds); + if (unsignalable && withdrawn) + throw new ArgumentException("A signal is either unsignalable or a withdrawal, not both.", nameof(withdrawn)); ConditionIds = conditionIds; Unsignalable = unsignalable; + Withdrawn = withdrawn; } /// The driver condition ids (= RawPaths) the completed read covers. Never "everything". @@ -65,4 +81,10 @@ public sealed class AlarmInitialStateEventArgs : EventArgs /// so the per-driver-type backstop timer (OpcUaClient only) decides when they become known. /// public bool Unsignalable { get; } + + /// + /// #926: the source lost events for these conditions after establishing them, so their state is no longer + /// known. The host withdraws "known" (never starting a backstop) until the next real signal. + /// + public bool Withdrawn { get; } } diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Authorization/DataOperationPolicy.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Authorization/DataOperationPolicy.cs index 7ef34cb44..9ccdc86d5 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Authorization/DataOperationPolicy.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Authorization/DataOperationPolicy.cs @@ -73,6 +73,29 @@ public sealed class DataOperationPolicy && CredentialUsable(snapshot, caller, false); } + /// + /// #922: would be granted on this mapped subject, judged on + /// everything EXCEPT the remote lease's validity? Used only to classify a refusal of a node whose lease lapsed — a caller + /// this answers false for is refused BadUserAccessDenied exactly as before; one it answers true for gets a retryable + /// status while the lease is renewed. It never authorizes serving anything: every served read still passes + /// against a renewed, valid lease. + /// + public bool AuthorizeMappedSubject(DataCallerIdentity caller, OpcUaOperation operation, DataView requested, + ServingIdentity serving, MappedNamespaceSubject live, MappedSubjectResolver resolver) + { + if (resolver is null || serving is null || caller is null) return false; + var snapshot = _authority.Current; + if (!CatalogIsCurrent(resolver.LocalAuthority, snapshot)) return false; + var resolved = resolver.Resolve(requested, live); + if (resolved.Kind != MappedSubjectResolutionKind.Mapped || resolved.Subject is not { } subject + || subject.Serving != serving || serving.CatalogEpoch <= 0 || serving.AuthorityEpoch <= 0 + || string.IsNullOrWhiteSpace(serving.NodeId) || string.IsNullOrWhiteSpace(serving.Incarnation) + || !AllowsMappedOperation(subject, operation)) return false; + return Authorize(snapshot, caller, operation, subject.Scope, false, subject, false) + && CatalogIsCurrent(resolver.LocalAuthority, snapshot) && ReferenceEquals(snapshot, _authority.Current) + && CredentialUsable(snapshot, caller, false); + } + private static bool CatalogIsCurrent(IDataMappedCatalogAuthority catalog, DataPlaneAuthoritySnapshot snapshot) => catalog.IsActive && catalog.CatalogEpoch > 0 && catalog.AuthorityEpoch == snapshot.GenerationId && snapshot.HasArtifact; diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs index dec26e1d6..b31fa1f75 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs @@ -169,6 +169,14 @@ public sealed class GalaxyDriver // _alarmHandlersLock). A sentinel signals only if it is still the live one — entries delivered before a later // subscription (or while none was live) were not delivered under it. private GalaxyAlarmSubscriptionHandle? _streamOpenedUnder; + // lmxopcua#925: whether the feed's CURRENT stream has delivered its snapshot_complete sentinel (guarded by + // _alarmHandlersLock). A subscription that becomes live after that point gets no sentinel of its own until the + // stream reopens, so it is established by a re-read of the active-alarm set instead. + private bool _streamSnapshotDelivered; + // lmxopcua#925: the active-alarm re-read coalescer — 0 idle, 1 running, 2 running with another run requested. + private int _alarmRefreshState; + // Cancelled (and replaced) by every runtime teardown, so an in-flight re-read or its retry wait stops quietly. + private CancellationTokenSource _alarmRefreshCts = new(); // Production runtime owned by InitializeAsync (BuildProductionRuntimeAsync). The // driver builds these when it opens a real gw session; tests bypass them by @@ -1002,7 +1010,8 @@ public sealed class GalaxyDriver // so they hang off the owned MxGatewayClient, not the worker session. _alarmAcknowledger ??= new GatewayGalaxyAlarmAcknowledger(_ownedMxClient, _logger); _alarmFeed ??= new GatewayGalaxyAlarmFeed( - _ownedMxClient.StreamAlarmsAsync, _logger, _options.MxAccess.ClientName); + _ownedMxClient.StreamAlarmsAsync, _logger, _options.MxAccess.ClientName, + queryFactory: _ownedMxClient.QueryActiveAlarmsAsync); } /// @@ -1092,6 +1101,11 @@ public sealed class GalaxyDriver } if (releaseFeed) _alarmFeed = null; } + // lmxopcua#925: the next feed (or the re-wired injected one) starts with no delivered stream snapshot. + lock (_alarmHandlersLock) _streamSnapshotDelivered = false; + // A re-read in flight (or waiting to retry) belongs to the torn-down runtime. Not disposed: its token may + // still be observed by the unwinding re-read. + Interlocked.Exchange(ref _alarmRefreshCts, new CancellationTokenSource()).Cancel(); if (releaseFeed) { try { await alarmFeed!.DisposeAsync().ConfigureAwait(false); } @@ -2789,6 +2803,14 @@ public sealed class GalaxyDriver } throw; } + + // lmxopcua#925: the feed's stream is already past its sentinel (a re-subscribe on a live stream — a changed + // alarm set, or a reconnect that kept the session-less feed), so no sentinel will ever come for THIS + // subscription until the stream happens to reopen. Re-read the active-alarm set instead. A stream still in its + // snapshot phase is handled at its sentinel (OnAlarmFeedSnapshotDelivered). + bool refresh; + lock (_alarmHandlersLock) refresh = _streamSnapshotDelivered && ReferenceEquals(_alarmSubscriptions.FirstOrDefault(), handle); + if (refresh) RequestAlarmSnapshotRefresh("alarm subscription changed while the feed stream was open"); return Task.FromResult(handle); } @@ -3039,7 +3061,11 @@ public sealed class GalaxyDriver /// A1 review round 2 F4: a feed stream (re)opened — record the subscription its snapshot is delivered under. private void OnAlarmFeedStreamOpened(object? sender, EventArgs e) { - lock (_alarmHandlersLock) _streamOpenedUnder = _alarmSubscriptions.Count > 0 ? _alarmSubscriptions[0] : null; + lock (_alarmHandlersLock) + { + _streamOpenedUnder = _alarmSubscriptions.Count > 0 ? _alarmSubscriptions[0] : null; + _streamSnapshotDelivered = false; + } } /// @@ -3049,18 +3075,143 @@ public sealed class GalaxyDriver private void OnAlarmFeedSnapshotDelivered(object? sender, EventArgs e) { IReadOnlyList refs; + bool deliveredUnderLive; lock (_alarmHandlersLock) { + _streamSnapshotDelivered = true; if (_alarmSubscriptions.Count == 0) return; - // A1 review round 2 F4: only a stream whose whole snapshot was delivered under THIS subscription. - if (!ReferenceEquals(_alarmSubscriptions[0], _streamOpenedUnder)) - { - _logger.LogDebug("GalaxyDriver alarm sentinel for a stream opened under an earlier (or no) subscription — not signalled; the next stream's sentinel will."); - return; - } refs = _alarmSubscriptionRefs; + // A1 review round 2 F4: only a stream whose whole snapshot was delivered under THIS subscription. + deliveredUnderLive = ReferenceEquals(_alarmSubscriptions[0], _streamOpenedUnder); } + if (!deliveredUnderLive) + { + // lmxopcua#925: the subscription changed during the snapshot phase, so this sentinel cannot vouch for it and + // no later sentinel comes until the stream reopens — re-read the active-alarm set instead (when the gateway + // client supports it; otherwise the next stream's sentinel signals, and F5 diagnoses the wait). + _logger.LogDebug("GalaxyDriver alarm sentinel for a stream opened under an earlier (or no) subscription — not signalled; re-reading the active-alarm set."); + RequestAlarmSnapshotRefresh("alarm subscription changed during the feed's snapshot phase"); + return; + } + + if (refs.Count == 0) return; + try + { + InitialAlarmStateDelivered?.Invoke(this, new AlarmInitialStateEventArgs(refs)); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "GalaxyDriver InitialAlarmStateDelivered handler threw — continuing."); + } + } + + /// Delay between attempts of a failed active-alarm re-read (lmxopcua#925) — tests shorten it. + internal TimeSpan AlarmSnapshotRefreshRetryDelay { get; set; } = TimeSpan.FromSeconds(5); + + /// Attempts per active-alarm re-read before it gives up (the next stream sentinel or F5 then takes over). + internal const int AlarmSnapshotRefreshAttempts = 3; + + private static readonly TimeSpan AlarmSnapshotRefreshTimeout = TimeSpan.FromSeconds(30); + + /// + /// lmxopcua#925: schedule a re-read of the gateway's active-alarm set that, once replayed, signals the live + /// subscription's refs as delivered — the gap-free replacement for a snapshot_complete sentinel the + /// open stream will not send again. Coalesced: at most one re-read runs, and requests made while it runs + /// collapse into ONE follow-up run. A no-op when the feed has no query (test fakes, or a feed built without one). + /// + private void RequestAlarmSnapshotRefresh(string reason) + { + IGalaxyAlarmFeed? feed; + lock (_alarmFeedLock) feed = _alarmFeedWired ? _alarmFeed : null; + if (feed is null || !feed.SupportsSnapshotRefresh || _disposed) return; + while (true) + { + switch (Volatile.Read(ref _alarmRefreshState)) + { + case 0: + if (Interlocked.CompareExchange(ref _alarmRefreshState, 1, 0) != 0) continue; + _logger.LogDebug("GalaxyDriver re-reading the active-alarm set: {Reason}", reason); + _ = Task.Run(RunAlarmSnapshotRefreshesAsync); + return; + case 1: + if (Interlocked.CompareExchange(ref _alarmRefreshState, 2, 1) != 1) continue; + return; + default: + return; // a follow-up run is already queued + } + } + } + + private async Task RunAlarmSnapshotRefreshesAsync() + { + while (true) + { + try + { + await RefreshAlarmSnapshotOnceAsync(Volatile.Read(ref _alarmRefreshCts).Token).ConfigureAwait(false); + } + catch (Exception ex) + { + // Logged, then the coalescing step below still runs: a follow-up requested meanwhile is not lost. + _logger.LogWarning(ex, "GalaxyDriver active-alarm re-read failed unexpectedly"); + } + // 1 → 0: nothing was requested meanwhile. 2: run once more for the requests that arrived. + if (Interlocked.CompareExchange(ref _alarmRefreshState, 0, 1) == 1) return; + Volatile.Write(ref _alarmRefreshState, 1); + } + } + + private async Task RefreshAlarmSnapshotOnceAsync(CancellationToken teardown) + { + GalaxyAlarmSubscriptionHandle? under; + IGalaxyAlarmFeed? feed; + lock (_alarmFeedLock) feed = _alarmFeedWired ? _alarmFeed : null; + lock (_alarmHandlersLock) under = _alarmSubscriptions.Count > 0 ? _alarmSubscriptions[0] : null; + if (feed is null || under is null) return; + + for (var attempt = 1; ; attempt++) + { + if (_disposed || teardown.IsCancellationRequested) return; + try + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(teardown); + timeout.CancelAfter(AlarmSnapshotRefreshTimeout); + if (!await feed.RefreshSnapshotAsync(timeout.Token).ConfigureAwait(false)) return; + break; + } + catch (Exception ex) when (ex is ObjectDisposedException || _disposed || teardown.IsCancellationRequested) + { + return; // the feed or the driver is being torn down + } + catch (Grpc.Core.RpcException ex) when (ex.StatusCode == Grpc.Core.StatusCode.Unimplemented) + { + _logger.LogWarning("GalaxyDriver: the gateway does not implement QueryActiveAlarms — alarm conditions of a changed subscription stay unestablished until the feed stream reopens"); + return; + } + catch (Exception ex) when (attempt < AlarmSnapshotRefreshAttempts) + { + _logger.LogWarning("GalaxyDriver active-alarm re-read attempt {Attempt} failed ({Reason}); retrying in {Delay}", + attempt, ex.Message, AlarmSnapshotRefreshRetryDelay); + try { await Task.Delay(AlarmSnapshotRefreshRetryDelay, teardown).ConfigureAwait(false); } + catch (OperationCanceledException) { return; } // torn down while waiting to retry + } + catch (Exception ex) + { + _logger.LogWarning(ex, "GalaxyDriver active-alarm re-read failed after {Attempts} attempts — the subscription's alarm conditions stay unestablished until the feed stream reopens", attempt); + return; + } + } + + // Signal only for the subscription the re-read was made under, through the feed that made it: a subscription + // that replaced it requested its own (coalesced) run; a torn-down feed's replay was never bridged. + IReadOnlyList refs; + lock (_alarmFeedLock) if (!_alarmFeedWired || !ReferenceEquals(_alarmFeed, feed)) return; + lock (_alarmHandlersLock) + { + if (_alarmSubscriptions.Count == 0 || !ReferenceEquals(_alarmSubscriptions[0], under)) return; + refs = _alarmSubscriptionRefs; + } if (refs.Count == 0) return; try { diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GatewayGalaxyAlarmFeed.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GatewayGalaxyAlarmFeed.cs index 010373705..19d48b4d5 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GatewayGalaxyAlarmFeed.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GatewayGalaxyAlarmFeed.cs @@ -43,6 +43,16 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed internal delegate IAsyncEnumerable AlarmStreamFactory( StreamAlarmsRequest request, CancellationToken cancellationToken); + /// + /// Reads the gateway's current active-alarm set (lmxopcua#925). Matches the method group + /// MxGatewayClient.QueryActiveAlarmsAsync. + /// + /// The query request parameters. + /// A cancellation token. + /// The async stream of active-alarm snapshots. + internal delegate IAsyncEnumerable ActiveAlarmQueryFactory( + QueryActiveAlarmsRequest request, CancellationToken cancellationToken); + private static readonly TimeSpan DefaultReconnectDelay = TimeSpan.FromSeconds(5); // Shares the driver meter name so a host-level MeterListener catches feed counters @@ -54,11 +64,35 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed private static readonly Counter AlarmTransitionsDecodingFailures = Meter.CreateCounter("galaxy.alarm_feed.transitions.decoding_failures", unit: "{event}", description: "Alarm feed messages dropped for a missing body or unspecified transition kind."); + private static readonly Counter AlarmSnapshotRefreshes = + Meter.CreateCounter("galaxy.alarm_feed.snapshot_refreshes", unit: "{refresh}", + description: "Active-alarm set re-reads (QueryActiveAlarms) completed while the alarm stream stayed open (lmxopcua#925)."); + private static readonly Counter AlarmSnapshotRefreshEntriesSuperseded = + Meter.CreateCounter("galaxy.alarm_feed.snapshot_refresh.superseded", unit: "{entry}", + description: "Re-read entries not replayed because the live stream delivered a newer message for the same alarm."); private static readonly Counter AlarmFeedReconnects = Meter.CreateCounter("galaxy.alarm_feed.reconnects", unit: "{reconnect}", description: "Times the alarm feed re-opened its StreamAlarms stream after a transport fault."); private readonly AlarmStreamFactory _streamFactory; + private readonly ActiveAlarmQueryFactory? _queryFactory; + + // lmxopcua#925: serialises live dispatch with a re-read's replay, so "did the live stream already deliver a newer + // message for this alarm" and the replay of the re-read entry are one atomic step. + private readonly Lock _dispatchLock = new(); + // The alarms the live stream delivered a message for since the in-flight re-read was issued (null when none is in + // flight), mapped to whether any of them carried the FULL state (snapshot entry, Raise, Retrigger, Clear) — true — + // or only the ack dimension (Acknowledge) — false. Guarded by _dispatchLock. + private Dictionary? _touchedDuringRefresh; + // Review r1 #2: bumped (under _dispatchLock) each time a stream is (re)opened, before any of its messages. A + // re-read replays only if no stream opened since it was issued: an alarm that cleared in a reopen gap is merely + // ABSENT from the new snapshot, so the touched map cannot catch the re-read's stale entry for it. + private long _streamEpoch; + // Whether the current stream has delivered its snapshot_complete sentinel. Guarded by _dispatchLock. A re-read is + // pointless (and could signal mid-snapshot) while it has not: that stream's own sentinel covers the subscription. + private bool _streamSnapshotComplete; + // One re-read at a time (a second one waits for the first). + private readonly SemaphoreSlim _refreshGate = new(1, 1); private readonly ILogger _logger; private readonly string _alarmFilterPrefix; private readonly TimeSpan _reconnectDelay; @@ -86,14 +120,20 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed /// An optional client name for tagging log entries. /// An optional prefix to filter alarms in the stream. /// An optional delay before reconnecting after a stream fault. + /// + /// An optional factory over the gateway's QueryActiveAlarms RPC; when given, + /// re-reads the active-alarm set without reopening the stream (lmxopcua#925). + /// public GatewayGalaxyAlarmFeed( AlarmStreamFactory streamFactory, ILogger? logger = null, string? clientName = null, string? alarmFilterPrefix = null, - TimeSpan? reconnectDelay = null) + TimeSpan? reconnectDelay = null, + ActiveAlarmQueryFactory? queryFactory = null) { _streamFactory = streamFactory ?? throw new ArgumentNullException(nameof(streamFactory)); + _queryFactory = queryFactory; _logger = logger ?? NullLogger.Instance; _alarmFilterPrefix = alarmFilterPrefix ?? string.Empty; _reconnectDelay = reconnectDelay ?? DefaultReconnectDelay; @@ -130,6 +170,12 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed AlarmFilterPrefix = _alarmFilterPrefix, }; + lock (_dispatchLock) + { + _streamEpoch++; + _streamSnapshotComplete = false; + } + // A1 review round 2 F4: before any message of this stream, on this (the dispatch) thread. try { StreamOpened?.Invoke(this, EventArgs.Empty); } catch (Exception ex) { _logger.LogWarning(ex, "Galaxy alarm feed StreamOpened handler threw — continuing."); } @@ -163,19 +209,134 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed } } + /// + public bool SupportsSnapshotRefresh => _queryFactory is not null; + + /// + public async Task RefreshSnapshotAsync(CancellationToken cancellationToken) + { + if (_queryFactory is null || _disposed) return false; + CancellationTokenSource linked; + try { linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _cts.Token); } + catch (ObjectDisposedException) { return false; } // disposed concurrently: not an RPC failure + using var _ = linked; + await _refreshGate.WaitAsync(linked.Token).ConfigureAwait(false); + try + { + // Track BEFORE the query is issued: any live message dispatched from here on may be newer than the + // query's view of that alarm. + var touched = new Dictionary(StringComparer.Ordinal); + long epoch; + lock (_dispatchLock) + { + if (!_streamSnapshotComplete) return false; // the current stream's own sentinel covers it + epoch = _streamEpoch; + _touchedDuringRefresh = touched; + } + try + { + var entries = new List(); + var request = new QueryActiveAlarmsRequest + { + ClientCorrelationId = Guid.NewGuid().ToString("N"), + AlarmFilterPrefix = _alarmFilterPrefix, + }; + await foreach (var entry in _queryFactory(request, linked.Token) + .WithCancellation(linked.Token).ConfigureAwait(false)) + { + entries.Add(entry); + } + + var superseded = 0; + lock (_dispatchLock) + { + linked.Token.ThrowIfCancellationRequested(); + if (_streamEpoch != epoch) + { + // Review r1 #2: a stream (re)opened meanwhile. Its snapshot (and sentinel) is the newer + // statement of every alarm; replaying this older view could resurrect one that cleared in the gap. + _logger.LogDebug("Galaxy alarm feed re-read discarded: the stream reopened while it was in flight."); + return false; + } + foreach (var entry in entries) + { + if (!touched.TryGetValue(entry.AlarmFullReference, out var fullState)) + { + DispatchSnapshotEntry(entry); + } + else if (fullState) + { + superseded++; // a newer full statement of this alarm already reached the host + } + else + { + // Review r1 #1: only acknowledged since the query read it — the entry's ACTIVE state still + // stands, merged with the ack (Active ⇒ ActiveAcked; ActiveAcked / Inactive unchanged). + DispatchSnapshotEntry(entry.CurrentState == AlarmConditionState.Active + ? MergeAcknowledged(entry) + : entry); + } + } + } + + AlarmSnapshotRefreshes.Add(1, _clientTag); + if (superseded > 0) AlarmSnapshotRefreshEntriesSuperseded.Add(superseded, _clientTag); + _logger.LogDebug( + "Galaxy alarm feed re-read the active-alarm set: {Count} entr(ies) replayed, {Superseded} superseded by the live stream.", + entries.Count - superseded, superseded); + return true; + } + finally + { + lock (_dispatchLock) _touchedDuringRefresh = null; + } + } + finally + { + _refreshGate.Release(); + } + } + + private static ActiveAlarmSnapshot MergeAcknowledged(ActiveAlarmSnapshot entry) + { + var merged = entry.Clone(); + merged.CurrentState = AlarmConditionState.ActiveAcked; + return merged; + } + + /// Under : note a live message for an alarm while a re-read is in flight. + private void NoteTouched(string reference, bool fullState) + { + if (_touchedDuringRefresh is not { } touched) return; + touched[reference] = fullState || (touched.TryGetValue(reference, out var prior) && prior); + } + private void Dispatch(AlarmFeedMessage message) + { + lock (_dispatchLock) + { + DispatchLocked(message); + } + } + + private void DispatchLocked(AlarmFeedMessage message) { switch (message.PayloadCase) { case AlarmFeedMessage.PayloadOneofCase.ActiveAlarm: + NoteTouched(message.ActiveAlarm.AlarmFullReference, fullState: true); DispatchSnapshotEntry(message.ActiveAlarm); break; case AlarmFeedMessage.PayloadOneofCase.Transition: + // An Acknowledge carries only the ack dimension; every other kind restates the active state too. + NoteTouched(message.Transition.AlarmFullReference, + fullState: message.Transition.TransitionKind != AlarmTransitionKind.Acknowledge); DispatchTransition(message.Transition); break; case AlarmFeedMessage.PayloadOneofCase.SnapshotComplete: _logger.LogDebug("Galaxy alarm feed active-alarm snapshot complete."); _initialSnapshot.TrySetResult(); + _streamSnapshotComplete = true; // before the signal, whose handler may request a re-read // grpc-data A1: the ordered per-sentinel signal — on THIS thread, after the snapshot entries above // were raised; every reopened stream's sentinel raises it again. RaiseSnapshotDelivered(); @@ -318,5 +479,6 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed try { await _loop.ConfigureAwait(false); } catch { /* shutdown */ } } _cts.Dispose(); + // _refreshGate is deliberately not disposed: a re-read unwinding from the cancellation above still releases it. } } diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/IGalaxyAlarmFeed.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/IGalaxyAlarmFeed.cs index b651cbbb6..a97fdccab 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/IGalaxyAlarmFeed.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/IGalaxyAlarmFeed.cs @@ -53,4 +53,26 @@ internal interface IGalaxyAlarmFeed : IAsyncDisposable /// sentinel signals only if that subscription is still the live one. The default accessors make it a no-op. /// event EventHandler? StreamOpened { add { } remove { } } + + /// + /// True when can re-read the gateway's active-alarm set without reopening + /// the stream (lmxopcua#925). The default is false, for feeds with no query (the test fakes). + /// + bool SupportsSnapshotRefresh => false; + + /// + /// lmxopcua#925: re-read the gateway's current active-alarm set (QueryActiveAlarms, the same monitor + /// cache the stream's opening snapshot comes from) and raise each entry on as a + /// restatement, exactly like a snapshot entry, while the live stream stays open. An entry is skipped when the + /// live stream delivered a full-state message (snapshot entry, Raise, Retrigger, Clear) for the same alarm after + /// the query was issued: that message is at least as new as the query's view, and replaying the older view after + /// it would be a phantom transition. An Acknowledge alone is merged instead (an Active entry replays as + /// ActiveAcked). Completes true once every entry was raised; false — nothing replayed — when the feed has no + /// query, is disposed, the current stream has not delivered its sentinel yet, or a stream (re)opened while the + /// query was in flight (that stream's own sentinel then covers the subscription). Throws on an RPC failure. + /// Raises no signal itself — the caller decides which subscription the re-read establishes. + /// + /// A cancellation token. + /// True when the set was re-read and its entries raised. + Task RefreshSnapshotAsync(CancellationToken cancellationToken) => Task.FromResult(false); } diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDiagnostics.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDiagnostics.cs index 7ac3da945..3059f720c 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDiagnostics.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDiagnostics.cs @@ -26,6 +26,10 @@ internal sealed class OpcUaClientDiagnostics public const string KeepAliveRecovered = "keepalive_recovered"; /// A late replayed notification (source time at or below the ref's high-water mark) was dropped inside the post-recovery replay window. public const string StaleNotificationDropped = "stale_notification_dropped"; + /// #926: the upstream reported an EventQueueOverflowEventType on an alarm event item (events lost). + public const string AlarmEventQueueOverflow = "alarm_event_queue_overflow"; + /// #926: a RefreshEnd was NOT taken as "initial alarm state delivered" because its replay was lossy. + public const string AlarmRefreshLossy = "alarm_refresh_lossy"; private readonly string _driverInstanceId; diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriver.cs index 0c5ba3f50..fe9d23324 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriver.cs @@ -268,6 +268,15 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit ReportRefreshUnsignalable(ras.Subscription); } + /// Test-only seam (#926): a ConditionRefresh call of 's subscription failed, as the + /// refresh catch reports it. + /// The alarm subscription handle. + internal void ReportRefreshFailedForTest(IAlarmSubscriptionHandle handle) + { + if (handle is OpcUaAlarmSubscriptionHandle h && _alarmSubscriptions.TryGetValue(h.Id, out var ras)) + NoteConditionRefreshFailed(ras.Subscription); + } + /// /// Test-only seam to install the that connect builds at /// runtime, so the v3 RawPath → upstream node id resolution can be exercised without a live @@ -1365,7 +1374,10 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit foreach (var key in _alarmSubscriptions.Keys) { - if (!_alarmSubscriptions.TryRemove(key, out var ras)) continue; + RemoteAlarmSubscription? ras; + // #926 review r2: removed under the emission lock, so no signal / withdrawal is mid-flight for it. + lock (_alarmStateLock) + if (!_alarmSubscriptions.TryRemove(key, out ras)) continue; try { ras.EventItem.Notification -= ras.Handler; } catch { /* best-effort */ } if (sessionAlive) deletes.Add(DeleteSubscriptionBestEffortAsync(ras.Subscription, budget.Token)); @@ -2434,6 +2446,16 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit private const int AlarmFieldAckedState = 8; private const int AlarmFieldBranchId = 9; + /// #926: the requested queue size of the alarm event item (was 1000). See its use. + internal const uint AlarmEventQueueSize = 10_000; + + /// #926 test seam (the live overflow gate shrinks it): the queue size the alarm event item requests. + internal uint AlarmEventItemQueueSize { get; set; } = AlarmEventQueueSize; + + /// #926 test seam (the live gate flips it to make a lossy replay KEEP its RefreshEnd): the alarm event + /// item's DiscardOldest. Production: false (the newest events are dropped on overflow). + internal bool AlarmEventItemDiscardOldest { get; set; } + /// public async Task SubscribeAlarmsAsync( IReadOnlyList sourceNodeIds, CancellationToken cancellationToken) @@ -2574,8 +2596,12 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit StartNodeId = ObjectIds.Server, AttributeId = Attributes.EventNotifier, MonitoringMode = MonitoringMode.Reporting, - QueueSize = 1000, // deep queue — a server can fire many alarms in bursts - DiscardOldest = false, + // #926: deep queue — a ConditionRefresh replays EVERY retained upstream condition in one burst, and a + // server can fire many alarms at once. An overflow is still detected (EventQueueOverflowEventType ⇒ the + // refresh's RefreshEnd does not signal and it is re-run); the depth only makes it rarer. The server + // may revise it down (logged with the retry budget's exhaustion). + QueueSize = AlarmEventItemQueueSize, + DiscardOldest = AlarmEventItemDiscardOldest, Filter = filter, }) { @@ -2623,7 +2649,10 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit public async Task UnsubscribeAlarmsAsync(IAlarmSubscriptionHandle handle, CancellationToken cancellationToken) { if (handle is not OpcUaAlarmSubscriptionHandle h) return; - if (!_alarmSubscriptions.TryRemove(h.Id, out var rs)) return; + RemoteAlarmSubscription? rs; + // #926 review r2: removed under the emission lock, so no signal / withdrawal is mid-flight for it. + lock (_alarmStateLock) + if (!_alarmSubscriptions.TryRemove(h.Id, out rs)) return; var emptied = NoteSubscriptionDeleted(); await _subscriptionGate.WaitAsync(cancellationToken).ConfigureAwait(false); @@ -2790,6 +2819,21 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit // without this it would feed RouteAlarmEvent alongside the real one. if (!_alarmSubscriptions.ContainsKey(handle.Id)) return; RecordLivenessEvidence(); + RouteAlarmEventFieldList(efl, sourceFilter, handle); + } + + /// + /// Route one delivered event: first #926's publish-sequence check (a gap inside a refresh bracket makes it + /// lossy — checked BEFORE the event, so a RefreshEnd in the first message after the gap is already suppressed), + /// then . + /// + /// The delivered event (the SDK sets Message to its notification message). + /// The subscription's upstream-key → RawPath index. + /// The subscription handle. + internal void RouteAlarmEventFieldList( + EventFieldList efl, IReadOnlyDictionary sourceFilter, IAlarmSubscriptionHandle handle) + { + NoteAlarmMessageSequence(handle, efl.Message?.SequenceNumber ?? 0); RouteAlarmEvent(efl.EventFields.ToList(), sourceFilter, handle); } @@ -2826,25 +2870,10 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit internal void RouteAlarmEvent( IReadOnlyList fields, IReadOnlyDictionary sourceFilter, IAlarmSubscriptionHandle handle) { - if (IsRefreshRequired(fields)) + if (fields.Count > AlarmFieldEventType && UpstreamValueMapping.ToClr(fields[AlarmFieldEventType]) is NodeId markerType + && IsBracketEventType(markerType)) { - // Part 9 §5.11.7: the server lost events (queue overflow / restart) and asks for a refresh. - // r2 R2-1: bound to the session's work token, which a shutdown cancels first thing. - var sessionWork = _sessionWorkCts.Token; - _ = Task.Run(() => RefreshAllAlarmSubscriptionsAsync(sessionWork)); - return; - } - - if (IsRefreshEnd(fields)) - { - // grpc-data A1 (F1): the refresh replay this subscription requested is complete and every refreshed event - // before it was routed (sequential publishing, G2). Under the emission lock, so the signal is ordered - // behind every emission. Covers the subscription's alarm RawPaths. - lock (_alarmStateLock) - { - if (handle is OpcUaAlarmSubscriptionHandle h && _alarmSubscriptions.TryGetValue(h.Id, out var ras)) - RaiseInitialAlarmState(ras.AlarmRefs, unsignalable: false); - } + RouteBracketEvent(markerType, handle); return; } @@ -2893,6 +2922,346 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit /// Exact severity last told (null before any event). private readonly record struct AlarmToldState(bool Active, bool Acked, string? Message, int? Severity); + /// #926: the event types that drive the refresh bracket (never alarms): the three ConditionRefresh + /// markers and the server's EventQueueOverflowEventType. + /// The event's EventType. + /// Whether it is a bracket event. + private static bool IsBracketEventType(NodeId t) => + t == ObjectTypeIds.RefreshStartEventType || t == ObjectTypeIds.RefreshEndEventType + || t == ObjectTypeIds.RefreshRequiredEventType || t == ObjectTypeIds.EventQueueOverflowEventType; + + /// + /// #926 — route one bracket event. Matched by EventType BEFORE any source filtering: an + /// EventQueueOverflowEventType (Part 4) and the refresh markers come from the Server object, never + /// from an authored condition source, so the projector's source filter would drop them. + /// + /// RefreshStart opens a bracket and clears the loss record — unless a bracket is still open (its + /// RefreshEnd never arrived): an overlapping start is itself a loss, kept. + /// EventQueueOverflow is a definite loss: the bracket's RefreshEnd will not signal, and a bounded driver + /// re-refresh is requested (also outside a bracket — a lost live transition is repaired by a replay). + /// RefreshRequired is a loss too; it keeps its existing (coalesced) sweep, which IS the re-refresh. + /// RefreshEnd signals (grpc-data A1) only for a bracket that was opened and saw no loss; otherwise it + /// stays silent — the conditions stay unknown (Uncertain), the safe invariant — and requests the + /// re-refresh if none was yet. + /// + /// Any loss after the subscription signalled also WITHDRAWS "known" from its conditions (see + /// ). + /// + /// The bracket event's EventType. + /// The subscription the event arrived on. + private void RouteBracketEvent(NodeId type, IAlarmSubscriptionHandle handle) + { + RemoteAlarmSubscription? ras = null; + if (handle is OpcUaAlarmSubscriptionHandle h) _alarmSubscriptions.TryGetValue(h.Id, out ras); + + if (type == ObjectTypeIds.RefreshRequiredEventType) + { + if (ras is not null) + lock (_alarmStateLock) + { + // The sweep below re-refreshes this subscription, so no driver retry is requested for it. + NoteBracketLoss(ras, "RefreshRequired", requestRetry: false); + ras.Bracket.RetryRequestedSinceStart = true; + } + RequestRefreshRequiredSweep(); + return; + } + + if (ras is null) return; // a released / stray subscription: no bracket, no signal (G5) + lock (_alarmStateLock) + { + var b = ras.Bracket; + if (type == ObjectTypeIds.RefreshStartEventType) + { + if (b.Open) + { + // The previous bracket's RefreshEnd never arrived (or brackets overlap): that is a loss, and it must + // not be erased by this start. + NoteBracketLoss(ras, "overlapping RefreshStart (the previous RefreshEnd never arrived)", requestRetry: false); + } + else + { + b.LossSinceStart = null; + b.RetryRequestedSinceStart = false; + } + b.Open = true; + } + else if (type == ObjectTypeIds.EventQueueOverflowEventType) + { + _diag.Record(OpcUaClientDiagnostics.AlarmEventQueueOverflow); + NoteBracketLoss(ras, "EventQueueOverflow (the upstream discarded events of this subscription)", + requestRetry: true); + } + else if (type == ObjectTypeIds.RefreshEndEventType) + { + var opened = b.Open; + b.Open = false; + if (opened && b.LossSinceStart is null) + { + // #926 review r2: re-checked UNDER the lock (the lookup above ran outside it, and an unsubscribe + // removes the record under this lock): a released subscription never signals. + if (!IsRegisteredLocked(ras)) return; + // grpc-data A1 (F1): the refresh replay this subscription requested is complete, lossless, and every + // refreshed event before it was routed (sequential publishing, G2). Under the emission lock, so the + // signal is ordered behind every emission. Covers the subscription's alarm RawPaths. Ends the + // lossy episode: the next loss gets a fresh budget. + b.Retries = 0; + b.ExhaustedLogged = false; + b.Signalled = true; + RaiseInitialAlarmState(ras.AlarmRefs, unsignalable: false); + return; + } + + var reason = b.LossSinceStart ?? "RefreshEnd without its RefreshStart (the bracket start was lost)"; + _diag.Record(OpcUaClientDiagnostics.AlarmRefreshLossy); + _logger.LogWarning( + "OpcUaClientDriver '{DriverInstanceId}': RefreshEnd on alarm subscription {SubscriptionId} NOT taken " + + "as 'initial alarm state delivered' — {Reason}; its conditions stay unknown until a lossless refresh.", + _driverInstanceId, ras.Handle.DiagnosticId, reason); + WithdrawKnownLocked(ras, reason); + if (!b.RetryRequestedSinceStart) + b.RetryRequestedSinceStart = ScheduleAlarmRefreshRetryLocked(ras, reason); + } + } + } + + /// + /// #926: record a loss against 's bracket, withdraw "known" if the subscription had + /// signalled (an event lost AFTER the conditions were declared known — a live Raise in an overflowed queue or a + /// skipped publish message — would otherwise leave a consumer holding a known-inactive condition that is active + /// upstream), and (once per bracket) request a bounded re-refresh. Caller holds _alarmStateLock. + /// + /// The alarm subscription. + /// What was lost (logged). + /// Whether the driver itself should re-run ConditionRefresh. + private void NoteBracketLoss(RemoteAlarmSubscription ras, string reason, bool requestRetry) + { + var b = ras.Bracket; + b.LossSinceStart ??= reason; + WithdrawKnownLocked(ras, reason); + if (!requestRetry || b.RetryRequestedSinceStart) return; + // Only a retry actually scheduled (or already pending) covers this bracket's loss; a spent budget leaves the + // request open, so a loss after the cool-down can still start one. + b.RetryRequestedSinceStart = ScheduleAlarmRefreshRetryLocked(ras, reason); + } + + /// #926: if signalled since its last loss, tell the host its conditions are no longer + /// known () — ordered after every alarm event already raised, as the + /// signal is. A later clean RefreshEnd signals them known again. Caller holds _alarmStateLock. + /// The alarm subscription. + /// Why (logged). + private void WithdrawKnownLocked(RemoteAlarmSubscription ras, string reason) + { + if (!ras.Bracket.Signalled) return; + ras.Bracket.Signalled = false; + // #926 review r2: a stale record (unsubscribed after the caller's lookup, still Signalled) must not withdraw + // refs that may now belong to a NEW subscription. Checked under the lock the unsubscribe removes it under. + if (!IsRegisteredLocked(ras)) return; + _logger.LogWarning( + "OpcUaClientDriver '{DriverInstanceId}': alarm subscription {SubscriptionId} lost events after its conditions " + + "were declared known ({Reason}); withdrawing 'known' until a lossless ConditionRefresh.", + _driverInstanceId, ras.Handle.DiagnosticId, reason); + RaiseInitialAlarmState(ras.AlarmRefs, unsignalable: false, withdrawn: true); + } + + /// #926 review r2: is still the registered subscription for its handle. Caller holds + /// _alarmStateLock; removals take it too, so the answer holds for the rest of the critical section. + /// The alarm subscription record. + /// Whether it is the live registration. + private bool IsRegisteredLocked(RemoteAlarmSubscription ras) => + _alarmSubscriptions.TryGetValue(ras.Handle.Id, out var current) && ReferenceEquals(current, ras); + + /// + /// #926: the publish-sequence check of alarm subscription . The alarm subscription holds + /// exactly one (event) monitored item, so every data-bearing notification message it receives carries its + /// events and consumes one sequence number (keep-alives consume none). With SequentialPublishing the SDK + /// delivers messages in order and waits for a missing one (republish); if the republish fails it SKIPS the gap + /// and delivers the next message. That skip is reported to nothing the driver can observe — SDK 2.0.1 raises its + /// PublishStateChangedMask.Republish only in a message-worker pass that also delivers a message, which a + /// gap holding every later message prevents (pinned by the real-SDK test). So the driver compares sequence + /// numbers itself: a newer message that is not the successor of the previous one means messages were lost — + /// inside a bracket the replay is lossy, outside it a live transition may be lost; either way it is a loss + /// (withdraw if signalled + bounded re-refresh). An OLDER (or repeated) number is ignored and not recorded, so a + /// stray late message cannot make the next in-order one read as a second gap. A StatusChange-only message + /// (transfer / timeout) also consumes a number and reads as a gap: a bounded extra refresh, never a wrong signal. + /// + /// The alarm subscription handle. + /// The delivered message's sequence number (0 = unknown, ignored). + internal void NoteAlarmMessageSequence(IAlarmSubscriptionHandle handle, uint sequenceNumber) + { + if (sequenceNumber == 0) return; + if (handle is not OpcUaAlarmSubscriptionHandle h || !_alarmSubscriptions.TryGetValue(h.Id, out var ras)) return; + lock (_alarmStateLock) + { + var b = ras.Bracket; + var last = b.LastSequenceNumber; + if (last == 0) { b.LastSequenceNumber = sequenceNumber; return; } + // Wrap-aware "newer" (RFC 1982-style, as the SDK compares): forward distance in (0, 2^31). Sequence numbers + // skip 0 on the wrap (… uint.MaxValue, 1 …), so the successor of uint.MaxValue is 1. + var forward = unchecked(sequenceNumber - last); + if (forward == 0 || forward >= 0x8000_0000u) return; // repeat or older: ignore, do not record + b.LastSequenceNumber = sequenceNumber; + var next = last == uint.MaxValue ? 1u : last + 1; + if (sequenceNumber == next) return; + NoteBracketLoss(ras, + $"publish message(s) lost (sequence {last} → {sequenceNumber}){(b.Open ? " during a refresh replay" : "")}", + requestRetry: true); + } + } + + /// #926: the bounded number of driver-initiated re-refreshes per lossy episode (an episode ends with a clean + /// RefreshEnd). When spent, the conditions stay unknown (Uncertain) and the host's + /// ConditionKnownSignalTimeout diagnostic reports them — never known-inactive. After + /// without a retry, a further loss starts a new budget, so a structurally + /// lossy upstream is retried at most times per cool-down — no storm, and no + /// permanent give-up either. + internal const int MaxAlarmRefreshRetries = 3; + + /// #926: the first re-refresh delay; each further retry doubles it (2 s, 4 s, 8 s), giving the + /// upstream time to drain whatever overflowed. Test seam. + internal TimeSpan AlarmRefreshRetryBaseDelay { get; set; } = TimeSpan.FromSeconds(2); + + /// #926: after the budget is spent, how long since the last retry before a new loss gets a new budget. + /// Test seam. + internal TimeSpan AlarmRefreshRetryCooldown { get; set; } = TimeSpan.FromMinutes(5); + + /// #926 test seam: replaces the ConditionRefresh call of a driver re-refresh. + internal Func? AlarmRefreshRetryInvokerForTest { get; set; } + + /// #926: schedule one bounded re-refresh of (coalesced while one is pending). + /// Caller holds _alarmStateLock. + /// The alarm subscription. + /// Why (logged). + /// Whether a retry is now pending (scheduled here or already) — false when the budget is spent. + private bool ScheduleAlarmRefreshRetryLocked(RemoteAlarmSubscription ras, string reason) + { + var b = ras.Bracket; + if (b.RetryPending) return true; + var now = Clock.GetUtcNow().UtcDateTime; + if (b.Retries >= MaxAlarmRefreshRetries && b.LastRetryUtc is { } lastRetry && now - lastRetry >= AlarmRefreshRetryCooldown) + { + b.Retries = 0; // a new episode after the cool-down + b.ExhaustedLogged = false; + } + if (b.Retries >= MaxAlarmRefreshRetries) + { + if (!b.ExhaustedLogged) + { + b.ExhaustedLogged = true; + _logger.LogWarning( + "OpcUaClientDriver '{DriverInstanceId}': alarm subscription {SubscriptionId} lost refresh events " + + "{Retries} time(s) in a row ({Reason}); no further re-refresh for {Cooldown}. Its conditions stay " + + "unknown (Uncertain) until a lossless ConditionRefresh (RefreshRequired, reconnect, resubscribe, or a " + + "loss after the cool-down). The event item's revised queue size is {QueueSize}.", + _driverInstanceId, ras.Handle.DiagnosticId, b.Retries, reason, AlarmRefreshRetryCooldown, + ras.EventItem.Status?.QueueSize); + } + return false; + } + b.Retries++; + b.RetryPending = true; + b.LastRetryUtc = now; + var generation = ++b.RetryGeneration; + var delay = AlarmRefreshRetryBaseDelay * (1 << (b.Retries - 1)); + _logger.LogWarning( + "OpcUaClientDriver '{DriverInstanceId}': alarm subscription {SubscriptionId}: {Reason}; re-running " + + "ConditionRefresh in {Delay} (attempt {Attempt}/{Max}).", + _driverInstanceId, ras.Handle.DiagnosticId, reason, delay, b.Retries, MaxAlarmRefreshRetries); + var sessionWork = _sessionWorkCts.Token; + _ = Task.Run(() => RetryAlarmRefreshAsync(ras, generation, delay, sessionWork)); + return true; + } + + /// #926: after , re-run ConditionRefresh on — only while it + /// is still the registered subscription for its handle (an unsubscribe / re-init releases it). + /// The alarm subscription. + /// This retry's generation: only it may clear RetryPending. + /// The back-off. + /// The session's work token (cancelled by shutdown / re-init). + /// A task completing when the refresh call returned (or was skipped). + private async Task RetryAlarmRefreshAsync( + RemoteAlarmSubscription ras, long generation, TimeSpan delay, CancellationToken cancellationToken) + { + var gateHeld = false; + try + { + if (delay > TimeSpan.Zero) await Task.Delay(delay, Clock, cancellationToken).ConfigureAwait(false); + await _subscriptionGate.WaitAsync(cancellationToken).ConfigureAwait(false); + gateHeld = true; + if (!_alarmSubscriptions.TryGetValue(ras.Handle.Id, out var current) || !ReferenceEquals(current, ras)) return; + // From here a further loss may request the next retry: it belongs to THIS refresh's replay. That matters + // when the replay's own RefreshStart is lost too (queue still full) — without the reset, no bracket opens + // and nothing could request again. A lossy RefreshEnd of the PREVIOUS replay still in flight can then + // request one extra refresh; that is inside the bound. + ReleaseRetryPending(ras, generation, resetRequested: true); + if (AlarmRefreshRetryInvokerForTest is { } invoke) + await invoke(ras.Subscription, cancellationToken).ConfigureAwait(false); + else if (ras.Subscription.Session is not null && ras.Subscription.Created) + await TryConditionRefreshAsync(ras.Subscription, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) { /* shutdown / re-init: the subscription is being released */ } + catch (ObjectDisposedException) { /* driver disposed */ } + catch (Exception ex) + { + _logger.LogWarning(ex, "OpcUaClientDriver '{DriverInstanceId}': alarm re-refresh of {SubscriptionId} failed; " + + "its conditions stay unknown until a later lossless ConditionRefresh.", + _driverInstanceId, ras.Handle.DiagnosticId); + } + finally + { + // Only THIS retry's pending flag: a retry scheduled while the refresh call ran (a new generation) stands. + ReleaseRetryPending(ras, generation, resetRequested: false); + if (gateHeld) + { + try { _subscriptionGate.Release(); } catch (ObjectDisposedException) { } + } + } + } + + /// #926: clear RetryPending if it still belongs to retry . + /// The alarm subscription. + /// The retry's generation. + /// Also re-allow a retry request for the current bracket. + private void ReleaseRetryPending(RemoteAlarmSubscription ras, long generation, bool resetRequested) + { + lock (_alarmStateLock) + { + if (ras.Bracket.RetryGeneration != generation) return; + ras.Bracket.RetryPending = false; + if (resetRequested) ras.Bracket.RetryRequestedSinceStart = false; + } + } + + /// #926: a ConditionRefresh call on failed (not "unsupported"): no + /// RefreshEnd will come for it, so request a bounded re-refresh instead of waiting for the next external trigger. + /// The SDK alarm subscription. + private void NoteConditionRefreshFailed(Subscription subscription) + { + foreach (var ras in _alarmSubscriptions.Values) + { + if (!ReferenceEquals(ras.Subscription, subscription)) continue; + lock (_alarmStateLock) _ = ScheduleAlarmRefreshRetryLocked(ras, "ConditionRefresh call failed"); + } + } + + /// 1 while a RefreshRequired-triggered sweep is queued and has not started (coalescing). + private int _refreshRequiredSweepQueued; + + /// + /// #926 (review r1 #7): a RefreshRequired asks for a refresh of every alarm subscription. Coalesced: while one + /// sweep is queued and not yet started, further RefreshRequired events add nothing (that sweep covers them). A + /// RefreshRequired arriving once the sweep has started queues the next one — it may report a later loss. + /// + private void RequestRefreshRequiredSweep() + { + if (Interlocked.CompareExchange(ref _refreshRequiredSweepQueued, 1, 0) != 0) return; + // Part 9 §5.11.7: the server lost events (queue overflow / restart) and asks for a refresh. + // r2 R2-1: bound to the session's work token, which a shutdown cancels first thing. + var sessionWork = _sessionWorkCts.Token; + _ = Task.Run(() => RefreshAllAlarmSubscriptionsAsync(sessionWork, + onStart: () => Interlocked.Exchange(ref _refreshRequiredSweepQueued, 0))); + } + /// True for a RefreshRequiredEventType event (the server asks the client to ConditionRefresh). /// The event's fields. /// Whether the event is a RefreshRequired marker. @@ -2907,12 +3276,12 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit fields.Count > AlarmFieldEventType && UpstreamValueMapping.ToClr(fields[AlarmFieldEventType]) is NodeId t && t == ObjectTypeIds.RefreshEndEventType; - private void RaiseInitialAlarmState(IReadOnlyList refs, bool unsignalable) + private void RaiseInitialAlarmState(IReadOnlyList refs, bool unsignalable, bool withdrawn = false) { if (refs.Count == 0) return; try { - InitialAlarmStateDelivered?.Invoke(this, new AlarmInitialStateEventArgs(refs, unsignalable)); + InitialAlarmStateDelivered?.Invoke(this, new AlarmInitialStateEventArgs(refs, unsignalable, withdrawn)); } catch (Exception ex) { @@ -2967,6 +3336,8 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit "OpcUaClientDriver '{DriverInstanceId}': ConditionRefresh on alarm subscription {SubscriptionId} failed; " + "conditions already active upstream may not be reported until their next transition.", _driverInstanceId, subscription.Id); + // #926 (review r1 #4): no RefreshEnd will come for this call — retry it, bounded. + NoteConditionRefreshFailed(subscription); } catch (OperationCanceledException) { @@ -2992,9 +3363,11 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit /// outage reach the host through the normal deduplicated path. /// /// Cancellation. + /// Invoked first thing (the RefreshRequired coalescing flag's release). /// A task completing when every refresh call has returned. - private async Task RefreshAllAlarmSubscriptionsAsync(CancellationToken cancellationToken) + private async Task RefreshAllAlarmSubscriptionsAsync(CancellationToken cancellationToken, Action? onStart = null) { + onStart?.Invoke(); if (_alarmSubscriptions.IsEmpty) return; try { @@ -3146,6 +3519,9 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit if (fields.Count <= AlarmFieldConditionId) return null; // ConditionRefresh brackets its re-delivery with RefreshStart/RefreshEnd — markers, never alarms. if (IsRefreshMarker(UpstreamValueMapping.ToClr(fields[AlarmFieldEventType]))) return null; + // #926: the server's queue-overflow notice is not an alarm either (pass-through would otherwise project it). + if (UpstreamValueMapping.ToClr(fields[AlarmFieldEventType]) is NodeId et && et == ObjectTypeIds.EventQueueOverflowEventType) + return null; // A condition BRANCH event reports a previous state with its own EventId: projecting it would flip the // trunk's state, remembering it would make Acknowledge ack the branch. if (fields.Count > AlarmFieldBranchId && UpstreamValueMapping.ToClr(fields[AlarmFieldBranchId]) is NodeId branch && !branch.IsNull) @@ -3238,7 +3614,54 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit OpcUaAlarmSubscriptionHandle Handle, MonitoredItem EventItem, MonitoredItemNotificationEventHandler Handler, - IReadOnlyList AlarmRefs); + IReadOnlyList AlarmRefs) + { + /// #926: this subscription's ConditionRefresh bracket + bounded re-refresh state. Mutated only + /// under _alarmStateLock. + public AlarmRefreshBracket Bracket { get; } = new(); + } + + /// + /// #926 — the RefreshStart…RefreshEnd bracket of one alarm subscription. A RefreshEnd declares the conditions it + /// covers state-known (grpc-data A1), so it may only signal when the replay it closes is provably complete: its + /// RefreshStart was seen and no loss (EventQueueOverflow, RefreshRequired, a publish-sequence gap) was + /// observed since. Every field is read and written under _alarmStateLock. + /// + internal sealed class AlarmRefreshBracket + { + /// A RefreshStart was routed and its RefreshEnd not yet. + public bool Open; + + /// The first loss observed since the last RefreshStart (null = none). A RefreshEnd with a loss + /// does not signal. + public string? LossSinceStart; + + /// A re-refresh was already requested for the loss since the last RefreshStart or the last re-refresh's + /// start (so the lossy RefreshEnd that follows does not request a second one). + public bool RetryRequestedSinceStart; + + /// A driver re-refresh is scheduled and has not started its ConditionRefresh call yet. + public bool RetryPending; + + /// Driver re-refreshes spent since the last clean (signalled) RefreshEnd. + public int Retries; + + /// The retry budget is spent and that was logged (once per episode). + public bool ExhaustedLogged; + + /// Sequence number of the last delivered notification message (0 = none yet). + public uint LastSequenceNumber; + + /// This subscription's conditions were declared known (a clean RefreshEnd) and no loss since: a loss + /// now must withdraw "known". + public bool Signalled; + + /// When the last driver re-refresh was scheduled (cool-down of a spent budget). + public DateTime? LastRetryUtc; + + /// Generation of the last scheduled re-refresh; only that retry may clear . + public long RetryGeneration; + } private sealed record OpcUaAlarmSubscriptionHandle(long Id) : IAlarmSubscriptionHandle { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/DeferredProjectedNodeAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/DeferredProjectedNodeAccess.cs index 2e70f49c2..8c5307e08 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/DeferredProjectedNodeAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/DeferredProjectedNodeAccess.cs @@ -11,6 +11,11 @@ public sealed class DeferredProjectedNodeAccess(DeferredAddressSpaceSink deferre definition = null; return deferred.GetCapability()?.TryResolve(nodeId, out definition) == true; } + public bool TryResolveForRenewal(NodeId nodeId, out ProjectedVariableDefinition? definition) + { + definition = null; + return deferred.GetCapability()?.TryResolveForRenewal(nodeId, out definition) == true; + } public bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId) { nodeId = null; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedDataAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedDataAccess.cs index ca5b55177..6714f4446 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedDataAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedDataAccess.cs @@ -18,6 +18,20 @@ public interface IProjectedDemandLease : IDisposable bool IsValid { get; } } +/// +/// #922: how a refused of a projected node is classified. A lapsed metadata +/// lease is NOT an authorization failure: only is answered BadUserAccessDenied. +/// +public enum ProjectedLapseOutcome +{ + /// Not a lapse the caller may wait out (no grant, not a lapse at all, or a revoked authority). + Denied, + /// The caller is granted the subject; its lapsed lease is being renewed (the task completes with the outcome). + Renewing, + /// The caller is granted the subject, but no renewal can run right now (capacity, a recent failure): retry later. + Unavailable, +} + /// Nonblocking local admission and bounded scheduling for projected data. public interface IProjectedDataAccess { @@ -30,6 +44,17 @@ public interface IProjectedDataAccess bool StartSubscription(IProjectedDemandLease demand, TimeSpan publishingInterval); /// Requests a coalesced fresh authenticated snapshot without changing caller ownership. bool RequestFreshSnapshot(IProjectedDemandLease demand) => false; + /// + /// #922: classifies a refused acquire of for (Read or HistoryRead) and, + /// when the only reason is a lapsed lease the caller would otherwise be granted, starts (or joins) ONE bounded asynchronous + /// exact renewal. Nonblocking and lock-free with respect to the caller: never call it, or wait on the task, under the + /// node-manager Lock — the renewal commits through the SDK sink, which takes it. + /// + ProjectedLapseOutcome RenewLapsed(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out Task? renewal) + { + renewal = null; + return ProjectedLapseOutcome.Denied; + } /// True while a demand or physically retained operation still owns this projection. bool HasLiveDemand(DataRealm realm, string localIdentifier) => true; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedNodeLookup.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedNodeLookup.cs index 844a59658..adfcbb454 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedNodeLookup.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedNodeLookup.cs @@ -13,6 +13,12 @@ public interface IProjectedNodeLookup { bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition); bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId); + /// + /// #922: the committed, still-live definition of a projected node WHETHER OR NOT its authority is current — used only to + /// renew a lapsed lease in place (the renewal re-proves authority at the origin and commits against this exact definition). + /// Confers nothing; never use it to serve. + /// + bool TryResolveForRenewal(NodeId nodeId, out ProjectedVariableDefinition? definition) { definition = null; return false; } } /// Installs and retires locally authorized mapping anchors. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index b516a2d3b..0bcfab13b 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -4428,6 +4428,23 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage return false; } + /// + /// #922: like but WITHOUT the authority check, so a node whose metadata lease lapsed can be renewed + /// in place. Lock-free (committed snapshot), confers nothing. + /// + public bool TryResolveForRenewal(NodeId nodeId, out ProjectedVariableDefinition? definition) + { + var committed = Volatile.Read(ref _committedProjectedDefinitions); + if (!_disposing && committed.TryGetValue(nodeId, out var current) && current.Lifetime.IsActive && + Volatile.Read(ref _committedProjectedDefinitions).TryGetValue(nodeId, out var latest) && ReferenceEquals(current, latest)) + { + definition = current; + return true; + } + definition = null; + return false; + } + private int _maxProjectedNodes = 4096; private long _maxProjectedNodeBytes = 16 * 1024 * 1024; private long _projectedNodeBytes; @@ -6307,8 +6324,18 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage if (identity is null || access is null || !access.TryAcquire(projected.NodeId, identity, DataOperations.Read, out demand) || demand is null || !demand.IsValid) { - errors[ii] = StatusCodes.BadUserAccessDenied; - values[ii] = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied); + demand?.Dispose(); demand = null; + // #922: a lapsed metadata lease is not an authorization failure. A caller granted the node gets the same + // retryable answer as a cold read while the lease renews on demand (off this thread, no Lock held). + var lapse = identity is null || access is null ? ProjectedLapseOutcome.Denied + : access.RenewLapsed(projected.NodeId, identity, DataOperations.Read, out _); + if (lapse == ProjectedLapseOutcome.Denied) + { + errors[ii] = StatusCodes.BadUserAccessDenied; + values[ii] = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied); + } + else values[ii] = new DataValue(Variant.Null, lapse == ProjectedLapseOutcome.Renewing + ? StatusCodes.BadWaitingForInitialData : StatusCodes.BadResourceUnavailable); continue; } ProjectedValueWrite? cached; @@ -6349,6 +6376,13 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage if (Permits(identity, OpcUaOperation.Read, nodeToRead.NodeId)) continue; nodeToRead.Processed = true; + // #922: an attribute of a projected node whose lease lapsed — retryable while it renews, never access-denied. + if (identity is not null && IsProjectedDescendant(nodeToRead.NodeId) && ProjectedDataAccess is { } lapsedAccess && + ClassifyProjectedLapse(lapsedAccess, nodeToRead.NodeId, identity, DataOperations.Read) != ProjectedLapseOutcome.Denied) + { + values[ii] = new DataValue(Variant.Null, StatusCodes.BadResourceUnavailable); + continue; + } errors[ii] = StatusCodes.BadUserAccessDenied; values[ii] = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied); denied++; @@ -8935,18 +8969,75 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage var identity = (context as ISessionOperationContext)?.UserIdentity as RoleCarryingUserIdentity ?? context.OperationContext?.UserIdentity as RoleCarryingUserIdentity; - var allowed = new List(nodesToProcess.Count); - foreach (var handle in nodesToProcess) - { - var veto = _authorizer?.AuthorizeIfRequired( + ServiceResult? Veto(NodeHandle handle) => _authorizer?.AuthorizeIfRequired( identity, OpcUaOperation.HistoryRead, handle.NodeId, RealmOf(handle.NodeId), cached: false) - ?? (_authorizer is null && _mappedSubjectResolver is not null ? new ServiceResult(StatusCodes.BadUserAccessDenied) : null); + ?? (_authorizer is null && _mappedSubjectResolver is not null ? new ServiceResult(StatusCodes.BadUserAccessDenied) : null); + + var vetoes = new ServiceResult?[nodesToProcess.Count]; + var lapses = new ProjectedLapseOutcome?[nodesToProcess.Count]; + var renewalTasks = new Task?[nodesToProcess.Count]; + List>? renewals = null; + var access = ProjectedDataAccess; + for (var i = 0; i < nodesToProcess.Count; i++) + { + var handle = nodesToProcess[i]; + vetoes[i] = Veto(handle); + // #922: a projected node refused only because its metadata lease lapsed is renewed within this request — never + // answered access-denied for the lapse. A caller without the grant is classified Denied and never reaches the origin. + if (vetoes[i] is null || identity is null || access is null || !IsProjectedDescendant(handle.NodeId)) continue; + Task? renewal = null; + try { lapses[i] = access.RenewLapsed(handle.NodeId, identity, DataOperations.HistoryRead, out renewal); } + catch (Exception) { lapses[i] = ProjectedLapseOutcome.Denied; renewal = null; } + renewalTasks[i] = renewal; + if (renewal is not null) (renewals ??= []).Add(renewal); + } + if (renewals is not null) + { + // Block-bridged once per batch, like the projected history read itself; the SDK released Lock before dispatching. + // #922 review: the wait holds an SDK request thread, so it takes one of the SAME non-local history slots a projected + // read takes (never waiting for one — none free ⇒ the lapsed nodes are simply retryable), honours the request's + // cancellation, and is clearly longer than the renewal's own budget so a renewal that completes is never answered late. + var slots = GetNonLocalHistoryLimiter(); + if (slots.Wait(0)) + { + try + { + var wait = HistoryReadDeadline > TimeSpan.Zero && HistoryReadDeadline < ProjectedLapseRenewalWait + ? HistoryReadDeadline : ProjectedLapseRenewalWait; + Task.WhenAll(renewals).Wait((int)wait.TotalMilliseconds, + context.OperationContext?.CancellationToken ?? CancellationToken.None); + } + catch (AggregateException) { } + catch (OperationCanceledException) { } + finally { slots.Release(); } + } + for (var i = 0; i < nodesToProcess.Count; i++) + if (lapses[i] is ProjectedLapseOutcome.Renewing) vetoes[i] = Veto(nodesToProcess[i]); + } + + var allowed = new List(nodesToProcess.Count); + for (var i = 0; i < nodesToProcess.Count; i++) + { + var handle = nodesToProcess[i]; + var veto = vetoes[i]; if (veto is null) { allowed.Add(handle); continue; } + // #922 review: the lapse classification and the veto are two authorities (DataOperationPolicy / DataPlaneAuthorizer). + // A renewal that SUCCEEDED and is still vetoed is a real refusal, never a retryable one. + if (lapses[i] is ProjectedLapseOutcome.Renewing && renewalTasks[i] is { IsCompletedSuccessfully: true, Result: true }) + lapses[i] = ProjectedLapseOutcome.Denied; + if (lapses[i] is ProjectedLapseOutcome.Renewing or ProjectedLapseOutcome.Unavailable) + { + // Granted, but the lease could not be renewed in time (origin unreachable, capacity): retryable. + errors[handle.Index] = new ServiceResult(StatusCodes.BadResourceUnavailable); + results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadResourceUnavailable }; + continue; + } + // Set both slots explicitly rather than relying on the base's pre-seeded // BadHistoryOperationUnsupported — "unsupported" would tell the client the node has no history, // which is a different fact from "you may not read it" and sends them debugging the wrong thing. @@ -8957,6 +9048,20 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage return allowed; } + /// + /// #922: the longest a HistoryRead waits for the on-demand renewal of lapsed projected leases (one wait per batch, capped by + /// ) — longer than the renewal's own budget (3 s), so a completed renewal is always seen. + /// + internal static readonly TimeSpan ProjectedLapseRenewalWait = TimeSpan.FromSeconds(4); + + /// #922: classifies (and, when it is a lapse, starts renewing) a refused projected node; total — a fault is Denied. + private static ProjectedLapseOutcome ClassifyProjectedLapse(IProjectedDataAccess access, NodeId nodeId, + RoleCarryingUserIdentity identity, DataOperations operation) + { + try { return access.RenewLapsed(nodeId, identity, operation, out _); } + catch (Exception) { return ProjectedLapseOutcome.Denied; } + } + /// /// A thin adapter over the history port (): authorize, then serve (H3: projected handles go remote). protected override void HistoryReadRawModified( diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs index dc2c20382..0eacac57d 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs @@ -55,6 +55,9 @@ public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddre /// public bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition) => _nodeManager.TryResolve(nodeId, out definition); + /// + public bool TryResolveForRenewal(NodeId nodeId, out ProjectedVariableDefinition? definition) => _nodeManager.TryResolveForRenewal(nodeId, out definition); + /// public bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId) => _nodeManager.TryGetNodeId(namespaceUri, identifier, out nodeId); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionKeys.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionKeys.cs index 2ce9ca776..51c289d24 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionKeys.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionKeys.cs @@ -19,7 +19,7 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; /// failover and re-deploys, identical on both pair members (the secret is a per-cluster ${secret:}), and /// equal across every listing and principal (m-T6), so a consumer dedupes a condition's Raw and UNS placements. /// Being keyed, it cannot be dictionary-reversed from guessable RawPaths, and it carries no RawPath or driver id -/// (unlike Metadata.stable_source_id, #916). +/// (the v1 Metadata.stable_source_id did, and is no longer sent, #916). /// /// /// Without a secret the origin advertises no conditions capability (fail closed): diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/FederatedBrowseService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/FederatedBrowseService.cs index 7906b5d7a..12386062e 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/FederatedBrowseService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/FederatedBrowseService.cs @@ -13,11 +13,18 @@ internal sealed class BoundProjectionLease(MetadataAuthorityLease remote, Cancel internal DataTarget? Target => target; internal object? BindingIdentity => bindingIdentity; internal TimeSpan Remaining => remote.Remaining; + internal MetadataAuthorityLease Remote => remote; internal TimeSpan UsableDuration => remote.UsableDuration; private bool RouteAlive => !route.IsCancellationRequested && (routeCurrent?.Invoke() ?? true); internal bool LiveContext => RouteAlive && local.IsActive && bindingCurrent() && cache.IsCurrentGeneration(mapping, generation); internal bool ExpiredNaturally => remote.ExpiredNaturally && LiveContext; public bool IsValid => LiveContext && remote.IsValid; + /// + /// #922: the authority is gone ONLY because it is transient — the remote lease's time ran out or its route was + /// replaced — while the local catalog authority, the mapping binding and the cache generation are all still current + /// and nothing revoked it. Such a lapse is renewed by an exact metadata refresh, never answered as an access denial. + /// + internal bool Renewable => !remote.Invalidated && local.IsActive && bindingCurrent() && cache.IsCurrentGeneration(mapping, generation); internal ProjectionLeaseDiagnostics CaptureDiagnostics() => new(RouteAlive, local.IsActive, remote.IsValid, bindingCurrent(), cache.IsCurrentGeneration(mapping, generation)); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs index b5345ac8d..a1c001907 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs @@ -394,11 +394,19 @@ public sealed partial class LocalDataServices : IDataConnectionFactory long bytes = 256; var maximum = Math.Min(request.Budget.MaxItems, limits.MaxPageItems); var scanned = 0; - while (offset < children.Count && page.Count < maximum && scanned++ < maximum) + while (offset < children.Count && page.Count < maximum && scanned < maximum) { cancellationToken.ThrowIfCancellationRequested(); if (Expired(start, request.Budget)) return Task.FromResult(Empty(DataItemStatus.Unavailable)); var child = children[offset++]; + // #917: an unsupported value node (an alarm-bearing tag, or a data type v1 cannot carry) is never listed. Every + // consumer build applies a browse page all-or-nothing and cannot materialise one, so listing it made the whole + // folder unbrowsable on the consumer (BadNoCommunication). It stays addressable (GetMetadata/Read/Subscribe on it + // answer Unsupported). An export rooted at it still compiles but grants nothing. A skipped node is not counted + // against the scan bound (it costs one check; the budget timeout above still bounds the call), so the skip never + // yields an empty Complete=false page. + if (child.Source is not null && !child.Supported) continue; + scanned++; if ((request.Filter is { Length: > 0 } filter && !child.Metadata.BrowseName.Contains(filter, StringComparison.Ordinal)) || !Allowed(catalog, context, child, DataOperations.Browse)) continue; var metadata = Metadata(catalog, context, target, child); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs index 887178e5a..36a9c876d 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs @@ -92,11 +92,16 @@ public sealed partial class LocalExportCatalog BackingSourceKey? source = null, DataValueKind valueKind = DataValueKind.Null, bool writable = false, bool array = false, uint? length = null, bool supported = true, bool enabled = true) { + writable &= supported; // #917 review: an unsupported value node is never writable, not even in internal metadata var operations = source is null ? navigation : data | (writable ? DataOperations.Write : DataOperations.None); var metadata = new DataMetadata(view, name, source is null ? "Folder" : supported ? "Variable" : "UnsupportedVariable", array && supported ? DataValueKind.Array : valueKind, array && supported ? 1 : -1, array && supported ? Array.AsReadOnly(new[] { length is { } n ? checked((int)n) : 0 }) : [], - writable, operations, serving.CatalogEpoch, source?.StableSourceId, null, false, + // #916: Metadata.stable_source_id is never sent. The internal key of a driver source is + // ":" (SourceKey.ForDriver), which told a UNS-only peer the origin's driver ids + // and RawPaths; no consumer uses the field (it is optional on the wire and old consumers decode its absence as + // null). Acquisition keys on the LocalDataNode.Source BackingSourceKey, which is unchanged. + writable, operations, serving.CatalogEpoch, null, null, false, array && supported ? valueKind : null); nodes.Add(new(kind, id, metadata, scope, parent, source, supported, enabled)); views.Add((view.Realm, kind, id.ToUpperInvariant()), view); @@ -131,7 +136,13 @@ public sealed partial class LocalExportCatalog var enabled = deviceById[tagById[plan.TagId].DeviceId].Enabled && driverById[plan.DriverInstanceId].Enabled; rawSources.Add(plan.NodeId, (source, enabled)); var kind = ValueKind(plan.DataType); - var supported = kind != DataValueKind.Unspecified && (!plan.IsArray || DataValue.IsSupportedArrayElementKind(kind)); + // #917: an alarm-bearing tag never gets a value (DriverHostActor keeps it out of the value fan-out; #896 gives it + // no UNS variable), so it is an unsupported value node: Browse does not list it (LocalDataServices) and every + // value operation answers Unsupported, instead of a Variable a consumer would wait on forever. The node is KEPT so + // an export rooted at it still compiles, but such a root grants nothing: its values are unsupported and its + // condition placement sits under its folder, not under the tag. The alarm is forwarded as a condition (A1–A4). + var supported = plan.Alarm is null && kind != DataValueKind.Unspecified + && (!plan.IsArray || DataValue.IsSupportedArrayElementKind(kind)); var rawView = View(DataRealm.Raw, plan.NodeId, scope); Add("RawTag", plan.TagId, plan.Name, rawView, scope, RawParent(scope), source, supported ? kind : DataValueKind.Null, plan.Writable && (!plan.IsArray || plan.ArrayWritable), diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/MetadataAuthorityLease.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/MetadataAuthorityLease.cs index ff91f8678..6a1da42c1 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/MetadataAuthorityLease.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/MetadataAuthorityLease.cs @@ -47,6 +47,8 @@ public sealed class MetadataAuthorityLease : IDataAuthorizationLease } } internal TimeSpan UsableDuration => _usableDuration; + /// True once ran: a revocation, never renewable (#922). + internal bool Invalidated => Volatile.Read(ref _invalidated) != 0; internal bool ExpiredNaturally => Volatile.Read(ref _invalidated) == 0 && _clock.GetElapsedTime(_requestStart, _clock.GetTimestamp()) >= _usableDuration; public bool IsValid diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedBrowseAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedBrowseAccess.cs index d9ac279aa..c2877b3b7 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedBrowseAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedBrowseAccess.cs @@ -22,6 +22,9 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable private readonly object _anchorGate = new(); private readonly ConcurrentDictionary _installed = new(StringComparer.OrdinalIgnoreCase); private readonly ConcurrentDictionary _inflight = new(); + // #922 review: background refreshes of cached pages, keyed by the parent NODE (not caller / MaxResults), so varying the + // browse parameters cannot multiply origin browses of one parent. + private readonly ConcurrentDictionary _refreshing = new(); private readonly record struct Failure(ProjectionPageStatus Status, long Until); private readonly object _resultGate = new(); private readonly Dictionary _failures = new(); @@ -176,15 +179,26 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable if (!guard.IsCurrent()) return Empty(ProjectedBrowseReadiness.Unavailable); var retainedBytes = checked(sourceGuard.RetainedBytes + 2048L + 2L * (snapshot.Continuation?.Length ?? 0) + expectedIds.Sum(node => 128L + 2L * node.IdentifierAsString.Length)); + // #922: a re-browse served from a cached page must still renew a lease that is running out — otherwise a client that + // re-browses to refresh a node it reads gets nothing until the page itself lapses. Past half its life an initial page + // is served as is AND refreshed in the background (at most one in flight per page key; a fresh page is untouched). + if (input.Cursor is null && lease is BoundProjectionLease bound && bound.Remaining < bound.UsableDuration / 2) + _ = TrySchedule(new WorkKey(input.Parent, identity, input.Cursor, maximum), request, anchor, input.Parent, refresh: true); return new(ProjectedBrowseReadiness.Ready, Array.AsReadOnly(expectedIds), snapshot.Continuation, snapshot.Complete, guard.IsCurrent, retainedBytes); } if (snapshot.Status == ProjectionPageStatus.InvalidContinuation) return Empty(ProjectedBrowseReadiness.InvalidContinuation); - var key = new WorkKey(input.Parent, identity, input.Cursor, maximum); + return TrySchedule(new WorkKey(input.Parent, identity, input.Cursor, maximum), request, anchor, input.Parent, refresh: false); + } + + private ProjectedBrowsePage TrySchedule(WorkKey key, ProjectedBrowseRequest request, Installed anchor, NodeId exactParent, bool refresh) + { lock (_resultGate) { var now = _catalog.Clock.GetTimestamp(); foreach (var expired in _failures.Where(x => x.Value.Until <= now).Select(x => x.Key).ToArray()) _failures.Remove(expired); + if (refresh && (_failures.ContainsKey(key) || _inflight.ContainsKey(key) || !_refreshing.TryAdd(exactParent, 0))) + return Empty(ProjectedBrowseReadiness.Pending); if (_failures.TryGetValue(key, out var failure)) return Empty(failure.Status switch { @@ -193,11 +207,14 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable _ => ProjectedBrowseReadiness.Unavailable }); if (_inflight.ContainsKey(key)) return Empty(ProjectedBrowseReadiness.Pending); - if (_failures.Count + _pending >= _maxPending) return Empty(ProjectedBrowseReadiness.Unavailable); - if (!_inflight.TryAdd(key, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously))) return Empty(ProjectedBrowseReadiness.Pending); + if (_failures.Count + _pending >= _maxPending || + !_inflight.TryAdd(key, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously))) + { + if (refresh) _refreshing.TryRemove(exactParent, out _); + return Empty(_failures.Count + _pending >= _maxPending ? ProjectedBrowseReadiness.Unavailable : ProjectedBrowseReadiness.Pending); + } _pending++; } - var exactParent = input.Parent; _ = Task.Run(async () => { var result = ProjectionPageStatus.Unavailable; @@ -208,6 +225,7 @@ public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable lock (_resultGate) { _inflight.TryRemove(key, out var completed); + if (refresh) _refreshing.TryRemove(exactParent, out _); _pending--; if (result != ProjectionPageStatus.Ready && !_stop.IsCancellationRequested) { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCatalogCache.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCatalogCache.cs index 920516760..5d8ef47e1 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCatalogCache.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCatalogCache.cs @@ -106,7 +106,8 @@ public sealed class ProjectedCatalogCache private static ParentKey Key(ProjectedBrowseRequest request) => new(request.MappingId.ToUpperInvariant(), request.Parent, request.Filter, request.Continuation, request.Caller, request.ConfiguredCapability); private static (string Mapping, DataView Parent) Parent(string mapping, DataView parent) => (mapping.ToUpperInvariant(), parent); - private bool ValidCore(ProjectedNodeProof proof) => proof.Generation > 0 && proof.Lease.IsValid && proof.Lease.Serving.ServingGeneration > 0 && + private bool ValidCore(ProjectedNodeProof proof, bool requireLease = true) => proof.Generation > 0 && + (requireLease ? proof.Lease.IsValid : proof.Lease is BoundProjectionLease { Renewable: true }) && proof.Lease.Serving.ServingGeneration > 0 && proof.Subject.Serving == proof.Lease.Serving && proof.Metadata.View == proof.Subject.View && proof.Metadata.Serving == proof.Lease.Serving && proof.OriginMetadata.Serving == proof.Lease.Serving && proof.OriginMetadata.View.MappingId is null && proof.OriginMetadata.View.MappingRevision == 0 && @@ -488,6 +489,26 @@ public sealed class ProjectedCatalogCache proof = null; return false; } } + /// + /// #922: the retained, non-retired proof of a node whose authority may be refreshed by an exact renewal — a valid one, + /// or one that is invalid ONLY because its lease lapsed (time, or a replaced route) while every local fence still holds + /// (). Never an authorization: the caller still authorizes the subject and + /// the renewal re-proves everything at the origin before anything is served. + /// + internal bool TryResolveForRenewal(DataRealm realm, string localId, out ProjectedNodeProof? proof) + { + lock (_sync) + { + if (_nodes.TryGetValue((realm, localId), out var entry) && !entry.Retired && (Valid(entry.Proof) || Renewable(entry.Proof))) + { proof = entry.Proof; return true; } + proof = null; return false; + } + } + private bool Renewable(ProjectedNodeProof proof) + { + try { return ValidCore(proof, requireLease: false); } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or NullReferenceException) { return false; } + } public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) { lock (_sync) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs index 18292622f..f479d7432 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs @@ -93,7 +93,7 @@ public sealed record ProjectedConditionOptions(TimeSpan Linger, int MaxImportedC /// /// Retained managed bytes per imported condition, measured by the A3 L2 harness (1,000 conditions in one mapping on a /// running SDK 2.0.1 server: node + children + ids + registry/indexes + EventId registry + verdict cache; X0's - /// node-only harness measured 160,997). A3b review S5: the WORST case — two placements, every EventId slot, three + /// node-only harness retains 79,085 B on the same method, #929 — its original 160,997 was a GC.GetTotalMemory delta). A3b review S5: the WORST case — two placements, every EventId slot, three /// event items, the runner's Live + Buffer records. A3 review round 2: measured with the retained heap /// (GCMemoryInfo, not GC.GetTotalMemory, which counted ~125 MiB of committed-but-free regions) and the /// settled working set, 8 EventId slots (§5.6): max of three runs = 158,629 B (working set; heap 111,715 B), rounded up. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs index 000d35ff8..0ecc07b47 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs @@ -19,6 +19,8 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable public TimeProvider Clock { get; } internal Func? RetryJitterForTests { get; set; } internal Action? BeforeSuccessorAdoptionForTests { get; set; } + /// #920: runs on the stream pump after a publish passed its demand check, before the duplicate-baseline check. + internal Action? AfterPublishDemandCheckForTests { get; set; } private readonly IFederatedProjectionCatalog _catalog; private readonly IProjectedNodeLookup _nodes; private readonly Func _connectionForMapping; @@ -201,6 +203,123 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable } catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireException); return false; } } + // #922: at most one on-demand renewal per projected node AND operation (each requests its own bit at the origin); a failed + // one is not retried for a short back-off so a client polling a node whose origin is unreachable cannot turn every Read into + // a metadata call. Renewals never use the unary budget (that would starve cold reads, writes and subscription renewals): + // they queue — at most MaxQueuedLapseRenewals — for the resolver's own on-demand pool, so a batch of N lapsed nodes renews + // them all, a few at a time. + private readonly Dictionary<(DataRealm Realm, string LocalIdentifier, DataOperations Operation), Task> _lapseRenewals = new(); + private readonly Dictionary<(DataRealm Realm, string LocalIdentifier, DataOperations Operation), long> _lapseRenewalBackoff = new(); + private const int MaxLapseRenewalBackoffEntries = 4096; + internal const int MaxQueuedLapseRenewals = 64; + internal static readonly TimeSpan LapseRenewalBackoff = TimeSpan.FromMilliseconds(250); + /// The whole on-demand renewal, pool wait included; clearly shorter than the longest a HistoryRead waits for it. + internal static readonly TimeSpan LapseRenewalTimeout = TimeSpan.FromSeconds(3); + /// One metadata item and its capability probe: never a multi-MiB unary reservation. + internal const long LapseRenewalBytes = 256 * 1024; + internal int LapseRenewalsStartedForTests => Volatile.Read(ref _lapseRenewalsStarted); + private int _lapseRenewalsStarted; + + /// + public ProjectedLapseOutcome RenewLapsed(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out Task? renewal) + { + renewal = null; + if (caller is null || operation is not (DataOperations.Read or DataOperations.HistoryRead) || _renewalSink is not { } sink || + _catalog is not RemoteNamespaceResolver resolver) return ProjectedLapseOutcome.Denied; + try + { + // The SDK node must still be live, and either it or its catalog proof must have lapsed — a refusal of a node whose + // authority is fully current was a real refusal (grant, capacity…), never a lapse. + if (!_nodes.TryResolveForRenewal(nodeId, out var definition) || definition is null || !definition.Lifetime.IsActive || + !resolver.TryResolveForRenewal(definition.Realm, definition.LocalIdentifier, out var proof) || proof is null || + definition.AuthorityIsCurrent() && _catalog.IsUsableProof(proof) || + proof.Generation != definition.ProjectionGeneration || !MetadataMatches(proof.Metadata, definition.Metadata) || + proof.Metadata.View.MappingId is not { } mapping || _connectionForMapping(mapping) is not { Length: > 0 } || + (operation == DataOperations.Read && proof.MaximumSampleAge <= TimeSpan.Zero) || + (operation == DataOperations.HistoryRead && (!definition.Historizing || !ProjectedHistoryAccess.Advertises(proof)))) + return ProjectedLapseOutcome.Denied; + var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc); + // The same grant the served operation needs, judged on everything but the lapsed lease: a caller without it is + // refused exactly as before, and never causes an origin call. + if (!_policy.AuthorizeMappedSubject(identity, Operation(operation), proof.Metadata.View, proof.Lease.Serving, proof.Subject, proof.Resolver)) + return ProjectedLapseOutcome.Denied; + var key = (definition.Realm, definition.LocalIdentifier, operation); + var budget = new DataBudget(LapseRenewalTimeout, 1, Math.Min(LapseRenewalBytes, _limits.MaxUnaryBytes)); + TaskCompletionSource started; + lock (_sync) + { + if (_disposed) return ProjectedLapseOutcome.Unavailable; + if (_lapseRenewals.TryGetValue(key, out var running)) { renewal = running; return ProjectedLapseOutcome.Renewing; } + var now = Clock.GetTimestamp(); + if (_lapseRenewalBackoff.TryGetValue(key, out var until)) + { + if (now < until) return ProjectedLapseOutcome.Unavailable; + _lapseRenewalBackoff.Remove(key); + } + if (_lapseRenewals.Count >= MaxQueuedLapseRenewals) return ProjectedLapseOutcome.Unavailable; + started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _lapseRenewals.Add(key, started.Task); + } + Interlocked.Increment(ref _lapseRenewalsStarted); + // Never on the caller's thread: the renewal awaits the origin and commits through the SDK sink (node-manager Lock). + _ = Task.Run(() => RunLapseRenewalAsync(resolver, sink, key, proof, definition, nodeId, caller, identity, operation, budget, started)); + renewal = started.Task; + return ProjectedLapseOutcome.Renewing; + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return ProjectedLapseOutcome.Denied; } + } + + private async Task RunLapseRenewalAsync(RemoteNamespaceResolver resolver, IProjectedNamespacePageSink sink, + (DataRealm Realm, string LocalIdentifier, DataOperations Operation) key, ProjectedNodeProof proof, ProjectedVariableDefinition definition, NodeId nodeId, + RoleCarryingUserIdentity caller, DataCallerIdentity identity, DataOperations operation, DataBudget budget, TaskCompletionSource completion) + { + var renewed = false; + try + { + renewed = await resolver.RenewExactAsync(proof, definition, nodeId, identity, null, sink, budget, + () => { lock (_sync) return !_disposed; }, CancellationToken.None, overlap: false, + authorizeAs: Operation(operation), required: operation, onDemand: true).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OutOfMemoryException) { renewed = false; } + finally + { + lock (_sync) + { + _lapseRenewals.Remove(key); + if (!renewed && !_disposed) + { + if (_lapseRenewalBackoff.Count >= MaxLapseRenewalBackoffEntries) EvictLapseBackoffLocked(); + var delay = (long)(LapseRenewalBackoff.TotalSeconds * Clock.TimestampFrequency); + _lapseRenewalBackoff[key] = Clock.GetTimestamp() + Math.Max(1, delay); + } + } + } + // A Read answered retryable while the lease renewed: fetch the value now, through the ordinary authorized path, so the + // client's retry is served from the fresh sample instead of starting another cold read. + if (renewed && operation == DataOperations.Read) + { + IProjectedDemandLease? demand = null; + try + { + if (TryAcquire(nodeId, caller, DataOperations.Read, out demand) && demand is not null && + ScheduleRead(demand, new DataBudget(LapseRenewalTimeout, 1, ProjectedReadBytes), Clock.GetTimestamp())) demand = null; + } + catch (Exception ex) when (ex is not OutOfMemoryException) { } + finally { demand?.Dispose(); } + } + completion.TrySetResult(renewed); + } + // Full map (rare): drop the expired entries; if none expired, the one that expires first — never the whole map, which would + // let every node's back-off lapse at once. + private void EvictLapseBackoffLocked() + { + var now = Clock.GetTimestamp(); + var expired = _lapseRenewalBackoff.Where(entry => entry.Value <= now).Select(entry => entry.Key).ToArray(); + foreach (var key in expired) _lapseRenewalBackoff.Remove(key); + if (expired.Length == 0) _lapseRenewalBackoff.Remove(_lapseRenewalBackoff.MinBy(entry => entry.Value).Key); + } + /// The per-read byte budget the SDK Read path schedules a cold projected read with. + internal const long ProjectedReadBytes = 4 * 1024 * 1024; internal bool TryAcquireConfigured(NodeId nodeId, ConfiguredProjectionCapability capability, out IProjectedDemandLease? demand) { demand = null; @@ -568,7 +687,11 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable internal bool HasFreshCachedLocked(Demand demand) { var sample = _cachedSample; - if (sample is null || _cachedVersion != LastVersion || !sample.SourceProof.IsValid || !demand.IsValid || !IsValid) return false; + // #920: deliberately NOT gated on demand.IsValid. This answers "is the sample already published for this version + // still fresh at this demand's age limit" — the duplicate-baseline suppression in Publish. A demand disposed + // concurrently (a failed SDK item construction) used to turn the answer into "not fresh", so a dying + // registration re-published the same acquisition as a new complete baseline to every item on the node. + if (sample is null || _cachedVersion != LastVersion || !sample.SourceProof.IsValid || !IsValid) return false; try { return sample.OriginAgeBounds.Advance(_owner.Clock.GetElapsedTime(sample.ReceivedTimestamp, @@ -1658,6 +1781,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable { validated = false; if (registration.Removed || !registration.Demand.IsValid || update.SourceProof is not AttemptProof proof) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishDemand); return false; } + _owner.AfterPublishDemandCheckForTests?.Invoke(registration.Demand); var source = proof.Source; if (!source.TryPrepareSuccessor(registration.Demand, out var successor)) return false; try @@ -1675,6 +1799,8 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable validated = update.IsCompleteSnapshot; if (version == source.LastVersion && update.IsCompleteSnapshot && !registration.Recovery && source.HasFreshCachedLocked(registration.Demand)) return false; + // A demand disposed since the check above publishes nothing (it is no longer anyone's subscription). + if (!registration.Demand.IsValid) { validated = false; ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishDemand); return false; } if (_owner._publisher.TryPublish([update])) { if (successor is not null) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs index 6bd3be6fa..b8c034db3 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs @@ -22,6 +22,10 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp private readonly DataOperationPolicy _policy; private readonly int _maxMappings; private readonly SemaphoreSlim _fetchSlots; + // #922 review: on-demand renewals of lapsed nodes (a Read / HistoryRead) run on their OWN small pool, never on _fetchSlots, + // so a burst of them cannot crowd out browse pages or the subscription renewals that keep live items from lapsing. + private readonly SemaphoreSlim _onDemandSlots; + internal int OnDemandRenewalSlots { get; } private readonly int _maximumWaiters; private readonly Func? _beforeFetch; private int _waiterCount; @@ -44,6 +48,8 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp _source = source ?? throw new ArgumentNullException(nameof(source)); _policy = policy ?? throw new ArgumentNullException(nameof(policy)); if (maxMappings <= 0 || maxConcurrentFetches <= 0) throw new ArgumentOutOfRangeException(nameof(maxMappings)); _maxMappings = maxMappings; _fetchSlots = new(maxConcurrentFetches, maxConcurrentFetches); + OnDemandRenewalSlots = Math.Max(1, maxConcurrentFetches / 2); + _onDemandSlots = new(OnDemandRenewalSlots, OnDemandRenewalSlots); _maximumWaiters = checked(maxConcurrentFetches * 16); _cache.Invalidated += OnInvalidated; } @@ -98,6 +104,8 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) => _cache.TryResolveProjected(realm, localId, out proof); public bool IsUsableProof(ProjectedNodeProof proof) => _cache.IsUsableProof(proof); public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) => _cache.TryPinProjected(realm, localId, out pin); + internal bool TryResolveForRenewal(DataRealm realm, string localId, out ProjectedNodeProof? proof) => + _cache.TryResolveForRenewal(realm, localId, out proof); internal bool TryPinExpiredRecoveryPair(ProjectedNodeProof previous, ProjectedNodeProof successor, out IDisposable? pin) => _cache.TryPinExpiredRecoveryPair(previous, successor, out pin); public async Task PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken) @@ -301,8 +309,14 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp // page, cursor or sibling visibility and does not create a physical subscription. internal async Task RenewExactAsync(ProjectedNodeProof previous, ProjectedVariableDefinition definition, NodeId nodeId, DataCallerIdentity? caller, ConfiguredProjectionCapability? configured, - IProjectedNamespacePageSink sink, DataBudget budget, Func demandActive, CancellationToken cancellationToken, bool overlap = false) + IProjectedNamespacePageSink sink, DataBudget budget, Func demandActive, CancellationToken cancellationToken, bool overlap = false, + OpcUaOperation authorizeAs = OpcUaOperation.CreateMonitoredItems, DataOperations required = DataOperations.Subscribe, + bool onDemand = false) { + // #922: a subscription renews for CreateMonitoredItems/Subscribe (the default); an on-demand renewal of a lapsed node + // renews for the operation the caller is performing (Read / HistoryRead) and requires exactly that bit at the origin. + if (authorizeAs is not (OpcUaOperation.CreateMonitoredItems or OpcUaOperation.Read or OpcUaOperation.HistoryRead) || + required is not (DataOperations.Subscribe or DataOperations.Read or DataOperations.HistoryRead)) return false; var mapping = previous.Metadata.View.MappingId; if (mapping is null || previous.Subject.Scope.Segments.Count == 0) return false; ProjectedMappingBinding binding; @@ -313,7 +327,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp bool CallerAllowed() => demandActive() && (configured is not null ? configured.Matches(mapping, previous.Metadata.View, binding.LocalAuthority) : caller is not null && _policy.IsCallerUsable(caller) && - _policy.AuthorizeLocal(caller, OpcUaOperation.CreateMonitoredItems, previous.Subject.Scope)); + _policy.AuthorizeLocal(caller, authorizeAs, previous.Subject.Scope)); if (!IsCurrent(binding) || !binding.LocalAuthority.IsActive || !CallerAllowed() || previous.Metadata.View.MappingRevision != binding.Mapping.Revision || previous.Metadata.View.Realm != binding.Mapping.Realm || previous.OriginMetadata.View.MappingId is not null || @@ -322,7 +336,17 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp previous.Subject.Scope.Segments.Count < binding.LocalScope.Segments.Count || !previous.Subject.Scope.Segments.Take(binding.LocalScope.Segments.Count).SequenceEqual(binding.LocalScope.Segments, StringComparer.Ordinal) || !previous.Subject.LocalAncestry.SequenceEqual(binding.LocalAncestry, StringComparer.OrdinalIgnoreCase)) return false; - if (!await _fetchSlots.WaitAsync(0, cancellationToken).ConfigureAwait(false)) return false; + // A subscription renewal never queues (it retries on its own cadence); an on-demand renewal waits for its own pool within + // its budget, and the wait is charged to that budget. + var slots = onDemand ? _onDemandSlots : _fetchSlots; + var queued = System.Diagnostics.Stopwatch.GetTimestamp(); + if (!await slots.WaitAsync(onDemand ? budget.Timeout : TimeSpan.Zero, cancellationToken).ConfigureAwait(false)) return false; + if (onDemand) + { + var left = budget.Timeout - System.Diagnostics.Stopwatch.GetElapsedTime(queued); + if (left <= TimeSpan.Zero) { slots.Release(); return false; } + budget = budget with { Timeout = left }; + } IGrpcDataAdapterConnectionLease? connection = null; try { @@ -356,7 +380,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp metadata.ValueKind != previous.OriginMetadata.ValueKind || metadata.ValueRank != previous.OriginMetadata.ValueRank || metadata.ArrayElementKind != previous.OriginMetadata.ArrayElementKind || !metadata.Dimensions.SequenceEqual(previous.OriginMetadata.Dimensions) || - (metadata.AllowedOperations & binding.Mapping.AllowedOperations & DataOperations.Subscribe) == 0 || + (metadata.AllowedOperations & binding.Mapping.AllowedOperations & required) == 0 || !IsCurrent(binding) || !CallerAllowed() || connection.CancellationToken.IsCancellationRequested) return false; metadata.Validate(); remoteLease.Validate(); var generation = _cache.CaptureGeneration(mapping); @@ -377,7 +401,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp var renewed = new ProjectedNodeProof(previous.LocalIdentifier, mapped, subject, resolver, lease, generation, metadata, TimeSpan.FromMilliseconds(binding.Mapping.StaleTimeoutMilliseconds)); var guard = new ExactAuthority(renewed); - if (!guard.IsCurrent() || caller is not null && !_policy.AuthorizeMapped(caller, OpcUaOperation.CreateMonitoredItems, + if (!guard.IsCurrent() || caller is not null && !_policy.AuthorizeMapped(caller, authorizeAs, mapped.View, serving, subject, resolver, lease)) return false; var newDefinition = new ProjectedVariableDefinition(definition.Realm, definition.LocalIdentifier, definition.Parent, mapped, generation, guard.IsCurrent) { Lifetime = definition.Lifetime, Historizing = ProjectedHistoryAccess.Advertises(renewed) }; @@ -400,7 +424,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp { try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); } catch (Exception) { } - finally { _fetchSlots.Release(); } + finally { slots.Release(); } } } public void Dispose() diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.ConditionSignals.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.ConditionSignals.cs index c24eb455e..e5508bc3e 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.ConditionSignals.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.ConditionSignals.cs @@ -213,6 +213,31 @@ public sealed partial class DriverHostActor return; } + if (msg.Args.Withdrawn) + { + // #926: the source lost events after establishing these conditions. Take "known" back (same chain as its + // projections, so it lands after them), keep them out of the backstop (which would re-mark them known by + // timer), and put them back in the F5 window so a source that never re-signals is diagnosed. + t.Unsignalable.ExceptWith(msg.Args.ConditionIds); + var withdrawn = MarkDriverConditionsKnown(msg.DriverInstanceId, msg.Args.ConditionIds, known: false); + if (t.GoodSinceUtc is not null && _alarmRefsByDriver.TryGetValue(msg.DriverInstanceId, out var owned)) + { + var ownedPaths = owned.Select(r => r.RawPath).ToHashSet(StringComparer.Ordinal); + var before = t.Pending.Count; + t.Pending.UnionWith(msg.Args.ConditionIds.Where(ownedPaths.Contains)); + // An F5 window already running covers them; otherwise start one now. A diagnostic already raised for + // that window must count them too (#926 review r2). + if (t.Pending.Count != before) + { + if (t.PendingSinceUtc is null) ArmSignalTimeout(msg.DriverInstanceId, t); + else if (t.DiagnosticRaised) _conditionSignals.Hub?.UpdateUnsignalled(msg.DriverInstanceId, t.Pending.Count); + } + } + _log.Info("DriverHost {Node}: driver {Driver} withdrew {Count} condition(s) ({Routed} routed) — state no longer known (events lost)", + _localNode, msg.DriverInstanceId, msg.Args.ConditionIds.Count, withdrawn); + return; + } + if (msg.Args.Unsignalable) { // InitialStateUnsignalable: no real signal will come. Only a driver type with a backstop (OpcUaClient) marks @@ -327,7 +352,7 @@ public sealed partial class DriverHostActor } /// Route driver condition ids (RawPaths) to their condition nodes and send one mark per realm. - private int MarkDriverConditionsKnown(string driverInstanceId, IReadOnlyCollection conditionIds) + private int MarkDriverConditionsKnown(string driverInstanceId, IReadOnlyCollection conditionIds, bool known = true) { if (_opcUaPublishActor is null || conditionIds.Count == 0) return 0; var byRealm = new Dictionary>(); @@ -344,7 +369,7 @@ public sealed partial class DriverHostActor var count = 0; foreach (var (realm, ids) in byRealm) { - _opcUaPublishActor.Tell(new PublishActor.MarkConditionsKnown(driverInstanceId, ids, realm)); + _opcUaPublishActor.Tell(new PublishActor.MarkConditionsKnown(driverInstanceId, ids, realm, Known: known)); count += ids.Count; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs index c5bd882ba..998c5ef06 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -3121,7 +3121,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn /// , the continuation both modes share. /// /// - /// Both begin-paths arm the watchdog, because both leave the + /// Both begin-paths arm the watchdog — after the synchronous + /// Applying-row write, immediately before the read/fetch starts — because both leave the /// host alive and dequeuing while it waits for bytes it does not have yet — which is exactly /// what makes a silent wedge possible. (Before the Direct read moved off the mailbox this was /// the only such path: an inline read could not be "stuck in Applying" in any sense a watchdog @@ -3131,7 +3132,6 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn { _applyingDeploymentId = deploymentId; Become(Applying); - Timers.StartSingleTimer(ApplyWedgeTimerKey, new ApplyWedged(deploymentId), _applyWedgeTimeout); // Persist Applying row (idempotent on PK) — same crash-boundary marker as the Direct apply. UpsertNodeDeploymentState(deploymentId, NodeDeploymentStatus.Applying, failureReason: null); @@ -3152,6 +3152,12 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn _log.Debug("DriverHost {Node}: fetching artifact for {Id} (rev {Rev}) from central over gRPC", _localNode, deploymentId, revision); + // Armed only now, AFTER the synchronous Applying-row write above and immediately before the + // read/fetch starts: the watchdog times the read/fetch (its Warning says so), and a slow row write + // armed-before enqueued the tick ahead of the fetch's pipe-back, reporting a fetch that answered at + // once as WEDGED (Runtime.Tests master failures: ACompletedApply_NeverReportsAWedge on a cold EF model). + Timers.StartSingleTimer(ApplyWedgeTimerKey, new ApplyWedged(deploymentId), _applyWedgeTimeout); + // A faulted fetch task maps to null bytes — the apply-failure path, exactly like an // all-endpoints-down fetch — so a fault can never escape as an unhandled actor message. _artifactFetcher.FetchAsync(deploymentId.ToString(), revision.Value, CancellationToken.None) @@ -3190,7 +3196,6 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn { _applyingDeploymentId = deploymentId; Become(Applying); - Timers.StartSingleTimer(ApplyWedgeTimerKey, new ApplyWedged(deploymentId), _applyWedgeTimeout); // Persist Applying row (idempotent on PK) — the crash-boundary marker, and deliberately still // on the actor thread: one bounded row write, and the apply must be recorded as in flight @@ -3200,6 +3205,9 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn _log.Debug("DriverHost {Node}: reading artifact for {Id} (rev {Rev}) from the ConfigDb, off the mailbox", _localNode, deploymentId, revision); + // Armed after the Applying-row write, immediately before the read starts — see BeginFetchAndCacheApply. + Timers.StartSingleTimer(ApplyWedgeTimerKey, new ApplyWedged(deploymentId), _applyWedgeTimeout); + Task.Run(() => LoadArtifactBlob(deploymentId)) .PipeTo( Self, diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs index a97c84030..c444541bf 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs @@ -238,7 +238,9 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers /// , so it reaches after every alarm event the /// driver raised before it. /// A1 review S2: is the connection (Connected entry) the driver raised - /// it under, matching of that Good edge. + /// it under, matching of that Good edge. #926: keep this message + /// IN-PROCESS (child → parent only) — it carries by reference, and a + /// serialized copy that dropped Withdrawn would default it to false and turn a withdrawal into a "known" mark. public sealed record AlarmInitialStatePublished(string DriverInstanceId, AlarmInitialStateEventArgs Args, long? ConnectionEpoch = null); private sealed record NativeAlarmInitialState(AlarmInitialStateEventArgs Args, long Epoch); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs index dc173ba12..850d97126 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs @@ -1165,47 +1165,89 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying {Count} deferred status writes threw", statuses.Count); } } + // G3 pre-pass: a deferred projection outside the applied scope is skipped — its source's KNOWN marks are discarded + // wherever they sit in the arrival order (the conservative reading of "never known over a projection that did + // not land"). + foreach (var (alarm, _) in _deferred.Alarms) + if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId))) _deferred.NoteAlarmLoss(alarm.Source); + + // #926 review r2: alarm states, alarm qualities and condition-known marks replay as ONE list in ARRIVAL order. + // Marks used to replay after every alarm, which was right for a "known" mark (it summarises the projections + // before it) but wrong for a withdrawal followed by a live transition: replayed transition-then-withdrawal, + // the condition ended unknown although the transition had re-established it — and the host, which saw the + // transition last, no longer counted it in F5. Arrival order is exactly what the live path applies. + var items = new List<(long Seq, int Kind, int Index)>(); + var alarmList = _deferred.Alarms.ToList(); + var qualityList = _deferred.AlarmQualities.ToList(); + var markList = _deferred.Marks.ToList(); + for (var i = 0; i < alarmList.Count; i++) items.Add((alarmList[i].Seq, 0, i)); + for (var i = 0; i < qualityList.Count; i++) items.Add((qualityList[i].Seq, 1, i)); + for (var i = 0; i < markList.Count; i++) items.Add((markList[i].Seq, 2, i)); + items.Sort((x, y) => x.Seq.CompareTo(y.Seq)); + var alarms = 0; - foreach (var alarm in _deferred.Alarms) - { - if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId))) - { - _deferred.NoteAlarmLoss(alarm.Source); // G3: a skipped projection — the source's marks go too - continue; - } - - alarms++; - try { _sink.WriteAlarmCondition(alarm.AlarmNodeId, alarm.State, alarm.TimestampUtc, alarm.Realm, alarm.EstablishesState); } - catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm write threw for {Node}", alarm.AlarmNodeId); } - } - var qualities = 0; - foreach (var quality in _deferred.AlarmQualities) - { - if (!scope.Conditions.Contains((quality.Realm, quality.AlarmNodeId))) continue; - qualities++; - try { _sink.WriteAlarmQuality(quality.AlarmNodeId, quality.StatusCode, quality.TimestampUtc, quality.Realm); } - catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm-quality write threw for {Node}", quality.AlarmNodeId); } - } - - // A1 F2/G3: the deferred "known" marks replay LAST, after every deferred alarm — and only for a source none of - // whose deferred projections was dropped or skipped. A discarded mark leaves its conditions unknown (Uncertain) - // until the source's next signal. var marks = 0; var discarded = 0; - foreach (var (mark, sender) in _deferred.Marks) + var discardedBySender = new Dictionary<(string Source, AddressSpaceRealm Realm), (IActorRef? Sender, List Ids)>(); + // Consecutive marks of one (source, realm, known) are applied as one sink call. + string? runSource = null; + AddressSpaceRealm runRealm = default; + var runKnown = false; + var runIds = new List(); + void FlushRun() { - // A withdrawal (Known: false) is never discarded: it only makes conditions unknown, which is always safe. - if (mark.Known && _deferred.SourceLost(mark.Source)) + if (runIds.Count == 0) return; + marks++; + ApplyMark(new MarkConditionsKnown(runSource!, runIds.ToList(), runRealm, runKnown)); + runIds.Clear(); + } + + foreach (var (_, kind, index) in items) + { + if (kind == 2) { - discarded++; - TellDiscarded(sender, new ConditionMarksDiscarded(mark.Source, mark.ConditionIds, mark.Realm)); + var m = markList[index]; + // A withdrawal (Known: false) is never discarded: it only makes conditions unknown, which is always safe. + if (m.Known && _deferred.SourceLost(m.Source)) + { + discarded++; + if (!discardedBySender.TryGetValue((m.Source, m.Realm), out var d)) + discardedBySender[(m.Source, m.Realm)] = d = (m.Sender, new List()); + d.Ids.Add(m.ConditionId); + continue; + } + + if (runIds.Count > 0 && (runSource != m.Source || runRealm != m.Realm || runKnown != m.Known)) FlushRun(); + runSource = m.Source; + runRealm = m.Realm; + runKnown = m.Known; + runIds.Add(m.ConditionId); continue; } - marks++; - ApplyMark(mark); + FlushRun(); + if (kind == 0) + { + var alarm = alarmList[index].Msg; + if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId))) continue; // counted in the pre-pass + alarms++; + try { _sink.WriteAlarmCondition(alarm.AlarmNodeId, alarm.State, alarm.TimestampUtc, alarm.Realm, alarm.EstablishesState); } + catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm write threw for {Node}", alarm.AlarmNodeId); } + } + else + { + var quality = qualityList[index].Msg; + if (!scope.Conditions.Contains((quality.Realm, quality.AlarmNodeId))) continue; + qualities++; + try { _sink.WriteAlarmQuality(quality.AlarmNodeId, quality.StatusCode, quality.TimestampUtc, quality.Realm); } + catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm-quality write threw for {Node}", quality.AlarmNodeId); } + } } + FlushRun(); + + foreach (var ((source, realm), (sender, ids)) in discardedBySender) + TellDiscarded(sender, new ConditionMarksDiscarded(source, ids, realm)); // N1: a KNOWN mark that did not fit the deferral was dropped (staying unknown is safe) — its sender hears it. foreach (var (source, sender) in _deferred.OverflowedMarkSources) @@ -1233,6 +1275,10 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers /// the two live writes leave on the node). Bounded by distinct keys across all kinds; /// beyond it a NEW key is not held (an existing key still updates), counted in . /// + /// One deferred condition-known mark (#926 review r2: per condition, with its arrival sequence). + private sealed record DeferredMark( + string Source, string ConditionId, AddressSpaceRealm Realm, bool Known, IActorRef? Sender, long Seq); + private sealed class DeferredWrites(int capacity) { private struct VariableEntry @@ -1246,11 +1292,14 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers } private readonly Dictionary<(AddressSpaceRealm, string), VariableEntry> _variables = new(); - private readonly Dictionary<(AddressSpaceRealm, string), AlarmStateUpdate> _alarms = new(); - private readonly Dictionary<(AddressSpaceRealm, string), AlarmQualityUpdate> _qualities = new(); - // A1: condition-known marks in arrival order (bounded by Capacity — a dropped mark only keeps conditions - // unknown, which is always safe), and the sources that lost a deferred alarm projection (G3). - private readonly List<(MarkConditionsKnown Msg, IActorRef? Sender)> _marks = new(); + private readonly Dictionary<(AddressSpaceRealm, string), (AlarmStateUpdate Msg, long Seq)> _alarms = new(); + private readonly Dictionary<(AddressSpaceRealm, string), (AlarmQualityUpdate Msg, long Seq)> _qualities = new(); + // A1 / #926 review r2: the LATEST condition-known mark per (realm, condition id), with its arrival sequence, and + // the sources that lost a deferred alarm projection (G3). Per-condition, so a withdrawal-heavy plan window holds + // at most one entry per condition (bounded by the address space), and replay can interleave marks with alarm + // states in arrival order. + private readonly Dictionary<(AddressSpaceRealm, string), DeferredMark> _marks = new(); + private long _seq; private readonly Dictionary _overflowedMarkSources = new(StringComparer.Ordinal); private readonly HashSet _lossySources = new(StringComparer.Ordinal); private bool _unattributedLoss; @@ -1259,20 +1308,31 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers public long Dropped { get; private set; } public int Count => _variables.Count + _alarms.Count + _qualities.Count; public bool IsEmpty => Count == 0 && _marks.Count == 0; - public IEnumerable Alarms => _alarms.Values; - public IEnumerable AlarmQualities => _qualities.Values; - public IReadOnlyList<(MarkConditionsKnown Msg, IActorRef? Sender)> Marks => _marks; + public IEnumerable<(AlarmStateUpdate Msg, long Seq)> Alarms => _alarms.Values; + public IEnumerable<(AlarmQualityUpdate Msg, long Seq)> AlarmQualities => _qualities.Values; + public IEnumerable Marks => _marks.Values; /// - /// Defer a mark. A withdrawal (Known: false) is never dropped — review round 2 N1: staying KNOWN over a - /// lost withdrawal is the unsafe direction, and withdrawals are bounded by connectivity edges. A known mark - /// beyond is dropped (unknown is safe) and its source is remembered so the sender hears - /// of it at replay (N2). + /// Defer a mark, per condition: a later mark of the same condition replaces the earlier (the later one is what + /// the live path leaves). A withdrawal (Known: false) is never dropped — review round 2 N1: staying KNOWN + /// over a lost withdrawal is the unsafe direction. It is bounded anyway: one entry per condition, so at most + /// the number of conditions in the address space (#926 made withdrawals routine, so the old "bounded by + /// connectivity edges" no longer held). A known mark for a NEW condition beyond marks is + /// dropped (unknown is safe) and its source is remembered so the sender hears of it at replay (N2). /// public void Mark(MarkConditionsKnown msg, IActorRef? sender) { - if (!msg.Known || _marks.Count < Capacity) _marks.Add((msg, sender)); - else _overflowedMarkSources[msg.Source] = sender; + foreach (var id in msg.ConditionIds) + { + if (string.IsNullOrEmpty(id)) continue; + var key = (msg.Realm, id); + if (msg.Known && !_marks.ContainsKey(key) && _marks.Count >= Capacity) + { + _overflowedMarkSources[msg.Source] = sender; + continue; + } + _marks[key] = new DeferredMark(msg.Source, id, msg.Realm, msg.Known, sender, ++_seq); + } } public IEnumerable<(string Source, IActorRef? Sender)> OverflowedMarkSources => @@ -1325,12 +1385,18 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers public bool Alarm(AlarmStateUpdate msg) { var key = (msg.Realm, msg.AlarmNodeId); - if (!Put(_alarms, key, msg)) return false; + if (!Put(_alarms, key, (msg, _seq + 1))) return false; + _seq++; _qualities.Remove(key); return true; } - public bool AlarmQuality(AlarmQualityUpdate msg) => Put(_qualities, (msg.Realm, msg.AlarmNodeId), msg); + public bool AlarmQuality(AlarmQualityUpdate msg) + { + if (!Put(_qualities, (msg.Realm, msg.AlarmNodeId), (msg, _seq + 1))) return false; + _seq++; + return true; + } public (List Values, List Statuses) VariableWrites(Func<(AddressSpaceRealm, string), bool> include) { @@ -1357,6 +1423,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers _lossySources.Clear(); _unattributedLoss = false; Dropped = 0; + _seq = 0; } private bool Put(Dictionary<(AddressSpaceRealm, string), T> map, (AddressSpaceRealm, string) key, T value) diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/Fakes/FakeOpcUaClientService.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/Fakes/FakeOpcUaClientService.cs index 151a58579..b63f64b6e 100644 --- a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/Fakes/FakeOpcUaClientService.cs +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/Fakes/FakeOpcUaClientService.cs @@ -199,6 +199,17 @@ public sealed class FakeOpcUaClientService : IOpcUaClientService public TimeSpan? LastMaximumAge { get; private set; } + /// The (node, attribute id) pairs passed to ReadAttributeAsync. + public List<(NodeId NodeId, uint AttributeId)> ReadAttributes { get; } = []; + + /// + public Task ReadAttributeAsync(NodeId nodeId, uint attributeId, CancellationToken ct = default) + { + ReadAttributes.Add((nodeId, attributeId)); + if (ReadException != null) throw ReadException; + return Task.FromResult(ReadValueResult); + } + public Task ReadValueAsync(NodeId nodeId, TimeSpan maximumAge, CancellationToken ct = default) { LastMaximumAge = maximumAge; diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/ReadCommandTests.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/ReadCommandTests.cs index 321c17a5e..86ff4a267 100644 --- a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/ReadCommandTests.cs +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/ReadCommandTests.cs @@ -42,6 +42,41 @@ public class ReadCommandTests service.ReadNodeIds.ShouldBeEmpty(); } + /// lmxopcua#921: --attribute Historizing reads that attribute (not the value) and labels the output. + [Fact] + public async Task Execute_ReadsTheRequestedAttribute() + { + var service = new FakeOpcUaClientService { ReadValueResult = new DataValue(new Variant(false), StatusCodes.Good) }; + var command = new ReadCommand(new FakeOpcUaClientServiceFactory(service)) + { + Url = "opc.tcp://localhost:4840", NodeId = "ns=2;s=Test", Attribute = "historizing" + }; + using var console = TestConsoleHelper.CreateConsole(); + await command.ExecuteAsync(console); + service.ReadAttributes.ShouldBe([(new NodeId("Test", 2), Attributes.Historizing)]); + service.ReadNodeIds.ShouldBeEmpty(); + var output = TestConsoleHelper.GetOutput(console); + output.ShouldContain("Attribute: historizing"); + output.ShouldContain("Value: False"); + } + + /// An unknown attribute, or --max-age with a non-Value attribute, is refused before connecting. + [Theory] + [InlineData("Bogus", 0)] + [InlineData("Historizing", 5000)] + public async Task Execute_RejectsAnUnknownAttributeOrMaxAgeOffTheValue(string attribute, double maxAge) + { + var service = new FakeOpcUaClientService(); + var command = new ReadCommand(new FakeOpcUaClientServiceFactory(service)) + { + Url = "opc.tcp://localhost:4840", NodeId = "ns=2;s=Test", Attribute = attribute, MaxAgeMilliseconds = maxAge + }; + using var console = TestConsoleHelper.CreateConsole(); + await Should.ThrowAsync(async () => await command.ExecuteAsync(console)); + service.ReadAttributes.ShouldBeEmpty(); + service.ReadNodeIds.ShouldBeEmpty(); + } + /// Verifies that execute prints the read value. [Fact] public async Task Execute_PrintsReadValue() diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataCodecTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataCodecTests.cs index 514422142..1ee96c60d 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataCodecTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataCodecTests.cs @@ -148,6 +148,31 @@ public sealed class GrpcDataCodecTests } } + /// + /// #916 defence in depth: the mapper never encodes stable_source_id (field 10), whatever a caller sets, and + /// drops it on decode so a consumer of a pre-fix origin never retains it. Engineering units (field 11) are the + /// positive control: an optional string in the same message still round-trips. + /// + [Fact] + public void Stable_source_id_is_never_encoded_and_is_dropped_on_decode_916() + { + var view = new DataView(new DataAddress("c", "urn:test", "string", "x"), DataRealm.Uns, null, 0, "subject"); + var metadata = new DataMetadata(view, "x", "Variable", DataValueKind.Int32, -1, [], false, DataOperations.Read, 1, + "8:driver-1Plant/Modbus/dev1/Speed", "rpm", false); + + var wire = DataProtoMapper.EncodeMetadata(metadata); + wire.HasStableSourceId.ShouldBeFalse(); + ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.Metadata.Parser.ParseFrom(wire.ToByteArray()).HasStableSourceId.ShouldBeFalse(); + wire.EngineeringUnits.ShouldBe("rpm"); + + // A pre-fix origin's bytes: field 10 present on the wire. + var legacy = wire.Clone(); + legacy.StableSourceId = "8:driver-1Plant/Modbus/dev1/Speed"; + var decoded = DataProtoMapper.DecodeMetadata(legacy); + decoded.StableSourceId.ShouldBeNull(); + decoded.EngineeringUnits.ShouldBe("rpm"); + } + [Fact] public void Array_metadata_rejects_missing_and_invalid_element_kind() { diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyAlarmSnapshotRefreshTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyAlarmSnapshotRefreshTests.cs new file mode 100644 index 000000000..e8813a5e9 --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyAlarmSnapshotRefreshTests.cs @@ -0,0 +1,392 @@ +using System.Runtime.CompilerServices; +using System.Threading.Channels; +using Google.Protobuf.WellKnownTypes; +using Grpc.Core; +using Shouldly; +using Xunit; +using ZB.MOM.WW.MxGateway.Contracts.Proto; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using AlarmTransitionKind = ZB.MOM.WW.MxGateway.Contracts.Proto.AlarmTransitionKind; +using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config; +using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime; + +namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime; + +/// +/// lmxopcua#925: a subscription that becomes live while the feed's stream is already past its +/// snapshot_complete sentinel (a changed alarm set, a reconnect that kept the session-less feed, or a change +/// during the snapshot phase — F4) is established by a re-read of the gateway's active-alarm set +/// (QueryActiveAlarms) instead of waiting, indefinitely, for the stream to reopen. The re-read is replayed as +/// restatements, never over a newer live message for the same alarm, and the signal follows its replay. +/// +[Trait("Feature", "GrpcData")] +[Trait("Phase", "A1")] +public sealed class GalaxyAlarmSnapshotRefreshTests +{ + private const string Tank1 = "Tank01.Level.HiHi"; + private const string Tank2 = "Tank02.Level.HiHi"; + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + /// The deploy-added condition is established without a stream reopen: re-read entry, then the signal. + [Fact] + public async Task A_resubscribe_on_a_live_stream_rereads_the_active_set_and_signals_after_its_entries() + { + await using var rig = new Rig(); + using var driver = NewDriver(rig.Feed); + var trace = Record(driver); + + var h1 = await driver.SubscribeAlarmsAsync([Tank1], Ct); + var s = await rig.NextStreamAsync(); + await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct); + await TestWait.UntilAsync(() => Count(trace) == 1, "the first sentinel's signal", () => Dump(trace)); + rig.QueryCount.ShouldBe(0, "the first subscription is covered by the stream's own sentinel"); + + await driver.UnsubscribeAlarmsAsync(h1, Ct); + await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct); + var q = await rig.NextQueryAsync(); + await Task.Delay(100, Ct); + Count(trace).ShouldBe(1, "no signal before the re-read completed"); + q.Complete(Entry(Tank2, AlarmConditionState.Active)); + + await TestWait.UntilAsync(() => Count(trace) == 3, "the re-read entry then the signal", () => Dump(trace)); + Snapshot(trace).ShouldBe(["signal:" + Tank1, "event:" + Tank2 + ":Retrigger:restatement", $"signal:{Tank1},{Tank2}"]); + rig.StreamOpens.ShouldBe(1, "the stream was not reopened"); + } + + /// + /// No phantom transition: a live message delivered after the re-read was issued is at least as new as the re-read's + /// view of that alarm, so the re-read's (older) entry for it is not replayed. Positive control: the other alarm's + /// entry in the same re-read IS replayed. + /// + [Fact] + public async Task A_live_transition_after_the_reread_was_issued_supersedes_its_entry_for_that_alarm() + { + await using var rig = new Rig(); + using var driver = NewDriver(rig.Feed); + var trace = Record(driver); + + var h1 = await driver.SubscribeAlarmsAsync([Tank1], Ct); + var s = await rig.NextStreamAsync(); + await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct); + await TestWait.UntilAsync(() => Count(trace) == 1, "the first sentinel's signal", () => Dump(trace)); + + await driver.UnsubscribeAlarmsAsync(h1, Ct); + await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct); + var q = await rig.NextQueryAsync(); + // While the query is in flight Tank2 clears on the live stream; the query's view still has it Active. + await s.WriteAsync(Transition(Tank2, AlarmTransitionKind.Clear), Ct); + await TestWait.UntilAsync(() => Count(trace) == 2, "the live clear", () => Dump(trace)); + q.Complete(Entry(Tank1, AlarmConditionState.ActiveAcked), Entry(Tank2, AlarmConditionState.Active)); + + await TestWait.UntilAsync(() => Count(trace) == 4, "the re-read's Tank1 entry then the signal", () => Dump(trace)); + await Task.Delay(100, Ct); + Snapshot(trace).ShouldBe([ + "signal:" + Tank1, + "event:" + Tank2 + ":Clear:live", + "event:" + Tank1 + ":ActiveAcknowledged:restatement", + $"signal:{Tank1},{Tank2}", + ]); + } + + /// + /// Review r1 #1: an Acknowledge carries only the ack dimension, so it does not supersede the re-read's view of + /// the alarm's ACTIVE state. Tank2 is Active+unacked when the query reads it; an operator acks it before the + /// replay ⇒ the replay must project Active+acked (not skip it and then signal a cold, inactive condition known). + /// + [Fact] + public async Task An_acknowledge_during_the_reread_merges_into_its_entry_instead_of_superseding_it() + { + await using var rig = new Rig(); + using var driver = NewDriver(rig.Feed); + var trace = Record(driver); + + var h1 = await driver.SubscribeAlarmsAsync([Tank1], Ct); + var s = await rig.NextStreamAsync(); + await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct); + await TestWait.UntilAsync(() => Count(trace) == 1, "the first sentinel's signal", () => Dump(trace)); + + await driver.UnsubscribeAlarmsAsync(h1, Ct); + await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct); + var q = await rig.NextQueryAsync(); + await s.WriteAsync(Transition(Tank2, AlarmTransitionKind.Acknowledge), Ct); + await TestWait.UntilAsync(() => Count(trace) == 2, "the live acknowledge", () => Dump(trace)); + q.Complete(Entry(Tank2, AlarmConditionState.Active)); + + await TestWait.UntilAsync(() => Count(trace) == 4, "the merged entry then the signal", () => Dump(trace)); + Snapshot(trace).ShouldBe([ + "signal:" + Tank1, + "event:" + Tank2 + ":Acknowledge:live", + "event:" + Tank2 + ":ActiveAcknowledged:restatement", + $"signal:{Tank1},{Tank2}", + ]); + } + + /// + /// Review r1 #2: the stream reopens while the query is in flight. An alarm that cleared in the gap is simply + /// absent from the reopened stream's snapshot (never "touched"), so the query's stale Active entry must NOT be + /// replayed, and the re-read must not signal — the reopened stream's own sentinel covers the subscription. + /// + [Fact] + public async Task A_stream_reopen_during_the_reread_drops_its_replay_and_its_signal() + { + await using var rig = new Rig(); + using var driver = NewDriver(rig.Feed); + var trace = Record(driver); + + var h1 = await driver.SubscribeAlarmsAsync([Tank1], Ct); + var s = await rig.NextStreamAsync(); + await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct); + await TestWait.UntilAsync(() => Count(trace) == 1, "the first sentinel's signal", () => Dump(trace)); + + await driver.UnsubscribeAlarmsAsync(h1, Ct); + await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct); + var q = await rig.NextQueryAsync(); + s.TryComplete(new InvalidOperationException("gateway stream fault")); + var s2 = await rig.NextStreamAsync(); + await s2.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct); // Tank2 cleared in the gap: absent + await TestWait.UntilAsync(() => Count(trace) == 2, "the reopened stream's signal", () => Dump(trace)); + q.Complete(Entry(Tank2, AlarmConditionState.Active)); // stale: read before the clear + + await Task.Delay(200, Ct); + Snapshot(trace).ShouldBe(["signal:" + Tank1, $"signal:{Tank1},{Tank2}"], + "no phantom Active from the stale re-read, and no second signal"); + rig.QueryCount.ShouldBe(1, "positive control: the re-read really ran"); + } + + /// F4: a subscription changed during the snapshot phase is re-read at the sentinel instead of waiting for a reopen. + [Fact] + public async Task A_sentinel_under_an_earlier_subscription_triggers_a_reread_that_signals() + { + await using var rig = new Rig(); + using var driver = NewDriver(rig.Feed); + var trace = Record(driver); + + var first = await driver.SubscribeAlarmsAsync([Tank1], Ct); + var s = await rig.NextStreamAsync(); + await driver.UnsubscribeAlarmsAsync(first, Ct); + await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct); // snapshot phase still running: no re-read yet + await Task.Delay(100, Ct); + rig.QueryCount.ShouldBe(0, "the stream has not delivered its sentinel, so the subscribe does not re-read"); + + await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct); + var q = await rig.NextQueryAsync(); + Count(trace).ShouldBe(0, "the mismatched sentinel itself still does not signal"); + q.Complete(); + + await TestWait.UntilAsync(() => Count(trace) == 1, "the re-read's signal", () => Dump(trace)); + Snapshot(trace).ShouldBe([$"signal:{Tank1},{Tank2}"]); + } + + /// + /// A failed re-read retries a bounded number of times, then gives up WITHOUT signalling (the conditions stay + /// unknown — F5 diagnoses them). Positive control: the next stream's sentinel still signals. + /// + [Fact] + public async Task A_failing_reread_retries_boundedly_and_never_signals() + { + await using var rig = new Rig(); + using var driver = NewDriver(rig.Feed); + driver.AlarmSnapshotRefreshRetryDelay = TimeSpan.FromMilliseconds(10); + var trace = Record(driver); + + var h1 = await driver.SubscribeAlarmsAsync([Tank1], Ct); + var s = await rig.NextStreamAsync(); + await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct); + await TestWait.UntilAsync(() => Count(trace) == 1, "the first sentinel's signal", () => Dump(trace)); + + await driver.UnsubscribeAlarmsAsync(h1, Ct); + await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct); + for (var i = 0; i < GalaxyDriver.AlarmSnapshotRefreshAttempts; i++) + (await rig.NextQueryAsync()).Fail(new RpcException(new Status(StatusCode.Unavailable, "gateway busy"))); + await Task.Delay(200, Ct); + rig.QueryCount.ShouldBe(GalaxyDriver.AlarmSnapshotRefreshAttempts); + Count(trace).ShouldBe(1, "a failed re-read never signals"); + + s.TryComplete(new InvalidOperationException("reopen")); + var s2 = await rig.NextStreamAsync(); + await s2.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct); + await TestWait.UntilAsync(() => Count(trace) == 2, "the reopened stream's signal", () => Dump(trace)); + Snapshot(trace)[1].ShouldBe($"signal:{Tank1},{Tank2}"); + } + + /// An old gateway without the RPC: one attempt, no retry, no signal. + [Fact] + public async Task An_unimplemented_query_is_not_retried() + { + await using var rig = new Rig(); + using var driver = NewDriver(rig.Feed); + driver.AlarmSnapshotRefreshRetryDelay = TimeSpan.FromMilliseconds(10); + var trace = Record(driver); + + var h1 = await driver.SubscribeAlarmsAsync([Tank1], Ct); + var s = await rig.NextStreamAsync(); + await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct); + await TestWait.UntilAsync(() => Count(trace) == 1, "the first sentinel's signal", () => Dump(trace)); + + await driver.UnsubscribeAlarmsAsync(h1, Ct); + await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct); + (await rig.NextQueryAsync()).Fail(new RpcException(new Status(StatusCode.Unimplemented, "no such method"))); + await Task.Delay(200, Ct); + rig.QueryCount.ShouldBe(1); + Count(trace).ShouldBe(1); + } + + /// + /// Bounded: a burst of re-subscribes while a re-read is in flight collapses into ONE follow-up re-read, and only + /// the follow-up (made under the subscription that is live at the end) signals. + /// + [Fact] + public async Task Resubscribes_during_a_reread_coalesce_into_one_followup() + { + await using var rig = new Rig(); + using var driver = NewDriver(rig.Feed); + var trace = Record(driver); + + var h = await driver.SubscribeAlarmsAsync([Tank1], Ct); + var s = await rig.NextStreamAsync(); + await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct); + await TestWait.UntilAsync(() => Count(trace) == 1, "the first sentinel's signal", () => Dump(trace)); + + await driver.UnsubscribeAlarmsAsync(h, Ct); + h = await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct); + var q1 = await rig.NextQueryAsync(); + for (var i = 0; i < 5; i++) + { + await driver.UnsubscribeAlarmsAsync(h, Ct); + h = await driver.SubscribeAlarmsAsync(i % 2 == 0 ? [Tank2] : [Tank1, Tank2], Ct); + } + q1.Complete(); + var q2 = await rig.NextQueryAsync(); + q2.Complete(); + + await TestWait.UntilAsync(() => Count(trace) == 2, "the follow-up's signal", () => Dump(trace)); + await Task.Delay(200, Ct); + rig.QueryCount.ShouldBe(2, "five re-subscribes during one re-read coalesce into one follow-up"); + Snapshot(trace).ShouldBe(["signal:" + Tank1, "signal:" + Tank2], + "the first re-read was made under a replaced subscription, so only the follow-up signals — for the live set"); + } + + private static int Count(List trace) { lock (trace) return trace.Count; } + + private static string[] Snapshot(List trace) { lock (trace) return trace.ToArray(); } + + private static string Dump(List trace) { lock (trace) return string.Join(" | ", trace); } + + private static List Record(GalaxyDriver driver) + { + var trace = new List(); + driver.OnAlarmEvent += (_, e) => + { + lock (trace) trace.Add($"event:{e.ConditionId}:{e.Kind}:{(e.IsRestatement ? "restatement" : "live")}"); + }; + driver.InitialAlarmStateDelivered += (_, e) => + { + lock (trace) trace.Add("signal:" + string.Join(',', e.ConditionIds)); + }; + return trace; + } + + private static ActiveAlarmSnapshot Entry(string reference, AlarmConditionState state) => new() + { + AlarmFullReference = reference, + SourceObjectReference = reference.Split('.')[0], + AlarmTypeName = "AnalogLimitAlarm.HiHi", + Severity = 750, + CurrentState = state, + Category = "Process", + Description = "Tank high-high level", + LastTransitionTimestamp = Timestamp.FromDateTime(DateTime.UtcNow), + }; + + private static AlarmFeedMessage Transition(string reference, AlarmTransitionKind kind) => new() + { + Transition = new OnAlarmTransitionEvent + { + AlarmFullReference = reference, + SourceObjectReference = reference.Split('.')[0], + AlarmTypeName = "AnalogLimitAlarm.HiHi", + TransitionKind = kind, + Severity = 750, + Description = "Tank high-high level", + TransitionTimestamp = Timestamp.FromDateTime(DateTime.UtcNow), + }, + }; + + private static GalaxyDriver NewDriver(IGalaxyAlarmFeed feed) + { + var options = new GalaxyDriverOptions( + new GalaxyGatewayOptions("http://localhost:5000", "literal-api-key"), + new GalaxyMxAccessOptions("RefreshTest"), + new GalaxyRepositoryOptions(), + new GalaxyReconnectOptions()); + return new GalaxyDriver( + driverInstanceId: "drv-1", + options: options, + hierarchySource: null, + alarmAcknowledger: null, + alarmFeed: feed, + ackCredentialResolver: FixedAckCredentialResolver.Fallback()); + } + + /// One scripted QueryActiveAlarms call: the test completes or fails it. + private sealed class ScriptedQuery + { + private readonly TaskCompletionSource _result = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public Task Result => _result.Task; + + public void Complete(params ActiveAlarmSnapshot[] entries) => _result.TrySetResult(entries); + + public void Fail(Exception ex) => _result.TrySetException(ex); + } + + /// A real feed over test-written streams and a scripted query. + private sealed class Rig : IAsyncDisposable + { + private readonly Channel> _opened = Channel.CreateUnbounded>(); + private readonly Channel _queries = Channel.CreateUnbounded(); + private int _queryCount; + private int _streamOpens; + + public Rig() + { + Feed = new GatewayGalaxyAlarmFeed((_, ct) => + { + Interlocked.Increment(ref _streamOpens); + var c = Channel.CreateUnbounded(); + _opened.Writer.TryWrite(c); + return c.Reader.ReadAllAsync(ct); + }, clientName: "RefreshTest", reconnectDelay: TimeSpan.FromMilliseconds(10), queryFactory: QueryAsync); + } + + public GatewayGalaxyAlarmFeed Feed { get; } + + public int QueryCount => Volatile.Read(ref _queryCount); + + public int StreamOpens => Volatile.Read(ref _streamOpens); + + private async IAsyncEnumerable QueryAsync( + QueryActiveAlarmsRequest request, [EnumeratorCancellation] CancellationToken ct) + { + Interlocked.Increment(ref _queryCount); + var q = new ScriptedQuery(); + _queries.Writer.TryWrite(q); + foreach (var entry in await q.Result.WaitAsync(ct)) yield return entry; + } + + public async Task> NextStreamAsync() + { + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + return (await _opened.Reader.ReadAsync(cts.Token)).Writer; + } + + public async Task NextQueryAsync() + { + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + return await _queries.Reader.ReadAsync(cts.Token); + } + + public ValueTask DisposeAsync() => Feed.DisposeAsync(); + } +} diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.IntegrationTests/OpcUaClientRefreshOverflowLiveTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.IntegrationTests/OpcUaClientRefreshOverflowLiveTests.cs new file mode 100644 index 000000000..7fb2ac904 --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.IntegrationTests/OpcUaClientRefreshOverflowLiveTests.cs @@ -0,0 +1,126 @@ +using System.Diagnostics.Metrics; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.Observability; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; + +namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.IntegrationTests; + +/// +/// #926 live gate against opc-plc --alm: an alarm event item whose queue is far smaller than one +/// ConditionRefresh replay overflows on the REAL server. The server's EventQueueOverflowEventType must reach +/// the driver (it comes from the Server object, past the source filter), the RefreshEnd must NOT signal, and the +/// driver's re-refresh is bounded. The positive control is the same driver with the production queue, which signals. +/// Read-only against the fixture. +/// +[Collection(OpcPlcCollection.Name)] +[Trait("Category", "LiveIntegration")] +[Trait("Feature", "GrpcData")] +[Trait("Issue", "926")] +public sealed class OpcUaClientRefreshOverflowLiveTests(OpcPlcFixture sim, ITestOutputHelper output) +{ + /// + /// discardOldest: false (production): the overflowing replay loses its RefreshEnd too (the newest events + /// are dropped), so nothing can signal. true: the RefreshEnd survives but the RefreshStart and the head of + /// the replay do not — the case a naive RefreshEnd signal gets wrong. (Observed on the fixture's opc-plc, 2026-11-28: + /// with discardOldest false a queue of 1 yields overflow notices; a queue of 2 yielded none at all — and no + /// RefreshEnd either, so it still never signalled.) + /// + [Theory] + [InlineData(false, 1u)] + [InlineData(true, 2u)] + public async Task Overflowing_refresh_never_signals_and_re_refresh_is_bounded(bool discardOldest, uint queueSize) + { + if (sim.SkipReason is not null) Assert.Skip(sim.SkipReason); + var ct = TestContext.Current.CancellationToken; + var id = $"opcua-926-live-{Guid.NewGuid():N}"; + using var counts = new EventCounts(id); + + await using var drv = new OpcUaClientDriver(OpcPlcProfile.BuildOptions(sim.EndpointUrl), id) + { + AlarmEventItemQueueSize = queueSize, // one replay = RefreshStart + every retained condition + RefreshEnd + AlarmEventItemDiscardOldest = discardOldest, + AlarmRefreshRetryBaseDelay = TimeSpan.FromMilliseconds(250), + }; + var signals = 0; + drv.InitialAlarmStateDelivered += (_, _) => Interlocked.Increment(ref signals); + drv.OnAlarmEvent += (_, _) => { }; + await drv.InitializeAsync("{}", ct); + await drv.SubscribeAlarmsAsync(["Plant/opc/plc/926"], ct); + + // 1 + 3 retries, back-off 0.25 + 0.5 + 1 s; allow the replays to arrive. + var until = DateTime.UtcNow.AddSeconds(20); + while (counts.Get(OpcUaClientDiagnostics.AlarmRefreshLossy) < 1 + OpcUaClientDriver.MaxAlarmRefreshRetries + && DateTime.UtcNow < until) + await Task.Delay(100, ct); + await Task.Delay(3000, ct); // quiet window: nothing further may arrive + output.WriteLine($"discardOldest={discardOldest} overflows={counts.Get(OpcUaClientDiagnostics.AlarmEventQueueOverflow)} " + + $"lossyRefreshEnds={counts.Get(OpcUaClientDiagnostics.AlarmRefreshLossy)} signals={signals}"); + + counts.Get(OpcUaClientDiagnostics.AlarmEventQueueOverflow).ShouldBeGreaterThan(0, + "the server's EventQueueOverflowEventType reached the driver past the source filter"); + Volatile.Read(ref signals).ShouldBe(0, "a lossy replay must never declare its conditions known"); + if (discardOldest) + counts.Get(OpcUaClientDiagnostics.AlarmRefreshLossy).ShouldBeGreaterThan(0, + "the RefreshEnd arrived and was refused as lossy (its RefreshStart was discarded)"); + counts.Get(OpcUaClientDiagnostics.AlarmRefreshLossy).ShouldBeLessThanOrEqualTo( + 1 + OpcUaClientDriver.MaxAlarmRefreshRetries, "re-refresh is bounded — no refresh storm"); + await drv.ShutdownAsync(ct); + } + + [Fact] + public async Task Production_queue_refresh_signals() + { + if (sim.SkipReason is not null) Assert.Skip(sim.SkipReason); + var ct = TestContext.Current.CancellationToken; + var id = $"opcua-926-live-ctl-{Guid.NewGuid():N}"; + using var counts = new EventCounts(id); + await using var drv = new OpcUaClientDriver(OpcPlcProfile.BuildOptions(sim.EndpointUrl), id); + var signalled = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + drv.InitialAlarmStateDelivered += (_, e) => signalled.TrySetResult(e); + drv.OnAlarmEvent += (_, _) => { }; + await drv.InitializeAsync("{}", ct); + await drv.SubscribeAlarmsAsync(["Plant/opc/plc/926"], ct); + + (await signalled.Task.WaitAsync(TimeSpan.FromSeconds(30), ct)).Unsignalable.ShouldBeFalse(); + counts.Get(OpcUaClientDiagnostics.AlarmEventQueueOverflow).ShouldBe(0); + counts.Get(OpcUaClientDiagnostics.AlarmRefreshLossy).ShouldBe(0); + await drv.ShutdownAsync(ct); + } + + /// Counts otopcua.driver.opcuaclient.events for ONE driver instance (the instance tag filters out + /// parallel tests' measurements). + private sealed class EventCounts : IDisposable + { + private readonly MeterListener _listener = new(); + private readonly Dictionary _counts = new(); + + public EventCounts(string driverInstanceId) + { + // Run the telemetry type's static initializer FIRST: if the counter is created while this listener is + // live, InstrumentPublished runs inside that initializer, where the field still reads null — the counter + // would never be enabled and every count would read 0 (seen when this class ran alone). + var counter = OtOpcUaTelemetry.OpcUaClientEvents; + _listener.InstrumentPublished = (inst, l) => + { + if (ReferenceEquals(inst, counter)) l.EnableMeasurementEvents(inst); + }; + _listener.SetMeasurementEventCallback((_, value, tags, _) => + { + string? instance = null, evt = null; + foreach (var t in tags) + { + if (t.Key == OtOpcUaTelemetry.PollOverrunDriverInstanceTag) instance = t.Value as string; + else if (t.Key == "event") evt = t.Value as string; + } + if (instance != driverInstanceId || evt is null) return; + lock (_counts) _counts[evt] = _counts.GetValueOrDefault(evt) + value; + }); + _listener.Start(); + } + + public long Get(string evt) { lock (_counts) return _counts.GetValueOrDefault(evt); } + + public void Dispose() => _listener.Dispose(); + } +} diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientInitialAlarmStateSignalTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientInitialAlarmStateSignalTests.cs index 01c4f3c34..de86380e9 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientInitialAlarmStateSignalTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientInitialAlarmStateSignalTests.cs @@ -53,7 +53,8 @@ public sealed class OpcUaClientInitialAlarmStateSignalTests drv.RouteAlarmEvent(Marker(ObjectTypeIds.RefreshEndEventType), index, new StrayHandle()); trace.ShouldBeEmpty(); - // Positive control: the live subscription's RefreshEnd does signal. + // Positive control: the live subscription's bracket does signal. + drv.RouteAlarmEvent(Marker(ObjectTypeIds.RefreshStartEventType), index, live); drv.RouteAlarmEvent(Marker(ObjectTypeIds.RefreshEndEventType), index, live); trace.ShouldBe(["signal:" + Trip1]); } @@ -97,6 +98,8 @@ public sealed class OpcUaClientInitialAlarmStateSignalTests var handle = drv.AddAlarmSubscriptionForTest([Trip1]); var index = new Dictionary { ["ns=3;s=Alarms.Trip1"] = Trip1 }; + // #926: the bracket's RefreshStart was routed in an earlier publish response. + drv.RouteAlarmEvent(Marker(ObjectTypeIds.RefreshStartEventType), index, handle); var replay = await SdkReplay.DeliverAsync(drv.BuildAlarmSubscriptionOptions(1), [(2u, Marker(ObjectTypeIds.RefreshEndEventType)), (1u, Condition(active: true, acked: false))], fields => drv.RouteAlarmEvent(fields, index, handle)); @@ -105,18 +108,18 @@ public sealed class OpcUaClientInitialAlarmStateSignalTests trace.ShouldBe(["event:" + Trip1 + ":Retrigger", "signal:" + Trip1]); } - private static List Record(OpcUaClientDriver drv) + internal static List Record(OpcUaClientDriver drv) { var trace = new List(); drv.OnAlarmEvent += (_, e) => { lock (trace) trace.Add($"event:{e.ConditionId}:{e.Kind}"); }; drv.InitialAlarmStateDelivered += (_, e) => { - lock (trace) trace.Add("signal:" + string.Join(',', e.ConditionIds)); + lock (trace) trace.Add((e.Withdrawn ? "withdraw:" : "signal:") + string.Join(',', e.ConditionIds)); }; return trace; } - private static List Marker(NodeId type) => + internal static List Marker(NodeId type) => [ Variant.From(new byte[] { 9 }.ToByteString()), new Variant(type), @@ -130,7 +133,7 @@ public sealed class OpcUaClientInitialAlarmStateSignalTests Variant.Null, ]; - private static List Condition(bool active, bool acked) => + internal static List Condition(bool active, bool acked) => [ Variant.From(new byte[] { 1 }.ToByteString()), new Variant(new NodeId("TripAlarmType", 3)), @@ -227,7 +230,7 @@ internal static class SdkReplay return delivered; } - private static object ToParam(System.Reflection.MethodInfo save, uint[] available) + internal static object ToParam(System.Reflection.MethodInfo save, uint[] available) { var t = save.GetParameters()[0].ParameterType; if (t.IsInstanceOfType(available)) return available; diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientRefreshBracketLossTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientRefreshBracketLossTests.cs new file mode 100644 index 000000000..343eacf09 --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientRefreshBracketLossTests.cs @@ -0,0 +1,547 @@ +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using static ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests.OpcUaClientInitialAlarmStateSignalTests; + +namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests; + +/// +/// #926 — a RefreshEnd declares the conditions it covers state-known (grpc-data A1), so it may signal only for a +/// LOSSLESS RefreshStart…RefreshEnd bracket. A loss inside the bracket (the server's EventQueueOverflowEventType, a +/// RefreshRequired, a publish-sequence gap the SDK skipped) or a missing RefreshStart suppresses the signal +/// and re-runs ConditionRefresh, bounded; a never-signal outcome leaves the conditions unknown (Uncertain). +/// +[Trait("Category", "Unit")] +[Trait("Feature", "GrpcData")] +[Trait("Issue", "926")] +public sealed class OpcUaClientRefreshBracketLossTests +{ + private const string Trip1 = "Plant/opc/plc/Trip1"; + + /// The authored source index: the overflow notice (SourceNode = Server) is NOT in it, so this also proves + /// the notice is seen before the source filter. + private static readonly Dictionary Index = new() { ["ns=3;s=Alarms.Trip1"] = Trip1 }; + + private static (OpcUaClientDriver Drv, List Trace, IAlarmSubscriptionHandle Handle, RetryProbe Retries) NewDriver(string id) + { + var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), id) + { + // Long enough that a replay's own (lossy) RefreshEnd is routed before its re-refresh starts, as in production + // (2 s back-off vs. a 500 ms publishing interval); short enough to keep the suite fast. + AlarmRefreshRetryBaseDelay = TimeSpan.FromMilliseconds(100), + }; + var trace = Record(drv); + var handle = drv.AddAlarmSubscriptionForTest([Trip1]); + var retries = new RetryProbe(); + drv.AlarmRefreshRetryInvokerForTest = (_, _) => { retries.Hit(); return Task.CompletedTask; }; + return (drv, trace, handle, retries); + } + + private static void Route(OpcUaClientDriver drv, IAlarmSubscriptionHandle h, NodeId type) => + drv.RouteAlarmEvent(Marker(type), Index, h); + + /// The issue's scenario: refreshed events overflowed the upstream queue, RefreshEnd still arrived. No signal + /// (the condition stays unknown), a re-refresh is run, and ITS clean bracket signals. + [Fact] + public async Task Overflow_inside_the_bracket_suppresses_the_signal_and_re_refreshes() + { + var (drv, trace, h, retries) = NewDriver("opcua-926-overflow"); + using var _ = drv; + + Route(drv, h, ObjectTypeIds.RefreshStartEventType); + drv.RouteAlarmEvent(Condition(active: false, acked: true), Index, h); // what survived; the active one was lost + Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); + Route(drv, h, ObjectTypeIds.RefreshEndEventType); + + trace.ShouldNotContain(t => t.StartsWith("signal:"), "a lossy replay must never declare its conditions known"); + await retries.WaitForAsync(1); + + // The re-refresh's replay is lossless ⇒ signalled (positive control: the bracket CAN signal). + Route(drv, h, ObjectTypeIds.RefreshStartEventType); + drv.RouteAlarmEvent(Condition(active: true, acked: false), Index, h); + Route(drv, h, ObjectTypeIds.RefreshEndEventType); + trace.Last().ShouldBe("signal:" + Trip1); + trace.Count(t => t.StartsWith("signal:")).ShouldBe(1); + retries.Count.ShouldBe(1, "one loss ⇒ one re-refresh (the lossy RefreshEnd does not request a second)"); + } + + /// A bracket whose RefreshStart never arrived (lost with the head of the replay) does not signal. + [Fact] + public async Task RefreshEnd_without_its_RefreshStart_does_not_signal() + { + var (drv, trace, h, retries) = NewDriver("opcua-926-nostart"); + using var _ = drv; + + Route(drv, h, ObjectTypeIds.RefreshEndEventType); + trace.ShouldBeEmpty(); + await retries.WaitForAsync(1); + } + + /// A RefreshRequired inside the bracket is a loss; its own sweep is the re-refresh, so the driver adds none. + [Fact] + public async Task RefreshRequired_inside_the_bracket_suppresses_the_signal() + { + var (drv, trace, h, retries) = NewDriver("opcua-926-required"); + using var _ = drv; + + Route(drv, h, ObjectTypeIds.RefreshStartEventType); + Route(drv, h, ObjectTypeIds.RefreshRequiredEventType); + Route(drv, h, ObjectTypeIds.RefreshEndEventType); + trace.ShouldBeEmpty(); + await Task.Delay(200, TestContext.Current.CancellationToken); + retries.Count.ShouldBe(0); + + // Positive control: the next clean bracket signals. + Route(drv, h, ObjectTypeIds.RefreshStartEventType); + Route(drv, h, ObjectTypeIds.RefreshEndEventType); + trace.ShouldBe(["signal:" + Trip1]); + } + + /// An overflow OUTSIDE a bracket lost live events: a re-refresh repairs them (and its bracket signals). + [Fact] + public async Task Overflow_outside_a_bracket_requests_a_re_refresh() + { + var (drv, trace, h, retries) = NewDriver("opcua-926-live-overflow"); + using var _ = drv; + + Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); + await retries.WaitForAsync(1); + trace.ShouldBeEmpty("the overflow notice is never projected as an alarm"); + + Route(drv, h, ObjectTypeIds.RefreshStartEventType); + Route(drv, h, ObjectTypeIds.RefreshEndEventType); + trace.ShouldBe(["signal:" + Trip1]); + } + + /// Liveness: a re-refresh whose own RefreshStart is lost (the queue is still full, so only overflow notices + /// arrive and no bracket ever opens) can still request the next one, up to the bound. + [Fact] + public async Task A_re_refresh_whose_RefreshStart_is_lost_can_request_the_next() + { + var (drv, trace, h, retries) = NewDriver("opcua-926-start-lost"); + using var _ = drv; + + for (var n = 1; n <= OpcUaClientDriver.MaxAlarmRefreshRetries; n++) + { + Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); + Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); // coalesced into the same request + await retries.WaitForAsync(n); + } + Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); + await Task.Delay(500, TestContext.Current.CancellationToken); + retries.Count.ShouldBe(OpcUaClientDriver.MaxAlarmRefreshRetries); + trace.ShouldBeEmpty(); + } + + /// A structurally lossy upstream (every replay overflows) costs at most + /// re-refreshes, then never signals — the conditions stay unknown. A later clean bracket signals and resets the budget. + [Fact] + public async Task Re_refresh_is_bounded_and_the_budget_resets_on_a_clean_bracket() + { + var (drv, trace, h, retries) = NewDriver("opcua-926-bounded"); + using var _ = drv; + + for (var i = 0; i < OpcUaClientDriver.MaxAlarmRefreshRetries + 3; i++) + { + Route(drv, h, ObjectTypeIds.RefreshStartEventType); + Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); + Route(drv, h, ObjectTypeIds.RefreshEndEventType); + await retries.WaitForAsync(Math.Min(i + 1, OpcUaClientDriver.MaxAlarmRefreshRetries)); + } + await Task.Delay(200, TestContext.Current.CancellationToken); + retries.Count.ShouldBe(OpcUaClientDriver.MaxAlarmRefreshRetries, "no refresh storm"); + trace.ShouldBeEmpty("never-signal is the safe outcome: Uncertain, not known-inactive"); + + // A lossless bracket (a RefreshRequired sweep, a reconnect) signals and gives the budget back. + Route(drv, h, ObjectTypeIds.RefreshStartEventType); + Route(drv, h, ObjectTypeIds.RefreshEndEventType); + trace.ShouldBe(["signal:" + Trip1]); + Route(drv, h, ObjectTypeIds.RefreshStartEventType); + Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); + await retries.WaitForAsync(OpcUaClientDriver.MaxAlarmRefreshRetries + 1); + } + + /// A publish-sequence gap inside a bracket (a message the SDK gave up on) suppresses its signal; contiguous + /// numbers, a repeat (several events in one message), an unknown number and the wrap are no loss. + [Fact] + public async Task Sequence_gap_inside_the_bracket_suppresses_the_signal() + { + var (drv, trace, h, retries) = NewDriver("opcua-926-seqgap"); + using var _ = drv; + + drv.NoteAlarmMessageSequence(h, 9); + Route(drv, h, ObjectTypeIds.RefreshStartEventType); + drv.NoteAlarmMessageSequence(h, 10); + drv.NoteAlarmMessageSequence(h, 10); // a second event of the same message + drv.NoteAlarmMessageSequence(h, 0); // unknown (no message): ignored + drv.NoteAlarmMessageSequence(h, 11); + Route(drv, h, ObjectTypeIds.RefreshEndEventType); + trace.ShouldBe(["signal:" + Trip1], "no loss inside that bracket"); + + retries.Count.ShouldBe(0); + + Route(drv, h, ObjectTypeIds.RefreshStartEventType); + drv.NoteAlarmMessageSequence(h, 12); + drv.NoteAlarmMessageSequence(h, 14); // message 13 lost + Route(drv, h, ObjectTypeIds.RefreshEndEventType); + trace.Count(t => t.StartsWith("signal:")).ShouldBe(1, "the replay with a lost message did not signal"); + await retries.WaitForAsync(1); + } + + /// The sequence-number wrap (… uint.MaxValue, 1 …) is contiguous. + [Fact] + public void Sequence_wrap_is_contiguous() + { + var (drv, trace, h, retries) = NewDriver("opcua-926-seqwrap"); + using var _ = drv; + + drv.NoteAlarmMessageSequence(h, uint.MaxValue); + Route(drv, h, ObjectTypeIds.RefreshStartEventType); + drv.NoteAlarmMessageSequence(h, 1); + drv.NoteAlarmMessageSequence(h, 2); + Route(drv, h, ObjectTypeIds.RefreshEndEventType); + trace.ShouldBe(["signal:" + Trip1]); + retries.Count.ShouldBe(0); + } + + /// Review r1 #6: an OLDER sequence number (a stray late message) is ignored and not recorded, so the next + /// in-order message is not a second, false gap. + [Fact] + public void An_older_sequence_number_is_ignored_and_not_recorded() + { + var (drv, trace, h, retries) = NewDriver("opcua-926-seqold"); + using var _ = drv; + + drv.NoteAlarmMessageSequence(h, 20); + Route(drv, h, ObjectTypeIds.RefreshStartEventType); + drv.NoteAlarmMessageSequence(h, 18); // late duplicate of an old message + drv.NoteAlarmMessageSequence(h, 21); // in order relative to 20 + Route(drv, h, ObjectTypeIds.RefreshEndEventType); + trace.ShouldBe(["signal:" + Trip1]); + retries.Count.ShouldBe(0); + } + + /// Review r1 #1: a gap OUTSIDE a bracket can hold a live transition (a Raise) — it is a loss: withdraw + /// "known" (the subscription had signalled) and re-refresh, whose clean bracket signals again. + [Fact] + public async Task Sequence_gap_outside_a_bracket_withdraws_known_and_re_refreshes() + { + var (drv, trace, h, retries) = NewDriver("opcua-926-seqgap-live"); + using var _ = drv; + SignalClean(drv, h); + drv.NoteAlarmMessageSequence(h, 1); + drv.NoteAlarmMessageSequence(h, 2); + trace.ShouldBe(["signal:" + Trip1], "contiguous live messages are no loss"); + + drv.NoteAlarmMessageSequence(h, 4); // message 3 (a live Raise) lost + trace.ShouldBe(["signal:" + Trip1, "withdraw:" + Trip1]); + await retries.WaitForAsync(1); + + SignalClean(drv, h); + trace.ShouldBe(["signal:" + Trip1, "withdraw:" + Trip1, "signal:" + Trip1]); + } + + /// Review r1 #2: an overflow AFTER the conditions were declared known withdraws "known" — once, until a + /// clean bracket re-signals — and the episode gets its own retry budget. + [Fact] + public async Task Loss_after_the_signal_withdraws_known_once_until_a_clean_bracket() + { + var (drv, trace, h, retries) = NewDriver("opcua-926-withdraw"); + using var _ = drv; + + // Episode 1 spends its whole budget, then ends clean. + for (var i = 0; i < OpcUaClientDriver.MaxAlarmRefreshRetries; i++) + { + Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); + await retries.WaitForAsync(i + 1); + } + SignalClean(drv, h); + trace.ShouldBe(["signal:" + Trip1], "no withdrawal before anything was known"); + + // Episode 2: a live overflow withdraws, a second loss does not withdraw again, and retries are available. + Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); + Route(drv, h, ObjectTypeIds.RefreshRequiredEventType); + trace.ShouldBe(["signal:" + Trip1, "withdraw:" + Trip1]); + await retries.WaitForAsync(OpcUaClientDriver.MaxAlarmRefreshRetries + 1); + + SignalClean(drv, h); + trace.ShouldBe(["signal:" + Trip1, "withdraw:" + Trip1, "signal:" + Trip1]); + } + + /// A RefreshRequired after the signal withdraws "known" too. + [Fact] + public void RefreshRequired_after_the_signal_withdraws_known() + { + var (drv, trace, h, _) = NewDriver("opcua-926-required-withdraw"); + using var __ = drv; + SignalClean(drv, h); + Route(drv, h, ObjectTypeIds.RefreshRequiredEventType); + trace.ShouldBe(["signal:" + Trip1, "withdraw:" + Trip1]); + } + + /// Review r1 #3: a RefreshStart while a bracket is still open (its RefreshEnd never arrived) must not erase the + /// open bracket's loss; the overlapping start is itself a loss. + [Fact] + public async Task An_overlapping_RefreshStart_does_not_erase_the_loss() + { + var (drv, trace, h, retries) = NewDriver("opcua-926-nested"); + using var _ = drv; + + Route(drv, h, ObjectTypeIds.RefreshStartEventType); + Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); + await retries.WaitForAsync(1); + Route(drv, h, ObjectTypeIds.RefreshStartEventType); // the first RefreshEnd never arrived + Route(drv, h, ObjectTypeIds.RefreshEndEventType); + trace.ShouldBeEmpty("an End only signals when no overlapping / lossy bracket remains"); + + // Positive control: a bracket that opens on a closed one, lossless, signals. + Route(drv, h, ObjectTypeIds.RefreshStartEventType); + Route(drv, h, ObjectTypeIds.RefreshEndEventType); + trace.ShouldBe(["signal:" + Trip1]); + } + + /// Review r1 #4: a failed ConditionRefresh call (no RefreshEnd will come) is retried, bounded. + [Fact] + public async Task A_failed_ConditionRefresh_is_retried_bounded() + { + var (drv, trace, h, retries) = NewDriver("opcua-926-refresh-failed"); + using var _ = drv; + + for (var i = 0; i < OpcUaClientDriver.MaxAlarmRefreshRetries + 2; i++) + { + drv.ReportRefreshFailedForTest(h); + await retries.WaitForAsync(Math.Min(i + 1, OpcUaClientDriver.MaxAlarmRefreshRetries)); + } + await Task.Delay(300, TestContext.Current.CancellationToken); + retries.Count.ShouldBe(OpcUaClientDriver.MaxAlarmRefreshRetries); + trace.ShouldBeEmpty(); + } + + /// Review r1 #5: a retry scheduled WHILE the previous retry's refresh call runs keeps its pending flag (the + /// earlier retry's completion must not clear it), so a further loss before it starts is coalesced into it. + [Fact] + public async Task A_retry_scheduled_during_a_refresh_call_keeps_coalescing() + { + var (drv, trace, h, retries) = NewDriver("opcua-926-generation"); + using var _ = drv; + var first = true; + drv.AlarmRefreshRetryBaseDelay = TimeSpan.FromMilliseconds(300); + drv.AlarmRefreshRetryInvokerForTest = (_, _) => + { + retries.Hit(); + if (first) + { + first = false; + // A loss inside the first retry's call schedules the second retry. + Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); + } + return Task.CompletedTask; + }; + + Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); + await retries.WaitForAsync(1); + await Task.Delay(50, TestContext.Current.CancellationToken); // the first retry's finally has run + // Still pending ⇒ coalesced, not a third retry. (Before the generation token the first retry's finally cleared + // the second's pending flag, so this scheduled one more.) A failed refresh call schedules without the + // per-bracket request flag, so it exercises the pending flag alone. + drv.ReportRefreshFailedForTest(h); + await retries.WaitForAsync(2); + await Task.Delay(1500, TestContext.Current.CancellationToken); + retries.Count.ShouldBe(2); + trace.ShouldBeEmpty(); + } + + /// A spent budget is not a permanent give-up: after the cool-down a further loss gets a new budget. + [Fact] + public async Task A_spent_budget_renews_after_the_cooldown() + { + var (drv, _, h, retries) = NewDriver("opcua-926-cooldown"); + using var __ = drv; + drv.AlarmRefreshRetryCooldown = TimeSpan.FromSeconds(1); + + for (var i = 0; i < OpcUaClientDriver.MaxAlarmRefreshRetries; i++) + { + Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); + await retries.WaitForAsync(i + 1); + } + Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); + await Task.Delay(200, TestContext.Current.CancellationToken); + retries.Count.ShouldBe(OpcUaClientDriver.MaxAlarmRefreshRetries, "inside the cool-down: no more"); + + await Task.Delay(1500, TestContext.Current.CancellationToken); + Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); + await retries.WaitForAsync(OpcUaClientDriver.MaxAlarmRefreshRetries + 1); + } + + private static void SignalClean(OpcUaClientDriver drv, IAlarmSubscriptionHandle h) + { + Route(drv, h, ObjectTypeIds.RefreshStartEventType); + Route(drv, h, ObjectTypeIds.RefreshEndEventType); + } + + /// The overflow notice is never an alarm, even pass-through (no authored refs). + [Fact] + public void Overflow_notice_is_never_projected() + { + OpcUaClientDriver.ProjectEvent(Marker(ObjectTypeIds.EventQueueOverflowEventType), new Dictionary(), + new StrayHandle(), n => n.ToString(), (_, _) => { }).ShouldBeNull(); + // Positive control: a non-marker event from the same source projects pass-through. + OpcUaClientDriver.ProjectEvent(Marker(ObjectTypeIds.BaseEventType), new Dictionary(), + new StrayHandle(), n => n.ToString(), (_, _) => { }).ShouldNotBeNull(); + } + + /// The alarm event item asks for the deeper queue. + [Fact] + public void Alarm_event_queue_is_deep() => OpcUaClientDriver.AlarmEventQueueSize.ShouldBeGreaterThanOrEqualTo(10_000u); + + /// + /// Through a REAL SDK subscription with the driver's alarm options: the publish message carrying a refreshed + /// event (seq 3) is lost and its republish fails (not available). The SDK skips the gap and delivers the + /// RefreshEnd (seq 4) — reporting the skip to nothing observable: its Republish publish-state is raised + /// only in a worker pass that also delivers a message, which the gap prevents. The driver's own sequence check + /// () suppresses that RefreshEnd. + /// + [Fact] + public async Task Abandoned_publish_gap_suppresses_the_RefreshEnd_through_the_real_SDK() + { + var (drv, trace, h, retries) = NewDriver("opcua-926-sdk-gap"); + using var _ = drv; + + var order = await GapReplay.DeliverAsync(drv.BuildAlarmSubscriptionOptions(1), drv, h, Index, skip: 3); + + order.ShouldBe(["live:1", "start:2", "end:4"], "the SDK skipped the lost message and delivered the RefreshEnd"); + trace.ShouldNotContain(t => t.StartsWith("signal:"), "a replay with a lost message must not declare its conditions known"); + await retries.WaitForAsync(1); + } + + /// Positive control for the real-SDK test: the same replay with nothing lost signals. + [Fact] + public async Task Lossless_publish_sequence_signals_through_the_real_SDK() + { + var (drv, trace, h, retries) = NewDriver("opcua-926-sdk-nogap"); + using var _ = drv; + + var order = await GapReplay.DeliverAsync(drv.BuildAlarmSubscriptionOptions(1), drv, h, Index, skip: null); + + order.ShouldBe(["live:1", "start:2", "refreshed:3", "end:4"]); + trace.ShouldBe(["event:" + Trip1 + ":Retrigger", "signal:" + Trip1]); + retries.Count.ShouldBe(0); + } + + private sealed class StrayHandle : IAlarmSubscriptionHandle + { + public string DiagnosticId => "stray"; + } + + private sealed class RetryProbe + { + private int _count; + public int Count => Volatile.Read(ref _count); + public void Hit() => Interlocked.Increment(ref _count); + + public async Task WaitForAsync(int n) + { + var until = DateTime.UtcNow.AddSeconds(10); + while (Count < n && DateTime.UtcNow < until) await Task.Delay(10); + Count.ShouldBeGreaterThanOrEqualTo(n); + } + } + + /// + /// Feeds publish responses 1 (a live event), 2 (RefreshStart), 3 (a refreshed Active event), 4 (RefreshEnd) and + /// 5..8 (unrelated events) into a real SDK , routing every delivered event through the + /// driver's production entry. skip: a sequence number that never arrives and is not available for + /// republish. Returns the order of what was delivered (kind:sequence) up to the RefreshEnd. + /// + private static class GapReplay + { + public static async Task> DeliverAsync(SubscriptionOptions options, OpcUaClientDriver drv, + IAlarmSubscriptionHandle handle, Dictionary index, uint? skip) + { + var order = new List(); + var ended = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var subscription = new Subscription(telemetry: null!, options); + var item = new MonitoredItem(telemetry: null!, new MonitoredItemOptions + { + DisplayName = "Server/Events", + StartNodeId = ObjectIds.Server, + AttributeId = Attributes.EventNotifier, + Filter = new EventFilter(), + }); + item.Notification += (_, args) => + { + if (args.NotificationValue is not EventFieldList efl) return; + lock (order) + { + if (ended.Task.IsCompleted) return; + var seq = efl.Message?.SequenceNumber ?? 0; + var kind = UpstreamValueMapping.ToClr(efl.EventFields[1]) is NodeId t + ? t == ObjectTypeIds.RefreshStartEventType ? "start" + : t == ObjectTypeIds.RefreshEndEventType ? "end" + : seq == 3 ? "refreshed" : "live" + : "?"; + order.Add($"{kind}:{seq}"); + drv.RouteAlarmEventFieldList(efl, index, handle); + if (kind == "end") ended.TrySetResult(); + } + }; + subscription.AddItem(item); + subscription.AddItem(item); + + const System.Reflection.BindingFlags all = System.Reflection.BindingFlags.Instance + | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic; + var save = typeof(Subscription).GetMethods(all) + .First(m => m.Name == "SaveMessageInCache" && m.GetParameters().Length == 2); + typeof(Subscription).GetMethod("StartKeepAliveTimer", all)!.Invoke(subscription, null); + + var available = new uint[] { 1, 2, 3, 4, 5, 6, 7, 8 }.Where(n => n != skip).ToArray(); + async Task Send(uint seq, List fields, int pauseMs) + { + var message = new NotificationMessage + { + SequenceNumber = seq, + PublishTime = DateTime.UtcNow, + NotificationData = + [ + new ExtensionObject(new EventNotificationList + { + Events = [new EventFieldList { ClientHandle = item.ClientHandle, EventFields = fields.ToArray() }], + }), + ], + }; + save.Invoke(subscription, [SdkReplay.ToParam(save, available), message]); + await Task.Delay(pauseMs); + } + + try + { + // seq 1 is a live event before the refresh: the SDK's first message only re-syncs its sequence. + await Send(1, Unrelated(), 300); + await Send(2, Marker(ObjectTypeIds.RefreshStartEventType), 300); + if (skip != 3) await Send(3, Condition(active: true, acked: false), 300); + await Send(4, Marker(ObjectTypeIds.RefreshEndEventType), 300); + await Send(5, Unrelated(), 300); + // The SDK republishes a gap once it is > 2.5 s old with later messages behind it, then skips it once + // the republish has failed; each step runs on a later arrival. + for (uint seq = 6; seq <= 8 && !ended.Task.IsCompleted; seq++) + await Send(seq, Unrelated(), 2700); + await ended.Task.WaitAsync(TimeSpan.FromSeconds(15)); + } + finally + { + subscription.Dispose(); + } + + lock (order) return order.ToList(); + } + + private static List Unrelated() + { + var f = Marker(ObjectTypeIds.BaseEventType); + f[2] = new Variant(NodeId.Parse("ns=9;s=Elsewhere")); // not an authored source ⇒ dropped by the filter + return f; + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataHistoryWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataHistoryWireTests.cs index e6d22dc68..f30877cde 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataHistoryWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataHistoryWireTests.cs @@ -69,7 +69,7 @@ public sealed class GrpcDataHistoryWireTests byId["Plant/Modbus/dev1/Speed"].History.Historizing.ShouldBeFalse(); (byId["Plant/Modbus/dev1/Speed"].AllowedOperations & 32u).ShouldBe(0u); // Header-less: the golden (no Metadata.history, no bit 32). - (await origin.DriveAsync("GetMetadata", new Metadata())).ShouldBe(GrpcDataV1RealOriginGoldens.Responses["GetMetadata"]); + (await origin.DriveAsync("GetMetadata", new Metadata())).ShouldBe(GrpcDataV1RealOriginCorrections.Expected("GetMetadata")); // A caller whose ACL lacks HistoryRead sees historizing=false on Flow: the same as an unhistorized node. await using var denied = new RealOrigin(permissions: NodePermissions.Operator & ~NodePermissions.HistoryRead); var deniedMeta = W.MetadataResponse.Parser.ParseFrom(Convert.FromHexString(await denied.DriveAsync("GetMetadata", History))); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1CompatibilityTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1CompatibilityTests.cs index 0b24ef423..a3119ce88 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1CompatibilityTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1CompatibilityTests.cs @@ -64,12 +64,30 @@ public sealed class GrpcDataV1CompatibilityTests Hex(V1Requests.Bytes(rpc)).ShouldBe(GrpcDataV1Goldens.Requests[rpc], $"recorded {rpc} request"); } + /// #916: the only correction of the fake-origin goldens is field 10, and the recording really carried it. + [Fact] + public void V1_correction_916_clears_only_stable_source_id() + { + foreach (var rpc in RpcNames.Where(r => r != "Subscribe")) + { + var golden = GrpcDataV1Goldens.Responses[rpc]; + if (GrpcDataV1Corrections.Corrected.Contains(rpc)) + { + GrpcDataV1Corrections.Expected(rpc).ShouldNotBe(golden, $"{rpc}: the recorded fake metadata carried field 10"); + IMessage parsed = rpc == "Browse" ? W.BrowseResponse.Parser.ParseFrom(Convert.FromHexString(golden)) + : W.MetadataResponse.Parser.ParseFrom(Convert.FromHexString(golden)); + Hex(parsed.ToByteArray()).ShouldBe(golden, $"{rpc}: re-serialising a golden is byte-identical"); + } + else GrpcDataV1Corrections.Expected(rpc).ShouldBe(golden); + } + } + [Theory] [MemberData(nameof(Rpcs))] public async Task V1_client_without_feature_header_gets_the_recorded_v1_response_bytes(string rpc) { var actual = await V1CompatibilityHarness.DriveAsync(rpc, new Metadata()); - actual.ShouldBe(GrpcDataV1Goldens.Responses[rpc], $"{rpc} response diverged from the recorded v1 bytes"); + actual.ShouldBe(GrpcDataV1Corrections.Expected(rpc), $"{rpc} response diverged from the recorded v1 bytes"); } [Theory] @@ -79,9 +97,9 @@ public sealed class GrpcDataV1CompatibilityTests // H2 supports history, but this origin advertises none (and conditions are A2): the effective set is empty. var headers = new Metadata { { "x-otopcua-data-features", "history,conditions" } }; var actual = await V1CompatibilityHarness.DriveAsync(rpc, headers, history: false, conditions: false); - actual.ShouldBe(GrpcDataV1Goldens.Responses[rpc], $"{rpc} response must not change when nothing requested is servable"); + actual.ShouldBe(GrpcDataV1Corrections.Expected(rpc), $"{rpc} response must not change when nothing requested is servable"); (await V1CompatibilityHarness.DriveAsync(rpc, new Metadata { { "x-otopcua-data-features", "conditions" } }, conditions: false)) - .ShouldBe(GrpcDataV1Goldens.Responses[rpc], $"{rpc}: conditions on an origin that cannot serve them change nothing"); + .ShouldBe(GrpcDataV1Corrections.Expected(rpc), $"{rpc}: conditions on an origin that cannot serve them change nothing"); } [Fact] @@ -254,6 +272,39 @@ public sealed class GrpcDataV1CompatibilityTests internal static IMessage Normalise(IMessage message) => message; } + +/// +/// #916 (pre-deploy, never re-recorded): DataProtoMapper no longer encodes Metadata.stable_source_id +/// (field 10), so the fake origin's metadata loses it on the wire. The expected bytes are the recorded golden with field 10 +/// cleared on every Metadata of Browse and GetMetadata. That is the only edit. The real-origin variant has its own corrections +/// (). +/// +internal static class GrpcDataV1Corrections +{ + internal static readonly string[] Corrected = ["Browse", "GetMetadata"]; + + internal static string Expected(string rpc) + { + var golden = GrpcDataV1Goldens.Responses[rpc]; + if (!Corrected.Contains(rpc)) return golden; + var bytes = Convert.FromHexString(golden); + IMessage corrected; + if (rpc == "Browse") + { + var response = W.BrowseResponse.Parser.ParseFrom(bytes); + foreach (var item in response.Items) item.ClearStableSourceId(); + corrected = response; + } + else + { + var response = W.MetadataResponse.Parser.ParseFrom(bytes); + foreach (var item in response.Items) item.Value?.ClearStableSourceId(); + corrected = response; + } + return Convert.ToHexString(corrected.ToByteArray()); + } +} + /// The recorded v1 client requests. Changing any value here invalidates the goldens. internal static class V1Requests { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1RealOriginCompatibilityTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1RealOriginCompatibilityTests.cs index d5d70d4cb..7bb085151 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1RealOriginCompatibilityTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1RealOriginCompatibilityTests.cs @@ -66,13 +66,53 @@ public sealed class GrpcDataV1RealOriginCompatibilityTests Hex(RealOriginRequests.Bytes(scenario)).ShouldBe(GrpcDataV1RealOriginGoldens.Requests[scenario], $"recorded {scenario} request"); } + /// + /// #916/#917: the corrections are exact and not vacuous — an unedited golden re-serialises byte-identically, the + /// uncorrected scenarios are the raw goldens, the recorded UNS browse really leaked the driver id + RawPath, and the + /// corrected bytes carry neither the leak nor a value-bearing HighTemp. + /// + [Fact] + public void V1_corrections_916_917_are_exact_and_the_recorded_leak_was_real() + { + foreach (var scenario in RealOriginRequests.Scenarios.Where(s => s != "Subscribe")) + { + var golden = GrpcDataV1RealOriginGoldens.Responses[scenario]; + IMessage parsed = scenario.Split('/')[0] switch + { + "GetCapabilities" => W.CapabilitiesResponse.Parser.ParseFrom(Convert.FromHexString(golden)), + "Browse" => W.BrowseResponse.Parser.ParseFrom(Convert.FromHexString(golden)), + "GetMetadata" => W.MetadataResponse.Parser.ParseFrom(Convert.FromHexString(golden)), + "Read" => W.ReadResponse.Parser.ParseFrom(Convert.FromHexString(golden)), + _ => W.WriteResponse.Parser.ParseFrom(Convert.FromHexString(golden)), + }; + Hex(parsed.ToByteArray()).ShouldBe(golden, $"{scenario}: re-serialising a golden is byte-identical"); + if (GrpcDataV1RealOriginCorrections.Corrected.Contains(scenario)) + GrpcDataV1RealOriginCorrections.Expected(scenario).ShouldNotBe(golden, $"{scenario} carries a corrected field"); + else + GrpcDataV1RealOriginCorrections.Expected(scenario).ShouldBe(golden); + } + var leak = Hex(System.Text.Encoding.UTF8.GetBytes("driver-1Plant/Modbus/dev1/")); + GrpcDataV1RealOriginGoldens.Responses["Browse/uns"].ShouldContain(leak, Case.Sensitive, "the recorded v1 UNS browse leaked it (#916)"); + foreach (var scenario in GrpcDataV1RealOriginCorrections.Corrected) + GrpcDataV1RealOriginCorrections.Expected(scenario).ShouldNotContain(leak, Case.Sensitive); + var metadata = W.MetadataResponse.Parser.ParseFrom(Convert.FromHexString(GrpcDataV1RealOriginCorrections.Expected("GetMetadata"))); + metadata.Items.Count(x => x.Status == (int)DataItemStatus.Unsupported).ShouldBe(1); + metadata.Items.ShouldNotContain(x => x.Value != null && x.Value.View.Address.Identifier == RealOriginRequests.HighTemp.Address.Identifier); + // HighTemp was in the recorded device page and is the only item the correction drops (positive control). + var recorded = W.BrowseResponse.Parser.ParseFrom(Convert.FromHexString(GrpcDataV1RealOriginGoldens.Responses["Browse"])); + var corrected = W.BrowseResponse.Parser.ParseFrom(Convert.FromHexString(GrpcDataV1RealOriginCorrections.Expected("Browse"))); + recorded.Items.Select(x => x.View.Address.Identifier).Except(corrected.Items.Select(x => x.View.Address.Identifier)) + .ShouldBe([RealOriginRequests.HighTemp.Address.Identifier]); + corrected.Items.Count.ShouldBe(recorded.Items.Count - 1); + } + [Theory] [MemberData(nameof(Scenarios))] public async Task V1_client_without_feature_header_gets_the_recorded_v1_response_bytes(string scenario) { await using var origin = new RealOrigin(); var actual = await origin.DriveAsync(scenario, new Metadata()); - actual.ShouldBe(GrpcDataV1RealOriginGoldens.Responses[scenario], $"{scenario} response diverged from the recorded v1 bytes"); + actual.ShouldBe(GrpcDataV1RealOriginCorrections.Expected(scenario), $"{scenario} response diverged from the recorded v1 bytes"); } [Theory] @@ -83,10 +123,10 @@ public sealed class GrpcDataV1RealOriginCompatibilityTests // effective set is empty and the bytes are v1. await using var origin = new RealOrigin(historian: false, conditions: false); var actual = await origin.DriveAsync(scenario, new Metadata { { "x-otopcua-data-features", "history,conditions" } }); - actual.ShouldBe(GrpcDataV1RealOriginGoldens.Responses[scenario], $"{scenario} response must not change when nothing requested is servable"); + actual.ShouldBe(GrpcDataV1RealOriginCorrections.Expected(scenario), $"{scenario} response must not change when nothing requested is servable"); await using var conditionsOnly = new RealOrigin(conditions: false); (await conditionsOnly.DriveAsync(scenario, new Metadata { { "x-otopcua-data-features", "conditions" } })) - .ShouldBe(GrpcDataV1RealOriginGoldens.Responses[scenario], $"{scenario}: conditions on an origin that cannot serve them change nothing"); + .ShouldBe(GrpcDataV1RealOriginCorrections.Expected(scenario), $"{scenario}: conditions on an origin that cannot serve them change nothing"); } [Fact] @@ -219,6 +259,56 @@ public sealed class GrpcDataV1RealOriginCompatibilityTests internal static IMessage Normalise(IMessage message) => message; } +/// +/// The deliberate pre-deploy v1 corrections (#916, #917; v1 was merged but never deployed, #915). The goldens in +/// are NOT re-recorded: the expected bytes are the recorded golden with exactly +/// these edits applied to its parsed message, and every other byte must still match. Re-serialising an unedited golden is +/// byte-identical (asserted), so the edit is the only difference. Nothing here changes the wire SHAPE — both corrections +/// use fields and values a v1 client already handles (an absent optional field; one item fewer in a page; the existing +/// per-item Unsupported status). +/// +/// #916 — Metadata.stable_source_id is never sent (it was <len>:<driverInstanceId><RawPath>, even on +/// UNS exports). Cleared on every Metadata of every Browse/GetMetadata response. +/// #917 — the alarm-bearing raw tag (HighTemp) is an unsupported value node: a Browse page no longer lists it +/// (every consumer build applies a page all-or-nothing and cannot materialise one), and a GetMetadata item for it is +/// status = Unsupported with no value and no lease. +/// +/// +internal static class GrpcDataV1RealOriginCorrections +{ + internal static readonly string[] Corrected = ["Browse", "Browse/uns", "GetMetadata"]; + + internal static string Expected(string scenario) + { + var golden = GrpcDataV1RealOriginGoldens.Responses[scenario]; + if (!Corrected.Contains(scenario)) return golden; + var bytes = Convert.FromHexString(golden); + var alarm = RealOriginRequests.HighTemp.Address.Identifier; + IMessage corrected; + if (scenario == "GetMetadata") + { + var response = W.MetadataResponse.Parser.ParseFrom(bytes); + foreach (var item in response.Items) + { + if (item.Value is null) continue; + if (item.Value.View.Address.Identifier == alarm && item.Value.View.Realm == (int)DataRealm.Raw) + { item.Status = (int)DataItemStatus.Unsupported; item.Value = null; item.Lease = null; continue; } + item.Value.ClearStableSourceId(); + } + corrected = response; + } + else + { + var response = W.BrowseResponse.Parser.ParseFrom(bytes); + var hidden = response.Items.Where(item => item.View.Address.Identifier == alarm && item.View.Realm == (int)DataRealm.Raw).ToArray(); + foreach (var item in hidden) response.Items.Remove(item); + foreach (var item in response.Items) item.ClearStableSourceId(); + corrected = response; + } + return GrpcDataV1RealOriginCompatibilityTests.Hex(corrected.ToByteArray()); + } +} + /// The recorded v1 client requests against 's catalog. Changing any value invalidates the goldens. internal static class RealOriginRequests { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1RealOriginGoldens.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1RealOriginGoldens.cs index 68f1c8c46..10dd3780c 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1RealOriginGoldens.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataV1RealOriginGoldens.cs @@ -6,6 +6,8 @@ namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; /// NEVER re-record these to make a later phase (H2, A2, A3, ...) pass: a difference is a v1 wire regression of the /// real origin, not a stale golden. A later phase extends 's snapshot with its new-shape data /// and must still produce these exact bytes for a headerless (and, while unsupported, a feature-requesting) v1 call. +/// The only sanctioned differences are the pre-deploy corrections #916/#917, applied to these bytes (not re-recorded) by +/// . /// internal static class GrpcDataV1RealOriginGoldens { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionPlacementTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionPlacementTests.cs index b6b0bb006..ef5f773ab 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionPlacementTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionPlacementTests.cs @@ -2,6 +2,7 @@ using System.Security.Cryptography; using System.Text.Json; using Shouldly; using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; using ZB.MOM.WW.OtOpcUa.Configuration.Entities; using ZB.MOM.WW.OtOpcUa.Configuration.Enums; @@ -45,7 +46,7 @@ public sealed class GrpcDataConditionPlacementTests Devices = [new() { DeviceId = "device", DriverInstanceId = "driver-id-7f3", Name = "Device", DeviceConfig = "{}" }], TagGroups = [new() { TagGroupId = "group", DeviceId = "device", Name = "Group" }], Tags = [new() { TagId = "tag", DeviceId = "device", Name = "Speed", DataType = "Int32", AccessLevel = TagAccessLevel.ReadWrite, TagConfig = "{}" }, - new() { TagId = "alarm-tag", DeviceId = "device", TagGroupId = "group", Name = "OverTemp", DataType = "Boolean", AccessLevel = TagAccessLevel.Read, + new() { TagId = "alarm-tag", DeviceId = "device", TagGroupId = "group", Name = "OverTemp", DataType = "Boolean", AccessLevel = TagAccessLevel.ReadWrite, TagConfig = withAlarms ? AlarmConfig : "{}" }], UnsAreas = [new() { UnsAreaId = "area-id", ClusterId = "cluster", Name = "Area" }], UnsLines = [new() { UnsLineId = "line-id", UnsAreaId = "area-id", Name = "Line" }], @@ -306,6 +307,83 @@ public sealed class GrpcDataConditionPlacementTests listedNative.ShouldBeGreaterThan(20); // the generator really exercised native UNS placements } + /// + /// #916: no exported metadata carries stable_source_id — a driver source's internal key is + /// <len>:<driverInstanceId><RawPath>, so sending it told a UNS-only peer the origin's driver ids and + /// RawPaths. The internal is unchanged (positive control: it still holds both, so the + /// search below would see a leak). Checked on the encoded wire bytes of every node, every realm, 60 seeds. + /// + [Fact] + public void No_exported_metadata_carries_the_internal_source_key_916() + { + var checkedSources = 0; + for (var seed = 1; seed <= 60; seed++) + { + var (snapshot, rawPaths, driverIds, _) = Generate(seed); + using var fixture = new LocalDataFixture(); + var catalog = LocalExportCatalog.Compile(snapshot, fixture.Serving, fixture.Activation.CaptureAuthority()); + foreach (var node in catalog.Nodes) + { + node.Metadata.StableSourceId.ShouldBeNull($"seed {seed} {node.EntityKind} {node.EntityId}"); + var wire = DataProtoMapper.EncodeMetadata(node.Metadata); + wire.HasStableSourceId.ShouldBeFalse(); + if (node.Metadata.View.Realm != DataRealm.Uns) continue; + var text = wire.ToString(); + foreach (var rawPath in rawPaths) text.ShouldNotContain(rawPath, Case.Sensitive, $"seed {seed}"); + foreach (var driverId in driverIds) text.ShouldNotContain(driverId, Case.Sensitive, $"seed {seed}"); + // Positive control: the internal key of a driver-backed UNS reference still names its driver and RawPath. + if (node.Source is { SourceKind: "driver" } source) + { + driverIds.ShouldContain(d => source.StableSourceId.Contains(d, StringComparison.Ordinal)); + rawPaths.ShouldContain(r => source.StableSourceId.EndsWith(r, StringComparison.Ordinal)); + checkedSources++; + } + } + } + checkedSources.ShouldBeGreaterThan(20); // the generator really produced driver-backed UNS references + } + + /// + /// #917: an alarm-bearing raw tag gets no value (DriverHostActor keeps it out of the value fan-out, and #896 gives it + /// no UNS variable), so v1 compiles it as an unsupported value node: kind UnsupportedVariable, never writable + /// (the fixture tag is ReadWrite), Unsupported on every value operation, and NOT listed by Browse — never a Variable + /// that waits forever. Its condition placements (A1) are untouched. An export rooted at it still compiles (the + /// deploy is not broken) but grants nothing: its values are unsupported and its condition is not under the root. + /// + [Fact] + public void An_alarm_bearing_raw_tag_is_an_UnsupportedVariable_and_keeps_its_condition_placements_917() + { + using var fixture = new LocalDataFixture(); + var catalog = LocalExportCatalog.Compile(Fixed(), fixture.Serving, fixture.Activation.CaptureAuthority()); + var alarm = catalog.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "alarm-tag"); + alarm.Supported.ShouldBeFalse(); + alarm.Metadata.NodeKind.ShouldBe("UnsupportedVariable"); + alarm.Metadata.ValueKind.ShouldBe(DataValueKind.Null); + alarm.Metadata.Writable.ShouldBeFalse(); + // (Every value gate keys on Supported; the operations a caller sees are masked to Browse by LocalDataServices — + // pinned on the wire by GrpcDataV1RealOriginCompatibilityTests.) + // Positive controls: a plain tag is still a Variable, and the same tag without its alarm config is one too. + var speed = catalog.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "tag"); + speed.Supported.ShouldBeTrue(); + speed.Metadata.NodeKind.ShouldBe("Variable"); + var plain = LocalExportCatalog.Compile(Fixed(withAlarms: false), fixture.Serving, fixture.Activation.CaptureAuthority()) + .Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "alarm-tag"); + plain.Supported.ShouldBeTrue(); + plain.Metadata.NodeKind.ShouldBe("Variable"); + plain.Metadata.ValueKind.ShouldBe(DataValueKind.Boolean); + plain.Metadata.Writable.ShouldBeTrue(); // the same ReadWrite tag without its alarm IS writable + + // Condition forwarding is unaffected: the Raw placement at its RawPath and both UNS placements remain. + catalog.PlacementsOf(new(AddressSpaceRealm.Raw, "Plant/Driver/Device/Group/OverTemp")).Count.ShouldBe(3); + catalog.ListConditions("raw-peer", LocalExportCatalog.RealmRoot("cluster", DataRealm.Raw), DataOperations.Subscribe, + ConditionKeys.FromSecret(Secret)).ShouldHaveSingleItem(); + + // A deployable export rooted at the alarm-bearing tag still compiles (the node is kept, not removed). + var b = Fixed(); + Should.NotThrow(() => LocalExportCatalog.Compile(With(b, exports: [.. b.DataExports, + Export("tag-root", DataRealm.Raw, "tag-peer", rootKind: "RawTag", rootId: "alarm-tag")]), fixture.Serving, fixture.Activation.CaptureAuthority())); + } + private static (DraftSnapshot Snapshot, string[] RawPaths, string[] DriverIds, int ExpectedUnsNative) Generate(int seed) { var random = new Random(seed); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLeaseLapseReviewTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLeaseLapseReviewTests.cs new file mode 100644 index 000000000..97d3b5240 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLeaseLapseReviewTests.cs @@ -0,0 +1,276 @@ +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using DataBrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest; +using DataReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest; +using DataReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// #922 security-review round 1: on-demand renewal admission must not starve the unary budget (cold reads, writes, subscription +/// renewals), a batch of N lapsed nodes renews all N, a slow origin cannot pin SDK threads, and every refusal that is not a +/// lapse (a revoked lease, a revoked grant, a removed node) stays a refusal. +/// +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Fact(Timeout = 90000), Trait("Issue", "922")] + public async Task A_read_batch_of_several_lapsed_nodes_renews_every_node_not_only_the_first() + { + var ct = TestContext.Current.CancellationToken; + using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1); + var connections = new GatedConnections(origin); + await WithComposedServer(origin, origin.Root, async (session, _, resolver, _, access, _, anchor) => + { + var client = (SessionClient)session; + var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray(); + children.Length.ShouldBe(3); + origin.Clock.Advance(TimeSpan.FromSeconds(16)); + var ids = children.Select(c => c.IdentifierAsString).ToArray(); + ids.Count(id => resolver.TryResolveProjected(DataRealm.Raw, id, out var _1)).ShouldBe(0); + + var read = await client.ReadAsync(new RequestHeader(), LongMaxAge, TimestampsToReturn.Both, + children.Select(c => new ReadValueId { NodeId = c, AttributeId = Attributes.Value }).ToArray(), ct); + read.Results.ToArray()!.ShouldAllBe(r => r.StatusCode.Code == StatusCodes.BadWaitingForInitialData.Code); + access.LapseRenewalsStartedForTests.ShouldBe(3, "every lapsed node in the batch is admitted for renewal"); + for (var i = 0; i < 400 && !ids.All(id => resolver.TryResolveProjected(DataRealm.Raw, id, out _)); i++) await Task.Delay(25, ct); + ids.Count(id => resolver.TryResolveProjected(DataRealm.Raw, id, out var _2)).ShouldBe(3, "all three renewed, with no re-browse"); + connections.BrowseCalls.ShouldBe(1); + }, connectionSource: connections, staleTimeoutMilliseconds: LongStale); + } + + [Fact(Timeout = 90000), Trait("Issue", "922")] + public async Task A_history_batch_of_several_lapsed_nodes_renews_and_serves_every_node() + { + await using var originServer = await HistoryOrigin.StartAsync(7, extra: 2); + using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1, history: originServer.Port); + await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray(); + children.Length.ShouldBe(3); + origin.Clock.Advance(TimeSpan.FromSeconds(16)); + var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(3)), TimestampsToReturn.Both, false, + children.Select(c => new HistoryReadValueId { NodeId = c }).ToArray(), TestContext.Current.CancellationToken); + var results = response.Results.ToArray()!; + results.ShouldAllBe(r => StatusCode.IsGood(r.StatusCode), string.Join(", ", results.Select(r => r.StatusCode.ToString()))); + results.ShouldAllBe(r => Values(r).Count == 3); + }, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin)); + } + + [Fact(Timeout = 90000), Trait("Issue", "922")] + public async Task A_renewal_in_flight_does_not_crowd_out_a_cold_read_of_another_node() + { + var ct = TestContext.Current.CancellationToken; + using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1); + var connections = new GatedConnections(origin); + await WithComposedServer(origin, origin.Root, async (session, _, _, _, access, _, anchor) => + { + var client = (SessionClient)session; + var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray(); + var (a, b) = (children[0], children[1]); + origin.Clock.Advance(TimeSpan.FromSeconds(16)); + connections.HoldMetadataFor = a.IdentifierAsString; + (await ReadValue(client, a, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadWaitingForInitialData.Code); + await connections.Held.Task.WaitAsync(TimeSpan.FromSeconds(10), ct); // A's renewal is now parked at the origin + + // Re-browse renews B (and A) by page; B's cold read must still be dispatched while A's renewal is in flight. + await BrowseAll(client, anchor, 10); + var reads = connections.ReadCalls; + (await ReadValue(client, b, ct)).StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code); + for (var i = 0; i < 200 && connections.ReadCalls == reads; i++) await Task.Delay(25, ct); + connections.ReadCalls.ShouldBeGreaterThan(reads, "an on-demand renewal holds no unary capacity"); + connections.Release(); + }, connectionSource: connections, staleTimeoutMilliseconds: LongStale); + } + + [Fact(Timeout = 90000), Trait("Issue", "922")] + public async Task An_invalidated_lease_is_a_refusal_not_a_lapse_and_never_reaches_the_origin() + { + var ct = TestContext.Current.CancellationToken; + using var origin = new LocalDataFixture(servingGeneration: 1); + origin.Publish(42); + var connections = new GatedConnections(origin); + await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, access, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + (await ReadUntilGood(client, anchor, ct)).ShouldBe(42); + resolver.TryResolveProjected(DataRealm.Raw, anchor.IdentifierAsString, out var proof).ShouldBeTrue(); + ((BoundProjectionLease)proof!.Lease).Remote.Invalidate(); + var metadata = connections.MetadataCalls; + (await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code); + access.LapseRenewalsStartedForTests.ShouldBe(0, "a revoked lease is never renewed"); + connections.MetadataCalls.ShouldBe(metadata); + }, connectionSource: connections, staleTimeoutMilliseconds: LongStale); + } + + [Fact(Timeout = 90000), Trait("Issue", "922")] + public async Task A_grant_revoked_while_the_renewal_is_at_the_origin_is_not_committed_and_the_read_is_denied() + { + var ct = TestContext.Current.CancellationToken; + using var origin = new LocalDataFixture(servingGeneration: 1); + origin.Publish(42); + var connections = new GatedConnections(origin); + LocalCatalogCoordinator? coordinator = null; + await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, access, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + origin.Clock.Advance(TimeSpan.FromSeconds(16)); + connections.HoldMetadataFor = anchor.IdentifierAsString; + (await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadWaitingForInitialData.Code); + await connections.Held.Task.WaitAsync(TimeSpan.FromSeconds(10), ct); + + Prepare(coordinator!, localPermissions: BrowseOnlyGrant); // the caller's Read grant is gone from now on + connections.Release(); + for (var i = 0; i < 40; i++) + { + var value = await ReadValue(client, anchor, ct); + StatusCode.IsGood(value.StatusCode).ShouldBeFalse("nothing is served after the grant was revoked"); + if (value.StatusCode.Code == StatusCodes.BadUserAccessDenied.Code) break; + await Task.Delay(50, ct); + } + (await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code); + resolver.TryResolveProjected(DataRealm.Raw, anchor.IdentifierAsString, out _).ShouldBeFalse("the renewal never committed"); + }, connectionSource: connections, staleTimeoutMilliseconds: LongStale, onCoordinator: value => coordinator = value); + } + + [Fact(Timeout = 90000), Trait("Issue", "922")] + public async Task A_node_whose_mapping_is_removed_while_it_renews_is_not_revived() + { + var ct = TestContext.Current.CancellationToken; + using var origin = new LocalDataFixture(servingGeneration: 1); + origin.Publish(42); + var connections = new GatedConnections(origin); + await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + origin.Clock.Advance(TimeSpan.FromSeconds(16)); + connections.HoldMetadataFor = anchor.IdentifierAsString; + (await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadWaitingForInitialData.Code); + await connections.Held.Task.WaitAsync(TimeSpan.FromSeconds(10), ct); + + resolver.ApplyMappings([]); // the mapping goes away mid-renewal + connections.Release(); + await Task.Delay(300, ct); + resolver.TryResolveProjected(DataRealm.Raw, anchor.IdentifierAsString, out _).ShouldBeFalse(); + resolver.TryResolveForRenewal(DataRealm.Raw, anchor.IdentifierAsString, out _).ShouldBeFalse(); + var value = await ReadValue(client, anchor, ct); + StatusCode.IsGood(value.StatusCode).ShouldBeFalse(); + value.StatusCode.Code.ShouldNotBe(StatusCodes.BadWaitingForInitialData.Code, "a removed node is not a lapse"); + }, connectionSource: connections, staleTimeoutMilliseconds: LongStale); + } + + [Fact(Timeout = 90000), Trait("Issue", "922")] + public async Task Concurrent_history_reads_against_a_slow_origin_are_bounded_and_retryable_and_recover() + { + await using var originServer = await HistoryOrigin.StartAsync(7); + using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); + var connections = new GatedConnections(origin); + OtOpcUaNodeManager? manager = null; + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + origin.Clock.Advance(TimeSpan.FromSeconds(16)); + connections.HoldMetadataFor = anchor.IdentifierAsString; // the origin never answers the renewal until released + var clock = System.Diagnostics.Stopwatch.StartNew(); + async Task<(Opc.Ua.HistoryReadResult Result, TimeSpan Took)> Timed() + { + var each = System.Diagnostics.Stopwatch.StartNew(); + var result = await RawHistory(client, anchor, 3, default); + return (result, each.Elapsed); + } + var reads = Enumerable.Range(0, 24).Select(_ => Timed()).ToArray(); + var all = Task.WhenAll(reads); + // Every waiter is bounded (a non-local history slot, then at most the lapse wait) — none is pinned until the origin + // answers, which it never does while held. + (await Task.WhenAny(all, Task.Delay(TimeSpan.FromSeconds(30), TestContext.Current.CancellationToken))).ShouldBe(all, + "every concurrent HistoryRead returned while the origin was still silent"); + clock.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(30)); + var statuses = all.Result.Select(r => r.Result.StatusCode.Code).ToArray(); + // Waiters are capped by the non-local history slots: the reads that found none answer at once instead of each pinning + // an SDK thread for the whole lapse wait (the pre-review code made all 24 wait it out). + var slots = OriginHistoryPort.RemoteSlots(manager!.MaxConcurrentHistoryReadBatches); + all.Result.Count(r => r.Took < TimeSpan.FromSeconds(2.5)).ShouldBeGreaterThanOrEqualTo(24 - slots, + string.Join(", ", all.Result.Select(r => r.Took.TotalMilliseconds.ToString("0")))); + statuses.ShouldAllBe(code => code == StatusCodes.BadResourceUnavailable.Code, "granted + lapsed + silent origin ⇒ retryable"); + originServer.Source.Calls.ShouldBe(0); + + connections.Release(); + Opc.Ua.HistoryReadResult? served = null; + for (var i = 0; i < 40; i++) + { + served = await RawHistory(client, anchor, 3, default); + if (StatusCode.IsGood(served.StatusCode)) break; + origin.Clock.Advance(ProjectedDataAccess.LapseRenewalBackoff + TimeSpan.FromMilliseconds(1)); + await Task.Delay(50, TestContext.Current.CancellationToken); + } + StatusCode.IsGood(served!.StatusCode).ShouldBeTrue(served.StatusCode.ToString()); + }, localPermissions: 15, allowHistory: true, connectionSource: connections, onHistory: (_, nm) => manager = nm); + } + + /// One persistent origin connection whose metadata call for one node can be parked; counts browse/metadata/read calls. + private sealed class GatedConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource + { + private IDataConnection? _inner; + private readonly object _gate = new(); + private readonly object _route = new(); + private int _browse, _metadata, _read; + private TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously); + public int BrowseCalls => Volatile.Read(ref _browse); + public int MetadataCalls => Volatile.Read(ref _metadata); + public int ReadCalls => Volatile.Read(ref _read); + /// The projected local identifier whose origin metadata call is parked until . + public volatile string? HoldMetadataFor; + public TaskCompletionSource Held { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public void Release() { HoldMetadataFor = null; _release.TrySetResult(); } + public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken) + { + if (connectionId != "link") return ValueTask.FromResult(null); + lock (_gate) _inner ??= peer.Connection(); + return ValueTask.FromResult(new Borrowed(new Gate(_inner, this), _route)); + } + private sealed class Borrowed(IDataConnection connection, object route) : IGrpcDataAdapterConnectionLease + { + public IDataConnection Connection => connection; + public CancellationToken CancellationToken => CancellationToken.None; + public object? RouteIdentity => route; + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + private sealed class Gate(IDataConnection inner, GatedConnections owner) : IDataConnection, IDataHistoryService + { + public DataTarget Target => inner.Target; + public TimeProvider Clock => inner.Clock; + public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => inner.GetCapabilitiesAsync(budget, cancellationToken); + public Task BrowseAsync(DataBrowseRequest request, CancellationToken cancellationToken) + { Interlocked.Increment(ref owner._browse); return inner.BrowseAsync(request, cancellationToken); } + public async Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) + { + Interlocked.Increment(ref owner._metadata); + if (owner.HoldMetadataFor is { } held && request.Views.Any(view => + ProjectedDataIds.Identifier("map", view.Address) == held)) + { + owner.Held.TrySetResult(); + await owner._release.Task.WaitAsync(cancellationToken); + } + return await inner.GetMetadataAsync(request, cancellationToken); + } + public Task> ReadAsync(DataReadRequest request, CancellationToken cancellationToken) + { Interlocked.Increment(ref owner._read); return inner.ReadAsync(request, cancellationToken); } + public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => inner.WriteAsync(request, cancellationToken); + public Task SubscribeAsync(CancellationToken cancellationToken) => inner.SubscribeAsync(cancellationToken); + public Task> ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) => + ((IDataHistoryService)inner).ReadAsync(request, cancellationToken); + public Task ReleaseAsync(IReadOnlyList continuations, CancellationToken cancellationToken) => + ((IDataHistoryService)inner).ReleaseAsync(continuations, cancellationToken); + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLeaseLapseWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLeaseLapseWireTests.cs new file mode 100644 index 000000000..777b0aaf9 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLeaseLapseWireTests.cs @@ -0,0 +1,250 @@ +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using DataBrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest; +using DataReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest; +using DataReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// #922 — a projected node idle longer than its MetadataLeaseMilliseconds (15 s here) is a LAPSE, not an +/// authorization failure: a value Read answers a retryable status and renews the lease on demand (no re-browse), a +/// HistoryRead renews it within the request's deadline and is served, and a re-browse served from a still-cached page +/// renews a lease that is past half its life. A real ACL denial stays BadUserAccessDenied after a lapse too, and +/// never reaches the origin. +/// +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + private const int BrowseOnlyGrant = 1; + // The fixture origin observes its one sample at t0 and never again, so the sample's ORIGIN age grows with the manual clock: + // a stale timeout and a client maxAge longer than the test's idle gaps keep that age out of what is under test (the lease). + private const int LongStale = 120_000; + private const double LongMaxAge = 120_000; + + [Fact(Timeout = 90000), Trait("Issue", "922")] + public async Task A_value_read_after_the_metadata_lease_lapses_is_retryable_and_renews_on_demand_without_a_browse() + { + var ct = TestContext.Current.CancellationToken; + using var origin = new LocalDataFixture(servingGeneration: 1); + origin.Publish(42); + var connections = new CountingConnections(origin); + await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + (await ReadUntilGood(client, anchor, ct)).ShouldBe(42); + var browses = connections.BrowseCalls; + var metadata = connections.MetadataCalls; + + origin.Clock.Advance(TimeSpan.FromSeconds(16)); + var id = ProjectedDataIds.Identifier("map", origin.Raw.Address); + resolver.TryResolveProjected(DataRealm.Raw, id, out _).ShouldBeFalse("precondition: the lease has lapsed"); + + // A non-Value attribute of the lapsed node is not access-denied either (retryable while the lease renews). + var name = (await client.ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Neither, + [new ReadValueId { NodeId = anchor, AttributeId = Attributes.DisplayName }], ct)).Results[0]; + name.StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code); + var lapsed = await ReadValue(client, anchor, ct); + lapsed.StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code, "a lease lapse is not an authorization failure"); + // The attribute read above already started the renewal, which may have finished (and fetched the value) by now. + (StatusCode.IsGood(lapsed.StatusCode) || lapsed.StatusCode.Code == StatusCodes.BadWaitingForInitialData.Code || + lapsed.StatusCode.Code == StatusCodes.BadResourceUnavailable.Code).ShouldBeTrue(lapsed.StatusCode.ToString()); + (await ReadUntilGood(client, anchor, ct)).ShouldBe(42); + resolver.TryResolveProjected(DataRealm.Raw, id, out _).ShouldBeTrue("the read renewed the node's authority"); + connections.BrowseCalls.ShouldBe(browses, "the renewal is an exact metadata refresh, not a re-browse"); + connections.MetadataCalls.ShouldBeGreaterThan(metadata, "renewed by an exact metadata call"); + + // And again: every idle gap longer than the lease renews the same way. + origin.Clock.Advance(TimeSpan.FromSeconds(16)); + (await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadWaitingForInitialData.Code); + (await ReadUntilGood(client, anchor, ct)).ShouldBe(42); + }, connectionSource: connections, staleTimeoutMilliseconds: LongStale); + } + + [Fact(Timeout = 90000), Trait("Issue", "922")] + public async Task Without_the_local_read_grant_a_lapsed_value_read_is_still_BadUserAccessDenied_and_never_renews() + { + var ct = TestContext.Current.CancellationToken; + using var origin = new LocalDataFixture(servingGeneration: 1); + origin.Publish(42); + var connections = new CountingConnections(origin); + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, access, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + // Positive control: before the lapse the same caller is refused for the ACL, not the lease. + (await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code); + origin.Clock.Advance(TimeSpan.FromSeconds(16)); + var metadata = connections.MetadataCalls; + for (var i = 0; i < 3; i++) + (await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code); + await Task.Delay(200, ct); + connections.MetadataCalls.ShouldBe(metadata, "an unauthorized caller never triggers a renewal at the origin"); + connections.ReadCalls.ShouldBe(0); + // Counted synchronously when a renewal is admitted, so this absence is not a race with a background task. + access.LapseRenewalsStartedForTests.ShouldBe(0); + }, connectionSource: connections, localPermissions: BrowseOnlyGrant); + } + + [Fact(Timeout = 90000), Trait("Issue", "922")] + public async Task A_history_read_after_the_metadata_lease_lapses_renews_within_the_request_and_is_served() + { + await using var originServer = await HistoryOrigin.StartAsync(7); + using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + StatusCode.IsGood((await RawHistory(client, anchor, 3, default)).StatusCode).ShouldBeTrue(); + origin.Clock.Advance(TimeSpan.FromSeconds(16)); + + var lapsed = await RawHistory(client, anchor, 3, default); + lapsed.StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code, "a lease lapse is not an authorization failure"); + StatusCode.IsGood(lapsed.StatusCode).ShouldBeTrue(lapsed.StatusCode.ToString()); + Values(lapsed).Count.ShouldBe(3); + }, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin)); + } + + [Fact(Timeout = 90000), Trait("Issue", "922")] + public async Task A_lapsed_history_read_whose_renewal_cannot_reach_the_origin_is_retryable_not_denied_and_recovers() + { + await using var originServer = await HistoryOrigin.StartAsync(7); + using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); + var connections = new DownableConnections(new PersistentConnections(origin)); + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + origin.Clock.Advance(TimeSpan.FromSeconds(16)); + connections.Down = true; + var calls = originServer.Source.Calls; + var down = await RawHistory(client, anchor, 3, default); + down.StatusCode.Code.ShouldBe(StatusCodes.BadResourceUnavailable.Code, "granted, lapsed, origin unreachable: retryable"); + originServer.Source.Calls.ShouldBe(calls, "nothing is read under a lapsed lease"); + + connections.Down = false; + origin.Clock.Advance(ProjectedDataAccess.LapseRenewalBackoff + TimeSpan.FromMilliseconds(1)); // past the failure back-off + var recovered = await RawHistory(client, anchor, 3, default); + StatusCode.IsGood(recovered.StatusCode).ShouldBeTrue(recovered.StatusCode.ToString()); + }, localPermissions: 15, allowHistory: true, connectionSource: connections); + } + + [Fact(Timeout = 90000), Trait("Issue", "922")] + public async Task Without_the_local_history_grant_a_lapsed_history_read_is_still_BadUserAccessDenied_and_unsent() + { + await using var originServer = await HistoryOrigin.StartAsync(7); + using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + origin.Clock.Advance(TimeSpan.FromSeconds(16)); + var result = await RawHistory(client, anchor, 3, default); + result.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code); + result.ContinuationPoint.IsEmpty.ShouldBeTrue(); + originServer.Source.Calls.ShouldBe(0); + }, localPermissions: 7, allowHistory: true, connectionSource: new PersistentConnections(origin)); + } + + [Fact(Timeout = 90000), Trait("Issue", "922")] + public async Task A_rebrowse_served_from_a_cached_page_past_half_its_lease_renews_the_lease() + { + var ct = TestContext.Current.CancellationToken; + using var origin = new LocalDataFixture(servingGeneration: 1); + origin.Publish(42); + var connections = new CountingConnections(origin); + await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, _, _, anchor) => + { + var client = (SessionClient)session; + var id = ProjectedDataIds.Identifier("map", origin.Raw.Address); + await BrowseAll(client, anchor, 1); + var browses = connections.BrowseCalls; + + // Inside the first half the cached page is served as is (no origin call). + origin.Clock.Advance(TimeSpan.FromSeconds(5)); + await BrowseAll(client, anchor, 1); + await Task.Delay(200, ct); + connections.BrowseCalls.ShouldBe(browses, "a fresh cached page is served without an origin call"); + + // Past half its life the cached page is still served, and the re-browse refreshes it in the background. + origin.Clock.Advance(TimeSpan.FromSeconds(5)); + await BrowseAll(client, anchor, 1); + for (var i = 0; i < 200 && connections.BrowseCalls == browses; i++) await Task.Delay(25, ct); + connections.BrowseCalls.ShouldBeGreaterThan(browses, "the re-browse refreshed the cached page"); + + // The original lease (t0 + 15 s) is gone; the renewed one still holds at t0 + 20 s. + ProjectedNodeProof? renewed = null; + for (var i = 0; i < 200; i++) + { + if (resolver.TryResolveProjected(DataRealm.Raw, id, out renewed) && renewed is not null && + ((BoundProjectionLease)renewed.Lease).Remaining > TimeSpan.FromSeconds(10)) break; + await Task.Delay(25, ct); + } + origin.Clock.Advance(TimeSpan.FromSeconds(10)); + resolver.TryResolveProjected(DataRealm.Raw, id, out _).ShouldBeTrue("the re-browse renewed the node's lease"); + (await ReadUntilGood(client, anchor, ct)).ShouldBe(42); + }, connectionSource: connections, staleTimeoutMilliseconds: LongStale); + } + + private static async Task ReadValue(SessionClient client, NodeId node, CancellationToken ct) => + (await client.ReadAsync(new RequestHeader(), LongMaxAge, TimestampsToReturn.Both, + [new ReadValueId { NodeId = node, AttributeId = Attributes.Value }], ct)).Results[0]; + + private static async Task ReadUntilGood(SessionClient client, NodeId node, CancellationToken ct) + { + var deadline = DateTime.UtcNow.AddSeconds(10); + Opc.Ua.DataValue value; + do + { + value = await ReadValue(client, node, ct); + if (StatusCode.IsGood(value.StatusCode)) return value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy); + value.StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code); + await Task.Delay(25, ct); + } while (DateTime.UtcNow < deadline); + throw new ShouldAssertException($"the projected read never became Good (last {value.StatusCode})"); + } + + /// A connection source that can be switched to "no connection" (an unreachable origin / undeployed route). + private sealed class DownableConnections(IGrpcDataAdapterConnectionSource inner) : IGrpcDataAdapterConnectionSource + { + public volatile bool Down; + public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken) => + Down ? ValueTask.FromResult(null) : inner.AcquireAsync(connectionId, cancellationToken); + } + + /// Like FakeConnections, counting browse, metadata and read calls separately. + private sealed class CountingConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource + { + private int _browse, _metadata, _read; + public int BrowseCalls => Volatile.Read(ref _browse); + public int MetadataCalls => Volatile.Read(ref _metadata); + public int ReadCalls => Volatile.Read(ref _read); + public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken) => + ValueTask.FromResult(connectionId == "link" ? new Lease(new Connection(peer.Connection(), this)) : null); + private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease + { + public IDataConnection Connection => connection; + public CancellationToken CancellationToken => CancellationToken.None; + public ValueTask DisposeAsync() => connection.DisposeAsync(); + } + private sealed class Connection(IDataConnection inner, CountingConnections owner) : IDataConnection + { + public DataTarget Target => inner.Target; + public TimeProvider Clock => inner.Clock; + public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => inner.GetCapabilitiesAsync(budget, cancellationToken); + public Task BrowseAsync(DataBrowseRequest request, CancellationToken cancellationToken) + { Interlocked.Increment(ref owner._browse); return inner.BrowseAsync(request, cancellationToken); } + public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) + { Interlocked.Increment(ref owner._metadata); return inner.GetMetadataAsync(request, cancellationToken); } + public Task> ReadAsync(DataReadRequest request, CancellationToken cancellationToken) + { Interlocked.Increment(ref owner._read); return inner.ReadAsync(request, cancellationToken); } + public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => inner.WriteAsync(request, cancellationToken); + public Task SubscribeAsync(CancellationToken cancellationToken) => inner.SubscribeAsync(cancellationToken); + public ValueTask DisposeAsync() => inner.DisposeAsync(); + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs index d7338e99f..9b3b91ac2 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs @@ -33,6 +33,43 @@ public sealed class GrpcDataLocalConnectionTests expired.Items.ShouldBeEmpty(); } + /// + /// #917 review: Browse skips unsupported value nodes across page boundaries. With a page size of 2 and children + /// [Speed, u, u, u, v, u, v], every supported child appears exactly once, no unsupported one appears, the walk + /// completes, and no page is empty: a skipped node does not count against the page's scan bound, so the skip + /// never produces an empty Complete = false page. + /// + [Fact] + public async Task Browse_skips_unsupported_value_nodes_across_page_boundaries_917() + { + using var fixture = new LocalDataFixture(siblingPattern: "uuuvuv"); + await using var connection = fixture.Connection(); + var budget = LocalDataFixture.Budget with { MaxItems = 2 }; + var seen = new List(); + var pages = 0; + string? continuation = null; + while (true) + { + var page = await connection.BrowseAsync(new(fixture.Root, null, continuation, budget), TestContext.Current.CancellationToken); + page.Status.ShouldBe(DataItemStatus.Good); + page.Items.ShouldNotBeEmpty($"page {pages}"); + page.Items.Count.ShouldBeLessThanOrEqualTo(2); + seen.AddRange(page.Items.Select(x => x.BrowseName)); + pages++; + if (page.Complete) { page.Continuation.ShouldBeNull(); break; } + page.Continuation.ShouldNotBeNull(); + continuation = page.Continuation; + pages.ShouldBeLessThan(10); + } + seen.ShouldBe(["Speed", "c3", "c5"]); + pages.ShouldBe(2); + // Positive control: the unsupported siblings are in the catalog and addressable (Unsupported, not NotFound). + fixture.Catalog.Nodes.Count(n => !n.Supported).ShouldBe(4); + var metadata = await connection.GetMetadataAsync(new([fixture.Root with { Address = fixture.Root.Address with { Identifier = "Plant/c0" }, + Subject = "Plant/c0" }], LocalDataFixture.Budget), TestContext.Current.CancellationToken); + metadata.ShouldHaveSingleItem().Status.ShouldBe(DataItemStatus.Unsupported); + } + [Fact] public async Task Metadata_bootstrap_resolves_address_and_never_uses_the_claimed_subject_as_authority() { @@ -136,7 +173,8 @@ internal sealed class LocalDataFixture : IDisposable bool advanceAuthority = false, string role = "Primary", long servingGeneration = 0, bool nestedCatalog = false, bool nestedUnsCatalog = false, Func? writes = null, bool denyReadExport = false, ManualTimeProvider? clock = null, string servingNode = "node-a", string servingIncarnation = "serving-1", - IOriginHistoryPort? history = null, DataValueKind rawValueKind = DataValueKind.Int32, int maxBatchItems = 100) + IOriginHistoryPort? history = null, DataValueKind rawValueKind = DataValueKind.Int32, int maxBatchItems = 100, + string? siblingPattern = null) { if (clock is not null) Clock = clock; Serving = Serving with { NodeId = servingNode, Incarnation = servingIncarnation, Role = role, ServingGeneration = servingGeneration }; @@ -191,6 +229,17 @@ internal sealed class LocalDataFixture : IDisposable nodes.Add(new("RawTag", "extra-" + i, rawMetadata with { View = view, BrowseName = "Speed" + i }, new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Driver", "Device", "Speed" + i] }, Root, Ticket.Key)); } + // #917: "u" = an unsupported value node (as an alarm-bearing tag compiles), "v" = a supported one, named c0, c1, ... + // in order (they sort after "Speed"), all under Root. + for (var i = 0; i < (siblingPattern?.Length ?? 0); i++) + { + var name = "c" + i.ToString(System.Globalization.CultureInfo.InvariantCulture); + var view = Raw with { Address = Raw.Address with { Identifier = "Plant/" + name }, Subject = "Plant/" + name }; + var supported = siblingPattern![i] == 'v'; + nodes.Add(new("RawTag", "sibling-" + name, supported ? rawMetadata with { View = view, BrowseName = name } + : rawMetadata with { View = view, BrowseName = name, NodeKind = "UnsupportedVariable", ValueKind = DataValueKind.Null, Writable = false }, + new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", name] }, Root, Ticket.Key, Supported: supported)); + } Catalog = new LocalExportCatalog("cluster", Serving, Activation.CaptureAuthority(), nodes, [new() { DataExportId = "raw-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw, RootKind = "RawFolder", RootEntityId = "folder", PrincipalId = "peer", AllowedOperations = operations }, new() { DataExportId = "uns-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = nestedUnsCatalog ? "UnsArea" : "UnsTagReference", RootEntityId = nestedUnsCatalog ? "area" : "reference", PrincipalId = "peer", AllowedOperations = operations }]); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkBadQualityEvidenceTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkBadQualityEvidenceTests.cs index 8dfa10423..d4be3e57d 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkBadQualityEvidenceTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkBadQualityEvidenceTests.cs @@ -56,6 +56,21 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests var item = keys.Cast().OfType().Single(x => x.ClientHandle == 1); var candidates = (System.Collections.IEnumerable)item.GetType().GetField("_candidates", flags)!.GetValue(item)!; candidates.Cast().Count().ShouldBe(scenario is "ambiguous" or "missing_timestamp" ? 2 : 1); + // #920: SDK 2.0.1 delivers a node change to its items asynchronously (MonitoredNode2's channel), so the + // sample published above can reach this item AFTER the mode cycle below — and, at queue size 1, overwrite + // the injected notification with the genuinely proven sample. Wait until the SDK has queued it, so the + // mode cycle discards it and the injected notification is the one delivered. (With two publishes the + // second may still be in flight; it is ambiguous against both candidates and denied either way.) + var lastValue = typeof(Opc.Ua.Server.MonitoredItem).GetField("m_lastValue", flags).ShouldNotBeNull(); + var delivered = System.Diagnostics.Stopwatch.StartNew(); + // The baseline sample shares the fake clock's timestamp, so match the status too. + static bool IsPublishedSample(Opc.Ua.DataValue value, DateTime at) => + value.SourceTimestamp == (DateTimeUtc)at && value.StatusCode == StatusCodes.BadNoCommunication; + while (!IsPublishedSample((Opc.Ua.DataValue)lastValue.GetValue(item)!, timestamp)) + { + delivered.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(10), "the SDK never queued the published sample"); + await Task.Delay(10, ct); + } item.SetMonitoringMode(MonitoringMode.Disabled); if (scenario == "different_status") { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkSourceLossTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkSourceLossTests.cs index b0d523e76..fac1beb35 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkSourceLossTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkSourceLossTests.cs @@ -111,6 +111,75 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests }); } + /// + /// #920: a subscription demand disposed while its stream pump is publishing the snapshot it asked for (a failed + /// SDK item construction disposes it on the SDK thread) must not re-publish the already-published, still-fresh + /// acquisition as a new complete baseline. It did: the duplicate-baseline check read the dying demand's validity + /// as "the cache is not fresh", so the same acquisition reached every existing item on the node again and left an + /// orphan proof candidate (and its shared budget charge) on each — no SDK notification ever consumes it, because + /// the node's value did not change. + /// + [Fact(Timeout = 90000), Trait("Phase", "P11Wire")] + public async Task A_demand_disposed_mid_publish_does_not_republish_a_fresh_baseline() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; subscriptions.SampleClock = origin.Clock; + var published = Channel.CreateUnbounded(); + await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, access, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + IProjectedDemandLease? first = null; + var armed = 0; + var disposed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + access.AfterPublishDemandCheckForTests = demand => + { + first ??= demand; + if (ReferenceEquals(demand, first) || Interlocked.Exchange(ref armed, 0) != 1) return; + demand.Dispose(); + disposed.TrySetResult(); + }; + var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, sub, anchor, 1, 100, ct); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + (await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.SourceVersion == 1, ct)).Snapshot.Value.ShouldBe(7); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic; + var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!; + var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!; + var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!; + var existing = keys.Cast().OfType().Single(x => x.ClientHandle == 1); + int Candidates() => ((System.Collections.IEnumerable)existing.GetType().GetField("_candidates", flags)!.GetValue(existing)!).Cast().Count(); + Candidates().ShouldBe(0, "the delivered baseline consumed its candidate"); + + // A second item on the same node: its stream snapshot repeats the same (still fresh) acquisition, and its + // demand is disposed on the pump right after the publish passed its demand check. + Volatile.Write(ref armed, 1); + await AddComposedItem(client, sub, anchor, 2, 100, ct); + var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + await disposed.Task.WaitAsync(TimeSpan.FromSeconds(10), ct); + // The pump handles the removal only after it finished that publish, so the publish is over once it is sent. + var removed = System.Diagnostics.Stopwatch.StartNew(); + while (stream.RemoveCommands == 0) + { + removed.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(10), "the disposed demand's item was never removed"); + await Task.Delay(10, ct); + } + + // Positive control: a third item's snapshot carries a NEW acquisition (v2) through the same in-order publisher. + subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8; + await AddComposedItem(client, sub, anchor, 3, 100, ct); + var seen = new List(); + ProjectedValueUpdate next; + do { next = await NextPublished(published.Reader, _ => true, ct); seen.Add(next); } while (next.SourceVersion != 2); + seen.Count(x => x.SourceVersion == 1).ShouldBe(0, "the disposed demand re-published the fresh v1 baseline"); + Candidates().ShouldBe(1, "only the v2 baseline holds a candidate on the existing item"); + }, onPublished: update => published.Writer.TryWrite(update)); + } + private sealed class ThrowingSourceProof(IProjectedSamplePublicationProof inner) : IProjectedSamplePublicationProof { public bool IsValid => inner.IsValid; diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorApplyingStashTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorApplyingStashTests.cs index 4cc820fa7..6fdeb52bc 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorApplyingStashTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorApplyingStashTests.cs @@ -1,12 +1,14 @@ using System.Text.Json; using Akka.Actor; using Akka.Event; +using Microsoft.EntityFrameworkCore; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.Interfaces; using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy; using ZB.MOM.WW.OtOpcUa.Commons.Messages.Fleet; using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.Configuration; using ZB.MOM.WW.OtOpcUa.Runtime.DeploymentCache; using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; @@ -292,6 +294,69 @@ public sealed class DriverHostActorApplyingStashTests() logs["appears WEDGED"].ShouldBe(0); } + /// + /// The watchdog times the artifact read/fetch, NOT the synchronous Applying-row write that + /// precedes it — a slow ConfigDb row write must not be reported as a wedged fetch. + /// + /// + /// + /// The wedge timer used to be armed BEFORE UpsertNodeDeploymentState(Applying), which + /// runs synchronously on the actor thread. Any write slower than the wedge delay therefore + /// enqueued the tick before the fetch had even started, so it was dequeued ahead of the + /// fetch's pipe-back and logged "the artifact read/fetch has neither answered nor failed" for + /// a fetch that answered immediately. This is what made + /// fail whenever it ran first in its process: + /// the cold EF Core model build on that first row write took ~350 ms against a 200 ms delay. + /// + /// + /// Every row write here is slowed to 4× the delay, deterministically. Writes that land + /// AFTER the fetch's pipe-back (the final Applied row) are harmless either way: a tick + /// enqueued during them is discarded by Akka's TimerScheduler once BecomeSteady cancels the + /// key. The presence control is the Applied ack — the apply really did run through the slow + /// writes. + /// + /// + [Fact] + public void ASlowApplyingRowWrite_IsNotReportedAsAWedgedFetch() + { + var wedgeTimeout = TimeSpan.FromMilliseconds(200); + var db = new SlowDbFactory(NewInMemoryDbFactory(), wedgeTimeout * 4); + var deploymentA = DeploymentId.NewId(); + + var coordinator = CreateTestProbe(); + var actor = Sys.ActorOf(DriverHostActor.Props( + db, TestNode, coordinator.Ref, + localRoles: new HashSet { "driver" }, + deploymentArtifactCache: new NullArtifactCache(), + fetchAndCacheMode: true, + artifactFetcher: new GatedFetcher(ArtifactBytes(), gatedCalls: 0), + applyWedgeTimeout: wedgeTimeout)); + + var logs = SubscribeToLogs("appears WEDGED"); + actor.Tell(new DispatchDeployment(deploymentA, RevA, CorrelationId.NewId())); + coordinator.ExpectMsg(TimeSpan.FromSeconds(20), cancellationToken: TestContext.Current.CancellationToken).Outcome.ShouldBe(ApplyAckOutcome.Applied); + db.Calls.ShouldBeGreaterThanOrEqualTo(1); + + logs.Drain(SpinWindow); + logs["appears WEDGED"].ShouldBe(0); + } + + /// Delays every on the calling thread. + private sealed class SlowDbFactory(IDbContextFactory inner, TimeSpan delay) + : IDbContextFactory + { + private int _calls; + + public int Calls => Volatile.Read(ref _calls); + + public OtOpcUaConfigDbContext CreateDbContext() + { + Interlocked.Increment(ref _calls); + Thread.Sleep(delay); + return inner.CreateDbContext(); + } + } + /// Subscribes a fresh counter to the EventStream's log events. /// /// Every fragment of interest must be declared up front, because draining is destructive: a diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmInitialStateSignalTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmInitialStateSignalTests.cs index bfd05f067..661ddb660 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmInitialStateSignalTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmInitialStateSignalTests.cs @@ -115,6 +115,82 @@ public sealed class NativeAlarmInitialStateSignalTests : NativeAlarmSignalTestBa AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(300)); } + /// + /// #926: a driver that signalled and then lost events WITHDRAWS: the host sends Known: false for exactly + /// those conditions (after the projections before it), puts them back in the F5 window (diagnosed if the driver + /// never re-signals), and a later real signal marks them known again. + /// + [Fact] + public void A_withdrawn_signal_takes_known_back_and_rearms_F5_until_the_next_signal() + { + var rig = StartRig(DriverTypeNames.OpcUaClient, ["hi", "lo"], + o => o.WithSignalTimeout(DriverTypeNames.OpcUaClient, TimeSpan.FromMilliseconds(400))); + rig.Driver.Signal([A, B]).ShouldBeTrue(); + rig.Publish.FishForMessage(m => m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct) + .ConditionIds.ShouldBe([A, B], ignoreOrder: true); + rig.Hub.Unsignalled.ContainsKey(DriverId).ShouldBeFalse(); + + rig.Driver.Raise(A).ShouldBeTrue(); + rig.Driver.Signal([A], withdrawn: true).ShouldBeTrue(); + var traffic = new List(); + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10); + while (DateTime.UtcNow < deadline) + { + var m = rig.Publish.ReceiveOne(deadline - DateTime.UtcNow, Ct); + if (m is null) break; + if (m is not (OpcUaPublishActor.AlarmStateUpdate or OpcUaPublishActor.MarkConditionsKnown)) continue; + traffic.Add(m); + if (m is OpcUaPublishActor.MarkConditionsKnown { Known: false }) break; + } + traffic[^1].ShouldBeOfType().Known.ShouldBeFalse(); + traffic.FindIndex(m => m is OpcUaPublishActor.AlarmStateUpdate u && u.AlarmNodeId == A) + .ShouldBeLessThan(traffic.Count - 1, "the withdrawal follows the projection raised before it"); + var withdrawal = (OpcUaPublishActor.MarkConditionsKnown)traffic[^1]; + withdrawal.ConditionIds.ShouldBe([A], "only the withdrawn conditions"); + + // Never re-signalled ⇒ F5 diagnoses it (and it is never marked known by a timer). + AwaitCondition(() => rig.Hub.Unsignalled.ContainsKey(DriverId), TimeSpan.FromSeconds(5), Ct); + rig.Hub.Unsignalled[DriverId].Conditions.ShouldBe(1); + AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(300)); + + // Positive control: the next real signal marks it known again and clears the diagnostic. + rig.Driver.Signal([A, B]).ShouldBeTrue(); + rig.Publish.FishForMessage(m => m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct); + AwaitCondition(() => !rig.Hub.Unsignalled.ContainsKey(DriverId), TimeSpan.FromSeconds(5), Ct); + } + + /// #926: a withdrawal removes the conditions from the OpcUaClient backstop — the timer must never mark a + /// condition known whose source just said it lost events. Positive control: the sibling it did not withdraw IS + /// marked by the same backstop. + [Fact] + public void A_withdrawal_cancels_the_backstop_for_its_conditions() + { + var rig = StartRig(DriverTypeNames.OpcUaClient, ["hi", "lo"], o => o.WithOpcUaClientSettle(TimeSpan.FromMilliseconds(600))); + rig.Driver.Signal([A, B], unsignalable: true); + rig.Driver.Signal([A], withdrawn: true); + var mark = rig.Publish.FishForMessage(m => m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct); + mark.ConditionIds.ShouldBe([B], "only the sibling the driver did not withdraw"); + AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(800)); + } + + /// #926 review r2: a withdrawal after F5 already raised its diagnostic updates the diagnostic's count. + [Fact] + public void A_withdrawal_after_the_diagnostic_updates_its_count() + { + var rig = StartRig(DriverTypeNames.OpcUaClient, ["hi", "lo"], + o => o.WithSignalTimeout(DriverTypeNames.OpcUaClient, TimeSpan.FromMilliseconds(300))); + rig.Driver.Signal([A]).ShouldBeTrue(); // B stays pending + AwaitCondition(() => rig.Hub.Unsignalled.TryGetValue(DriverId, out var d) && d.Conditions == 1, TimeSpan.FromSeconds(5), Ct); + + rig.Driver.Signal([A], withdrawn: true).ShouldBeTrue(); + AwaitCondition(() => rig.Hub.Unsignalled.TryGetValue(DriverId, out var d) && d.Conditions == 2, TimeSpan.FromSeconds(5), Ct); + } + + /// #926: the payload is either unsignalable or a withdrawal. + [Fact] + public void Unsignalable_and_withdrawn_are_exclusive() => + Should.Throw(() => new AlarmInitialStateEventArgs([A], unsignalable: true, withdrawn: true)); + // ---------------------------------------------------------------- review S2 / re-arm F5 / nits /// diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmSignalTestBase.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmSignalTestBase.cs index eeb65ca06..b125b4f8f 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmSignalTestBase.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmSignalTestBase.cs @@ -290,10 +290,10 @@ public sealed class FakeSignallingAlarmDriver(string driverInstanceId, string dr /// The conditions it covers. /// Report InitialStateUnsignalable instead. /// Whether it was raised. - public bool Signal(IReadOnlyList conditionIds, bool unsignalable = false) + public bool Signal(IReadOnlyList conditionIds, bool unsignalable = false, bool withdrawn = false) { if (!_subscribed) return false; - InitialAlarmStateDelivered?.Invoke(this, new AlarmInitialStateEventArgs(conditionIds, unsignalable)); + InitialAlarmStateDelivered?.Invoke(this, new AlarmInitialStateEventArgs(conditionIds, unsignalable, withdrawn)); return true; } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorConditionKnownTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorConditionKnownTests.cs index 523a0e65c..0e35fffb5 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorConditionKnownTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorConditionKnownTests.cs @@ -13,8 +13,9 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.OpcUa; /// /// A1 (plan §5.1 F2/G3): is an alarm message. Live it applies in -/// arrival order; while a plan is in flight it is deferred beside the alarm states and replayed AFTER them — and a -/// source that lost a deferred projection (overflow or out-of-scope skip) has its deferred marks discarded. +/// arrival order; while a plan is in flight it is deferred beside the alarm states and replayed with them in arrival +/// order (#926 review r2) — and a source that lost a deferred projection (overflow or out-of-scope skip) has its +/// deferred KNOWN marks discarded. /// [Trait("Feature", "GrpcData")] [Trait("Phase", "A1")] @@ -171,7 +172,8 @@ public sealed class OpcUaPublishActorConditionKnownTests : RuntimeActorTestBase } /// Review round 2 N1: a deferred withdrawal is never dropped by the deferral's capacity (a known mark may be — - /// unknown is the safe side). + /// unknown is the safe side). #926 review r2: deferred marks are held per condition, so repeated withdrawals of one + /// condition coalesce into one replayed withdrawal (bounded by the number of conditions). [Fact] public void A_withdrawal_beyond_the_deferral_capacity_is_never_dropped() { @@ -187,7 +189,45 @@ public sealed class OpcUaPublishActorConditionKnownTests : RuntimeActorTestBase gate.Set(); ExpectMsg(PlanBudget, cancellationToken: TestContext.Current.CancellationToken); - AwaitAssert(() => sink.Log.Count(l => l == "unknown:al-1").ShouldBe(6), PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + AwaitAssert(() => sink.Log.Count(l => l == "unknown:al-1").ShouldBe(4), PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + sink.IsKnown("al-1").ShouldBeFalse(); + } + + /// + /// #926 review r2: a withdrawal followed by a live transition of the same condition, both deferred by a plan, + /// replays in ARRIVAL order — withdrawal, then the transition that re-establishes it — so the condition ends known, + /// as the live path leaves it (marks used to replay after every alarm, ending it unknown while the host no longer + /// counted it in F5). The mirror order (transition, then withdrawal) ends unknown. + /// + [Fact] + public void Deferred_alarms_and_marks_replay_in_arrival_order() + { + var sink = new OrderSink(); + using var gate = new ManualResetEventSlim(false); + var actor = Spawn(sink, gate); + + actor.Tell(Rebuild()); + actor.Tell(new OpcUaPublishActor.MarkConditionsKnown("drv-1", ["al-1"], AddressSpaceRealm.Uns, Known: false)); + actor.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-1", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, "drv-1")); + AwaitAssert(() => sink.Skipped.ShouldContain("alarm:al-1"), PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + + gate.Set(); + ExpectMsg(PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + sink.Log.ShouldBe(["unknown:al-1", "alarm:al-1:True"], "replayed in arrival order"); + sink.IsKnown("al-1").ShouldBeTrue("the transition after the withdrawal re-established it"); + + // Mirror (positive control for the order): transition, then withdrawal ⇒ unknown. + var sink2 = new OrderSink(); + using var gate2 = new ManualResetEventSlim(false); + var actor2 = Spawn(sink2, gate2); + actor2.Tell(Rebuild()); + actor2.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-1", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, "drv-1")); + actor2.Tell(new OpcUaPublishActor.MarkConditionsKnown("drv-1", ["al-1"], AddressSpaceRealm.Uns, Known: false)); + AwaitAssert(() => sink2.Skipped.ShouldContain("alarm:al-1"), PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + gate2.Set(); + ExpectMsg(PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + sink2.Log.ShouldBe(["alarm:al-1:True", "unknown:al-1"]); + sink2.IsKnown("al-1").ShouldBeFalse(); } /// Review round 2 N2: a G3 discard of a driver's deferred mark is reported back to the mark's sender, so its diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorWarmTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorWarmTests.cs index 3f3201218..8b5fd960f 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorWarmTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorWarmTests.cs @@ -338,11 +338,17 @@ public sealed class OpcUaPublishActorWarmTests : RuntimeActorTestBase Encoding.UTF8.GetBytes("{\"Clusters\":[{\"ClusterId\":\"a\",\"RedundancyMode\":\"None\"},{\"ClusterId\":\"b\",\"RedundancyMode\":\"Hot\"}]," + "\"Nodes\":[{\"NodeId\":\"x:1\",\"ClusterId\":\"b\"}]}"), "x:1").ShouldBe("Hot"); + // Read the counter BEFORE the listener exists. If OtOpcUaTelemetry's static initializer has not run + // yet (this test alone in its process), it runs at the actor's first use while the listener is live, + // Meter.CreateCounter publishes each instrument to the live listener from INSIDE that initializer, and + // the field still reads null there — the counter was never enabled and the count stayed 0 + // (Runtime.Tests master failures). A captured local is assigned by the time anything is published. + var counter = ZB.MOM.WW.OtOpcUa.Commons.Observability.OtOpcUaTelemetry.RedundancyModeMismatch; using var listener = new System.Diagnostics.Metrics.MeterListener(); long mismatches = 0; listener.InstrumentPublished = (instrument, l) => { - if (ReferenceEquals(instrument, ZB.MOM.WW.OtOpcUa.Commons.Observability.OtOpcUaTelemetry.RedundancyModeMismatch)) + if (ReferenceEquals(instrument, counter)) l.EnableMeasurementEvents(instrument); }; listener.SetMeasurementEventCallback((_, value, _, _) => Interlocked.Add(ref mismatches, value));