diff --git a/.claude/rules/drivers.md b/.claude/rules/drivers.md index 1676f81f2..41fcf79e1 100644 --- a/.claude/rules/drivers.md +++ b/.claude/rules/drivers.md @@ -211,8 +211,11 @@ host logger factory (wired in `DriverFactoryBootstrap`; the FOCAS and TwinCAT fa retain handling rides only a 5.0 SUBSCRIBE (MQTTnet refuses it on 3.1.1). Sparkplug metadata rebirths are capped at 3 per SCOPE and re-armed only by clean data for that scope (never by a birth — a rebirth request provokes one); gap rebirths escalate to one per 5 min after 3 with no contiguous message. A `Faulted` - primary-host claim connection is not a held claim (re-claimed); with `clientId` unset the claim id is a - random `spbhost-<12 hex>`. + primary-host claim connection is not a held claim (re-claimed); with `clientId` unset the claim id is + `spbhost-<12 hex>` = a STABLE hash of host id + group id — the same on both nodes of a pair, so a cold-starting + Secondary's claim takes the Primary's over instead of coexisting (never make it random again). The claim + subscribes to its own STATE topic and re-asserts over an OFFLINE it did not publish (older/equal ts ⇒ republish; + newer ⇒ fresh claim with a newer ts; ≤ 1 per 2 s). - **No driver-side history (#655):** `IHistoryProvider`, `DriverCapability.HistoryRead`, `HistoryReadStatusException` and the OpcUaClient history passthrough are deleted — nothing ever dispatched HistoryRead to a driver; it is served only by the server-wide `IHistorianDataSource`. `isHistorized` on an OpcUaClient tag means OtOpcUa records it, not that upstream diff --git a/docs/Configuration.md b/docs/Configuration.md index 73231e647..99c1c6210 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -459,7 +459,7 @@ The Galaxy/MxAccess connection settings are **not an `appsettings` section.** Th | Record | Key fields (default) | Meaning | |---|---|---| | `GalaxyGatewayOptions` (`Gateway`) | `Endpoint`; `ApiKeySecretRef`; `UseTls` (`true`); `CaCertificatePath` (`null`); `ConnectTimeoutSeconds` (`10`); `DefaultCallTimeoutSeconds` (`30`); `StreamTimeoutSeconds` (`0` = unlimited); `KeepAlivePingDelaySeconds` (`15`, `0` = no pings); `KeepAlivePingTimeoutSeconds` (`10`) — HTTP/2 keep-alive on the driver's gateway channels, so a silently dead connection faults the event stream (#991 G-19) | mxaccessgw gateway connection. `ApiKeySecretRef` supports `secret:galaxy/` (or `secret:otopcua/galaxy/`) / `env:OTOPCUA_GALAXY_` (or legacy `env:GALAXY_MXGW_`) / `dev:KEY` / literal forms (resolved at `InitializeAsync`); prefer `secret:` in production. Any other `secret:`/`env:` reference and every `file:` reference is refused at save, deploy (`CredentialReferenceOutOfScope`), Test Connect, browse and resolve — #815, see `docs/security.md` §"Credential references are namespaced per driver". Never store a cleartext key. | -| `GalaxyMxAccessOptions` (`MxAccess`) | `ClientName`; `PublishingIntervalMs` (`1000`); `WriteUserId` (`0` = anonymous; the user a raw `Write` and a `WriteSecured` carry); `EventPumpChannelCapacity` (`50000`) | MXAccess client identity + tuning. `ClientName` **must be unique per OtOpcUa instance** (redundancy pairs enforce this). | +| `GalaxyMxAccessOptions` (`MxAccess`) | `ClientName`; `PublishingIntervalMs` (`1000`); `WriteUserId` (`0` = anonymous; the user a raw `Write` carries; SecuredWrite/VerifiedWrite attributes are refused `BadUserAccessDenied`); `EventPumpChannelCapacity` (`50000`) | MXAccess client identity + tuning. `ClientName` **must be unique per OtOpcUa instance** (redundancy pairs enforce this). | | `GalaxyRepositoryOptions` (`Repository`) | `DiscoverPageSize` (`5000`); `WatchDeployEvents` (`true`) | Galaxy Repository browse paging + deploy-event watching. | | `GalaxyReconnectOptions` (`Reconnect`) | `InitialBackoffMs` (`500`); `MaxBackoffMs` (`30000`); `ReplayOnSessionLost` (`true`) | In-driver reconnect-supervisor backoff. | | (top-level) | `ProbeTimeoutSeconds` (`30`, range 1–60) | AdminUI Test-Connect probe timeout. | diff --git a/docs/drivers/AbCip.md b/docs/drivers/AbCip.md index e29690560..bd93b3ab8 100644 --- a/docs/drivers/AbCip.md +++ b/docs/drivers/AbCip.md @@ -191,7 +191,7 @@ The driver has two interchangeable wire transports, selected by one `DriverConfi a held connection idling out, so this shape follows a controller restart / re-download or a network gap. - `ConnectionSize` / `Timeout` / `AllowPacking` are honoured per pooled connection, and the **first** driver/device to open a given device key wins — including a Test Connect probe on a fused `admin,driver` - node (a Test Connect probe carries its own probe timeout). The driver's own probe loop leases with the DRIVER's `Timeout` and bounds only its wait with the probe timeout (#983 P-22: it used to lease with the probe's, so a short probe timeout became every data read's). A later opener with different options is ignored and + node (a Test Connect probe carries its own probe timeout). The driver's own probe loop leases with the DRIVER's `Timeout` and bounds only its probe READ with the probe timeout (#983 P-22: it used to lease with the probe's, so a short probe timeout became every data read's; #983 review: the cold probe initialisation — connect + RegisterSession + Forward Open — is bounded by the driver's `Timeout`, not the probe's, or a slow-but-healthy open never completed and the host stayed `Stopped`). A later opener with different options is ignored and logged once as a Warning (`DeviceSessionPool`). ⚠️ The device key compares the **host string**, so the same controller addressed by DNS name in one driver and by IP in another gets two connections and two Forward Open throttles (up to two opens per second); address a controller the same way everywhere. ControlLogix, GuardLogix and (since T21) CompactLogix default to 4002, a Large @@ -517,7 +517,7 @@ UDT-typed tags found in the walk. ## Operational Notes -- **A dead device does not stall the others, and logs once (#983, review 2026-12-02 P-2/P-16).** Three layers: (1) the native request scheduler faults everything queued behind a failed *channel* exchange (timeout / closed session / failed open) with the same exception — it used to start one fresh attempt per queued batch, ~N/20 timeouts for a 1000-tag device; a request submitted afterwards is a fresh attempt, so recovery is not delayed; (2) `ReadAsync` keeps one read window **per device** and a per-call fault latch — the first connection-level failure of a device (`Timeout`/`BadConnection`/`Abort`, not a device refusal) makes that device's remaining items fail fast `BadCommunicationError` and evicts their handles, so the next poll goes through the cold-create backoff instead of the wire; (3) per-read comms failures log one Warning **per device per outage** (Debug after), a throttled create no longer logs per tag, and the first success logs one Info with the suppressed count. The latch is deliberately per call and does not open the connect backoff itself: a transient single failure must still re-create the handle on the next read (`AbCipDriverCodeReviewRegressionTests`). +- **A dead device does not stall the others, and logs once (#983, review 2026-12-02 P-2/P-16).** Three layers: (1) the native request scheduler faults everything queued behind a failed *channel* exchange (timeout / closed session / failed open) with the same exception — it used to start one fresh attempt per queued batch, ~N/20 timeouts for a 1000-tag device; a request submitted afterwards is a fresh attempt, so recovery is not delayed; (2) `ReadAsync` keeps one read window **per device** and a per-call fault latch — the first connection-level failure of a device (`BadConnection`/`Abort`, a socket/IO failure, and on the **native** transport a `Timeout` — which faults the device's one shared channel; not a device refusal) makes that device's remaining items fail fast `BadCommunicationError`. #983 review: a **libplctag** `Timeout` does NOT latch — each libplctag tag is its own request with its own timeout, so one slow tag used to fail every later sibling of the call; and the latched-out items' handles are **kept** (they never reached the wire — evicting them re-created, and for a sole lease holder re-Forward-Opened, every one on the next poll). The failed item's own handle is evicted, so the next poll re-creates it through the cold-create backoff, and a throttled create latches the device too (its kept warm handles then fail fast instead of each paying a timeout); (3) per-read comms failures log one Warning **per device per outage** (Debug after), a throttled create no longer logs per tag, and the first success logs one Info with the suppressed count. The latch is deliberately per call and does not open the connect backoff itself: a transient single failure must still re-create the handle on the next read (`AbCipDriverCodeReviewRegressionTests`). - **Whole BOOL-array reads count DWORDs (#983, P-13).** A Logix `BOOL[n]` is `ceil(n/32)` DWORDs (type `0xD3`) and a Read Tag's element count is in DWORDs; the native runtime now asks for that and, when the reply type is `0xC1` (one byte per BOOL, as `ab_server` answers), re-reads once with `n` and remembers it. **Not hardware-verified** — the unit evidence is a fake controller that refuses a 64-element read of `BOOL[64]`; the live gate is a whole read of a real `BOOL[64]`. Controller *browse* still maps symbol type `0xD3` to `Structure` (no hardware capture of the symbol-listing dims for a BOOL array exists), so browse-commit does not yet produce a correct Bool-array tag. - **Bit selector 0..63; whole-word writes share the RMW lock (#983, P-23).** `Tag.n` accepts 0..63 (a LINT host); the width check refuses a bit the host does not have. A whole-word write to an integer tag takes the same per-parent lock as the bit read-modify-writes of `Tag.n` (case-insensitive, like the parent runtime table), so neither can land between the other's read and write. Probe / alarm-poll intervals are floored at 100 ms at config parse (0 hot-looped, negative killed the loop). The discovered-UDT cycle guard keys on the struct *type* (template id), not the member name, so a nested member sharing its parent's name is browsed. A connection-level fault reading a program's symbol listing now aborts the browse instead of silently dropping the program. - **Native heap is invisible to the GC.** libplctag's native `Tag` heap does not show up in CLR allocation figures. Watch whole-process RSS, and use `ReinitializeAsync` (tears down + re-creates every device's libplctag handles) as the remediation for native-heap growth. (There is no per-driver footprint number to consult: `IDriver.GetMemoryFootprint()` was deleted as unconsumed in Gitea #525.) diff --git a/docs/drivers/AbLegacy.md b/docs/drivers/AbLegacy.md index 3ffc4f93d..c7ed9cf62 100644 --- a/docs/drivers/AbLegacy.md +++ b/docs/drivers/AbLegacy.md @@ -27,16 +27,18 @@ fixture coverage map, see [AbLegacy-Test-Fixture.md](AbLegacy-Test-Fixture.md). Per family the `AbLegacyPlcFamilyProfile` supplies the libplctag `plc` attribute, default CIP path, max-payload bytes, and the `SupportsStringFile` / `SupportsLongFile` capability flags. MicroLogix uses direct EIP (empty default -path); MicroLogix and PLC-5 don't ship L-files; PLC-5 predates them entirely. +path); PLC-5 predates L-files and is the only family without them. MicroLogix 1100/1200/1400/1500 ship L files (#984 +review — only the ML 1000 lacks them, and the family flag cannot tell it apart, so an ML 1000 answers an L read with +its own PCCC refusal, per tag). Tag types are validated against the device's profile — declaring a `Long` or `String` tag on a family that can't support it is **that tag's** configuration error (review 2026-12-02 P-5): init still succeeds, the tag reads and writes `BadConfigurationError` without touching the wire, one Warning is logged, and the tag appears in the skipped-tag report. The deploy gate (`AbLegacyTagDefinitionFactory.Inspect` with the device's `PlcFamily`, same `AbLegacyPlcFamilyProfile.UnsupportedDataTypeReason` -authority) warns earlier. Note the MicroLogix profile says `SupportsLongFile: false`; -MicroLogix 1100/1400 may in fact ship L files (product knowledge, unverified on -hardware here) — flipping the flag is a one-line change once a real controller confirms. +authority) warns earlier. The MicroLogix profile said `SupportsLongFile: false` until the #984 review, which refused +every `Long` tag on the family; it is now `true` per Rockwell's MicroLogix 1100/1200/1400/1500 documentation. ⚠️ Not yet +hardware-confirmed: a read of one authored `L` tag on an ML 1400 (Vitamine press fleet) is the pending gate. ## Capability Surface diff --git a/docs/drivers/Galaxy.md b/docs/drivers/Galaxy.md index 1ae83ce52..35c51965b 100644 --- a/docs/drivers/Galaxy.md +++ b/docs/drivers/Galaxy.md @@ -82,7 +82,7 @@ Project root files: `DriverConfig` JSON binds to `Config/GalaxyDriverOptions.cs`. The four sections are: - **`Gateway`** — endpoint, API key secret ref (`secret:galaxy/` · `secret:otopcua/galaxy/` · `env:OTOPCUA_GALAXY_` · legacy `env:GALAXY_MXGW_` · `dev:KEY` · literal; anything else, incl. `file:`, is refused — #815 (an already-deployed driver keeps resolving a pre-#815 ref on init and every gateway reconnect in deprecated warn-only mode until its next deploy), [`docs/security.md`](../security.md) §"Credential references are namespaced per driver"), TLS knobs, connect/call/stream timeouts. `StreamTimeoutSeconds = 0` keeps the long-lived `StreamEvents` RPC open for the driver's lifetime. `KeepAlivePingDelaySeconds` (`15`) / `KeepAlivePingTimeoutSeconds` (`10`) — HTTP/2 keep-alive pings on every gateway channel (#991 G-19, below); `0` disables them. -- **`MxAccess`** — `ClientName` (must be unique per OtOpcUa instance — redundancy pairs enforce uniqueness at install time), `PublishingIntervalMs` (forwarded as `buffered_update_interval_ms` on subscribe), `WriteUserId` — the user id a raw `Write` and (#991 G-1) a `WriteSecured` carry, `EventPumpChannelCapacity` (default 50_000 — one second of headroom at 50k tags / 1Hz; tune via the `galaxy.events.dropped` metric). +- **`MxAccess`** — `ClientName` (must be unique per OtOpcUa instance — redundancy pairs enforce uniqueness at install time), `PublishingIntervalMs` (forwarded as `buffered_update_interval_ms` on subscribe), `WriteUserId` — the user id a raw `Write` carries (secured/verified writes are refused, see below), `EventPumpChannelCapacity` (default 50_000 — one second of headroom at 50k tags / 1Hz; tune via the `galaxy.events.dropped` metric). - **`Repository`** — `DiscoverPageSize`, `WatchDeployEvents`. - **`Reconnect`** — `InitialBackoffMs`, `MaxBackoffMs`, `ReplayOnSessionLost` (default `true`: after a gateway session is recreated, re-issue `SubscribeBulk` for every tracked subscription; `false` leaves them stranded — Bad + Degraded, see [Reconnect + Replay](#reconnect--replay)). - **`AlarmAck`** (optional, lmxopcua#749) — `FallbackUser`, `FallbackDomain`, `FallbackPasswordSecretRef`. See [Alarm acknowledge credential](#alarm-acknowledge-credential). `ConfirmTimeoutMs` (default `10000`, max `120000`, `0` = do not wait, negative = default; #869) — see [Ack confirmation](#ack-confirmation-869). @@ -235,10 +235,24 @@ Every (re)open of `StreamAlarms` replays the gateway's active-alarm snapshot. `G - **MXAccess `ClientName` collisions**: two OtOpcUa instances sharing a `ClientName` cause the older Wonderware session to lose subscription state. Redundancy pairs (decision #149) enforce uniqueness via install scripts. - **Channel saturation**: `galaxy.events.dropped > 0` indicates `EventPump` is back-pressured. Raise `EventPumpChannelCapacity` or investigate downstream slowness in the server-side fan-out. -- **A dropped change is re-read (#991 G-4).** MXAccess sends a value only when it changes, so a data change the full channel drops (newest-dropped) used to leave its tag at the previous value, Good, until the attribute next changed. The pump records the item handles of dropped data changes and, once its channel has drained (so the resync is not lost to the same congestion), the driver re-advises exactly those tags — an advise is answered with the current value — rebinds them, and releases the superseded handles. One coalescing background worker; serialised with the replay-gap re-snapshot. The `galaxy.events.dropped` counter is unchanged; each burst logs one Warning ("re-reading them") and one Information line with the re-advised count. +- **A dropped change is re-read (#991 G-4).** MXAccess sends a value only when it changes, so a data change the full channel drops (newest-dropped) used to leave its tag at the previous value, Good, until the attribute next changed. The pump records the item handles of dropped data changes and, once its channel has drained (so the resync is not lost to the same congestion), the driver re-advises exactly those tags — an advise is answered with the current value — rebinds them, and releases the superseded handles. One coalescing background worker; serialised with the replay-gap re-snapshot. The `galaxy.events.dropped` counter is unchanged; each burst logs one Warning ("re-reading them") and one Information line with the re-advised count. **Rate-limited (#991 review):** passes are at least 5 s apart and drops reported meanwhile coalesce into the next pass — repeated overflow bursts used to start a pass as soon as the previous one ended, re-advising (and pushing initial values into) the very channel that was overflowing. **A pass whose gateway session is gone no longer dials:** a reconnect completing between two subscriptions of a re-advise pass (resync, replay-gap re-snapshot, reconnect replay) used to send the next SubscribeBulk to the NEW session under the OLD session number; the rebind refused it and those live advises were never bound or released (then duplicated by the new session's replay). They cannot simply be released afterwards — once the session has moved, which session issued a reply's handles is ambiguous and old numbers are reused (#861) — so the pass stops before dialling. - **OPC DA limit bits do not warn (#991 G-2).** `StatusCodeMap.FromQualityByte` masks the two limit bits (`QQSSSSLL`) before its table lookup, so `Good | LowLimited` (0xC1) and friends map like the unlimited quality. A byte still unlisted after the mask logs one Warning per distinct value per process — it used to log one per event on the pump's dispatch thread, enough to back the channel up into drops. - **The deploy watcher paces every stream end (#991 G-3).** A `WatchDeployEvents` stream the gateway completes cleanly is re-subscribed after the same capped exponential backoff as a faulted one (1 s doubling to 30 s), and the backoff resets only after a stream stayed open 60 s — an event alone (the bootstrap every stream delivers) no longer resets it. It used to re-open immediately, hammering a gateway that ends its streams after the bootstrap. -- **Secured writes are routed without a discovery pass (#991 G-1).** `WriteAsync` sends SecuredWrite / VerifiedWrite attributes through `WriteSecured` and everything else through the supervisory raw `Write`, by a per-tag classification map. Only `DiscoverAsync` used to fill it — and the runtime never calls `DiscoverAsync` on a served driver (only the `/raw` picker's throwaway instance does) — so every authored tag resolved `FreeAccess` and a secured attribute's writes were refused as `BadUserAccessDenied`. The map is now seeded for the authored tags at `InitializeAsync` and on every deploy-watcher rediscovery, in the background, by one rooted depth-0 `DiscoverHierarchy` per authored object (`Browse/GatewayGalaxyAttributeSecuritySource`, 4 concurrent; cost tracks the authored objects, not the Galaxy). Until the seed lands, or if it fails, a tag keeps the `FreeAccess` default (raw path, fails closed). ⚠️ `WriteSecured` now carries `MxAccess.WriteUserId` as the current user (it was a hard-coded 0) and no verifier: with the default `WriteUserId = 0` MXAccess is expected to refuse a secured write (a Warning says so at seed time), and a VerifiedWrite needs a verifier identity nothing supplies yet. Not live-gated. +- **Secured / verified writes are REFUSED `BadUserAccessDenied`, locally (#991 G-1 + review).** The driver has no + ArchestrA user identity: no `AuthenticateUser` flow, no supervisory advise for a secured item, and a gateway key would + additionally need `invoke:secure`. G-1 briefly routed SecuredWrite / VerifiedWrite attributes to `WriteSecured`, which + therefore could never succeed, and the gateway's refusal surfaced as `BadCommunicationError` (a comms fault). Until a + real per-caller identity flow exists (follow-up — like the #749 ack credential) a write to such an attribute returns + `BadUserAccessDenied` before anything reaches the wire (no AddItem / advise / Write; one Warning per attribute; no + health impact). The per-tag classification map that makes the refusal local is still **seeded for the authored tags** + at `InitializeAsync` and on every deploy-watcher rediscovery, in the background, by one rooted depth-0 + `DiscoverHierarchy` per authored object (`Browse/GatewayGalaxyAttributeSecuritySource`, 4 concurrent; cost tracks the + authored objects, not the Galaxy) — only `DiscoverAsync` filled it before, and the runtime never calls that on a served + driver. **Why keep the seed:** unseeded, a secured attribute takes the supervisory raw path and the refusal rests on + MXAccess answering `MX_E_SecuredWrite` (1012) to a supervisory write — a code no live capture has shown (mxaccessgw + `gateway.md`). Until the seed lands, or if it fails, a tag keeps the `FreeAccess` default (that raw path). + **Gateway caller refusals are access refusals:** a gRPC `PermissionDenied` / `Unauthenticated` on the write or its + supervisory advise maps to `BadUserAccessDenied` (was `BadCommunicationError`). Not live-gated. - **Connectivity surface**: per-platform probe state is exposed through `IHostConnectivityProbe` and aggregated by the server's connectivity bus — there is no driver-private dashboard surface anymore. The Admin UI's Host Status panel is the consumer. - **A stream the gateway ends cleanly is treated as a fault.** A closed or evicted gateway session completes the `StreamEvents` RPC *without an error*, so nothing throws. `EventPump` reports that to the `ReconnectSupervisor` exactly as it reports a transport fault. Before this it exited silently: the supervisor was never told, `GetHealth()` kept reporting `Healthy`, and because the [comms-loss watchdog](../DriverLifecycle.md) requires a **non-Healthy** state to trip, it never fired either — the driver went permanently deaf with no signal anywhere. Nothing else in the system can observe this, so do not remove the notification on the grounds that "a clean end isn't an error". - **Replay gaps** (`galaxy.events.replay_gaps`): the gateway signals that events were evicted from its replay ring before we could read them. The driver responds by re-issuing `SubscribeBulk` for every tracked subscription — MXAccess delivers an initial value per item on subscribe, so re-subscribing *is* the re-snapshot the contract asks for. Since the session is the same, the pre-gap handles are still advised: the re-snapshot releases every handle it supersedes (driver subscriptions and probe handles alike — #991 G-6; a tag whose re-advise fails keeps its live handle), so a gap no longer doubles the gateway's advise count. It does **not** restart the event pump (the stream carrying the sentinel is healthy) and it honours `Reconnect:ReplayOnSessionLost=false` by logging and standing down, on the grounds that an operator who delegated recovery to the gateway did not ask for a re-subscribe on a different trigger. diff --git a/docs/drivers/Heidenhain.md b/docs/drivers/Heidenhain.md index 1e2c92419..70577d205 100644 --- a/docs/drivers/Heidenhain.md +++ b/docs/drivers/Heidenhain.md @@ -440,10 +440,12 @@ overrides, axes, tool, the whole alarm walk) and aliased custom addresses are re then drops is backed off, not re-dialled every `InitialDelayMs`. Unlike the Java base, an initial connect failure also retries (no manual restart). The loop survives any unexpected fault (logged, retired, backed off); JSON-`null` config sections are normalised to defaults by the parser. - (#990) A deliberate stop (deploy / Force Reconnect) is never an outage: the runtime's generation is bumped before - the session closes, and its values are invalidated. The backoff count is carried across a watchdog re-init, so a + (#990) A deliberate stop (deploy / Force Reconnect) is never an outage: the runtime's generation is bumped and its + loop CANCELLED before the session closes (closing first let a woken loop report `Backoff` — host `Stopped` — for a + plain stop), and its values are invalidated. The backoff count is carried across a watchdog re-init, so a `MaxDelayMs` above ~90 s is reachable. While a control is down its host status stays `Stopped` (no - `Stopped`/`Unknown` flap, "since" time stable). A refused optional DNC/DATA login is retried per session on a + `Stopped`/`Unknown` flap, "since" time stable) — across a re-init too: the announced host state is kept per + `host:port` (not per runtime instance), and a runtime being stopped by a re-init announces nothing. A refused optional DNC/DATA login is retried per session on a 5 s to 5 min exponential schedule instead of on every poll batch. - Subscriptions: the initial push and later publications are ordered under one lock, so a subscriber never receives an older value after a newer one. A re-init disposes every control loop first; a late start of a diff --git a/docs/drivers/Modbus.md b/docs/drivers/Modbus.md index 3a05d0231..675510e28 100644 --- a/docs/drivers/Modbus.md +++ b/docs/drivers/Modbus.md @@ -69,7 +69,7 @@ appear across consecutive registers when decoding a multi-register value. - **`Generic`** (default) — only Modicon (`4xxxx`) and mnemonic (`HR1`, `C100`) forms are accepted. - **`DL205`** — AutomationDirect DirectLOGIC. V-memory (octal) → HoldingRegisters, `Y`/`C` → Coils, `X`/`SP` → DiscreteInputs. A `C` relay with a non-octal digit (`C18`) is a parse error - it never falls back to the generic `C` coil mnemonic (#981). Strings can be packed low-byte-first via `ModbusTagDefinition.StringByteOrder` (the grammar can't express this — see `ModbusStringByteOrder`). -- **`MELSEC`** — Mitsubishi. D-registers → HoldingRegisters, `X` → DiscreteInputs, `Y`/`M` → Coils; the `MelsecSubFamily` selector switches Q/L/iQR (hex) vs FX (octal) X/Y interpretation. +- **`MELSEC`** — Mitsubishi. D-registers → HoldingRegisters, `X` → DiscreteInputs, `Y`/`M` → Coils; the `MelsecSubFamily` selector switches Q/L/iQR (hex) vs FX (octal) X/Y interpretation. MELSEC has no `DI` device, so `DI` stays the generic discrete-input mnemonic (#981 review — the D-register grammar briefly claimed it and rejected it as a malformed register). Per-family register caps are honoured through `MaxRegistersPerRead` / `MaxRegistersPerWrite` / `MaxCoilsPerRead` (e.g. DL205/DL260 cap reads at 128, diff --git a/docs/drivers/Mqtt.md b/docs/drivers/Mqtt.md index f53fa452d..8a18910fe 100644 --- a/docs/drivers/Mqtt.md +++ b/docs/drivers/Mqtt.md @@ -155,8 +155,9 @@ Every key has a default, so nothing is strictly required by the binder. Notable > nodes reconnect every few seconds while still reporting `Healthy`. Unset (the default) lets MQTTnet > generate a unique id per connection, which is correct. This was observed live during the P1 gate. > (The probe and browser already self-uniquify with `-probe-` / `-browse-` suffixes, and with `clientId` -> unset the Sparkplug primary-host claim presents a random per-instance `spbhost-<12 hex>` — #988 M-3; it was -> the literal `-spbhost`, so two claiming drivers on one broker evicted each other.) `MqttDriverForm` +> unset the Sparkplug primary-host claim presents `spbhost-<12 hex>`, a stable hash of the host id + group id — +> #988 M-3; it was the literal `-spbhost`, so two claiming drivers on one broker evicted each other. It is +> deliberately the SAME on both nodes of a pair, so a broker client-id takeover keeps the claim single.) `MqttDriverForm` > defaults the field blank and raises this warning inline the moment a value is typed. The form validates every knob against the driver's own `[Range]` bounds (port 1–65535, keep-alive / @@ -393,8 +394,9 @@ warning — the driver does not publish to `spBv1.0/STATE/`, which is a legal to ### The claim is a whole connection, not a message A Will can only be registered in the **CONNECT packet**. It cannot be added to a live session, changed, -or withdrawn. So the claim gets its **own** broker connection (client id `{clientId}-spbhost`, or a random -per-instance `spbhost-<12 hex>` when `clientId` is unset — #988 M-3; forced clean-session) whose lifetime *is* the claim: opened on gaining Primary, closed on losing it. Every leg +or withdrawn. So the claim gets its **own** broker connection (client id `{clientId}-spbhost`, or +`spbhost-<12 hex>` — a stable hash of the trimmed host id + group id — when `clientId` is unset; forced +clean-session) whose lifetime *is* the claim: opened on gaining Primary, closed on losing it. Every leg then follows from the connection's lifecycle rather than from bookkeeping that could drift. The ingest session is untouched by a role change — no dropped subscriptions, no lost birth cache, and @@ -430,6 +432,21 @@ raising events at per-instance drivers outlives every driver it holds a referenc > members, which is the single-node row: a node cold-starting into a pair whose peer is already Primary > can open the claim until its join completes (seconds; up to the bootstrap guard's 25 s partner probe), > so both nodes may briefly hold it (review R6 MINOR-2). +> +> **Two mechanisms keep that window from ending on the wrong `STATE` (#988 review round 2):** +> - **One claim id per pair.** With `clientId` unset the claim id is a pure function of the host id + group id, +> so both nodes present the same id: the cold-starting node's CONNECT takes the Primary's claim session over +> (the broker closes the older one), and the Primary's supervisor reconnects and re-asserts. A briefly random +> per-instance id (the first M-3 fix) let both hold the topic at once, and the Secondary's stand-down `OFFLINE` +> then sat retained, newer than the Primary's `ONLINE`, with nothing to correct it. +> - **The claim watches its own `STATE` topic** (as Sparkplug 3.0 asks a host to) and re-asserts over an +> `OFFLINE` it did not publish — its own stand-down detaches the claim before publishing, so the broker's echo +> is ignored. An `OFFLINE` no newer than the claim's session (its own Will replayed, a stale death) is answered +> by republishing the session's `ONLINE`; a **newer** one (another claimant's stand-down or Will) by a **fresh** +> claim — clean disconnect, new Will + `ONLINE` with a timestamp past the observed one — because conformant +> edge nodes ignore a `STATE` older than the one they hold. Re-asserts are coalesced, at most one per 2 s. On a +> reconnect the claim re-subscribes BEFORE republishing, so the retained replay shows what the takeover left +> behind. A broker ACL that refuses the subscription costs only this safety net (one Warning), never the claim. > **Accepted trade: a brief edge-visible `OFFLINE` during failover**, while the old Primary stands down > and the new one connects and republishes. That is a genuine state transition — for that window there diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbCip/AbCipDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbCip/AbCipDriver.cs index 2a6912353..8d183ea7a 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbCip/AbCipDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbCip/AbCipDriver.cs @@ -244,6 +244,12 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery, /// Describes the OPTION only: injected factories (tests) are used regardless. public AbCipTransport EffectiveTransport => _transport; + /// + /// Whether a read TIMEOUT latches the device for the rest of a read call (#983 review): on the native transport + /// a reply timeout faults the device's one shared channel; on libplctag it is one tag's own request. + /// + private bool LatchesOnTimeout => _transport == AbCipTransport.Native; + // The transport chosen at construction (see the ctor); logged at every init so an operator can tell // from the node log which stack serves this instance. private readonly AbCipTransport _transport; @@ -739,17 +745,20 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery, try { probeRuntime ??= _tagFactory.Create(probeParams); - // The probe's own timeout bounds this tick's wait (cancelling a waiter never faults the shared + // Lazy-init on first attempt; re-init after a transport failure has caused the + // native handle to be destroyed. #983 review: NOT under the probe timeout — a cold initialisation is + // the connect + RegisterSession + Forward Open, bounded by the DRIVER's timeout (the pooled + // connection's); the short probe timeout here meant a slow-but-healthy open never completed and the + // host stayed Stopped, re-dialling every tick. + if (!state.ProbeInitialized) + { + await probeRuntime.InitializeAsync(ct).ConfigureAwait(false); + state.ProbeInitialized = true; + } + // The probe's own timeout bounds only the probe READ (cancelling a waiter never faults the shared // session — scheduler B2); the pooled connection keeps the driver's timeout. using var tick = CancellationTokenSource.CreateLinkedTokenSource(ct); tick.CancelAfter(_options.Probe.Timeout); - // Lazy-init on first attempt; re-init after a transport failure has caused the - // native handle to be destroyed. - if (!state.ProbeInitialized) - { - await probeRuntime.InitializeAsync(tick.Token).ConfigureAwait(false); - state.ProbeInitialized = true; - } await probeRuntime.ReadAsync(tick.Token).ConfigureAwait(false); var status = probeRuntime.GetStatus(); if (status == 0) @@ -1170,11 +1179,12 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery, try { // P-2: an earlier item of THIS call already proved the device's connection dead — fail fast - // instead of paying another timeout, and drop the handle so the next poll goes through the - // cold-create backoff rather than the wire. + // instead of paying another timeout. The handle is KEPT (#983 review): this item never reached + // the wire, so nothing proves its handle bad, and evicting it re-created it (and, for a sole lease + // holder, re-Forward-Opened) on the next poll. The failed item itself was evicted; its cold + // re-create goes through the connect backoff, and a throttled create latches the device too. if (batch.IsFaulted(device, out var latched)) { - EvictRuntime(device, def.Name); results[fb.OriginalIndex] = new DataValueSnapshot(null, AbCipStatusMapper.BadCommunicationError, null, now); return ReadOutcome.Degraded(latched); } @@ -1212,7 +1222,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery, results[fb.OriginalIndex] = new DataValueSnapshot(null, AbCipStatusMapper.MapStatus(status), null, now); var statusMessage = $"transport status {status} reading {reference}"; - if (AbCipRefusals.IsConnectionFault(status)) batch.Latch(device, statusMessage); + if (AbCipRefusals.LatchesDevice(status, LatchesOnTimeout)) batch.Latch(device, statusMessage); LogReadFault(device, null, "AbCip read returned non-zero transport status {Status} for tag {Tag} on device {Device}; " + "evicting cached runtime so next call re-creates it", @@ -1316,6 +1326,9 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery, // eviction (nothing cached) and no stack trace; one Warning per device per outage (shared with the // failure that opened the window), Debug after. results[fb.OriginalIndex] = new DataValueSnapshot(null, AbCipStatusMapper.BadCommunicationError, null, now); + // The device's backoff window is open — a device-wide verdict: latch, so its warm handles behind this one + // fail fast instead of each paying a timeout on the wire (#983 review: they are no longer evicted). + batch.Latch(device, throttled.Message); LogReadFault(device, null, "AbCip reads on device {Device} are throttled while its connect backoff window is open: {Reason}", def.DeviceHostAddress, throttled.Message); @@ -1329,7 +1342,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery, EvictRuntime(device, def.Name); results[fb.OriginalIndex] = new DataValueSnapshot(null, AbCipStatusMapper.MapException(ex), null, now); - if (AbCipRefusals.IsConnectionFault(ex)) batch.Latch(device, ex.Message); + if (AbCipRefusals.LatchesDevice(ex, LatchesOnTimeout)) batch.Latch(device, ex.Message); LogReadFault(device, ex, "AbCip read transport exception for tag {Tag} on device {Device}", reference, def.DeviceHostAddress); @@ -1373,7 +1386,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery, // P-2: see ReadSingleAsync — an earlier item of this call already proved the connection dead. if (batch.IsFaulted(device, out var latched)) { - EvictRuntime(device, parent.Name); + // Handle kept — never attempted (#983 review, see ReadSingleAsync). StampGroupStatus(group, results, now, AbCipStatusMapper.BadCommunicationError); return ReadOutcome.Degraded(latched); } @@ -1403,7 +1416,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery, var mapped = AbCipStatusMapper.MapStatus(status); StampGroupStatus(group, results, now, mapped); var statusMessage = $"transport status {status} reading UDT {group.ParentName}"; - if (AbCipRefusals.IsConnectionFault(status)) batch.Latch(device, statusMessage); + if (AbCipRefusals.LatchesDevice(status, LatchesOnTimeout)) batch.Latch(device, statusMessage); LogReadFault(device, null, "AbCip whole-UDT read returned non-zero transport status {Status} for parent {Parent} " + "on device {Device}; {MemberCount} member values stamped with mapped status", @@ -1474,6 +1487,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery, { // P-16: see ReadSingleAsync — a throttled create is not a per-parent Warning. StampGroupStatus(group, results, now, AbCipStatusMapper.BadCommunicationError); + batch.Latch(device, throttled.Message); // device-wide verdict — see ReadSingleAsync LogReadFault(device, null, "AbCip reads on device {Device} are throttled while its connect backoff window is open: {Reason}", parent.DeviceHostAddress, throttled.Message); @@ -1483,7 +1497,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery, { EvictRuntime(device, parent.Name); StampGroupStatus(group, results, now, AbCipStatusMapper.MapException(ex)); - if (AbCipRefusals.IsConnectionFault(ex)) batch.Latch(device, ex.Message); + if (AbCipRefusals.LatchesDevice(ex, LatchesOnTimeout)) batch.Latch(device, ex.Message); LogReadFault(device, ex, "AbCip whole-UDT read transport exception for parent {Parent} on device {Device}", group.ParentName, parent.DeviceHostAddress); diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbCip/AbCipRefusals.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbCip/AbCipRefusals.cs index a3aedfc17..b0094bbfa 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbCip/AbCipRefusals.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbCip/AbCipRefusals.cs @@ -53,6 +53,40 @@ internal static class AbCipRefusals _ => false, }; + /// + /// True when a read failure with proves the DEVICE's connection dead for the rest of a + /// read call — the P-2 per-call latch (#983 review). / + /// always do. does only on the native transport, where every tag of a device shares + /// one channel and a reply timeout FAULTS that channel (EncapsulationClient); on libplctag each tag is its + /// own request with its own timeout, so one slow tag proves nothing about its siblings. + /// + /// The transport status. + /// Whether the device is served by the native transport. + /// when the device should be latched for the rest of the call. + public static bool LatchesDevice(AbStatus status, bool nativeTransport) => + status is AbStatus.BadConnection or AbStatus.Abort || (nativeTransport && status == AbStatus.Timeout); + + /// The status-word form of . + /// The runtime status word. + /// Whether the device is served by the native transport. + /// when the device should be latched for the rest of the call. + public static bool LatchesDevice(int status, bool nativeTransport) => LatchesDevice((AbStatus)status, nativeTransport); + + /// + /// The exception form of : a socket / IO / timeout exception is a + /// channel failure (only the native transport raises them). + /// + /// The exception. + /// Whether the device is served by the native transport. + /// when the device should be latched for the rest of the call. + public static bool LatchesDevice(Exception ex, bool nativeTransport) => ex switch + { + AbCipLocalRefusalException => false, + AbTransportException ate => LatchesDevice(ate.Status, nativeTransport), + System.Net.Sockets.SocketException or IOException or TimeoutException => true, + _ => false, + }; + /// True when (an value) is a device refusal. /// The runtime status word. /// for a deterministic device refusal. diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Contracts/AbLegacyDataType.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Contracts/AbLegacyDataType.cs index 3c066c7e3..86ab88cf4 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Contracts/AbLegacyDataType.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Contracts/AbLegacyDataType.cs @@ -10,7 +10,7 @@ public enum AbLegacyDataType Bit, /// N-file integer (signed 16-bit). Int, - /// L-file long integer — SLC 5/05+ only (signed 32-bit). + /// L-file long integer (signed 32-bit) — SLC 5/05+, MicroLogix 1100/1200/1400/1500 (not ML 1000), Logix PCCC; not PLC-5. Long, /// F-file float (32-bit IEEE-754). Float, diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Contracts/AbLegacyPlcFamilyProfile.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Contracts/AbLegacyPlcFamilyProfile.cs index d7ba582b7..67151aaaf 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Contracts/AbLegacyPlcFamilyProfile.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Contracts/AbLegacyPlcFamilyProfile.cs @@ -72,7 +72,11 @@ public sealed record AbLegacyPlcFamilyProfile( DefaultCipPath: "", // MicroLogix 1100/1400 use direct EIP, no backplane path MaxTagBytes: 232, SupportsStringFile: true, - SupportsLongFile: false, // ML 1100/1200/1400 don't ship L files + // #984 review: MicroLogix 1100/1200/1400/1500 all have L (32-bit integer) files — only the ML 1000 lacks them, + // and the family cannot tell the two apart, so the profile allows L and an ML 1000 answers the read itself + // (a PCCC refusal, per tag). It used to say false, refusing L tags the parser, coalescer and L-bit RMW + // already handle. Pending a hardware read of one L tag on an ML 1400 (Vitamine press fleet). + SupportsLongFile: true, SupportsFunctionFiles: true); // ML 1100/1400 expose RTC/HSC/DLS/MMI/PTO/PWM/STI/EII/IOS/BHI public static readonly AbLegacyPlcFamilyProfile Plc5 = new( diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy/AbLegacyDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy/AbLegacyDriver.cs index f5d48492a..36420911f 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy/AbLegacyDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy/AbLegacyDriver.cs @@ -250,7 +250,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag }; tags[entry.RawPath] = resolved; - // A data type the owning device's PLC family does not ship (an L-file Long on a MicroLogix, an ST-file + // A data type the owning device's PLC family does not ship (an L-file Long on a PLC-5, an ST-file // String on a family without one) is THIS TAG's configuration error — it reads/writes // BadConfigurationError and is reported in the skipped-tag ledger — never a reason to fault every other // tag and device of the instance (review 2026-12-02 P-5). The deploy gate says the same thing earlier diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Browse/IGalaxyAttributeSecuritySource.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Browse/IGalaxyAttributeSecuritySource.cs index ebd7331eb..c660dfc64 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Browse/IGalaxyAttributeSecuritySource.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Browse/IGalaxyAttributeSecuritySource.cs @@ -7,7 +7,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Browse; /// /// Driver-side seam for the per-attribute security_classification of the AUTHORED Galaxy objects -/// (#991 G-1). WriteAsync routes SecuredWrite / VerifiedWrite attributes to WriteSecured; that +/// (#991 G-1). WriteAsync refuses SecuredWrite / VerifiedWrite attributes locally (BadUserAccessDenied); that /// classification used to come only from DiscoverAsync, which the runtime never calls on a served driver, /// so every write took the raw path. The driver seeds its security map from this at InitializeAsync and /// on every deploy-watcher rediscovery. 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 0fc0d0910..367bfce8e 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs @@ -72,7 +72,7 @@ public sealed class GalaxyDriver private IGalaxyDataReader? _dataReader; // PR 4.3 — IGalaxyDataWriter is the test seam for IWritable. Production wraps - // GalaxyMxSession via GatewayGalaxyDataWriter (Write / WriteSecured routing). The + // GalaxyMxSession via GatewayGalaxyDataWriter (raw Write; secured writes refused). The // per-tag SecurityClassification map is populated during ITagDiscovery and consumed // here at write time. private IGalaxyDataWriter? _dataWriter; @@ -251,7 +251,7 @@ public sealed class GalaxyDriver private readonly IGalaxyPlatformSource? _platformSource; private IGalaxyPlatformSource? _ownedPlatformSource; - // #991 G-1: the authored tags' security classifications, for WriteAsync's WriteSecured routing. Injected seam + // #991 G-1: the authored tags' security classifications, for WriteAsync's local secured-write refusal. Injected seam // (tests) or, on the production path, per-object DiscoverHierarchy queries over the owned repository client. // Seeded by the same background worker as the platform set (init + every rediscovery). private readonly IGalaxyAttributeSecuritySource? _securitySource; @@ -910,9 +910,15 @@ public sealed class GalaxyDriver /// #991 G-1 — one security seed pass: fetch the authored objects' attributes and record each authored tag's /// under its RawPath, the key resolves against. /// Before this the map was filled only by , which the runtime never calls on a - /// served driver, so every write — SecuredWrite / VerifiedWrite attributes included — took the raw path and - /// was refused. Never throws; a failed or late pass leaves the map as it was (FreeAccess for anything unseen, - /// i.e. the raw path, which fails closed). + /// served driver. Never throws; a failed or late pass leaves the map as it was (FreeAccess for anything + /// unseen, i.e. the raw path). + /// Kept after the #991 review (secured writes are refused, not routed) — on purpose. The seed is + /// what makes the refusal LOCAL: a SecuredWrite/VerifiedWrite attribute is refused BadUserAccessDenied + /// without an AddItem / AdviseSupervisory / Write reaching the gateway. Unseeded, such a write goes down the + /// supervisory raw path and the refusal rests on MXAccess answering MX_E_SecuredWrite (1012) to a + /// supervisory write — a code no live capture has shown (mxaccessgw gateway.md), so the driver would be + /// relying on an unverified bypass not happening. Cost: one DiscoverHierarchy (depth 0) per authored + /// object at init and per deploy-watcher rediscovery, ≤ 4 in flight. /// private async Task SeedSecurityClassificationsAsync(string reason, int generation, CancellationToken cancellationToken) { @@ -965,15 +971,9 @@ public sealed class GalaxyDriver var secured = seeded.Values.Count(c => c is SecurityClassification.SecuredWrite or SecurityClassification.VerifiedWrite); _logger.LogInformation( - "GalaxyDriver {InstanceId} security classifications seeded for {Count} authored tag(s), {Secured} secured/verified ({Reason}).", + "GalaxyDriver {InstanceId} security classifications seeded for {Count} authored tag(s), {Secured} secured/verified " + + "— writes to those are refused BadUserAccessDenied (no ArchestrA identity) ({Reason}).", _driverInstanceId, seeded.Count, secured, reason); - if (secured > 0 && _options.MxAccess.WriteUserId == 0) - { - _logger.LogWarning( - "GalaxyDriver {InstanceId} has {Secured} SecuredWrite/VerifiedWrite tag(s) but MxAccess.WriteUserId is 0 — " + - "WriteSecured carries no ArchestrA user, so MXAccess is expected to refuse those writes.", - _driverInstanceId, secured); - } } catch (Exception ex) when (cancellationToken.IsCancellationRequested || Volatile.Read(ref _runtimeGeneration) != generation) @@ -1650,6 +1650,16 @@ public sealed class GalaxyDriver IReadOnlyList results; using (_subscriptions.BeginPendingSubscribe()) { + // #991 review: a pass whose session is gone must not dial. A reconnect that completes between two + // subscriptions of one pass (the dropped-event resync loop, or the replay loop between its own check and + // here) left this SubscribeBulk going to the NEW gateway session under the OLD session number: the rebind + // below refused it (SessionChanged) and the fresh, live advises were never bound or released — leaked on + // the gateway, then duplicated by the new session's replay. Releasing them afterwards is not an option in + // general: once the session has moved, which session issued a reply's handles is ambiguous, and an + // old-session number may be reused by the new one (#861). Not dialling is the only unambiguous fix. The + // check and the dial are synchronous back to back; ReopenAsync's session swap awaits network I/O between + // its two fences, so a swap cannot complete in between. + if (_subscriptions.CurrentSession != session) return (false, 0); results = await _subscriber! .SubscribeBulkAsync(refs, _options.MxAccess.PublishingIntervalMs, cancellationToken) .ConfigureAwait(false); @@ -2942,6 +2952,41 @@ public sealed class GalaxyDriver private int _droppedSession; private int _dropResyncRunning; + /// + /// #991 review: the floor between two dropped-event resync passes. Repeated overflow bursts used to start a + /// pass as soon as the previous one finished — re-advising (and pushing initial values into) the very channel + /// that was overflowing. Drops reported inside the window coalesce into the next pass. + /// + internal static readonly TimeSpan DefaultDropResyncMinInterval = TimeSpan.FromSeconds(5); + + private TimeSpan _dropResyncMinInterval = DefaultDropResyncMinInterval; + + // Stopwatch timestamp of the last resync pass start (0 = none yet). Worker-owned. + private long _lastDropResyncTimestamp; + + /// Test seam: the floor between two dropped-event resync passes. + internal TimeSpan DropResyncMinIntervalForTests + { + get => _dropResyncMinInterval; + set => _dropResyncMinInterval = value; + } + + /// Test seam: report dropped events for as the current pump would. + /// The handles whose events were dropped. + internal void NotifyEventsDroppedForTests(IReadOnlyCollection itemHandles) + { + EventPump? pump; + lock (_pumpLock) pump = _eventPump; + OnEventPumpEventsDropped(pump, itemHandles); + } + + /// Test seam: one dropped-event resync pass, run inline. + /// The dropped handles. + /// The session that issued them. + /// A task completing when the pass does. + internal Task ResyncDroppedHandlesForTestsAsync(IReadOnlyCollection itemHandles, int session) => + ResyncDroppedHandlesAsync(itemHandles, session); + // Serialises the same-session re-advise passes (replay-gap re-snapshot, dropped-event resync): both rebind a // subscription from a snapshot of its bindings, so two interleaved passes could rebind over each other and // release handles the other one bound. @@ -2976,6 +3021,15 @@ public sealed class GalaxyDriver { while (true) { + // Rate limit (#991 review): at most one pass per DropResyncMinInterval; drops reported while waiting + // join the pending set and ride the next pass together. + var last = Volatile.Read(ref _lastDropResyncTimestamp); + if (last != 0) + { + var wait = _dropResyncMinInterval - System.Diagnostics.Stopwatch.GetElapsedTime(last); + if (wait > TimeSpan.Zero) await Task.Delay(wait).ConfigureAwait(false); + } + int[] batch; int batchSession; lock (_droppedLock) @@ -2990,6 +3044,7 @@ public sealed class GalaxyDriver _droppedPending.Clear(); batchSession = _droppedSession; } + Volatile.Write(ref _lastDropResyncTimestamp, System.Diagnostics.Stopwatch.GetTimestamp()); try { diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GatewayGalaxyDataWriter.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GatewayGalaxyDataWriter.cs index 854db7a35..92344e07e 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GatewayGalaxyDataWriter.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GatewayGalaxyDataWriter.cs @@ -1,5 +1,6 @@ using System.Collections.Concurrent; using System.Diagnostics.Metrics; +using Grpc.Core; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using ZB.MOM.WW.MxGateway.Client; @@ -11,9 +12,11 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime; /// /// Production over . /// For each batch entry: lazy-AddItem to obtain the MXAccess item handle, encode -/// the value via , route through Write or WriteSecured -/// based on the per-tag , and translate the -/// reply's MxStatusProxy into an OPC UA . +/// the value via , supervisory-advise + Write, and translate the +/// reply's MxStatusProxy into an OPC UA . A SecuredWrite / +/// VerifiedWrite attribute (per-tag ) is refused +/// BadUserAccessDenied without a round trip — the driver has no ArchestrA identity to +/// write it under (#991 review G-1). /// /// /// Item handle cache survives across writes — repeated writes to the same tag avoid @@ -36,6 +39,8 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter // Item handles we've already AdviseSupervisory'd this session — supervisory advise is // idempotent but the round-trip isn't free, so do it once per handle (see EnsureSupervisoryAdvisedAsync). private readonly ConcurrentDictionary _supervisedHandles = new(); + // Attributes whose secured/verified-write refusal has been logged (once per attribute, #991 review G-1). + private readonly ConcurrentDictionary _securedRefusalWarned = new(StringComparer.OrdinalIgnoreCase); private int _addItemCallCount; // Write failure-visibility meters (archreview 06/S-1). Reuse the pump's meter name so the single host @@ -219,38 +224,44 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter IMxWriteOps ops, WriteRequest request, SecurityClassification classification, CancellationToken ct) { + if (NeedsSecuredWrite(classification)) + { + // #991 review (G-1): REFUSED, before anything reaches the wire. A SecuredWrite/VerifiedWrite attribute + // needs a real ArchestrA identity — AuthenticateUser (+ a verifier for VerifiedWrite), the item advised + // for that user, and a gateway key holding invoke:secure — none of which this driver has. Routing it to + // WriteSecured could only fail, and the gateway's refusal surfaced as BadCommunicationError (a comms + // fault). Until a per-caller identity flow exists this is an access refusal: no health impact. + if (_securedRefusalWarned.TryAdd(request.FullReference, 0)) + { + _logger.LogWarning( + "GalaxyDriver write to {FullRef} refused BadUserAccessDenied — the attribute is {Classification} and the " + + "driver has no ArchestrA user identity to write it under (logged once per attribute).", + request.FullReference, classification); + } + return new WriteResult(StatusCodeMap.BadUserAccessDenied); + } + try { var itemHandle = await EnsureItemHandleAsync(ops, request.FullReference, ct) .ConfigureAwait(false); var mxValue = MxValueEncoder.Encode(request.Value); - MxCommandReply reply; - if (NeedsSecuredWrite(classification)) + // A raw Write runs with NO user login (WriteUserId is typically 0), so MXAccess + // only COMMITS the value when the item is advised in SUPERVISORY mode. Without it + // the write is refused by the automation object (SECURITY_ERROR detail 1008 on the + // correlated reply — live-captured). FAIL-CLOSED (archreview 06/S-1): when + // AdviseSupervisory fails we do NOT issue the raw Write; we return Bad so the + // Write-outcome self-correction reverts the phantom-Good node instead of leaving it. + // A correlated gateway (mxaccessgw ≥ 53f69cd) would also surface the refusal in the + // reply's statuses[0], but the short-circuit avoids a write we know cannot commit. + if (!await EnsureSupervisoryAdvisedAsync(ops, itemHandle, ct).ConfigureAwait(false)) { - // SecuredWrite/VerifiedWrite tags carry their own ArchestrA user identity - // (current/verifier user), so they don't use the supervisory path. - reply = await InvokeWriteSecuredAsync(ops, itemHandle, mxValue, ct) - .ConfigureAwait(false); - } - else - { - // A raw Write runs with NO user login (WriteUserId is typically 0), so MXAccess - // only COMMITS the value when the item is advised in SUPERVISORY mode. Without it - // the write is refused by the automation object (SECURITY_ERROR detail 1008 on the - // correlated reply — live-captured). FAIL-CLOSED (archreview 06/S-1): when - // AdviseSupervisory fails we do NOT issue the raw Write; we return Bad so the - // Write-outcome self-correction reverts the phantom-Good node instead of leaving it. - // A correlated gateway (mxaccessgw ≥ 53f69cd) would also surface the refusal in the - // reply's statuses[0], but the short-circuit avoids a write we know cannot commit. - if (!await EnsureSupervisoryAdvisedAsync(ops, itemHandle, ct).ConfigureAwait(false)) - { - WriteAdviseFailed.Add(1); - return new WriteResult(StatusCodeMap.BadCommunicationError); - } - reply = await ops.WriteRawAsync(itemHandle, mxValue, _writeUserId, ct) - .ConfigureAwait(false); + WriteAdviseFailed.Add(1); + return new WriteResult(StatusCodeMap.BadCommunicationError); } + var reply = await ops.WriteRawAsync(itemHandle, mxValue, _writeUserId, ct) + .ConfigureAwait(false); return TranslateReply(reply, request.FullReference); } @@ -262,6 +273,15 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter return new WriteResult(StatusCodeMap.BadInternalError); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } + catch (Exception ex) when (IsCallerRefused(ex)) + { + // #991 review (G-1): the gateway refused the CALLER (API key lacks the scope, revoked, or + // unauthenticated). That is an access refusal, not a communication failure. + _logger.LogWarning(ex, + "GalaxyDriver write to {FullRef} refused by the gateway ({Reason}) — BadUserAccessDenied.", + request.FullReference, ((RpcException)UnwrapRpc(ex)!).StatusCode); + return new WriteResult(StatusCodeMap.BadUserAccessDenied); + } catch (Exception ex) { _logger.LogWarning(ex, "GalaxyDriver write failed for {FullRef}", request.FullReference); @@ -272,6 +292,19 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter private static bool NeedsSecuredWrite(SecurityClassification classification) => classification is SecurityClassification.SecuredWrite or SecurityClassification.VerifiedWrite; + /// Whether (or an inner exception) is the gateway refusing the caller. + internal static bool IsCallerRefused(Exception ex) => + UnwrapRpc(ex) is { StatusCode: StatusCode.PermissionDenied or StatusCode.Unauthenticated }; + + private static RpcException? UnwrapRpc(Exception ex) + { + for (var e = ex; e is not null; e = e.InnerException) + { + if (e is RpcException rpc) return rpc; + } + return null; + } + private async Task EnsureItemHandleAsync( IMxWriteOps ops, string fullRef, CancellationToken ct) { @@ -289,7 +322,7 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter /// i.e. a non-zero WriteUserId, as the ScadaBridge sister driver uses — would commit via /// a regular Advise instead; we don't log in, so we use the supervisory context.) /// The gateway client doesn't expose a typed method, so we build the - /// and route through InvokeAsync (same pattern as ). + /// and route through InvokeAsync (no typed helper exists for it). /// Idempotent per handle for the session lifetime. The keyed-by-handle dedupe is reset on a /// session reconnect via , so a fresh session always /// re-advises — the supervisory state never outlives the handle it was taken against. @@ -332,6 +365,12 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter _supervisedHandles.TryRemove(itemHandle, out _); throw; } + catch (Exception ex) when (IsCallerRefused(ex)) + { + // The gateway refused the caller: forget the handle and let the write report an access refusal. + _supervisedHandles.TryRemove(itemHandle, out _); + throw; + } catch (Exception ex) { _supervisedHandles.TryRemove(itemHandle, out _); @@ -355,41 +394,6 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter return true; } - /// - /// Issue a WriteSecured command. The high-level session client doesn't expose - /// WriteSecuredAsync as a typed method — we build the - /// directly and route through InvokeAsync. Verifier user is left at zero - /// for SecuredWrite; VerifiedWrite uses the same path because the gw's worker - /// interprets the underlying MXAccess command kind. - /// #991 G-1: the current user is the configured MxAccess.WriteUserId — the same identity the - /// raw path writes under — instead of a hard-coded 0. With the default 0 a secured write carries no - /// ArchestrA user and MXAccess is expected to refuse it; a VerifiedWrite additionally needs a verifier, - /// which nothing supplies yet (follow-up: a per-caller Galaxy identity, like the #749 ack credential). - /// - private Task InvokeWriteSecuredAsync( - IMxWriteOps ops, int itemHandle, MxValue value, CancellationToken ct) - { - var command = new MxCommand - { - Kind = MxCommandKind.WriteSecured, - WriteSecured = new WriteSecuredCommand - { - ServerHandle = ops.ServerHandle, - ItemHandle = itemHandle, - Value = value, - CurrentUserId = _writeUserId, - VerifierUserId = 0, - }, - }; - var request = new MxCommandRequest - { - SessionId = ops.SessionId, - ClientCorrelationId = Guid.NewGuid().ToString("N"), - Command = command, - }; - return ops.InvokeAsync(request, ct); - } - /// /// Translate a gateway into an OPC UA /// . Honours the protocol-level Status field first @@ -457,7 +461,7 @@ internal interface IMxWriteOps /// The MXAccess item handle. Task AddItemAsync(string fullRef, CancellationToken ct); - /// Invoke a raw (AdviseSupervisory / WriteSecured) and return the reply. + /// Invoke a raw (AdviseSupervisory) and return the reply. /// The command request. /// The cancellation token. /// The gateway reply. diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/IGalaxyDataWriter.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/IGalaxyDataWriter.cs index bdcd730f7..db0f6a83e 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/IGalaxyDataWriter.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/IGalaxyDataWriter.cs @@ -3,10 +3,10 @@ using ZB.MOM.WW.OtOpcUa.Core.Abstractions; namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime; /// -/// Driver-side seam for batched writes. Production implementation routes by -/// : SecuredWrite / VerifiedWrite go through -/// MxCommandKind.WriteSecured, everything else through -/// MxGatewaySession.WriteAsync. Tests substitute a fake to record routing +/// Driver-side seam for batched writes. Production implementation decides by +/// : SecuredWrite / VerifiedWrite are refused +/// BadUserAccessDenied (no ArchestrA identity to write them under — #991 review G-1), +/// everything else goes supervisory-advise + raw Write. Tests substitute a fake to record routing /// decisions without touching real gw infrastructure. /// public interface IGalaxyDataWriter @@ -20,10 +20,9 @@ public interface IGalaxyDataWriter /// Pairs of full reference + value to write. /// /// Maps a full reference to its discovered - /// so the writer can route SecuredWrite / VerifiedWrite tags through the - /// WriteSecured command instead of Write. Returns - /// when the tag isn't tracked - /// (the safest default — non-secured Write). + /// so the writer can refuse SecuredWrite / VerifiedWrite tags locally. Returns + /// when the tag isn't tracked (the raw + /// path, on which MXAccess itself refuses a secured attribute). /// /// Aborts the in-flight batch. /// One per request entry, in input order. diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDeviceRuntime.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDeviceRuntime.cs index 68a373ec0..ab41681de 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDeviceRuntime.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDeviceRuntime.cs @@ -442,7 +442,10 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable catch (Exception ex) { _logger.LogDebug(ex, "Heidenhain state-change handler threw"); } } - /// Stops the loop: closes the session first (unblocks a read), cancels, joins ≤ 5 s, invalidates. + /// Test seam: awaited by right after it closes the session. + internal Func? AfterSessionCloseForTests { get; set; } + + /// Stops the loop: cancels, then closes the session (unblocks a read), joins ≤ 5 s, invalidates. public async ValueTask DisposeAsync() { Task? loop; @@ -467,8 +470,13 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable session = _session; } - session?.Close(); + // #990 review: CANCEL before closing. Closing first unblocked an in-flight read while the loop's token was + // still live, so a loop that woke before the cancel landed ran its "session gone" tail — a Backoff state, + // i.e. host Stopped — and a deliberate stop showed as an outage. Cancelled first, whatever the closed read + // does next, the loop sees its token cancelled and exits. if (cts is not null) await cts.CancelAsync().ConfigureAwait(false); + session?.Close(); + if (AfterSessionCloseForTests is { } hook) await hook().ConfigureAwait(false); if (loop is not null) { try { await loop.WaitAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false); } diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDriver.cs index 0323cba50..a048269a6 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDriver.cs @@ -240,6 +240,11 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi _devices = runtimes; _byRawPath = byPath; + lock (_facing) + { + var live = runtimes.Select(r => r.HostName).ToHashSet(StringComparer.Ordinal); + foreach (var stale in _facing.Keys.Where(k => !live.Contains(k)).ToList()) _facing.Remove(stale); + } _alarms.Tags = alarmTags; } @@ -267,6 +272,7 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi _initialized = false; await StopDevicesAsync().ConfigureAwait(false); _carriedFailures = new Dictionary(StringComparer.Ordinal); + lock (_facing) _facing.Clear(); _subscriptions.Clear(); lock (_lifecycleLock) _state = DriverState.Unknown; } @@ -400,7 +406,17 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi return a.Equals(b); } - private readonly Dictionary _facing = new(); + /// + /// Host-facing state last announced, per host:port (#990 review). Keyed by HOST, not by runtime instance: + /// a re-init (the comms-loss watchdog's remedy for a down control, every ~90 s) replaces every runtime, and + /// an instance key both grew forever and restarted each new runtime at Unknown — flapping a down control's + /// status Stopped → Unknown → Stopped across every re-init. Runtimes no longer in (being + /// stopped by a re-init/shutdown) announce nothing; entries for hosts no longer configured are pruned at init. + /// + private readonly Dictionary _facing = new(StringComparer.Ordinal); + + /// Test seam: entries in the host-facing state map. + internal int FacingEntryCountForTests { get { lock (_facing) return _facing.Count; } } private void OnRuntimeState(HeidenhainDeviceRuntime runtime, HeidenhainConnectionState old, HeidenhainConnectionState next) { @@ -409,8 +425,11 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi HostState o; lock (_facing) { - o = _facing.GetValueOrDefault(runtime, HostState.Unknown); - _facing[runtime] = n; + // A runtime being stopped by a re-init/shutdown is no longer the host's voice: its Stopped/Unknown tail + // must not reach the operator (its successor carries the failure state on, #990 M-19). + if (!_devices.Contains(runtime)) return; + o = _facing.GetValueOrDefault(runtime.HostName, HostState.Unknown); + _facing[runtime.HostName] = n; } if (o == n) return; diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Addressing/ModbusAddressParser.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Addressing/ModbusAddressParser.cs index a0ca61d7e..0ff245443 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Addressing/ModbusAddressParser.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Addressing/ModbusAddressParser.cs @@ -346,6 +346,13 @@ public static class ModbusAddressParser // The MelsecAddress helpers honour the sub-family (Q hex vs F octal) and use // bank base 0; users with non-zero assignment bases must use the structured // tag form to override. The grammar string covers the common base-0 path. + // + // #981 review: MELSEC has no `DI` device, so `DI…` is NOT claimed here — it is the generic + // discrete-input mnemonic, which the S-8 gate (no generic fallback once a family grammar claimed an + // address) would otherwise reject as a malformed D-register. Narrow on purpose: every other `D…` + // stays native, and DL205's non-octal rejection is untouched. + if (text.StartsWith("DI", StringComparison.OrdinalIgnoreCase)) + return false; if (text.StartsWith("D", StringComparison.OrdinalIgnoreCase)) { offset = MelsecAddress.DRegisterToHolding(text); diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/Sparkplug/SparkplugPrimaryHost.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/Sparkplug/SparkplugPrimaryHost.cs index 346c11ea2..c84da8668 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/Sparkplug/SparkplugPrimaryHost.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/Sparkplug/SparkplugPrimaryHost.cs @@ -108,6 +108,26 @@ public sealed class SparkplugPrimaryHost : IAsyncDisposable private int _disposed; + /// Re-assert request kinds, in precedence order (a higher one subsumes a lower). + private const int ReassertRepublish = 1; + + private const int ReassertFresh = 2; + + /// Floor between two re-asserts, so a burst of foreign OFFLINEs costs one, not one per message. + internal static readonly TimeSpan ReassertMinInterval = TimeSpan.FromSeconds(2); + + /// Pending re-assert request (0 = none, else the highest kind requested since the last run). + private int _reassertRequest; + + /// 1 while a re-assert worker is running. + private int _reassertRunning; + + /// When the last re-assert ran (worker-owned). + private DateTimeOffset _lastReassertUtc = DateTimeOffset.MinValue; + + /// A fresh claim's session timestamp is at least this — one past the newest foreign OFFLINE observed. + private long _minNextSessionTimestampMs; + /// Creates a primary-host claim. Opens nothing — does that. /// Broker connection settings; the host id comes from its Sparkplug section. /// Driver instance id, for log correlation. @@ -158,21 +178,35 @@ public sealed class SparkplugPrimaryHost : IAsyncDisposable /// sharing a configured id already collide on their ingest connections). /// /// - /// Blank clientId (the documented default): the id used to be the literal - /// -spbhost — the ONE connection in the driver with a fixed, fleet-wide id (ingest gets a - /// library-generated id, the probe and browser a random suffix). A plant with two Sparkplug groups - /// needs two drivers, both claimed with -spbhost, and each CONNECT evicted the other: both - /// STATE topics flapped ONLINE/OFFLINE about once a second while both drivers reported Healthy. A - /// random per-instance id fixes it, and nothing depends on the id being stable — the claim session - /// is forced clean. 20 characters, inside MQTT 3.1.1's guaranteed 23. + /// Blank clientId (the documented default): spbhost-{12 hex}, the hex being a + /// stable hash of the (trimmed) Sparkplug host id and group id. It used to be the literal + /// -spbhost — one fixed, fleet-wide id — so two drivers for two Sparkplug groups evicted each + /// other's claim about once a second (#988 M-3). The first fix made it RANDOM per instance, which + /// broke the other half of the contract: both nodes of a redundant pair run the same driver config, + /// and a Secondary that claims while cold-starting (before its cluster join tells it a Primary + /// exists) must present the SAME id as the Primary, so the broker's client-id takeover keeps the + /// claim single — the evicted Primary's supervisor reconnects and re-asserts. With two random ids both + /// held the topic, and the Secondary's stand-down OFFLINE landed newer than the Primary's ONLINE with + /// nothing to correct it (#988 review round 2). Deterministic over (host id, group) gives both: a pair + /// shares one id, distinct groups/hosts differ. 20 characters, inside MQTT 3.1.1's guaranteed 23. /// /// /// The claim connection's options (blank client id already normalised to null). /// The suffix. - internal static string BuildClaimClientIdSuffix(MqttDriverOptions claimOptions) => - claimOptions.ClientId is null - ? GeneratedClientIdPrefix + Guid.NewGuid().ToString("N")[..12] - : ClientIdSuffix; + internal static string BuildClaimClientIdSuffix(MqttDriverOptions claimOptions) + { + if (claimOptions.ClientId is not null) + { + return ClientIdSuffix; + } + + var identity = string.Concat( + claimOptions.Sparkplug?.HostId?.Trim() ?? string.Empty, + "\n", + claimOptions.Sparkplug?.GroupId?.Trim() ?? string.Empty); + var hash = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(identity)); + return GeneratedClientIdPrefix + Convert.ToHexStringLower(hash.AsSpan(0, 6)); + } /// Test seam: the client id the claim connection presents. internal string ClaimClientIdForTests => string.Concat(_claimOptions.ClientId ?? string.Empty, _claimClientIdSuffix); @@ -495,8 +529,13 @@ public sealed class SparkplugPrimaryHost : IAsyncDisposable // ONE timestamp for both bodies — the Will is built here, before CONNECT, and the birth // published after CONNACK. See SparkplugStatePayload's remarks on why they must match. + // + // Never older than a foreign OFFLINE this claim has already observed (see OnOwnStateMessage): + // Sparkplug 3.0 edge nodes ignore a STATE older than the one they hold, so a re-claim answering a + // newer OFFLINE must out-date it even across a little clock skew between the two claimants. var session = SparkplugStatePayload.ForSession( - _hostId, _timeProvider.GetUtcNow().ToUnixTimeMilliseconds()); + _hostId, + Math.Max(_timeProvider.GetUtcNow().ToUnixTimeMilliseconds(), Interlocked.Read(ref _minNextSessionTimestampMs))); var connection = new MqttConnection( _claimOptions, @@ -511,10 +550,19 @@ public sealed class SparkplugPrimaryHost : IAsyncDisposable // single state this whole mechanism exists to make impossible. cleanSessionOverride: true); + // Watch our own STATE topic (Sparkplug 3.0 asks a host to): an OFFLINE this claim did not just + // publish — another claimant's stand-down or Will — is re-asserted over. Non-blocking: the + // observer runs on MQTTnet's pump and only queues work. + connection.MessageReceived += (topic, payload, _) => OnOwnStateMessage(connection, session, topic, payload); + // Re-assert on every reconnect. A broker restart drops retained messages; without this the - // host would be connected and believed offline by every edge node, silently. + // host would be connected and believed offline by every edge node, silently. The clean session + // lost the STATE subscription, so re-subscribe FIRST: the retained replay then shows what was + // there before this ONLINE — e.g. the OFFLINE of a same-id claimant (a cold-starting Secondary) + // whose takeover caused this reconnect, which a same-timestamp republish would not out-date. connection.Reconnected += async ct => { + await WatchOwnStateAsync(connection, session.Topic, ct).ConfigureAwait(false); await connection.PublishAsync( session.Topic, session.OnlineBody, SparkplugStatePayload.StateQos, retain: true, ct) .ConfigureAwait(false); @@ -545,6 +593,9 @@ public sealed class SparkplugPrimaryHost : IAsyncDisposable _session = session; Volatile.Write(ref _connection, connection); + // After the commit, so a replayed/live OFFLINE observed from here on finds this claim current. + await WatchOwnStateAsync(connection, session.Topic, cancellationToken).ConfigureAwait(false); + _logger?.LogInformation( "MQTT driver '{DriverId}': claimed Sparkplug primary host '{HostId}' — retained ONLINE published on '{Topic}', " + "OFFLINE armed as the Last Will.", @@ -558,6 +609,213 @@ public sealed class SparkplugPrimaryHost : IAsyncDisposable } } + /// + /// Subscribes the claim connection to its own STATE topic. Best effort: a broker ACL that refuses it + /// costs the re-assert safety net, never the claim. + /// + private async Task WatchOwnStateAsync(MqttConnection connection, string topic, CancellationToken cancellationToken) + { + try + { + var outcomes = await connection + .SubscribeAsync([new MqttTopicSubscription(topic, SparkplugStatePayload.StateQos, SeedRetained: true)], cancellationToken) + .ConfigureAwait(false); + if (outcomes is [{ Granted: false } refused]) + { + _logger?.LogWarning( + "MQTT driver '{DriverId}': the broker refused the Sparkplug primary host's subscription to its own STATE " + + "topic '{Topic}' ({Reason}); a foreign OFFLINE for '{HostId}' will not be re-asserted over.", + _driverId, + topic, + refused.Reason, + _hostId); + } + } + catch (Exception ex) + { + _logger?.LogWarning( + ex, + "MQTT driver '{DriverId}': could not subscribe the Sparkplug primary host to its own STATE topic '{Topic}'.", + _driverId, + topic); + } + } + + /// + /// The claim's own-STATE observer (MQTTnet pump thread — classify and queue only). An OFFLINE seen + /// while this connection is still the held claim was not published by this claim: its own stand-down + /// detaches the connection BEFORE publishing (), so the broker's echo of it is + /// ignored here. + /// + /// + /// + /// Timestamp <= this session's: our own Will (replayed after the broker thought we died) or a + /// stale death — republishing this session's ONLINE out-dates or pairs with it. + /// Timestamp > this session's: a newer claimant's death (a same-host-id Secondary that claimed + /// while cold-starting, then stood down). Conformant edge nodes would ignore our older ONLINE, so the + /// claim is re-made with a FRESH, newer session (new Will + ONLINE). + /// + /// Both are coalesced and rate-limited (). + /// + private void OnOwnStateMessage( + MqttConnection connection, SparkplugStateSession session, string topic, ReadOnlySpan payload) + { + if (!string.Equals(topic, session.Topic, StringComparison.Ordinal) + || !SparkplugStatePayload.TryDecode(payload, out var online, out var timestampMs) + || online + || !ReferenceEquals(Volatile.Read(ref _connection), connection) + || Volatile.Read(ref _disposed) != 0) + { + return; + } + + var kind = ReassertRepublish; + if (timestampMs > session.TimestampMs) + { + kind = ReassertFresh; + var floor = timestampMs + 1; + long current; + while ((current = Interlocked.Read(ref _minNextSessionTimestampMs)) < floor + && Interlocked.CompareExchange(ref _minNextSessionTimestampMs, floor, current) != current) + { + } + } + + int pending; + while ((pending = Volatile.Read(ref _reassertRequest)) < kind + && Interlocked.CompareExchange(ref _reassertRequest, kind, pending) != pending) + { + } + + TryStartReassertWorker(); + } + + private void TryStartReassertWorker() + { + if (Volatile.Read(ref _reassertRequest) == 0 || Interlocked.CompareExchange(ref _reassertRunning, 1, 0) != 0) + { + return; + } + + CancellationToken token; + try + { + token = Volatile.Read(ref _loopCts)?.Token ?? new CancellationToken(canceled: true); + } + catch (ObjectDisposedException) + { + token = new CancellationToken(canceled: true); + } + + if (token.IsCancellationRequested) + { + Interlocked.Exchange(ref _reassertRequest, 0); + Volatile.Write(ref _reassertRunning, 0); + return; + } + + _ = Task.Run(() => ReassertLoopAsync(token), CancellationToken.None); + } + + private async Task ReassertLoopAsync(CancellationToken ct) + { + try + { + while (!ct.IsCancellationRequested) + { + var wait = _lastReassertUtc == DateTimeOffset.MinValue + ? TimeSpan.Zero + : _lastReassertUtc + ReassertMinInterval - _timeProvider.GetUtcNow(); + if (wait > TimeSpan.Zero) + { + await Task.Delay(wait, _timeProvider, ct).ConfigureAwait(false); + } + + var kind = Interlocked.Exchange(ref _reassertRequest, 0); + if (kind == 0) + { + break; + } + + _lastReassertUtc = _timeProvider.GetUtcNow(); + await ReassertAsync(kind, ct).ConfigureAwait(false); + } + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + // Stand-down / shutdown. + } + catch (Exception ex) + { + // The reconcile loop still owns "no claim held → claim"; this only lost promptness. + _logger?.LogWarning( + ex, + "MQTT driver '{DriverId}': could not re-assert the Sparkplug primary host '{HostId}' over a foreign OFFLINE.", + _driverId, + _hostId); + } + finally + { + Volatile.Write(ref _reassertRunning, 0); + } + + // A request that landed between the last exchange and the flag reset must not be stranded. + if (!ct.IsCancellationRequested) + { + TryStartReassertWorker(); + } + } + + private async Task ReassertAsync(int kind, CancellationToken ct) + { + if (!_roleSource.ShouldActAsPrimary) + { + return; // the reconcile loop is about to release; re-asserting would fight it + } + + await _gate.WaitAsync(ct).ConfigureAwait(false); + try + { + if (Volatile.Read(ref _disposed) != 0 || _connection is not { } connection || _session is not { } session + || IsDead(connection)) + { + return; // nothing held — the reconcile loop claims afresh on its own + } + + if (kind == ReassertFresh && session.TimestampMs < Interlocked.Read(ref _minNextSessionTimestampMs)) + { + _logger?.LogWarning( + "MQTT driver '{DriverId}': observed a newer Sparkplug OFFLINE for primary host '{HostId}' than its own claim " + + "(another claimant stood down or died); re-claiming with a fresh session.", + _driverId, + _hostId); + + // A clean DISCONNECT: the broker discards this session's Will, so no OFFLINE of ours lands + // between here and the fresh claim's ONLINE. + Volatile.Write(ref _connection, null); + _session = null; + await connection.DisposeAsync().ConfigureAwait(false); + } + else + { + await connection.PublishAsync( + session.Topic, session.OnlineBody, SparkplugStatePayload.StateQos, retain: true, ct) + .ConfigureAwait(false); + _logger?.LogInformation( + "MQTT driver '{DriverId}': re-published Sparkplug primary-host ONLINE for '{HostId}' over an observed OFFLINE.", + _driverId, + _hostId); + return; + } + } + finally + { + _gate.Release(); + } + + await ClaimAsync(ct).ConfigureAwait(false); + } + private async Task ReleaseAsync(string reason, CancellationToken cancellationToken) { if (Volatile.Read(ref _connection) is null) diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbCip.Tests/AbCip983ReviewTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbCip.Tests/AbCip983ReviewTests.cs new file mode 100644 index 000000000..fcedeae0b --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbCip.Tests/AbCip983ReviewTests.cs @@ -0,0 +1,166 @@ +using System.Collections.Concurrent; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport; +using ZB.MOM.WW.OtOpcUa.Driver.AbCip; + +namespace ZB.MOM.WW.OtOpcUa.Driver.AbCip.Tests; + +/// +/// #983 review round: the P-2 per-call device fault latch fired on ANY timeout and evicted handles it never tried, +/// and P-22 put the probe's short timeout on the cold initialisation (connect + Forward Open). +/// +[Trait("Category", "Unit")] +public sealed class AbCip983ReviewTests +{ + private const string Dev = "ab://10.0.0.6/1,0"; + + private static AbCipDriverOptions Options(int tags, AbCipTransport transport) => new() + { + Devices = [new AbCipDeviceOptions(Dev)], + RawTags = AbCipRawTags.From([.. Enumerable.Range(0, tags).Select(i => new AbCipTagDefinition($"T{i}", Dev, $"T{i}", AbCipDataType.DInt))]), + Probe = new AbCipProbeOptions { Enabled = false }, + MaxConcurrentReads = 1, // deterministic order: T0, T1, … one at a time + Transport = transport, + }; + + /// + /// On libplctag every tag is its own request with its own timeout: ONE tag timing out (a slow/large tag, a bad + /// element) proves nothing about its siblings. It used to latch the whole device for the call — every later + /// tag read BadCommunicationError without being tried, and was evicted. + /// + [Fact] + public async Task On_libplctag_one_tag_timeout_does_not_latch_the_device() + { + var creates = 0; + var factory = new FakeAbCipTagFactory + { + Customise = p => + { + Interlocked.Increment(ref creates); + return new FakeAbCipTag(p) { Value = 5 }; + }, + }; + var drv = new AbCipDriver(Options(10, AbCipTransport.Libplctag), "abcip-983-lib", factory); + await drv.InitializeAsync("{}", CancellationToken.None); + string[] refs = [.. Enumerable.Range(0, 10).Select(i => $"T{i}")]; + (await drv.ReadAsync(refs, CancellationToken.None)).ShouldAllBe(s => s.StatusCode == AbCipStatusMapper.Good); + + var slow = factory.Tags["T3"]; + slow.ThrowOnRead = true; + slow.Exception = new AbTransportException(AbStatus.Timeout, "reply timeout"); + + var r = await drv.ReadAsync(refs, CancellationToken.None); + + r[3].StatusCode.ShouldNotBe(AbCipStatusMapper.Good); + r.Where((_, i) => i != 3).ShouldAllBe(s => s.StatusCode == AbCipStatusMapper.Good); + factory.Tags.Where(t => t.Key != "T3").ShouldAllBe(t => t.Value.ReadCount == 2, "every sibling was actually read"); + creates.ShouldBe(10, "no sibling handle was evicted"); + await drv.DisposeAsync(); + } + + /// A libplctag connection-level status (BadConnection) still latches — the positive control for the above. + [Fact] + public async Task On_libplctag_a_bad_connection_still_latches() + { + var factory = new FakeAbCipTagFactory { Customise = p => new FakeAbCipTag(p) { Value = 5 } }; + var drv = new AbCipDriver(Options(10, AbCipTransport.Libplctag), "abcip-983-lib2", factory); + await drv.InitializeAsync("{}", CancellationToken.None); + string[] refs = [.. Enumerable.Range(0, 10).Select(i => $"T{i}")]; + await drv.ReadAsync(refs, CancellationToken.None); + + foreach (var tag in factory.Tags.Values) + { + tag.ThrowOnRead = true; + tag.Exception = new AbTransportException(AbStatus.BadConnection, "session gone"); + } + + var r = await drv.ReadAsync(refs, CancellationToken.None); + + r.ShouldAllBe(s => s.StatusCode != AbCipStatusMapper.Good); + factory.Tags.Values.Sum(t => t.ReadCount).ShouldBe(10 + 1, "only the first item reached the wire"); + await drv.DisposeAsync(); + } + + /// + /// On the native transport a timeout faults the shared channel, so it latches — but the items latched out were + /// never attempted and their handles are fine: they must not be evicted (each eviction re-creates the handle + /// and, for a sole lease holder, re-Forward-Opens on the next poll). + /// + [Fact] + public async Task On_native_a_channel_timeout_latches_but_never_attempted_handles_are_kept() + { + var creates = 0; + var factory = new FakeAbCipTagFactory + { + Customise = p => + { + Interlocked.Increment(ref creates); + return new FakeAbCipTag(p) { Value = 5 }; + }, + }; + var drv = new AbCipDriver(Options(10, AbCipTransport.Native), "abcip-983-nat", factory); + await drv.InitializeAsync("{}", CancellationToken.None); + string[] refs = [.. Enumerable.Range(0, 10).Select(i => $"T{i}")]; + await drv.ReadAsync(refs, CancellationToken.None); + + var first = factory.Tags["T0"]; + first.ThrowOnRead = true; + first.Exception = new AbTransportException(AbStatus.Timeout, "no reply"); + + var r = await drv.ReadAsync(refs, CancellationToken.None); + r.ShouldAllBe(s => s.StatusCode != AbCipStatusMapper.Good); // latched: the rest fail fast + factory.Tags.Where(t => t.Key != "T0").ShouldAllBe(t => t.Value.ReadCount == 1, "latched items never reached the wire"); + + // The channel recovers: only the ATTEMPTED (failed) handle is re-created. + first.ThrowOnRead = false; + await drv.ReadAsync(refs, CancellationToken.None); + creates.ShouldBeLessThanOrEqualTo(11); + await drv.DisposeAsync(); + } + + /// + /// P-22 put the probe's own (short, default 2 s) timeout on the probe runtime's COLD initialisation too — on the + /// native transport that is the TCP connect + RegisterSession + Forward Open, bounded by the driver's Timeout. A + /// slow-but-healthy open longer than the probe timeout then never completed: the probe re-created and timed out + /// every tick, holding the host Stopped. Only the probe READ is bounded by the probe timeout. + /// + [Fact] + public async Task A_cold_probe_initialisation_slower_than_the_probe_timeout_still_completes() + { + var factory = new FakeAbCipTagFactory { Customise = p => new SlowInitTag(p) }; + var transitions = new ConcurrentQueue(); + var drv = new AbCipDriver(new AbCipDriverOptions + { + Devices = [new AbCipDeviceOptions(Dev)], + Probe = new AbCipProbeOptions + { + Enabled = true, + Interval = TimeSpan.FromMilliseconds(100), + Timeout = TimeSpan.FromMilliseconds(100), + ProbeTagPath = "@raw_cpu_type", + }, + Timeout = TimeSpan.FromSeconds(5), + }, "abcip-983-probe", factory); + drv.OnHostStatusChanged += (_, e) => transitions.Enqueue(e); + + await drv.InitializeAsync("{}", CancellationToken.None); + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(5); + while (drv.GetHostStatuses().Single().State != HostState.Running && DateTime.UtcNow < deadline) + await Task.Delay(20, TestContext.Current.CancellationToken); + + drv.GetHostStatuses().Single().State.ShouldBe(HostState.Running); + await drv.ShutdownAsync(CancellationToken.None); + } + + /// An initialisation that takes 400 ms (a slow Forward Open) and then works. + private sealed class SlowInitTag(AbCipTagCreateParams p) : FakeAbCipTag(p) + { + public override async Task InitializeAsync(CancellationToken cancellationToken) + { + await Task.Delay(400, cancellationToken); + await base.InitializeAsync(cancellationToken); + } + } +} diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbCip.Tests/AbCipDeadDeviceBatchTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbCip.Tests/AbCipDeadDeviceBatchTests.cs index 75c2ad3be..b888783e8 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbCip.Tests/AbCipDeadDeviceBatchTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbCip.Tests/AbCipDeadDeviceBatchTests.cs @@ -112,9 +112,10 @@ public sealed class AbCipDeadDeviceBatchTests } /// - /// After the failed call the dead device's handles are evicted, so the next poll re-creates cold: ONE - /// single-flight attempt reaches the wire, fails, opens the backoff window, and the other 19 tags (and every - /// later poll) are throttled without touching it. Once the window passes a recovered device reads Good. + /// After the failed call the handles that reached the wire are evicted (the latched-out ones are kept — #983 + /// review), so the next poll re-creates those cold: ONE single-flight attempt reaches the wire, fails, opens the + /// backoff window, the rest are throttled, and a throttled create latches the device so the kept warm handles + /// fail fast too. Once the window passes a recovered device reads Good. /// [Fact] public async Task The_next_poll_of_a_dead_device_makes_one_attempt_then_throttles_and_recovery_still_works() @@ -144,7 +145,7 @@ public sealed class AbCipDeadDeviceBatchTests tag.ThrowOnRead = true; tag.Exception = new AbTransportException(AbStatus.Timeout, "reply timeout"); } - await drv.ReadAsync(refs, CancellationToken.None); // warm failures; handles evicted + await drv.ReadAsync(refs, CancellationToken.None); // warm failures; the attempted handles evicted bCreates.ShouldBe(20); var r = await drv.ReadAsync(refs, CancellationToken.None); // cold: one real attempt, rest throttled @@ -155,8 +156,9 @@ public sealed class AbCipDeadDeviceBatchTests await drv.ReadAsync(refs, CancellationToken.None); // inside the window: nothing re-created bCreates.ShouldBe(21); - // Recovery once the window passes. + // Recovery once the window passes: the device answers again, on its kept warm handles too. down = false; + foreach (var tag in factory.Tags.Where(t => t.Key.StartsWith('B')).Select(t => t.Value)) tag.ThrowOnRead = false; await Task.Delay(TimeSpan.FromMilliseconds(1300), TestContext.Current.CancellationToken); r = await drv.ReadAsync(refs, CancellationToken.None); r.ShouldAllBe(s => s.StatusCode == AbCipStatusMapper.Good); diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Tests/AbLegacyDriverTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Tests/AbLegacyDriverTests.cs index 4714bb25c..6fec60503 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Tests/AbLegacyDriverTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Tests/AbLegacyDriverTests.cs @@ -89,7 +89,7 @@ public sealed class AbLegacyDriverTests AbLegacyPlcFamilyProfile.Slc500.DefaultCipPath.ShouldBe("1,0"); AbLegacyPlcFamilyProfile.MicroLogix.DefaultCipPath.ShouldBe(""); - AbLegacyPlcFamilyProfile.MicroLogix.SupportsLongFile.ShouldBeFalse(); + AbLegacyPlcFamilyProfile.MicroLogix.SupportsLongFile.ShouldBeTrue(); // ML 1100/1200/1400/1500 have L files (#984 review) AbLegacyPlcFamilyProfile.Plc5.LibplctagPlcAttribute.ShouldBe("plc5"); AbLegacyPlcFamilyProfile.Plc5.SupportsLongFile.ShouldBeFalse(); @@ -165,25 +165,26 @@ public sealed class AbLegacyDriverTests } /// - /// A Long tag on a MicroLogix is THAT TAG's configuration error and must not fault the whole instance (review - /// 2026-12-02 P-5; this test used to pin the throw). Init succeeds, the tag reads BadConfigurationError, and the - /// skipped-tag ledger names it. + /// #984 review: a Long tag on a MicroLogix is ACCEPTED. MicroLogix 1100/1200/1400/1500 all have L (32-bit integer) + /// files (only the ML 1000 lacks them); the profile used to say otherwise and refused every L tag on the family + /// the driver's own parser, coalescer and L-bit RMW already handle. The per-tag rejection rule is pinned on PLC-5. /// [Fact] - public async Task Long_tag_on_MicroLogix_device_is_rejected_per_tag_not_at_init() + public async Task Long_tag_on_MicroLogix_device_is_accepted() { + var factory = new FakeAbLegacyTagFactory { Customise = p => new FakeAbLegacyTag(p) { Value = 70000 } }; var drv = new AbLegacyDriver(new AbLegacyDriverOptions { Devices = [new AbLegacyDeviceOptions("ab://10.0.0.5/", AbLegacyPlcFamily.MicroLogix)], RawTags = AbLegacyRawTags.Entries([new AbLegacyTagDefinition("X", "ab://10.0.0.5/", "L9:0", AbLegacyDataType.Long)]), Probe = new AbLegacyProbeOptions { Enabled = false }, - }, "drv-1", new FakeAbLegacyTagFactory()); + }, "drv-1", factory); await drv.InitializeAsync("{}", CancellationToken.None); drv.GetHealth().State.ShouldBe(DriverState.Healthy); - (await drv.ReadAsync(["X"], CancellationToken.None)).Single().StatusCode.ShouldBe(AbLegacyStatusMapper.BadConfigurationError); - drv.GetSkippedTags()!.Sample.ShouldContain(t => t.RawPath == "X"); + (await drv.ReadAsync(["X"], CancellationToken.None)).Single().StatusCode.ShouldBe(AbLegacyStatusMapper.Good); + drv.GetSkippedTags()?.Sample.ShouldNotContain(t => t.RawPath == "X"); } /// Verifies that long tag on SLC 500 device is accepted. diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Tests/AbLegacyReview20261202Tests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Tests/AbLegacyReview20261202Tests.cs index 19e719d35..3dc54b0f3 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Tests/AbLegacyReview20261202Tests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Tests/AbLegacyReview20261202Tests.cs @@ -15,7 +15,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Tests; public sealed class AbLegacyReview20261202Tests { private const string Slc = "ab://10.0.0.5/1,0"; - private const string Ml = "ab://10.0.0.6/"; + private const string Plc5 = "ab://10.0.0.6/1,0"; private static AbLegacyDriver NewDriver( FakeAbLegacyTagFactory factory, IReadOnlyList devices, @@ -31,16 +31,17 @@ public sealed class AbLegacyReview20261202Tests // ---- P-5 ---- [Fact] - public async Task P5_one_Long_tag_on_a_MicroLogix_does_not_fault_the_other_devices_or_tags() + public async Task P5_one_Long_tag_on_a_Plc5_does_not_fault_the_other_devices_or_tags() { var factory = new FakeAbLegacyTagFactory { Customise = p => new FakeAbLegacyTag(p) { Value = 7 } }; var drv = NewDriver(factory, - [new AbLegacyDeviceOptions(Slc), new AbLegacyDeviceOptions(Ml, AbLegacyPlcFamily.MicroLogix)], + // PLC-5 has no L files (since the #984 review MicroLogix does — the rule is exercised on PLC-5). + [new AbLegacyDeviceOptions(Slc), new AbLegacyDeviceOptions(Plc5, AbLegacyPlcFamily.Plc5)], null, new AbLegacyTagDefinition("Good", Slc, "N7:0", AbLegacyDataType.Int), new AbLegacyTagDefinition("LongOnSlc", Slc, "L9:0", AbLegacyDataType.Long), // positive control: SLC has L files - new AbLegacyTagDefinition("GoodMl", Ml, "N7:1", AbLegacyDataType.Int), - new AbLegacyTagDefinition("LongOnMl", Ml, "L9:0", AbLegacyDataType.Long)); + new AbLegacyTagDefinition("GoodMl", Plc5, "N7:1", AbLegacyDataType.Int), + new AbLegacyTagDefinition("LongOnMl", Plc5, "L9:0", AbLegacyDataType.Long)); await drv.InitializeAsync("{}", CancellationToken.None); // used to throw and fault every device @@ -52,7 +53,7 @@ public sealed class AbLegacyReview20261202Tests r[3].StatusCode.ShouldBe(AbLegacyStatusMapper.BadConfigurationError); r[3].Value.ShouldBeNull(); factory.Tags.ContainsKey("L9:0").ShouldBeTrue(); // the SLC's Long created its runtime ... - drv.GetDeviceState(Ml)!.Runtimes.ContainsKey("LongOnMl").ShouldBeFalse(); // ... the rejected one never did + drv.GetDeviceState(Plc5)!.Runtimes.ContainsKey("LongOnMl").ShouldBeFalse(); // ... the rejected one never did var report = drv.GetSkippedTags()!; report.SkippedCount.ShouldBe(1); @@ -64,20 +65,20 @@ public sealed class AbLegacyReview20261202Tests } [Fact] - public void P5_deploy_gate_flags_a_Long_on_a_MicroLogix_only_when_the_family_is_known() + public void P5_deploy_gate_flags_a_Long_on_a_Plc5_only_when_the_family_is_known() { const string longCfg = """{"address":"L9:0","dataType":"Long"}"""; - AbLegacyTagDefinitionFactory.Inspect(longCfg, AbLegacyPlcFamily.MicroLogix) - .ShouldContain(w => w.Contains("Long") && w.Contains("MicroLogix") && w.Contains("BadConfigurationError")); - AbLegacyTagDefinitionFactory.Inspect(longCfg, AbLegacyPlcFamily.Plc5).ShouldNotBeEmpty(); + AbLegacyTagDefinitionFactory.Inspect(longCfg, AbLegacyPlcFamily.Plc5) + .ShouldContain(w => w.Contains("Long") && w.Contains("Plc5") && w.Contains("BadConfigurationError")); - // Controls: a family that ships L files, an unknown family and the family-less overload stay clean; and an - // Int on a MicroLogix is not touched. + // Controls: families that ship L files (SLC 500, and MicroLogix since the #984 review), an unknown family and + // the family-less overload stay clean; and an Int on a PLC-5 is not touched. AbLegacyTagDefinitionFactory.Inspect(longCfg, AbLegacyPlcFamily.Slc500).ShouldBeEmpty(); + AbLegacyTagDefinitionFactory.Inspect(longCfg, AbLegacyPlcFamily.MicroLogix).ShouldBeEmpty(); AbLegacyTagDefinitionFactory.Inspect(longCfg, family: null).ShouldBeEmpty(); AbLegacyTagDefinitionFactory.Inspect(longCfg).ShouldBeEmpty(); - AbLegacyTagDefinitionFactory.Inspect("""{"address":"N7:0","dataType":"Int"}""", AbLegacyPlcFamily.MicroLogix).ShouldBeEmpty(); + AbLegacyTagDefinitionFactory.Inspect("""{"address":"N7:0","dataType":"Int"}""", AbLegacyPlcFamily.Plc5).ShouldBeEmpty(); } // ---- P-14 ---- diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/DroppedEventResyncTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/DroppedEventResyncTests.cs index fa55fa1f9..68d225f28 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/DroppedEventResyncTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/DroppedEventResyncTests.cs @@ -141,6 +141,79 @@ public sealed class DroppedEventResyncTests await TestWait.UntilAsync(() => values.Contains(("Tank.B", 9.0)), "data must flow on the post-gap handles"); } + /// + /// #991 review: a reconnect that completes in the MIDDLE of a multi-subscription re-advise pass (here: between + /// the dropped-event resync's first and second subscription) made the pass dial its next SubscribeBulk on the + /// NEW gateway session with the OLD session number — the rebind then refused it (SessionChanged) and the fresh, + /// live new-session advises were never bound nor released: a leak on the gateway, doubled by the replay that + /// re-advises the same tags. A pass whose session is gone must not dial at all. + /// + [Fact] + public async Task A_session_swap_mid_resync_leaves_no_unbound_new_session_advises() + { + var subscriber = new AdvisingSubscriber(); + subscriber.Current["Tank.A"] = 1.0; + subscriber.Current["Tank.B"] = 2.0; + using var driver = NewDriver(subscriber); + await driver.SubscribeAsync(["Tank.A"], TimeSpan.Zero, TestContext.Current.CancellationToken); + await driver.SubscribeAsync(["Tank.B"], TimeSpan.Zero, TestContext.Current.CancellationToken); + var hA = subscriber.LiveHandlesFor("Tank.A").ShouldHaveSingleItem(); + var hB = subscriber.LiveHandlesFor("Tank.B").ShouldHaveSingleItem(); + var session = driver.SubscriptionsForTests.CurrentSession; + + var swapped = 0; + var createdAfterSwap = new ConcurrentQueue(); + subscriber.AfterSubscribe = handles => + { + if (Volatile.Read(ref swapped) == 1) foreach (var h in handles) createdAfterSwap.Enqueue(h); + }; + // Tank.A's re-advise ends by releasing hA: the reconnect completes right there, before Tank.B's re-advise. + subscriber.AfterUnsubscribe = handles => + { + if (handles.Contains(hA) && Interlocked.Exchange(ref swapped, 1) == 0) driver.SubscriptionsForTests.StartNewSession(); + }; + + await driver.ResyncDroppedHandlesForTestsAsync([hA, hB], session); + + Volatile.Read(ref swapped).ShouldBe(1, "the swap must have happened mid-pass"); + createdAfterSwap.Where(h => !subscriber.Unsubscribed.Contains(h)) + .ShouldBeEmpty("no advise issued after the swap may be left unbound and unreleased"); + } + + /// + /// #991 review: repeated overflow bursts each started a resync pass as soon as the previous one finished — + /// re-advising (and pushing initial values into) the very channel that was overflowing. Passes are now at least + /// DropResyncMinInterval apart, and the drops reported meanwhile coalesce into the next pass. + /// + [Fact] + public async Task Repeated_drop_bursts_are_rate_limited_and_coalesced() + { + var subscriber = new AdvisingSubscriber(); + subscriber.Current["Tank.A"] = 1.0; + using var driver = NewDriver(subscriber); + driver.DropResyncMinIntervalForTests = TimeSpan.FromSeconds(1.5); + await driver.SubscribeAsync(["Tank.A"], TimeSpan.Zero, TestContext.Current.CancellationToken); + var baseline = subscriber.SubscribeCalls; + + driver.NotifyEventsDroppedForTests([subscriber.LiveHandlesFor("Tank.A").Single()]); + await TestWait.UntilAsync(() => subscriber.SubscribeCalls == baseline + 1, "the first burst resyncs at once"); + await TestWait.UntilAsync(() => subscriber.LiveHandlesFor("Tank.A").Length == 1, "superseded handle released"); + + // Five more bursts in quick succession, each against the tag's current handle. + for (var i = 0; i < 5; i++) + { + driver.NotifyEventsDroppedForTests([subscriber.LiveHandlesFor("Tank.A").Single()]); + await Task.Delay(50, TestContext.Current.CancellationToken); + } + + await Task.Delay(500, TestContext.Current.CancellationToken); + subscriber.SubscribeCalls.ShouldBe(baseline + 1, "no second pass inside the minimum interval"); + + await TestWait.UntilAsync(() => subscriber.SubscribeCalls == baseline + 2, "the coalesced bursts resync once the interval passes"); + await Task.Delay(500, TestContext.Current.CancellationToken); + subscriber.SubscribeCalls.ShouldBe(baseline + 2, "five bursts cost one pass, not five"); + } + /// /// Behaves like the gateway + MXAccess for the parts these tests need: every SubscribeBulk issues fresh item /// handles and pushes each one's current value (an advise's initial value), a change is pushed on every live @@ -185,6 +258,12 @@ public sealed class DroppedEventResyncTests SourceTimestamp = Timestamp.FromDateTime(DateTime.UtcNow), }).ShouldBeTrue(); + /// Called with the handles each SubscribeBulk issued, after issuing them. + public Action>? AfterSubscribe { get; set; } + + /// Called with the handles each UnsubscribeBulk retired, after retiring them. + public Action>? AfterUnsubscribe { get; set; } + public Task> SubscribeBulkAsync( IReadOnlyList fullReferences, int bufferedUpdateIntervalMs, CancellationToken cancellationToken) { @@ -197,6 +276,7 @@ public sealed class DroppedEventResyncTests results.Add(new SubscribeResult { TagAddress = r, ItemHandle = handle, WasSuccessful = true }); if (Current.TryGetValue(r, out var v)) Emit(handle, v); // the advise's initial value } + AfterSubscribe?.Invoke([.. results.Select(x => x.ItemHandle)]); return Task.FromResult>(results); } @@ -207,6 +287,7 @@ public sealed class DroppedEventResyncTests Unsubscribed.Enqueue(h); _live.TryRemove(h, out _); } + AfterUnsubscribe?.Invoke(itemHandles); return Task.CompletedTask; } diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GatewayGalaxyDataWriterFailClosedTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GatewayGalaxyDataWriterFailClosedTests.cs index 964de2d20..0b832d966 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GatewayGalaxyDataWriterFailClosedTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GatewayGalaxyDataWriterFailClosedTests.cs @@ -21,34 +21,69 @@ public sealed class GatewayGalaxyDataWriterFailClosedTests // ---------------- T5: seam ---------------- - /// A secured-write classification routes through WriteSecured and never advises (regression via the seam). - [Fact] - public async Task WriteOne_SecuredClassification_RoutesThroughWriteSecured_NoAdvise() + /// + /// #991 review (G-1): a SecuredWrite/VerifiedWrite attribute is REFUSED BadUserAccessDenied without + /// touching the wire. Routing it to WriteSecured could not succeed — the driver has no + /// AuthenticateUser identity, does not supervisory-advise for it, and the gateway key needs + /// invoke:secure — and the gateway's refusal mapped to BadCommunicationError, a comms fault. + /// + [Theory] + [InlineData(SecurityClassification.SecuredWrite)] + [InlineData(SecurityClassification.VerifiedWrite)] + public async Task WriteOne_SecuredOrVerifiedClassification_IsRefused_WithoutTouchingTheWire(SecurityClassification classification) { var ops = new FakeMxWriteOps(); var writer = NewWriter(); var result = await writer.WriteOneForTestAsync( - ops, new WriteRequest("Tag.Sec", true), SecurityClassification.SecuredWrite, CancellationToken.None); + ops, new WriteRequest("Tag.Sec", true), classification, CancellationToken.None); - result.StatusCode.ShouldBe(StatusCodeMap.Good); - ops.Invokes.Count(r => r.Command.Kind == MxCommandKind.WriteSecured).ShouldBe(1); - ops.Invokes.Any(r => r.Command.Kind == MxCommandKind.AdviseSupervisory).ShouldBeFalse(); + result.StatusCode.ShouldBe(StatusCodeMap.BadUserAccessDenied); + ops.AddItemRefs.ShouldBeEmpty(); + ops.Invokes.ShouldBeEmpty(); ops.RawWriteHandles.ShouldBeEmpty(); } - /// #991 G-1: WriteSecured carries the configured WriteUserId as the current user, not a hard-coded 0. - [Fact] - public async Task WriteOne_SecuredClassification_CarriesTheConfiguredWriteUserId() + /// + /// #991 review (G-1): a gateway that refuses the caller (PermissionDenied — the API key lacks the + /// scope — or Unauthenticated) is an access refusal, not a communication failure. + /// + [Theory] + [InlineData(Grpc.Core.StatusCode.PermissionDenied)] + [InlineData(Grpc.Core.StatusCode.Unauthenticated)] + public async Task WriteOne_GatewayRefusesTheCaller_OnTheWrite_IsBadUserAccessDenied(Grpc.Core.StatusCode code) { - var ops = new FakeMxWriteOps(); - var writer = new GatewayGalaxyDataWriter( - new GalaxyMxSession(new Config.GalaxyMxAccessOptions(ClientName: "OtOpcUa-Test")), writeUserId: 42); + var ops = new FakeMxWriteOps + { + InvokeResponder = _ => new MxCommandReply { ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok } }, + RawWriteResponder = () => throw new Grpc.Core.RpcException(new Grpc.Core.Status(code, "scope missing")), + }; + var writer = NewWriter(); - await writer.WriteOneForTestAsync( - ops, new WriteRequest("Tag.Sec", true), SecurityClassification.SecuredWrite, CancellationToken.None); + var result = await writer.WriteOneForTestAsync( + ops, new WriteRequest("Tag.A", 1), SecurityClassification.FreeAccess, CancellationToken.None); - ops.Invokes.Single(r => r.Command.Kind == MxCommandKind.WriteSecured).Command.WriteSecured.CurrentUserId.ShouldBe(42); + result.StatusCode.ShouldBe(StatusCodeMap.BadUserAccessDenied); + } + + /// …and the same refusal on the supervisory ADVISE is an access refusal too (the handle is still forgotten). + [Fact] + public async Task WriteOne_GatewayRefusesTheCaller_OnTheAdvise_IsBadUserAccessDenied() + { + using var advise = new MeterRecorder("galaxy.writes.advise_failed"); + var ops = new FakeMxWriteOps + { + InvokeResponder = _ => throw new Grpc.Core.RpcException(new Grpc.Core.Status(Grpc.Core.StatusCode.PermissionDenied, "no")), + }; + var writer = NewWriter(); + + var result = await writer.WriteOneForTestAsync( + ops, new WriteRequest("Tag.A", 1), SecurityClassification.FreeAccess, CancellationToken.None); + + result.StatusCode.ShouldBe(StatusCodeMap.BadUserAccessDenied); + ops.RawWriteHandles.ShouldBeEmpty(); + writer.CachedSupervisedHandleCount.ShouldBe(0); + advise.Total.ShouldBe(0); } // ---------------- T6: fail-closed on advise failure ---------------- diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests/HeidenhainReviewFixTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests/HeidenhainReviewFixTests.cs index 550ea8649..4d90249a4 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests/HeidenhainReviewFixTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests/HeidenhainReviewFixTests.cs @@ -346,4 +346,72 @@ public sealed class HeidenhainReviewFixTests (_, _) => ValueTask.FromResult(""), publish, (_, o, n) => onState?.Invoke(o, n), (h, p, t) => new Lsv2Client(h, p, t), TimeProvider.System, NullLogger.Instance); } + + // ---- #990 review: a deliberate stop cancels BEFORE it closes the session. ---- + + /// + /// Closing the session first unblocked the in-flight read while the loop's token was still live, so a loop that + /// woke before the cancel landed ran its normal "session gone" tail — a Backoff transition, i.e. a stop shown as + /// an outage (host Stopped). The seam holds the dispose right after the close to let the loop win that race. + /// + [Fact] + public async Task Disposing_mid_read_cancels_first_so_the_woken_loop_never_reports_backoff() + { + var inRead = new ManualResetEventSlim(); + var release = new ManualResetEventSlim(); + var control = new SimulatedControl(); + control.Runtime[23] = () => { inRead.Set(); release.Wait(TimeSpan.FromSeconds(5)); return SimulatedControl.U16(4); }; + await using var sim = Lsv2Simulator.WithControl(control); + var states = new ConcurrentQueue(); + var runtime = NewRuntime(sim.Port, (_, _) => { }, onState: (_, n) => states.Enqueue(n)); + runtime.AfterSessionCloseForTests = async () => + { + release.Set(); + await Task.Delay(500, Ct); // the closed read fails now; give the loop every chance to run its tail + }; + runtime.Start(); + inRead.Wait(TimeSpan.FromSeconds(5), Ct).ShouldBeTrue(); + + await runtime.DisposeAsync(); + + states.ShouldNotContain(HeidenhainConnectionState.Backoff); + runtime.State.ShouldBe(HeidenhainConnectionState.Stopped); + } + + // ---- #990 review: host-facing state is per HOST and survives a re-init. ---- + + /// + /// The facing map was keyed by runtime INSTANCE: it grew by one entry per re-init (the comms-loss watchdog + /// re-inits a down control every ~90 s), and each new runtime started from Unknown — so the old runtime's + /// stop (→ Unknown) and the new one's first retry (→ Stopped) flapped the host status across every re-init, + /// the M-17 flap the per-retry fix had removed within one runtime. + /// + [Fact] + public async Task Reinitialize_of_a_down_control_keeps_its_host_status_and_does_not_grow_the_facing_map() + { + var options = new HeidenhainDriverOptions + { + TimeoutMs = 500, + Devices = [new HeidenhainDeviceOptions { Host = "127.0.0.1", Port = 1, DeviceName = "dev1" }], + RawTags = [TestTags.Raw("Status/ExecutionState")], + Reconnect = new HeidenhainReconnectOptions { InitialDelayMs = 100, MaxDelayMs = 200 }, + }; + await using var d = new HeidenhainDriver(options, "hh", null, new HeidenhainCredentials(null), null, null); + var events = new ConcurrentQueue(); + d.OnHostStatusChanged += (_, e) => events.Enqueue(e); + await d.InitializeAsync("{}", Ct); + await d.SubscribeAsync([options.RawTags[0].RawPath], TimeSpan.FromSeconds(1), Ct); + await WaitFor(() => d.GetHostStatuses().Single().State == HostState.Stopped); + + for (var i = 0; i < 3; i++) + { + await d.ReinitializeAsync("{}", Ct); + await d.SubscribeAsync([options.RawTags[0].RawPath], TimeSpan.FromSeconds(1), Ct); + await Task.Delay(400, Ct); // several retries of the new runtime + } + + events.ShouldNotContain(e => e.OldState == HostState.Stopped, "a down control never leaves Stopped across a re-init"); + events.Count(e => e.NewState == HostState.Stopped).ShouldBe(1); + d.FacingEntryCountForTests.ShouldBe(1); + } } diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Addressing.Tests/ModbusFamilyParserTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Addressing.Tests/ModbusFamilyParserTests.cs index 6798d7530..5a194dfc4 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Addressing.Tests/ModbusFamilyParserTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Addressing.Tests/ModbusFamilyParserTests.cs @@ -202,6 +202,37 @@ public sealed class ModbusFamilyParserTests generic.Offset.ShouldBe((ushort)17); } + /// + /// #981 review: the S-8 gate stopped the generic mnemonic table whenever the family grammar CLAIMED an address, + /// and the MELSEC grammar claims every D prefix (D-registers) — so DI100, the generic + /// discrete-input mnemonic, stopped parsing under MELSEC (it failed as a malformed D-register). MELSEC has no + /// DI device, so the grammar must not claim it. + /// + /// A generic discrete-input mnemonic. + /// Its zero-based offset. + [Theory] + [InlineData("DI100", 99)] + [InlineData("di1", 0)] + public void MELSEC_Generic_DiscreteInput_Mnemonic_Still_Parses(string addr, int expectedOffset) + { + ModbusAddressParser.TryParse(addr, ModbusFamily.MELSEC, MelsecFamily.Q_L_iQR, out var result, out var error) + .ShouldBeTrue(error); + result!.Region.ShouldBe(ModbusRegion.DiscreteInputs); + result.Offset.ShouldBe((ushort)expectedOffset); + } + + /// Controls for the narrow MELSEC fix: a D-register still resolves natively, and a malformed one still errors. + [Fact] + public void MELSEC_D_Register_Still_Native_And_Malformed_Still_Errors() + { + var d = ModbusAddressParser.Parse("D100", ModbusFamily.MELSEC); + d.Region.ShouldBe(ModbusRegion.HoldingRegisters); + d.Offset.ShouldBe((ushort)100); + + ModbusAddressParser.TryParse("DX12", ModbusFamily.MELSEC, MelsecFamily.Q_L_iQR, out _, out var error).ShouldBeFalse(); + error.ShouldNotBeNull(); + } + /// Verifies suffix grammar composes correctly with native addresses. [Fact] public void Suffix_Grammar_Composes_With_Native_Address() diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.IntegrationTests/MqttPrimaryHostLiveTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.IntegrationTests/MqttPrimaryHostLiveTests.cs index 141046998..b21f5ac04 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.IntegrationTests/MqttPrimaryHostLiveTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.IntegrationTests/MqttPrimaryHostLiveTests.cs @@ -235,6 +235,59 @@ public sealed class MqttPrimaryHostLiveTests(MqttFixture fixture) await ClearRetainedAsync(idB, ct); } + /// + /// #988 review round 2, live: a redundant pair — same driver config, blank clientId, same host id. + /// The Primary holds the claim; the Secondary cold-starts before its cluster join, believes it is alone + /// and claims too (same claim id ⇒ the broker takes the Primary's session over), then learns its role and + /// stands down, publishing its OFFLINE. The Primary must end up holding the claim with a retained ONLINE a + /// late subscriber still sees — with the random per-instance id the Secondary's newer OFFLINE was left + /// retained and nothing corrected it. + /// + [Fact] + public async Task A_cold_starting_secondary_that_briefly_claims_leaves_the_primary_online() + { + SkipIfUnconfigured(); + + var ct = TestContext.Current.CancellationToken; + var hostId = NewHostId(); + var pairOptions = Options(hostId) with { ClientId = null }; + var primaryRole = new MutableRole(true); + var secondaryRole = new MutableRole(true); // pre-join: sees no peer, claims + await using var primary = new SparkplugPrimaryHost(pairOptions, "live-pair", primaryRole); + await using var secondary = new SparkplugPrimaryHost(pairOptions, "live-pair", secondaryRole); + primary.ClaimClientIdForTests.ShouldBe(secondary.ClaimClientIdForTests); + + await primary.StartAsync(ct); + primary.IsClaimed.ShouldBeTrue(); + await secondary.StartAsync(ct); + + // Cluster join completes: the secondary stands down (explicit OFFLINE, newer than the primary's ONLINE). + await Task.Delay(TimeSpan.FromSeconds(2), ct); + secondaryRole.IsPrimary = false; + await WaitUntilAsync(() => !secondary.IsClaimed, ct); + + // Settle, then ask the broker what a late-joining edge node would see. + long lastOnline = 0; + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(30); + while (DateTime.UtcNow < deadline) + { + await Task.Delay(TimeSpan.FromSeconds(3), ct); + await using var late = await StateWatcher.StartAsync(fixture, hostId, ct); + var retained = await late.WaitForOneAsync(Timeout, ct); + if (SparkplugStatePayload.TryDecode(retained, out var online, out var ts) && online && primary.IsClaimed) + { + lastOnline = ts; + break; + } + } + + lastOnline.ShouldBeGreaterThan(0, "the Primary must re-assert a retained ONLINE after the Secondary's stand-down"); + + await secondary.StopAsync(ct); + await primary.StopAsync(ct); + await ClearRetainedAsync(hostId, ct); + } + // ---- helpers ----------------------------------------------------------------------------------- /// A per-test host id: the retained STATE outlives the test that wrote it. diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/MiniBroker.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/MiniBroker.cs index 0a232f642..c04e55820 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/MiniBroker.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/MiniBroker.cs @@ -36,6 +36,9 @@ internal sealed class MiniBroker : IDisposable private readonly CancellationTokenSource _cts = new(); private readonly HashSet _live = []; + + /// Per-socket write lock: writes beside the serve loop. + private readonly System.Runtime.CompilerServices.ConditionalWeakTable _writeLocks = new(); private readonly TcpListener _listener; private int _acceptedCount; @@ -106,6 +109,7 @@ internal sealed class MiniBroker : IDisposable var topic = System.Text.Encoding.UTF8.GetString(buffer, at + 2, Math.Min(length, Math.Max(0, end - at - 2))); at += 2 + length; if (at >= end) return null; + Subscribed.Enqueue(topic); grants.Add(RefuseSubscribe?.Invoke(topic) == true ? (byte)0x80 : (byte)(buffer[at] & 0x03)); at++; } @@ -124,13 +128,76 @@ internal sealed class MiniBroker : IDisposable /// Every PUBLISH received, in arrival order, as (topic, payload). public System.Collections.Concurrent.ConcurrentQueue<(string Topic, byte[] Payload)> Published { get; } = new(); + /// Every topic filter a SUBSCRIBE carried, in arrival order (all clients). + public System.Collections.Concurrent.ConcurrentQueue Subscribed { get; } = new(); + + /// + /// Delivers one QoS 0 PUBLISH to every live client — the fake never forwards client publishes, so + /// this is how a test plays "another client published on a topic you subscribed to". + /// + /// The topic. + /// The body. + /// The retain flag as delivered (true = a retained replay). + /// A task completing once written. + public async Task InjectPublishAsync(string topic, byte[] payload, bool retain = false) + { + var topicBytes = System.Text.Encoding.UTF8.GetBytes(topic); + var remaining = 2 + topicBytes.Length + payload.Length; + var packet = new List { (byte)(0x30 | (retain ? 0x01 : 0x00)) }; + do + { + var digit = (byte)(remaining % 128); + remaining /= 128; + packet.Add(remaining > 0 ? (byte)(digit | 0x80) : digit); + } + while (remaining > 0); + + packet.Add((byte)(topicBytes.Length >> 8)); + packet.Add((byte)(topicBytes.Length & 0xFF)); + packet.AddRange(topicBytes); + packet.AddRange(payload); + var bytes = packet.ToArray(); + + TcpClient[] targets; + lock (_live) + { + targets = [.. _live]; + } + + foreach (var client in targets) + { + try + { + await WriteAsync(client.GetStream(), bytes); + } + catch (Exception) + { + // Torn down concurrently. + } + } + } + + private async Task WriteAsync(NetworkStream stream, byte[] bytes) + { + var gate = _writeLocks.GetValue(stream, _ => new SemaphoreSlim(1, 1)); + await gate.WaitAsync(_cts.Token); + try + { + await stream.WriteAsync(bytes, _cts.Token); + } + finally + { + gate.Release(); + } + } + /// Handles one complete packet; returns false when the connection must close. private async Task HandlePacketAsync(NetworkStream stream, byte[] packet) { var packetType = packet[0] & 0xF0; if (packetType == 0x10) { - await stream.WriteAsync(new byte[] { 0x20, 0x02, 0x00, ConnAckReturnCode }, _cts.Token); + await WriteAsync(stream, new byte[] { 0x20, 0x02, 0x00, ConnAckReturnCode }); // A real broker closes the socket straight after refusing, which is what drives // MQTTnet's DisconnectedAsync. Mirroring it keeps the fake honest. @@ -139,11 +206,11 @@ internal sealed class MiniBroker : IDisposable if (packetType == 0xC0) { - await stream.WriteAsync(PingResp, _cts.Token); + await WriteAsync(stream, PingResp); } else if (packetType == 0x80 && AnswerSubscribe && TryBuildSubAck(packet, packet.Length) is { } subAck) { - await stream.WriteAsync(subAck, _cts.Token); + await WriteAsync(stream, subAck); } else if (packetType == 0x30) { @@ -163,7 +230,7 @@ internal sealed class MiniBroker : IDisposable Published.Enqueue((topic, packet[at..])); if (qos == 1 && AckPublish) { - await stream.WriteAsync(new byte[] { 0x40, 0x02, idHigh, idLow }, _cts.Token); + await WriteAsync(stream, new byte[] { 0x40, 0x02, idHigh, idLow }); } } diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/SparkplugPrimaryHostTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/SparkplugPrimaryHostTests.cs index fe80256f8..647b47510 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/SparkplugPrimaryHostTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/SparkplugPrimaryHostTests.cs @@ -153,17 +153,19 @@ public sealed class SparkplugPrimaryHostTests /// #988 review M-3: with the recommended blank clientId the claim id was the literal /// -spbhost, the one fixed, fleet-wide id — two drivers claiming on one broker (two Sparkplug /// groups need two drivers) evicted each other about once a second, flapping both STATE topics. Each - /// claim now presents its own id. + /// distinct (host id, group) claim now presents its own id. /// [Fact] - public void Claims_with_a_blank_client_id_present_distinct_ids() + public void Claims_for_different_groups_or_hosts_present_distinct_ids() { var blank = Options() with { ClientId = null }; var a = new SparkplugPrimaryHost(blank, "drv-1", new FixedRole(true)); - var b = new SparkplugPrimaryHost(blank with { Sparkplug = blank.Sparkplug! with { GroupId = "Other" } }, "drv-2", new FixedRole(true)); - var whitespace = new SparkplugPrimaryHost(Options() with { ClientId = " " }, "drv-3", new FixedRole(true)); + var otherGroup = new SparkplugPrimaryHost(blank with { Sparkplug = blank.Sparkplug! with { GroupId = "Other" } }, "drv-2", new FixedRole(true)); + var otherHost = new SparkplugPrimaryHost(blank with { Sparkplug = blank.Sparkplug! with { HostId = "other-host" } }, "drv-3", new FixedRole(true)); + var whitespace = new SparkplugPrimaryHost(Options() with { ClientId = " " }, "drv-4", new FixedRole(true)); - a.ClaimClientIdForTests.ShouldNotBe(b.ClaimClientIdForTests); + a.ClaimClientIdForTests.ShouldNotBe(otherGroup.ClaimClientIdForTests); + a.ClaimClientIdForTests.ShouldNotBe(otherHost.ClaimClientIdForTests); a.ClaimClientIdForTests.ShouldNotBe(SparkplugPrimaryHost.ClientIdSuffix); a.ClaimClientIdForTests.ShouldStartWith("spbhost-"); a.ClaimClientIdForTests.Length.ShouldBeLessThanOrEqualTo(23, "MQTT 3.1.1 servers need only accept 23-character ids"); @@ -174,6 +176,29 @@ public sealed class SparkplugPrimaryHostTests .ClientId.ShouldBe(a.ClaimClientIdForTests); } + /// + /// #988 review (round 2): the M-3 fix made the blank-clientId claim id RANDOM per instance, which + /// broke the single-claim exclusivity a redundant pair relied on. A Secondary cold-starting before its + /// cluster join claims too; with one shared id its CONNECT evicts the Primary's claim (whose supervisor + /// reconnects and re-asserts), with two random ids both hold the topic, and the Secondary's later + /// stand-down OFFLINE lands newer than the Primary's ONLINE with nothing to correct it. Both nodes of a + /// pair run the same driver config, so the id must be a pure function of it. + /// + [Fact] + public void Both_nodes_of_a_pair_present_the_same_claim_id() + { + var blank = Options() with { ClientId = null }; + var nodeA = new SparkplugPrimaryHost(blank, "drv-1", new FixedRole(true)); + var nodeB = new SparkplugPrimaryHost(blank, "drv-1", new FixedRole(false)); + + nodeA.ClaimClientIdForTests.ShouldBe(nodeB.ClaimClientIdForTests); + + // The host id is trimmed everywhere else; the claim id must not depend on padding either. + var padded = new SparkplugPrimaryHost( + blank with { Sparkplug = blank.Sparkplug! with { HostId = " otopcua-primary " } }, "drv-1", new FixedRole(true)); + padded.ClaimClientIdForTests.ShouldBe(nodeA.ClaimClientIdForTests); + } + /// Control: an operator-configured client id keeps its stable, ACL-friendly {clientId}-spbhost. [Fact] public void A_configured_client_id_keeps_the_stable_claim_id() @@ -222,6 +247,122 @@ public sealed class SparkplugPrimaryHostTests await host.DisposeAsync(); } + /// + /// #988 review (round 2), part 2: the claim subscribes to its own STATE topic and re-asserts when it sees an + /// OFFLINE it did not publish. A NEWER OFFLINE (another claimant's stand-down / Will) is answered with a + /// FRESH session — a new, newer timestamp — because Sparkplug 3.0 edge nodes ignore a STATE older than the + /// one they hold, so republishing the old ONLINE would be discarded. + /// + [Trait("Category", "SlowUnit")] + [Fact] + public async Task A_newer_foreign_offline_is_answered_with_a_fresh_newer_online() + { + using var broker = new MiniBroker { AckPublish = true }; + var host = new SparkplugPrimaryHost(LocalBroker(broker), "drv-1", new FixedRole(shouldActAsPrimary: true)); + await host.StartAsync(TestContext.Current.CancellationToken); + host.IsClaimed.ShouldBeTrue(); + (await WaitUntilAsync(() => broker.Subscribed.Contains(StateTopic), TimeSpan.FromSeconds(10))) + .ShouldBeTrue("the claim must subscribe to its own STATE topic"); + var firstTs = OnlineTimestamps(broker).Single(); + + await broker.InjectPublishAsync(StateTopic, SparkplugStatePayload.Encode(online: false, firstTs + 60_000)); + + (await WaitUntilAsync(() => OnlineTimestamps(broker).Count >= 2, TimeSpan.FromSeconds(15))) + .ShouldBeTrue("a foreign OFFLINE must be answered with a new ONLINE"); + OnlineTimestamps(broker).Last().ShouldBeGreaterThan(firstTs + 60_000, "the re-asserted ONLINE must out-date the OFFLINE"); + (await WaitUntilAsync(() => host.IsClaimed, TimeSpan.FromSeconds(10))).ShouldBeTrue(); + + await host.DisposeAsync(); + } + + /// An OFFLINE carrying this session's own timestamp (its Will, replayed) is answered by republishing the same ONLINE. + [Trait("Category", "SlowUnit")] + [Fact] + public async Task An_offline_for_this_session_republishes_the_same_online() + { + using var broker = new MiniBroker { AckPublish = true }; + var host = new SparkplugPrimaryHost(LocalBroker(broker), "drv-1", new FixedRole(shouldActAsPrimary: true)); + await host.StartAsync(TestContext.Current.CancellationToken); + (await WaitUntilAsync(() => broker.Subscribed.Contains(StateTopic), TimeSpan.FromSeconds(10))).ShouldBeTrue(); + var ts = OnlineTimestamps(broker).Single(); + + await broker.InjectPublishAsync(StateTopic, SparkplugStatePayload.Encode(online: false, ts), retain: true); + + (await WaitUntilAsync(() => OnlineTimestamps(broker).Count >= 2, TimeSpan.FromSeconds(15))).ShouldBeTrue(); + OnlineTimestamps(broker).ShouldAllBe(t => t == ts); + + await host.DisposeAsync(); + } + + /// + /// Control: the claim's OWN stand-down OFFLINE (echoed back by the broker — 3.1.1 has no No-Local) must not + /// be "re-asserted" over, or a released host would immediately claim itself back. + /// + [Trait("Category", "SlowUnit")] + [Fact] + public async Task The_claims_own_stand_down_offline_is_not_reasserted() + { + using var broker = new MiniBroker { AckPublish = true }; + var role = new FixedRole(shouldActAsPrimary: true); + var host = new SparkplugPrimaryHost(LocalBroker(broker), "drv-1", role); + await host.StartAsync(TestContext.Current.CancellationToken); + (await WaitUntilAsync(() => broker.Subscribed.Contains(StateTopic), TimeSpan.FromSeconds(10))).ShouldBeTrue(); + var ts = OnlineTimestamps(broker).Single(); + + role.PublishPrimaryRole(false); + (await WaitUntilAsync(() => !host.IsClaimed, TimeSpan.FromSeconds(10))).ShouldBeTrue(); + + // The echo of the stand-down arrives after release; nothing may react to it. + await broker.InjectPublishAsync(StateTopic, SparkplugStatePayload.Encode(online: false, ts)); + await Task.Delay(TimeSpan.FromSeconds(3), TestContext.Current.CancellationToken); + OnlineTimestamps(broker).Count.ShouldBe(1); + + await host.DisposeAsync(); + } + + /// A burst of foreign OFFLINEs coalesces rather than producing one re-claim per message. + [Trait("Category", "SlowUnit")] + [Fact] + public async Task A_burst_of_foreign_offlines_coalesces() + { + using var broker = new MiniBroker { AckPublish = true }; + var host = new SparkplugPrimaryHost(LocalBroker(broker), "drv-1", new FixedRole(shouldActAsPrimary: true)); + await host.StartAsync(TestContext.Current.CancellationToken); + (await WaitUntilAsync(() => broker.Subscribed.Contains(StateTopic), TimeSpan.FromSeconds(10))).ShouldBeTrue(); + var ts = OnlineTimestamps(broker).Single(); + + for (var i = 1; i <= 20; i++) + { + await broker.InjectPublishAsync(StateTopic, SparkplugStatePayload.Encode(online: false, ts + i)); + } + + (await WaitUntilAsync(() => OnlineTimestamps(broker).Count >= 2, TimeSpan.FromSeconds(15))).ShouldBeTrue(); + await Task.Delay(TimeSpan.FromSeconds(1), TestContext.Current.CancellationToken); + OnlineTimestamps(broker).Count.ShouldBeLessThanOrEqualTo(3, "20 OFFLINEs in a burst must not cost 20 re-claims"); + + await host.DisposeAsync(); + } + + private const string StateTopic = "spBv1.0/STATE/otopcua-primary"; + + private static MqttDriverOptions LocalBroker(MiniBroker broker) => Options() with + { + ClientId = null, + Host = "127.0.0.1", + Port = broker.Port, + UseTls = false, + ProtocolVersion = MqttProtocolVersion.V311, + ConnectTimeoutSeconds = 2, + ReconnectMinBackoffSeconds = 1, + ReconnectMaxBackoffSeconds = 1, + }; + + private static List OnlineTimestamps(MiniBroker broker) => + [.. broker.Published + .Where(p => p.Topic == StateTopic) + .Select(p => SparkplugStatePayload.TryDecode(p.Payload, out var online, out var ts) && online ? ts : -1) + .Where(ts => ts >= 0)]; + private static int OnlinePublishes(MiniBroker broker) => broker.Published.Count(p => p.Topic == "spBv1.0/STATE/otopcua-primary"