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 6abcf2173..3bb941db9 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -194,11 +194,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) @@ -224,6 +248,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.** @@ -503,8 +531,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..1fcc62dfa 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 @@ -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) | @@ -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 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/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 464425720..ff0b95cd9 100644 --- a/docs/plans/evidence/grpc-data-ext/H3.md +++ b/docs/plans/evidence/grpc-data-ext/H3.md @@ -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..5cc1562b3 100644 --- a/docs/plans/evidence/grpc-data-ext/X0.md +++ b/docs/plans/evidence/grpc-data-ext/X0.md @@ -220,6 +220,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/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 752ced183..903aa4bd8 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") -TIMEOUTS = {"A01": 420, "A02": 360, "A03": 1200, "A04": 480, "A05": 720, "A06": 1200, "A07": 900, "A08": 720} +SCENARIOS = ("A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "A09") +TIMEOUTS = {"A01": 420, "A02": 360, "A03": 1200, "A04": 480, "A05": 720, "A06": 1200, "A07": 900, "A08": 720, "A09": 600} +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) @@ -510,6 +511,88 @@ class ConditionScenarios: return {"code": code, "output": text[-300:], "good": code == 0 and ("successful" in text or "Comment added" in text), "event_id_unknown": "BadEventIdUnknown" in text} + # ---- 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 @@ -800,6 +883,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_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/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.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/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/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 3e74d18c4..1538fb5db 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -3095,7 +3095,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 @@ -3105,7 +3106,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); @@ -3126,6 +3126,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) @@ -3164,7 +3170,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 @@ -3174,6 +3179,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/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/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));