diff --git a/docs/requirements/Component-Commons.md b/docs/requirements/Component-Commons.md index 7a86d89d..0ddb6eb3 100644 --- a/docs/requirements/Component-Commons.md +++ b/docs/requirements/Component-Commons.md @@ -26,7 +26,7 @@ Referenced by all component libraries and the Host. Commons must define shared primitive and utility types used across multiple components, including but not limited to: -- **`DataType` enum**: Enumerates the data types supported by the system: Boolean, Int32, Float, Double, String, DateTime, Binary, and **List** (a homogeneous multi-value attribute). A `List` attribute carries a companion `ElementDataType` (one of the scalar types — String, Int32, Float, Double, Boolean, DateTime; not Binary, not nested List) on `TemplateAttribute` / `InstanceAttributeOverride` and the flattened `ResolvedAttribute`. List values are stored and transmitted as a canonical **native-typed** JSON array via the `AttributeValueCodec` helper — numbers and booleans unquoted, strings quoted, `DateTime` as ISO-8601 (e.g. `[10,20]`, `[true,false]`, `["2026-06-16T00:00:00Z"]`); scalars keep their historical invariant-culture string form. `AttributeValueCodec.Decode` is backward compatible: it reads both the native form and the earlier array-of-strings form (`["10","20"]`). Already-persisted old-form values are normalized to native on the fly — an idempotent central startup normalizer (`ListValueNormalizer`, run after migrations) rewrites MS SQL rows, the `InstanceActor` re-persists site SQLite overrides on load, and bundle import re-encodes List values. The `ElementDataType` is fixed by the defining level and cannot be changed on a derived template or instance override. +- **`DataType` enum**: Enumerates the data types supported by the system: Boolean, Int32, Float, Double, String, DateTime, Binary, and **List** (a homogeneous multi-value attribute). A `List` attribute carries a companion `ElementDataType` (one of the scalar types — String, Int32, Float, Double, Boolean, DateTime; not Binary, not nested List) on `TemplateAttribute` / `InstanceAttributeOverride` and the flattened `ResolvedAttribute`. List values are stored and transmitted as a canonical **native-typed** JSON array via the `AttributeValueCodec` helper — numbers and booleans unquoted, strings quoted, `DateTime` as ISO-8601 (e.g. `[10,20]`, `[true,false]`, `["2026-06-16T00:00:00Z"]`); scalars keep their historical invariant-culture string form, except `DateTime`/`DateTimeOffset`, which encode as ISO-8601 round-trip (`"O"`; a `DateTime` is normalised to UTC, an Unspecified kind is taken as UTC) so the scalar keeps its zone and sub-second precision — the older invariant general form (`06/15/2026 13:45:30`) still parses everywhere a value is read. Non-finite `Float`/`Double` list elements encode as the JSON strings `"NaN"`/`"Infinity"`/`"-Infinity"` and decode back. `AttributeValueCodec.Decode` is backward compatible: it reads both the native form and the earlier array-of-strings form (`["10","20"]`). Already-persisted old-form values are normalized to native on the fly — an idempotent central startup normalizer (`ListValueNormalizer`, run after migrations) rewrites MS SQL rows, the `InstanceActor` re-persists site SQLite overrides on load, and bundle import re-encodes List values. The `ElementDataType` is fixed by the defining level and cannot be changed on a derived template or instance override. - **`RetryPolicy`**: A record or immutable class describing retry behavior (max retries, fixed delay between retries). - **`Result`**: A discriminated result type that represents either a success value or an error, enabling consistent error handling across component boundaries without exceptions. - **`InstanceState` enum**: Enabled, Disabled. diff --git a/docs/requirements/Component-DataConnectionLayer.md b/docs/requirements/Component-DataConnectionLayer.md index ccf6e6a5..d5ebdd47 100644 --- a/docs/requirements/Component-DataConnectionLayer.md +++ b/docs/requirements/Component-DataConnectionLayer.md @@ -300,7 +300,7 @@ Three subscribe paths, deliberately paced differently: | **Reconnect re-subscribe** (`ReSubscribeAll`) | **Sequential** chunks of `SubscribeBatchSize` with `SubscribeBatchDelay` between them, all inside ONE background task; each chunk reports its per-tag results back to the actor as its own message. Replaces a tight loop that fired one fire-and-forget task per tag. | | **Tag-resolution probe** | The whole not-in-flight unresolved set, chunked at `SubscribeBatchSize`, as one probe round per timer tick. | -Seeding (the initial-value read that keeps a STATIC tag from staying Uncertain) issues chunked bulk reads — `SeedReadBatchSize` per chunk, `SeedReadMaxParallelism` chunks in flight, `SeedReadTimeout` per chunk — under a single `SeedOverallTimeout` deadline covering every chunk and retry round. The reconnect re-seed is additionally bound to its session: entering Reconnecting, an adapter swap or actor stop cancels it, so a flapping link no longer stacks one full-tag-set seed read per flap (review 2026-10-21). +Seeding (the initial-value read that keeps a STATIC tag from staying Uncertain) issues chunked bulk reads — `SeedReadBatchSize` per chunk, `SeedReadMaxParallelism` chunks in flight, `SeedReadTimeout` per chunk — under a single `SeedOverallTimeout` deadline covering every chunk and retry round. The reconnect re-seed **and the reconnect re-subscribe loop** are additionally bound to their session (one shared token, created before either starts): entering Reconnecting, an adapter swap or actor stop cancels them, so a flapping link no longer stacks one full-tag-set seed read per flap (review 2026-10-21), and a re-subscribe loop whose chunk wedged across a reconnect stops at that chunk instead of issuing its remaining chunks against the same adapter's new client (2026-12-02 review DCL-4 — previously duplicate OPC UA monitored items / MxGateway subscribes whose stale-generation results were dropped unreleased). The adapters dereference their session client once per batch call. **The MxGateway per-handle supervisory advise is shared by concurrent callers and runs under the client's lifetime (bounded at 60 s), not the token of the caller that created it** (DCL-9) — each caller applies its own deadline to its wait only, so a write timing out no longer cancels the advise a concurrent subscribe awaits; a faulted/timed-out shared advise is evicted and retried by the next caller. **Value timestamps (DCL-7):** OPC UA reads and subscription notifications stamp a value with its source timestamp, falling back to the server timestamp and then to now — a connection configured for `TimestampsToReturn = Server` (or a server that omits source timestamps) used to stamp every seeded/read value `0001-01-01T00:00:00Z`. **Browse/search while disconnected (DCL-6)** always reply with a typed `ConnectionNotConnected` failure: the actor turns an adapter that throws before returning a task into a faulted task, and the OPC UA adapter's browse/search are `async` so a missing client faults the task. **A connection-level failure row in a reconnect re-subscribe or probe batch (DCL-8)** now puts the tag into the resolution retry set (previously it was only logged, and with `_subscriptionIds`/`_unresolvedTags` already cleared by `ReSubscribeAll` the tag sat in no retry set until an unrelated reconnect when the session stayed up). **A seed never overwrites a newer live value (2026-12-02 review DCL-1).** The subscription is live before the seed read starts, and a seed is held until its whole seed operation finishes, so a live change inside that window used to be regressed to the older seed value (Good quality, indefinitely for a rarely-changing tag). Seed values now travel as `TagValueReceived` marked with their origin, and the actor keeps the latest live value per tag for the current adapter generation (cleared when the generation advances on reconnect/swap, dropped when the tag loses its last subscriber). A reconnect or tag-resolution re-seed for a tag that has already delivered a live value in that generation is **dropped**; an initial-subscribe seed for such a tag is **replaced by the latest live value** (the joining instance may have registered after the tag's earlier live values were fanned out, and a static tag would otherwise never give it a value). The rule is generation-based, not a timestamp comparison, which would depend on device/server clocks and the configured timestamp mode. **On re-entering Connected after a reconnect the actor tells every subscriber `ConnectionQualityChanged(Good)`** (SRT-6) — a restore signal the Instance Actor uses only to reset its tag-subscribe backoff; per-tag quality is restored by the re-subscribe and re-seed. **OPC UA subscription sharding.** `RealOpcUaClient` places monitored items on the first subscription shard with free capacity (`MaxMonitoredItemsPerSubscription`), creating a shard when all are full and deleting one once it empties. A batch is N × `AddItem` plus **one** `ApplyChanges` per touched shard. Alarms & Conditions event items are pinned to a **dedicated event shard**, so `ConditionRefresh` has a single subscription id to target and `QueueSize:1000` event items never consume data-shard capacity. Every structural mutation (AddItem / RemoveItem / ApplyChanges / Create / Delete) and every shard-list mutation serializes behind ONE per-client gate — the SDK `Subscription` is not safe under concurrent structural mutation, and the subscribe task, resolution probe and alarm subscribe are otherwise unordered. @@ -378,7 +378,7 @@ Other/custom protocols do not implement the capability; a subscribe request agai ### Connection Actor Behavior -The `DataConnectionActor` opens **one alarm feed per source** (not per subscriber) and routes incoming transitions to instance subscribers by **source-object reference** — a prefix match of the transition's `SourceObjectReference` (falling back to `SourceReference`) against each subscriber's registered `SourceReference`. Subscribers (the Site Runtime's `NativeAlarmActor` instances) are **ref-counted per source**, so the underlying feed is opened once and torn down only when the last subscriber for that source unsubscribes. +The `DataConnectionActor` opens **one alarm feed per source** (not per subscriber) and routes incoming transitions to instance subscribers by **source-object reference** — a **separator-aware** prefix match of the transition's `SourceObjectReference` (falling back to `SourceReference`) against each subscriber's registered `SourceReference`: the reference must be the source itself or continue at a `.` or `/` separator (an empty source — the OPC UA Server-object feed — still covers everything). A raw string prefix used to let `Tank1` / `ns=2;s=Tank1` also receive, cache and mirror every alarm of `Tank10` / `ns=2;s=Tank10` (2026-12-02 review DCL-5). Subscribers (the Site Runtime's `NativeAlarmActor` instances) are **ref-counted per source**, so the underlying feed is opened once and torn down only when the last subscriber for that source unsubscribes. The registered `SourceReference` is a **NodeId** for OPC UA (the picker, CSV and config all store NodeIds), so the transition's routing identity must live in the same space or nothing matches. **Gitea #17**: the OPC UA adapter previously set `SourceObjectReference` from the event's `SourceName` (a plain name — the RawPath for OtOpcUa), which never prefix-matches a NodeId binding, so every native OPC UA alarm transition was silently dropped. Because each OPC UA feed is opened for exactly one binding, the adapter now tags every transition on that feed with the **binding string verbatim** (via the pure `OpcUaAlarmMapper.BuildIdentity`), making the routing key an exact match independent of whether the binding is stored as `ns=` or the durable `nsu=` form. The Server-object aggregate feed (empty binding) keeps an empty routing identity, so it reaches only "mirror everything" subscribers and never leaks into a specific-node binding. The per-condition `SourceReference` key stays the human-readable `SourceName.ConditionName`, so persistence and display are unchanged — with one exception, below. MxGateway is unaffected — its bindings are object names and its mapper already emits matching names. @@ -391,11 +391,11 @@ The registered `SourceReference` is a **NodeId** for OPC UA (the picker, CSV and - **State gating**: `SubscribeAlarmsRequest` is handled only in the **Connected** state; requests arriving while **Connecting**/**Reconnecting** are coalesced to the latest request per subscriber actor/source and processed on entering Connected. Unsubscribes and subscriber termination are handled in every state. - **Capability check**: if `_adapter is not IAlarmSubscribableConnection`, the actor replies `SubscribeAlarmsResponse(Success = false, ...)`. -- **Reconnect handling**: on entering **Reconnecting**, the actor pushes a `NativeAlarmSourceUnavailable` to every alarm subscriber (consumers mark mirrored alarms uncertain rather than clearing them). On successful reconnection it re-subscribes the feed; the adapter re-emits a snapshot, reconciling state. +- **Reconnect handling**: on entering **Reconnecting**, the actor pushes a `NativeAlarmSourceUnavailable` to every alarm subscriber (consumers mark mirrored alarms uncertain rather than clearing them). On successful reconnection it re-subscribes the feed; the adapter re-emits a snapshot, reconciling state. **A re-subscribe that fails is retried by the DCL itself (2026-12-02 review DCL-2):** the reconnect re-subscribe has no requester (the `NativeAlarmActor` already counts its feed as established and does not re-subscribe on `NativeAlarmSourceUnavailable`), so a failed one — e.g. an `nsu=` namespace the restarted server has not loaded yet — is re-issued on a per-source backed-off timer (`TagResolutionRetryInterval` doubling to `TagResolutionRetryMaxInterval`) while the source still has subscribers; a later reconnect or the last unsubscribe cancels it. **The OPC UA alarm subscribe checks the event monitored item's create status (DCL-3)**, as the data path does: `ApplyChanges` does not throw for a per-item rejection (unknown node, not an event notifier, rejected filter), so the item is removed from the event shard, its per-handle bookkeeping dropped, and the subscribe fails instead of reporting a live feed that never delivers. - **Server-initiated refresh**: a RefreshStart/RefreshEnd pair the server sends on its own on an existing feed (OtOpcUa's promotion refresh under Warm redundancy, #138) takes the same snapshot path — forwarded in order under its own epoch, and it replaces the cached state for the source. - **RefreshRequired (Gitea #148)**: an OPC UA server sends `RefreshRequiredEventType` (`SourceNode = Server`, no condition fields) when the client's view can no longer be trusted — OtOpcUa sends it on an incomplete condition snapshot, a removed imported condition, and a resync that left pre-failover EventIds un-ackable (`BadEventIdUnknown`). Part 9 says the client must call ConditionRefresh. `RealOpcUaClient.HandleAlarmEvent` therefore never maps it as an alarm (it used to fall through as a phantom condition keyed `Server`); it hands the item's handle to `ConditionRefreshCoalescer`, which runs off the SDK publish thread, debounces 500 ms so a burst (the server sends one event per item that may see the condition) costs one refresh, and never overlaps refreshes (a request during an in-flight refresh is served by the next one). The refresh is a targeted `ConditionRefresh2(eventSubscription, item)` per asking item, or one subscription-wide `ConditionRefresh` when every live alarm item asked, an item has no server id yet, or `ConditionRefresh2` fails. Failures are logged, never thrown, and leave the mirror on its last-known state until the next RefreshRequired or reconnect; a disconnect drops pending requests. The replay is the ordinary RefreshStart → conditions → RefreshEnd frame, so the Native Alarm Actor's snapshot swap clears every condition the refreshed snapshot no longer lists (a removed condition gets its return-to-normal). Because the server queues RefreshRequired through the item's WhereClause, the server-side `OfType` clause built from a condition filter always ORs in `OfType(RefreshRequiredEventType)`. Covered by `RealOpcUaRefreshRequiredTests` and `RealOpcUaClientAlarmFilterTests`. - **Shared condition filter (last-subscriber-wins)**: because the feed is opened once per source, it carries a single condition filter. A second subscriber that registers a *different* filter for the same source overwrites it (last writer wins) and the actor logs a warning — co-subscribers to one source are expected to agree on the filter. -- **Routing index**: subscribed sources are bucketed by the **first path segment** of their reference (everything before the first `.`), and a transition is matched only against the bucket for its own first segment, plus a residue list of sources that carry no separator at all (a prefix shorter than one segment, which can match other buckets). This is sound because a source reference containing a separator can only prefix a reference sharing its entire first segment. The per-source `StartsWith` test and the condition-type gate inside the bucket are unchanged, so routing decisions are identical to the previous linear scan over every subscribed source; snapshot boundaries bypass the condition filter, but OPC UA boundaries are sent only to the exact source binding. Connection-wide Mx boundaries broadcast to all subscribers while preserving their refresh epoch. +- **Routing index**: subscribed sources are bucketed by the **first path segment** of their reference (everything before the first `.`), and a transition is matched only against the bucket for its own first segment, plus a residue list of sources that carry no separator at all (a prefix shorter than one segment, which can match other buckets). This is sound because a source reference containing a separator can only prefix a reference sharing its entire first segment. The per-source separator-aware containment test and the condition-type gate inside the bucket are applied as in a linear scan, so routing decisions are identical to a linear scan over every subscribed source; snapshot boundaries bypass the condition filter, but OPC UA boundaries are sent only to the exact source binding. Connection-wide Mx boundaries broadcast to all subscribers while preserving their refresh epoch. - **Gateway union filter (MxGateway)**: `StreamAlarms` carries a single `alarm_filter_prefix`, so the adapter opens the stream on the **longest common prefix** of the currently subscribed source references and restarts it for each new source, including one covered by the existing prefix, so every newly bound source receives standing state. Restarts are **coalesced** (review 2026-10-21): subscribes arriving within `MxAlarmStreamReopenDebounce` (200 ms) of the first share ONE restart on the union prefix, so a staggered deploy batch of N alarm-bound instances costs one close/reopen and one connection-wide snapshot replay instead of N (each of which was broadcast to every already-subscribed source — O(N·M) boundary messages). A reconnect, teardown or last unsubscribe invalidates a pending restart. Each transport refresh has connection-wide start/end markers and a distinct epoch. An unsubscribe never restarts the stream — the prefix it leaves behind is at worst too broad, which may increase bandwidth. Correctness also depends on the epoch-scoped snapshot cache merging concurrent live updates and rejecting stale snapshot ends (DC-5); a broad filter alone provides no such guarantee. The prefix is a bandwidth optimisation only; the actor's per-source + condition-type gate remains authoritative, mirroring the OPC UA server-side WhereClause stance. ### Protocol-Neutral Types & Messages diff --git a/docs/requirements/Component-NotificationService.md b/docs/requirements/Component-NotificationService.md index b6f07a9c..cc9a2059 100644 --- a/docs/requirements/Component-NotificationService.md +++ b/docs/requirements/Component-NotificationService.md @@ -109,7 +109,7 @@ NotificationStatus status = Notify.Status(id); - Available to instance scripts (via Script Execution Actors), alarm on-trigger scripts (via Alarm Execution Actors), and shared scripts (executing inline). - `Notify.To("listName").Send(...)` is **asynchronous**: it generates a `NotificationId` (GUID) locally, hands the notification to the site Store-and-Forward Engine for forwarding to central, and returns the `NotificationId` to the script **immediately**. The script does not block waiting for delivery. - The message body is **plain text** only. No HTML content. -- `Notify.Status(notificationId)` returns a small **status record** — the current status, retry count, last error, and key timestamps (enqueued, delivered). While the notification is still in the site Store-and-Forward buffer, the site answers the query **locally** with status `Forwarding`; once forwarded to central, the query round-trips to central and reads the `Notifications` table. +- `Notify.Status(notificationId)` returns a small **status record** — the current status, retry count, last error, and key timestamps (enqueued, delivered). While the notification is still in the site Store-and-Forward buffer, the site answers the query **locally** with status `Forwarding` — the buffer is checked **first**, without contacting central (2026-12-02 review SRT-8; it used to ask central first with the script's whole execution timeout, exactly when central was unreachable); once forwarded to central, the query round-trips to central and reads the `Notifications` table. That central query is bounded by 10 s (or the script's ask timeout if shorter) and by the run's deadline. - The returned `NotificationId` is a `TrackedOperationId` — the shared Commons tracking-handle type used by all store-and-forward producers; `NotificationId` is simply the notification-domain name for it. Likewise, `Notify.Status` is a thin alias of the unified `Tracking.Status` accessor, retained for backward compatibility. This is a naming/type clarification only — notification delivery behavior is unchanged. ## Notification Delivery Behavior diff --git a/docs/requirements/Component-SiteRuntime.md b/docs/requirements/Component-SiteRuntime.md index 9689308a..d2b12e96 100644 --- a/docs/requirements/Component-SiteRuntime.md +++ b/docs/requirements/Component-SiteRuntime.md @@ -219,7 +219,7 @@ flowchart TD 2. Set quality to **uncertain** for all attributes that have a data source reference. Static attributes (no data source reference) have quality **good**. The uncertain quality persists until the first value update arrives from the Data Connection Layer, distinguishing "not yet received" from "known good" or "connection lost." 3. Register data source references with the Data Connection Layer for subscriptions. - > **Tag-subscribe retry (S4/UA6, hardened by Lever 1 of the MxGateway subscribe-storm design, 2026-08-28).** The Instance Actor groups its data-sourced tag paths by connection and sends one `SubscribeTagsRequest` per connection, arming a per-connection watchdog *on send* so both a failed reply and a lost reply are retried. **At most one request per connection is outstanding:** a watchdog tick while the in-flight request is younger than `TagSubscribeInFlightCeilingMs` (45 s, sized above the gateway's 30 s command deadline) only re-arms — it never issues a duplicate — so a gateway that is slow to answer is not handed a fresh N-tag subscribe every interval on top of the one it is still processing (the amplifier behind the 2026-08-26 QA freeze). Past the ceiling the reply is presumed lost and a new request goes out; a late reply for the superseded id is ignored. The retry interval is exponential: floor `TagSubscribeRetryIntervalMs` (5 s), ×2 with ±20 % jitter per failed/lost attempt, capped at `TagSubscribeRetryMaxIntervalMs` (60 s); a `Success` reply or the connection returning to `Good` quality resets it to the floor — but the `Good` reset does **not** release an outstanding request (it still owns the connection until the ceiling), so it shortens the wait only when nothing is in flight; and once the backed-off interval exceeds the ceiling the guard is inert on ticks and the interval itself is the rate limit (one re-send per 60 s at the defaults). All three keys are startup-validated (`SiteRuntimeOptionsValidator`). Design: `docs/plans/2026-08-28-mxgateway-subscribe-storm-prevention-design.md` §3; plan: `docs/plans/2026-08-28-tag-subscribe-inflight-guard-backoff.md`. + > **Tag-subscribe retry (S4/UA6, hardened by Lever 1 of the MxGateway subscribe-storm design, 2026-08-28).** The Instance Actor groups its data-sourced tag paths by connection and sends one `SubscribeTagsRequest` per connection, arming a per-connection watchdog *on send* so both a failed reply and a lost reply are retried. **At most one request per connection is outstanding:** a watchdog tick while the in-flight request is younger than `TagSubscribeInFlightCeilingMs` (45 s, sized above the gateway's 30 s command deadline) only re-arms — it never issues a duplicate — so a gateway that is slow to answer is not handed a fresh N-tag subscribe every interval on top of the one it is still processing (the amplifier behind the 2026-08-26 QA freeze). Past the ceiling the reply is presumed lost and a new request goes out; a late reply for the superseded id is ignored. The retry interval is exponential: floor `TagSubscribeRetryIntervalMs` (5 s), ×2 with ±20 % jitter per failed/lost attempt, capped at `TagSubscribeRetryMaxIntervalMs` (60 s); a `Success` reply or the connection returning to `Good` quality (the DCL connection actor sends `ConnectionQualityChanged(Good)` to its subscribers when it re-enters Connected after a reconnect — 2026-12-02 review SRT-6; before that the reset was dead code) resets it to the floor. `Good` is a **restore signal only**: unlike `Bad`, it does **not** stamp the bound attributes `Good` with their pre-outage last-known values — their quality comes back through the DCL's re-subscribe and re-seed as ordinary `TagValueUpdate`s — but the `Good` reset does **not** release an outstanding request (it still owns the connection until the ceiling), so it shortens the wait only when nothing is in flight; and once the backed-off interval exceeds the ceiling the guard is inert on ticks and the interval itself is the rate limit (one re-send per 60 s at the defaults). All three keys are startup-validated (`SiteRuntimeOptionsValidator`). Design: `docs/plans/2026-08-28-mxgateway-subscribe-storm-prevention-design.md` §3; plan: `docs/plans/2026-08-28-tag-subscribe-inflight-guard-backoff.md`. 4. Create child Script Actors (one per script defined on the instance). 5. Create child Alarm Actors (one per alarm defined on the instance). @@ -241,7 +241,7 @@ flowchart TD > **Routed multi-attribute reads and writes are one message each (review 2026-10-21 01/SR-P4).** `Route.To().GetAttributes()` / `SetAttributes()` used to cost one Ask — a temp actor, a mailbox round trip and a 30 s timer — per attribute. The Deployment Manager now sends the Instance Actor a single site-local `InstanceGetAttributesRequest` / `InstanceSetAttributesRequest` (`SiteRuntime/Messages/InstanceAttributeBatch.cs`, never on the wire). Reads are answered in one pass from one consistent point in the mailbox. Writes are applied in order exactly as the equivalent single `SetStaticAttributeCommand`s (static → in-memory + coalesced persist, data-sourced → DCL write, unknown/poison values rejected); data-sourced writes are issued concurrently and the reply waits only for those, each still bounded by its own 30 s DCL Ask (the batch Ask allows that 30 s plus 10 s of mailbox slack, so a device timeout or a busy instance mailbox surfaces as that attribute's own failure, not as a whole-batch timeout over writes that were applied). Both replies carry the per-attribute `GetAttributeResponse` / `SetStaticAttributeResponse`, so the routed response is unchanged: a failed device write or unknown attribute is still reported by name. -> **Loaded overrides are republished to the children and the stream (review 2026-10-21 01/SR-U1).** The override load is asynchronous and lands *after* `PreStart` has already created the Script/Alarm Actors, whose trigger snapshots are seeded from the attribute set at that moment — the deploy **defaults**. Static attributes never re-emit a change on their own, so before this fix every trigger on an instance that restarted, failed over, was enabled or was started by the reconcile sweep evaluated an overridden attribute at its default indefinitely (an Expression alarm on `Mode == "Auto"` never raised), and the Debug View live stream showed the default, while `GetAttribute` answered correctly. The load now republishes each override that changed the in-memory value or quality (quality from the load, no `SourceExecutionId`), with waiter evaluation **off** — nothing can legitimately be waiting on a replay. The site stream / Debug View receive it as an ordinary `AttributeValueChanged`; the children receive it as a site-local **`AttributeValueSeed`** (decision 2026-10-22): **Script Actors adopt the value without running** — the snapshot, a Conditional trigger's truth value and an Expression trigger's last result (evaluated, never fired) are brought up to date, so a restart/failover never re-fires ValueChange/Conditional/Expression scripts and the next real change is judged against the real value; a WhileTrue trigger whose condition already holds is seeded true without starting its re-fire timer. A seed evaluation whose task **faults** adopts nothing — it is not replayed as a real `false`, which would stop a running WhileTrue timer and make the next true evaluation fire as a spurious fresh edge (review 2026-10-21 follow-up L4). **Alarm Actors evaluate the seed like any change**, so an alarm whose condition already holds raises. A static write that lands before the load is newer than the stored row, so the load skips that attribute rather than rolling it back. Overrides for attributes the deployed config no longer defines are still applied (unchanged) but not republished. +> **Loaded overrides are republished to the children and the stream (review 2026-10-21 01/SR-U1).** The override load is asynchronous and lands *after* `PreStart` has already created the Script/Alarm Actors, whose trigger snapshots are seeded from the attribute set at that moment — the deploy **defaults**. Static attributes never re-emit a change on their own, so before this fix every trigger on an instance that restarted, failed over, was enabled or was started by the reconcile sweep evaluated an overridden attribute at its default indefinitely (an Expression alarm on `Mode == "Auto"` never raised), and the Debug View live stream showed the default, while `GetAttribute` answered correctly. The load now republishes each override that changed the in-memory value or quality (quality from the load, no `SourceExecutionId`), with waiter evaluation **off** — nothing can legitimately be waiting on a replay. The site stream / Debug View receive it as an ordinary `AttributeValueChanged`; the children receive it as a site-local **`AttributeValueSeed`** (decision 2026-10-22): **Script Actors adopt the value without running** — the snapshot, a Conditional trigger's truth value and an Expression trigger's last result (evaluated, never fired) are brought up to date, so a restart/failover never re-fires ValueChange/Conditional/Expression scripts and the next real change is judged against the real value; a WhileTrue trigger whose condition already holds is seeded true **and starts its re-fire timer** (first run one cadence later — the seed itself still never fires; 2026-12-02 review SRT-4: it used to lose its periodic re-fire until the condition went false and back to true). A seed evaluation whose task **faults** adopts nothing — it is not replayed as a real `false`, which would stop a running WhileTrue timer and make the next true evaluation fire as a spurious fresh edge (review 2026-10-21 follow-up L4). **Alarm Actors evaluate the seed like any change**, so an alarm whose condition already holds raises. A static write that lands before the load is newer than the stored row, so the load skips that attribute rather than rolling it back. Overrides for attributes the deployed config no longer defines are still applied (unchanged) but not republished. > **Stopping an instance answers its pending waits (review 2026-10-21 01/SR-M3).** `PostStop` cancels every registered `WaitForAttribute` timeout and replies `Matched=false, TimedOut=false, ErrorMessage="… abandoned: instance stopped"`, so a script parked in `Attributes.WaitAsync` across a redeploy/disable/delete learns why immediately instead of burning its whole wait plus the Ask timeout and reporting a time-out, and no `WaitForAttributeTimeout` lands in dead letters (a monitored health metric). @@ -330,9 +330,9 @@ When the Instance Actor is stopped (due to disable, delete, or redeployment), Ak - On each value update, evaluates the trigger condition: - **Value Match**: Incoming value equals the predefined target. Supports `"!=X"` prefix for not-equals semantics. - **Range Violation**: Value is outside the allowed min/max range. - - **Rate of Change**: Value change rate exceeds the defined threshold over a configurable time window. Direction filter (rising / falling / either) restricts which side of the rate triggers. + - **Rate of Change**: Value change rate exceeds the defined threshold over a configurable time window. Direction filter (rising / falling / either) restricts which side of the rate triggers. Because subscriptions report on change, a value that steps and then holds produces no further sample; while the window holds two or more samples the Alarm Actor arms a single-shot tick for the moment the oldest sample ages out and re-evaluates with the value held flat — fewer than two samples in the window is "not triggered", so the alarm clears once the step has left the window (2026-12-02 review SRT-3; it used to stay Active indefinitely). - **HiLo**: Multi-setpoint level alarm with up to four configurable setpoints (LoLo, Lo, Hi, HiHi). Any subset may be configured. Each setpoint may carry its own priority that overrides the alarm-level priority for that band. -- **Expression** trigger evaluation runs on the shared .NET thread pool behind a process-wide concurrency gate (`TriggerEvalGate`, sized by `TriggerEvalMaxConcurrency`, default `max(2, ProcessorCount)`) — **not** on the bounded script-execution pool. This is the WP3.1 fix for arch-review finding #4 (High): when evaluation shared that pool, N script bodies blocked in synchronous I/O stalled *every* Expression trigger on the node — scripts and alarms alike — for an unbounded time, and the evaluation's own 2 s timeout was constructed inside the queued body, so it did not start ticking until dequeue. An alarm that should have raised in milliseconds simply never raised, with neither a raise nor a timeout visible to the operator. Trigger expressions are non-blocking **by construction** (`TriggerExpressionGlobals` exposes only reads over an in-memory snapshot, and the script trust gate has already denied I/O, network, threading, and reflection), so the shared pool is where they belong; a second dedicated pool was considered and rejected as adding threads, gauges, and a second starvation surface for no isolation gain. The evaluation deadline (`TriggerEvalTimeoutSeconds`, default 2, previously hardcoded) is now armed **at enqueue**, so gate-wait time burns the same budget and a saturated gate yields a timely `false` rather than an unbounded stall. Per-actor coalescing (one evaluation in flight, one pending) is unchanged and caps waiters at one per Expression trigger, so the gate queue is bounded by trigger count. +- **Expression** trigger evaluation runs on the shared .NET thread pool behind a process-wide concurrency gate (`TriggerEvalGate`, sized by `TriggerEvalMaxConcurrency`, default `max(2, ProcessorCount)`) — **not** on the bounded script-execution pool. This is the WP3.1 fix for arch-review finding #4 (High): when evaluation shared that pool, N script bodies blocked in synchronous I/O stalled *every* Expression trigger on the node — scripts and alarms alike — for an unbounded time, and the evaluation's own 2 s timeout was constructed inside the queued body, so it did not start ticking until dequeue. An alarm that should have raised in milliseconds simply never raised, with neither a raise nor a timeout visible to the operator. Trigger expressions are non-blocking **by construction** (`TriggerExpressionGlobals` exposes only reads over an in-memory snapshot, and the script trust gate has already denied I/O, network, threading, and reflection), so the shared pool is where they belong; a second dedicated pool was considered and rejected as adding threads, gauges, and a second starvation surface for no isolation gain. The evaluation deadline (`TriggerEvalTimeoutSeconds`, default 2, previously hardcoded) is now armed **at enqueue**, so gate-wait time burns the same budget and a saturated gate yields a timely result rather than an unbounded stall. **A throwing or timed-out evaluation is "unknown", never `false` (2026-12-02 review SRT-2):** the alarm keeps its current state and a Script Actor's Expression trigger adopts nothing (an OnTrue edge is not re-armed, a WhileTrue timer keeps running); the error is still logged and counted every time, and a `site_events` row is written at most once a minute per alarm/script (naming how many failures it suppressed). Coercing it to `false` used to clear an Active alarm on one slow evaluation under load and re-raise it — with a second on-trigger run — on the next successful one. A non-bool result is still an evaluated `false`. Per-actor coalescing (one evaluation in flight, one pending) is unchanged and caps waiters at one per Expression trigger, so the gate queue is bounded by trigger count. - For binary trigger types (ValueMatch / RangeViolation / RateOfChange), when the condition is met and the alarm is currently in **normal** state, the alarm transitions to **active**: - Updates the alarm state on the parent Instance Actor (which publishes to the Akka stream). - If an on-trigger script is defined, launches its run via `ScriptRunLauncher` (see Alarm On-Trigger Run below) — no per-run child actor. @@ -614,7 +614,7 @@ Scripts execute **in-process** with constrained access. The following restrictio - **Allowed**: Access to the Script Runtime API (GetAttribute, SetAttribute, CallScript, CallShared, ExternalSystem, Notify, Database, Tracking, Alarms, Log), standard C# language features, basic .NET types (collections, string manipulation, math, date/time). `System.Diagnostics.Stopwatch`, `Debug`, and `Activity` are permitted. - **Forbidden**: File system access (`System.IO`), process spawning (`System.Diagnostics.Process`), threading (`System.Threading` — except `Tasks`, `CancellationToken`, and `CancellationTokenSource`), reflection (`System.Reflection`), all raw network access (`System.Net` — must use `ExternalSystem.Call`), native interop (`System.Runtime.InteropServices`, `Microsoft.Win32`), assembly loading, unsafe code, `dynamic`, `Activator`. -- **Execution timeout**: Configurable per-script maximum execution time, **measured from enqueue** (WP3.1) — a run that spends its whole budget queued behind blocked scripts is shed at dequeue without executing, rather than being granted a fresh full budget for work whose triggering condition is already stale. Exceeding the timeout cancels the script **cooperatively** (S2/UA5): a script blocked in synchronous I/O or a tight CPU loop does not observe cancellation and continues to occupy its dedicated script-execution thread. A **watchdog names the script** once its thread has not returned within a grace period after the timeout — and, as of WP3.1, **detaches and replaces that worker thread**, so a wedged script costs the pool a thread only until the watchdog fires rather than for the rest of the process. The detached worker exits (instead of pulling more work) when its body finally returns, so capacity never silently doubles. Its slot is then handed back and reused by the next worker start, so a script that wedges on every run does not grow the scheduler's slot table (or start a fresh slot) for the process lifetime. Live detached workers are capped at the pool size — at the cap no replacement is started and an Error site event says so, because bounded starvation is preferable to unbounded thread growth when scripts wedge en masse. The scheduler's **queue depth / busy-thread / oldest-busy-age / detached-thread gauges** and the **per-interval shed count** are reported through Health Monitoring so a saturated, stuck, or shedding scheduler is visible. +- **Execution timeout**: Configurable per-script maximum execution time, **measured from enqueue** (WP3.1) — a run that spends its whole budget queued behind blocked scripts is shed at dequeue without executing, rather than being granted a fresh full budget for work whose triggering condition is already stale. Exceeding the timeout cancels the script **cooperatively** (S2/UA5): a script blocked in synchronous I/O or a tight CPU loop does not observe cancellation and continues to occupy its dedicated script-execution thread. A **watchdog names the script** once its thread has not returned within a grace period after the timeout — and, as of WP3.1, **detaches and replaces that worker thread**, so a wedged script costs the pool a thread only until the watchdog fires rather than for the rest of the process. The watchdog detaches the worker the run is blocking **at the moment it fires**, not the one it started on (2026-12-02 review SRT-1): a script's `await` continuation runs on whichever worker dequeues it, under a new run stamp, so the run carries a small tracker in its execution context (`ScriptRunWorkerTracker`, an `AsyncLocal` change callback) that records the current worker each time a piece of the run starts on one — previously a script that had awaited anything before wedging (nearly every real script reads an attribute first) was never detached. Only the run's **own deadline** is reported as a timeout (SRT-10): any other `OperationCanceledException` (an HTTP client's internal timeout, a script's own token) is a failure carrying its real message and stack. The detached worker exits (instead of pulling more work) when its body finally returns, so capacity never silently doubles. Its slot is then handed back and reused by the next worker start, so a script that wedges on every run does not grow the scheduler's slot table (or start a fresh slot) for the process lifetime. Live detached workers are capped at the pool size — at the cap no replacement is started and an Error site event says so, because bounded starvation is preferable to unbounded thread growth when scripts wedge en masse. The scheduler's **queue depth / busy-thread / oldest-busy-age / detached-thread gauges** and the **per-interval shed count** are reported through Health Monitoring so a saturated, stuck, or shedding scheduler is visible. - **Memory**: Scripts share the host process memory. No per-script memory limit, but the execution timeout prevents runaway allocations. The forbidden-API policy is defined authoritatively in `ScriptTrustPolicy` (Script Analysis component, #25). `ScriptCompilationService.ValidateTrustModel` delegates to `ScriptTrustValidator.FindViolations` for the trust verdict; the Site Runtime also performs a `CSharpScript.Compile` against the real `ScriptGlobals` for execution. This is defence-in-depth static enforcement, not a true runtime sandbox. @@ -644,7 +644,7 @@ Per Akka.NET best practices, internal actor communication uses **Tell** (fire-an **Ask** is reserved for system boundaries where a synchronous response is needed: - **`Instance.CallScript()`**: Ask pattern from the running script (via `ScriptRuntimeContext.CallScript`) to sibling Script Actor. The caller needs the return value. Acceptable because script calls are infrequent relative to tag updates. -- **`Route.To().Call()`**: Ask from Inbound API to site Instance Actor via Communication Layer. External caller needs a response. +- **`Route.To().Call()`**: Ask from Inbound API to site Instance Actor via Communication Layer. External caller needs a response. On the site, the Deployment Manager's Ask to the Instance Actor waits as long as the **target script** may run — its resolved execution timeout (per-script override, else the site default) plus the stuck-script grace and 5 s — instead of a hard-coded 30 s (2026-12-02 review SRT-13: a 120 s handshake script used to fail its caller at 30 s while it ran on, so a retrying caller ran it twice). Script-facing Asks (`GetAttribute`, `SetAttribute`, `CallScript`) are cancelled by the run's own deadline token (SRT-9), so a run parked in one takes the timeout path at its deadline instead of sailing past it. - **Debug view snapshot**: Ask from Communication Layer to Instance Actor for initial state. ## Concurrency & Serialization @@ -711,5 +711,5 @@ Per Akka.NET best practices, internal actor communication uses **Tell** (fire-an - Alarm on-trigger runs resolve the same scoped integration services as ordinary scripts, including external systems, databases, notifications, operation tracking, auditing, and site/node provenance. The scope remains alive for the run and is disposed on every exit. - Native alarm subscription retries retain the current correlation ID until its response deadline, reject stale replies, and back off to a bounded interval. Rehydration cannot overwrite a condition touched by a live event, including deletion, or a completed authoritative snapshot. - Audited raw ADO connections expose no connection string and reject `ConnectionString` assignment and `ChangeDatabase`; their configured database name remains the audit target. -- Static override persistence runs in order off the actor dispatcher. Redeployment waits for both predecessor termination and successful final persistence acknowledgement before clearing old state; failed persistence fails the redeployment. At most four redeployment predecessor stops are in progress per deployment manager. Delete and disable retain the same-name stop barrier until the final flush and lifecycle persistence finish; an overlapping deploy/enable is rejected with a retryable busy diagnostic. Timer flushes keep coalescing while a previous SQLite write is pending. +- Static override persistence runs in order off the actor dispatcher. Redeployment waits for both predecessor termination and successful final persistence acknowledgement before clearing old state; failed persistence fails the redeployment. At most four redeployment predecessor stops are in progress per deployment manager. Delete and disable retain the same-name stop barrier until the final flush and lifecycle persistence finish; an overlapping deploy/enable is rejected with a retryable busy diagnostic. Timer flushes keep coalescing while a previous SQLite write is pending. The redeploy reset (clear static overrides, then clear native alarms) gates the **successor's whole start**, not only its override load (2026-12-02 review SRT-12): the native-alarm rehydration read and the first static-override flush are chained behind it as well, so the successor can neither re-emit the predecessor's native conditions nor have an early static write deleted by a clear that landed after it. A successful static write refreshes the attribute's stored quality (`Good`) and timestamp along with its value (SRT-11) — a List attribute whose default failed to decode used to stay `Bad` for the actor's lifetime after a valid write. - Synchronous operation-tracking disposal drains and joins its thread-pool writer before disposing SQLite resources, including when invoked under a synchronization context. diff --git a/docs/requirements/Component-StoreAndForward.md b/docs/requirements/Component-StoreAndForward.md index c26d0938..95d81a97 100644 --- a/docs/requirements/Component-StoreAndForward.md +++ b/docs/requirements/Component-StoreAndForward.md @@ -129,7 +129,7 @@ The telemetry-emitting `ICachedCallLifecycleObserver` hook is dispatched through ### Retry Sweep Indexing -`GetMessagesForRetryAsync` orders candidates `ORDER BY created_at ASC` within the due `status`. The existing `idx_sf_messages_status_due (status, last_attempt_at_ms)` matches the status filter and due-time predicate but not this ordering, forcing a sort/scan on a large sweep. The sweep page is ranked **per `(category, target)` lane** (`ROW_NUMBER() OVER (PARTITION BY category, target ORDER BY created_at)`, ordered by lane rank then `created_at`, limited to `SweepBatchLimit`), so a dead target with hundreds of due rows contributes one row per round like every other lane instead of owning the whole page and starving healthy targets (review 2026-10-21 02/C2); per-target FIFO is preserved. A second covering index, `idx_sf_messages_status_created (status, created_at)`, lets the sweep walk matching rows already in `created_at` order and stop at the batch limit without re-sorting or touching non-pending rows (arch-review WP1.4). Both indexes are retained — `idx_sf_messages_status_due` still backs status+due-time lookups that don't order by `created_at`. +`GetMessagesForRetryAsync` orders candidates `ORDER BY created_at ASC` within the due `status`. The existing `idx_sf_messages_status_due (status, last_attempt_at_ms)` matches the status filter and due-time predicate but not this ordering, forcing a sort/scan on a large sweep. The sweep page is ranked **per `(category, target)` lane** (`ROW_NUMBER() OVER (PARTITION BY category, target ORDER BY created_at)`, ordered by lane rank then `created_at`, limited to `SweepBatchLimit`), so a dead target with hundreds of due rows contributes one row per round like every other lane instead of owning the whole page and starving healthy targets (review 2026-10-21 02/C2); per-target FIFO is preserved. **Due-ness is decided per lane, not per row (2026-12-02 review SF-1):** the window runs over every *pending* row of the lane in enqueue order (`created_at`, then `rowid` as the same-instant tie-break) and only the prefix of due rows before the first not-yet-due row is eligible, so a younger row is never delivered while an older row of the same lane is still backing off (previously the failed head's `last_attempt_at` moved forward while the rows behind it kept older stamps, and a later sweep delivered B before A). An older *parked* row does not hold a lane. A dead target is therefore probed once per head retry interval. **A storage error after the handler has answered is not a delivery failure (SF-2):** the try covers the handler only; on success the row delete is retried (3 attempts) and, if it still fails, the row stays `Pending` with `RetryCount`/`LastError` untouched (never parked), the lane stops for that sweep, and the next due sweep re-delivers it (at-least-once; downstream idempotency remains the caller's). A failed park write after a permanent failure is handled the same way. A second covering index, `idx_sf_messages_status_created (status, created_at)`, lets the sweep walk matching rows already in `created_at` order and stop at the batch limit without re-sorting or touching non-pending rows (arch-review WP1.4). Both indexes are retained — `idx_sf_messages_status_due` still backs status+due-time lookups that don't order by `created_at`. ## Parked Message Management diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/AttributeValueCodec.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/AttributeValueCodec.cs index 8649b9c1..ca81da3b 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/AttributeValueCodec.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/AttributeValueCodec.cs @@ -14,7 +14,26 @@ namespace ZB.MOM.WW.ScadaBridge.Commons.Types; /// public static class AttributeValueCodec { - private static readonly JsonSerializerOptions JsonOpts = new() { WriteIndented = false }; + // AllowNamedFloatingPointLiterals: a List/List holding NaN or ±Infinity + // (a bad-scaled analog, a divide-by-zero) encodes as the JSON strings "NaN" / + // "Infinity" / "-Infinity" instead of throwing ArgumentException from the serializer + // (CMN-3). Decode reads them back through the invariant-culture double/float parse, + // which accepts the same literals. + private static readonly JsonSerializerOptions JsonOpts = new() + { + WriteIndented = false, + NumberHandling = System.Text.Json.Serialization.JsonNumberHandling.AllowNamedFloatingPointLiterals, + }; + + /// + /// The scalar DateTime wire format: ISO-8601 round-trip ("O"), always UTC, with + /// full sub-second precision. Replaced the invariant general format + /// ("06/15/2026 13:45:30" — no zone, whole seconds) that the + /// branch used to produce (CMN-4). Every reader parses with + /// + invariant culture, which still accepts + /// the old form, so values persisted or sent by an older node keep decoding. + /// + private const string DateTimeWireFormat = "O"; /// Encodes a value to its canonical string form. /// The value to encode; scalars use invariant-culture formatting, enumerables encode as a JSON array. @@ -25,6 +44,12 @@ public static class AttributeValueCodec { case null: return null; case string s: return s; // already canonical + // DateTime/DateTimeOffset before the generic IFormattable branch: ISO-8601 + // round-trip so the scalar keeps its zone and sub-second precision (CMN-4). + // All timestamps are UTC system-wide, so an Unspecified kind is taken as UTC + // and a Local one is converted. + case DateTime dt: return ToUtc(dt).ToString(DateTimeWireFormat, CultureInfo.InvariantCulture); + case DateTimeOffset dto: return dto.ToString(DateTimeWireFormat, CultureInfo.InvariantCulture); case IFormattable f: return f.ToString(null, CultureInfo.InvariantCulture); case IEnumerable e: // Native-typed JSON: serialize the runtime collection so System.Text.Json emits @@ -35,6 +60,13 @@ public static class AttributeValueCodec } } + private static DateTime ToUtc(DateTime dt) => dt.Kind switch + { + DateTimeKind.Utc => dt, + DateTimeKind.Local => dt.ToUniversalTime(), + _ => DateTime.SpecifyKind(dt, DateTimeKind.Utc), + }; + /// /// Decodes a canonical string. For returns a typed /// List<T>; for scalars returns the string unchanged. Throws diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/DynamicJsonElement.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/DynamicJsonElement.cs index 797dcbb9..e196b03f 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/DynamicJsonElement.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/DynamicJsonElement.cs @@ -96,7 +96,20 @@ public class DynamicJsonElement : DynamicObject return true; } - result = ConvertTo(binder.Type); + // A JSON null converts to null for any target that can hold null (reference + // types and Nullable), e.g. (string)resp or (int?)resp on a JSON-null body. + // A non-nullable value type (e.g. int) genuinely cannot represent it: report + // failure so the binder surfaces a binding error (CMN-10). + var underlying = Nullable.GetUnderlyingType(binder.Type); + if (_element.ValueKind == JsonValueKind.Null) + { + result = null; + return !binder.Type.IsValueType || underlying != null; + } + + // Nullable targets convert through their underlying type: (int?)resp on a + // JSON number yields the boxed int, which the binder lifts to int?. + result = ConvertTo(underlying ?? binder.Type); // A non-object target with a null result means ConvertTo could not handle the // element/type pair — report failure so the binder surfaces a binding error. return result != null; diff --git a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Actors/DataConnectionActor.cs b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Actors/DataConnectionActor.cs index 64ddc575..4d0e23af 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Actors/DataConnectionActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Actors/DataConnectionActor.cs @@ -492,6 +492,9 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers // No session yet — a probe would fail for every tag. ReSubscribeAll's chunk // completions re-arm the timer once the link is up. break; + case RetryAlarmResubscribe: + // No session — ReSubscribeAllAlarms re-issues every feed once the link is up. + break; case ServiceLevelPollTick or ServiceLevelSampled or ServiceLevelProbed: // ScadaBridge#138: belongs to a session that is over; BecomeConnected restarts it. break; @@ -621,6 +624,9 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers case RetryTagResolution: HandleRetryTagResolution(); break; + case RetryAlarmResubscribe retryAlarm: + HandleRetryAlarmResubscribe(retryAlarm); + break; case BrowseNodeCommand browse: HandleBrowse(browse); break; @@ -985,6 +991,9 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers // Ignore — the adapter has no live session; ReSubscribeAll's chunk // completions re-arm the retry timer after reconnect. break; + case RetryAlarmResubscribe: + // Ignore — ReSubscribeAllAlarms re-issues every feed after reconnect. + break; case ServiceLevelProbed { AfterDisconnect: true } lostLinkProbe: // ScadaBridge#141: the other endpoint's verdict for a link lost after a Degraded level. HandleDisconnectProbed(lostLinkProbe); @@ -1260,6 +1269,7 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers ReSubscribeAllAlarms(); BecomeConnected(); + PushConnectionRestored(); } else { @@ -1970,7 +1980,7 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers foreach (var seed in msg.SeedValues) { if (_subscriptionIds.ContainsKey(seed.TagPath)) - Self.Tell(new TagValueReceived(seed.TagPath, seed.Value, _adapterGeneration)); + Self.Tell(new TagValueReceived(seed.TagPath, seed.Value, _adapterGeneration, SeedKind.InitialSubscribe)); } } @@ -2268,7 +2278,20 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers _log.Debug("[{0}] Browsing children of {1}", _connectionName, command.ParentNodeId ?? "(root)"); - browsable.BrowseChildrenAsync(command.ParentNodeId, command.ContinuationToken).ContinueWith(t => + // DCL-6: an adapter that throws BEFORE returning a task (not yet connected, a null client) + // must still produce a typed reply — the mapping below only sees a faulted task, so a + // synchronous throw used to escape on the actor thread and leave the caller to time out. + Task browseTask; + try + { + browseTask = browsable.BrowseChildrenAsync(command.ParentNodeId, command.ContinuationToken); + } + catch (Exception ex) + { + browseTask = Task.FromException(ex); + } + + browseTask.ContinueWith(t => { if (t.IsCompletedSuccessfully) { @@ -2349,7 +2372,18 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers _log.Debug("[{0}] Searching address space for '{1}' (maxDepth={2}, maxResults={3})", _connectionName, command.Query, command.MaxDepth, command.MaxResults); - searchable.SearchAddressSpaceAsync(command.Query, command.MaxDepth, command.MaxResults).ContinueWith(t => + // DCL-6: see HandleBrowse — a synchronous throw must still reply. + Task searchTask; + try + { + searchTask = searchable.SearchAddressSpaceAsync(command.Query, command.MaxDepth, command.MaxResults); + } + catch (Exception ex) + { + searchTask = Task.FromException(ex); + } + + searchTask.ContinueWith(t => { if (t.IsCompletedSuccessfully) { @@ -2633,7 +2667,7 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers { var seeds = await SeedTagsAsync(adapter, resolved); foreach (var seed in seeds) - self.Tell(new TagValueReceived(seed.TagPath, seed.Value, generation)); + self.Tell(new TagValueReceived(seed.TagPath, seed.Value, generation, SeedKind.Reseed)); } catch (Exception ex) { @@ -2780,10 +2814,17 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers } else if (row.ConnectionLevelFailure) { - // Connection-level fault: not a tag-resolution problem. The reconnect - // cycle re-issues everything from _subscriptionsByInstance. + // Connection-level fault on a re-subscribe / probe row. If the adapter also + // raises Disconnected, the reconnect cycle re-issues everything from + // _subscriptionsByInstance — but nothing here starts that cycle, and + // ReSubscribeAll already cleared _subscriptionIds/_unresolvedTags, so a + // chunk that failed while the session stayed healthy used to leave its tags + // in NO retry set: Bad until some unrelated reconnect (DCL-8). Put them in + // the resolution retry set; a reconnect clears it and re-issues them anyway. _log.Warning("[{0}] Batch subscribe for {1} failed at connection level: {2}", _connectionName, row.TagPath, row.Error); + if (_instancesByTag.ContainsKey(row.TagPath) && !_subscriptionIds.ContainsKey(row.TagPath)) + _unresolvedTags.Add(row.TagPath); } else { @@ -2819,6 +2860,27 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers ScheduleTagResolutionRetry(); } + // ── Connection-restored signal ── + + /// + /// SRT-6 / WP3 task 3.8: tells every subscriber ConnectionQualityChanged(Good) when the + /// connection re-enters Connected after a reconnect. It is a RESTORE SIGNAL only — the Instance + /// Actor uses it to reset its Lever-1 tag-subscribe backoff so a subscribe that failed during + /// the outage is retried at the floor instead of up to TagSubscribeRetryMaxIntervalMs + /// later. It deliberately says nothing about any tag's value: per-tag quality is restored by + /// the re-subscribe and the re-seed, and the Instance Actor must not stamp bound attributes + /// Good with their last-known values before the device re-reports. + /// + private void PushConnectionRestored() + { + var now = DateTimeOffset.UtcNow; + foreach (var instanceName in _subscriptionsByInstance.Keys) + { + if (_subscribers.TryGetValue(instanceName, out var subscriber)) + subscriber.Tell(new ConnectionQualityChanged(_connectionName, QualityCode.Good, now)); + } + } + // ── Bad Quality Push ── private void PushBadQualityForAllTags() @@ -2939,6 +3001,17 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers var batchSize = Math.Max(1, _options.SubscribeBatchSize); var chunkDelay = _options.SubscribeBatchDelay; + // Session-bound background work (the re-subscribe loop below AND the re-seed further + // down) shares ONE token, created BEFORE either starts. CancelSessionWork — entering + // Reconnecting, an adapter swap, actor stop — cancels it. DCL-4: the loop used to have + // no token, so a loop left over from a dead session (a chunk wedged across a reconnect) + // carried on issuing its remaining chunks against the SAME adapter object's NEW client: + // duplicate OPC UA monitored items / MxGateway subscribes whose stale-generation results + // were then dropped without release. + CancelSessionWork(); + _sessionWorkCts = new CancellationTokenSource(); + var sessionToken = _sessionWorkCts.Token; + // Bounded, sequential chunks in ONE background task — replacing the previous // "one fire-and-forget task per tag" storm (37,500 concurrent subscribes at the // sizing target). Sequential because subscription creation on one session is @@ -2949,8 +3022,22 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers { for (var offset = 0; offset < allTags.Count; offset += batchSize) { - if (offset > 0 && chunkDelay > TimeSpan.Zero) - await Task.Delay(chunkDelay); + try + { + if (offset > 0 && chunkDelay > TimeSpan.Zero) + await Task.Delay(chunkDelay, sessionToken); + } + catch (OperationCanceledException) + { + // Fall through to the cancellation check below. + } + + if (sessionToken.IsCancellationRequested) + { + _log.Debug("[{0}] Reconnect re-subscribe abandoned at tag {1}/{2} — its session has ended", + _connectionName, offset, allTags.Count); + return; + } var chunk = allTags.GetRange(offset, Math.Min(batchSize, allTags.Count - offset)); try @@ -2984,16 +3071,14 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers // repopulated for the new adapter generation. Seeds delivered after registration is // already established, so the ordering hazard does not apply here. var reseedAdapter = _adapter; - CancelSessionWork(); - _sessionWorkCts = new CancellationTokenSource(); - var reseedToken = _sessionWorkCts.Token; + var reseedToken = sessionToken; Task.Run(async () => { try { var seeds = await SeedTagsAsync(reseedAdapter, allTags, reseedToken); foreach (var seed in seeds) - self.Tell(new TagValueReceived(seed.TagPath, seed.Value, generation)); + self.Tell(new TagValueReceived(seed.TagPath, seed.Value, generation, SeedKind.Reseed)); } catch (Exception ex) { @@ -3041,9 +3126,24 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers private void UnindexTag(string tag, string instance) { if (_instancesByTag.TryGetValue(tag, out var insts) && insts.Remove(instance) && insts.Count == 0) + { _instancesByTag.Remove(tag); + _lastLiveValue.Remove(tag); + } } + /// + /// DCL-1: the latest LIVE (subscription-delivered, non-seed) value per tag in the generation + /// recorded in . A tag present here has already delivered a + /// live value in the current subscribe generation, so a later seed for it is stale. Cleared + /// lazily when the adapter generation advances (every reconnect / adapter swap); an entry is + /// dropped when the tag loses its last subscriber. + /// + private readonly Dictionary _lastLiveValue = new(); + + /// The adapter generation belongs to. + private int _liveValuesGeneration = -1; + private void HandleTagValueReceived(TagValueReceived msg) { // Drop values delivered by a disposed adapter. After a @@ -3064,6 +3164,38 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers if (!_instancesByTag.TryGetValue(msg.TagPath, out var interestedInstances)) return; + // DCL-1: a seed must never overwrite a newer live value. The subscription is live + // before the seed read starts, and a seed is held until its whole seed operation + // completes, so a live change inside that window would otherwise be regressed to the + // older seed value — with Good quality, indefinitely, for a tag that changes rarely. + // The rule is generation-based (decided 2026-12-03), NOT a timestamp comparison, + // which would depend on device/server clocks and the configured timestamp mode. + if (_liveValuesGeneration != _adapterGeneration) + { + _lastLiveValue.Clear(); + _liveValuesGeneration = _adapterGeneration; + } + var value = msg.Value; + if (msg.Seed == SeedKind.None) + { + _lastLiveValue[msg.TagPath] = value; + } + else if (_lastLiveValue.TryGetValue(msg.TagPath, out var latestLive)) + { + if (msg.Seed == SeedKind.Reseed) + { + // Every interested instance was registered while the subscription was live, + // so each already holds the live value: drop the seed outright. + _log.Debug("[{0}] Dropping seed for {1}: a live value already arrived in generation {2}", + _connectionName, msg.TagPath, _adapterGeneration); + return; + } + + // Initial subscribe: the joining instance may have missed live values delivered + // before it registered, so re-deliver the LATEST live value instead of the seed. + value = latestLive; + } + // Fan out to exactly the instances subscribed to this tag via the reverse index — // O(subscribers of this tag) instead of scanning every instance's tag set per update. foreach (var instanceName in interestedInstances) @@ -3071,7 +3203,7 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers if (_subscribers.TryGetValue(instanceName, out var subscriber)) { subscriber.Tell(new TagValueUpdate( - _connectionName, msg.TagPath, msg.Value.Value, msg.Value.Quality, msg.Value.Timestamp)); + _connectionName, msg.TagPath, value.Value, value.Quality, value.Timestamp)); } } @@ -3082,7 +3214,7 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers // 30s. Now: unchanged quality is a no-op; a genuine transition updates the buckets // and arms the coalescing flush timer. var hadPrevious = _lastTagQuality.TryGetValue(msg.TagPath, out var prevQuality); - if (hadPrevious && prevQuality == msg.Value.Quality) + if (hadPrevious && prevQuality == value.Quality) return; if (hadPrevious) @@ -3096,13 +3228,13 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers } } // Increment new quality bucket - switch (msg.Value.Quality) + switch (value.Quality) { case QualityCode.Good: _tagsGoodQuality++; break; case QualityCode.Bad: _tagsBadQuality++; break; case QualityCode.Uncertain: _tagsUncertainQuality++; break; } - _lastTagQuality[msg.TagPath] = msg.Value.Quality; + _lastTagQuality[msg.TagPath] = value.Quality; MarkQualityDirty(); } @@ -3356,8 +3488,19 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers { _log.Warning("[{0}] Alarm subscribe failed for source {1}: {2}", _connectionName, msg.SourceReference, msg.Error); + + // DCL-2: a reconnect re-subscribe (ReplyTo == null) has no requester to retry it — + // the NativeAlarmActor already counts the feed as established and its + // NativeAlarmSourceUnavailable handler deliberately does not re-subscribe — so the + // DCL retries it itself on a backed-off timer while the source still has + // subscribers. An interactive subscribe's failure is retried by its requester. + if (msg.ReplyTo is null) + ScheduleAlarmResubscribeRetry(msg.SourceReference); } + if (msg.Success) + CancelAlarmResubscribeRetry(msg.SourceReference); + // ReplyTo is null for reconnect re-subscribes (no original requester to answer). msg.ReplyTo?.Tell(new SubscribeAlarmsResponse( msg.CorrelationId ?? string.Empty, msg.InstanceUniqueName ?? string.Empty, @@ -3402,9 +3545,10 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers continue; // A subscriber bound to source S receives a transition whose source - // object (or full reference) falls under S. - var match = transition.SourceObjectReference.StartsWith(sourceRef, StringComparison.Ordinal) - || transition.SourceReference.StartsWith(sourceRef, StringComparison.Ordinal); + // object (or full reference) falls under S — S itself or a descendant + // separated by a path separator, never a mere string prefix (DCL-5). + var match = IsUnderAlarmSource(transition.SourceObjectReference, sourceRef) + || IsUnderAlarmSource(transition.SourceReference, sourceRef); if (!match) continue; @@ -3484,6 +3628,29 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers /// full StartsWith test and the condition-type gate, so routing is identical to the /// previous linear scan. /// + /// + /// True when is the alarm source itself or + /// lies beneath it: the prefix must end at a path separator (. or /). A raw string + /// prefix let Tank1 (or ns=2;s=Tank1) also receive — and mirror as its own — + /// every alarm of Tank10 (DCL-5). An empty source (the OPC UA Server-object aggregate + /// feed) covers everything, as before. + /// + internal static bool IsUnderAlarmSource(string reference, string source) + { + if (source.Length == 0) + return true; + if (!reference.StartsWith(source, StringComparison.Ordinal)) + return false; + if (reference.Length == source.Length) + return true; + // The source already ends in a separator (an explicit area prefix such as "Area1."). + var last = source[^1]; + if (last is '.' or '/') + return true; + var next = reference[source.Length]; + return next is '.' or '/'; + } + private IEnumerable CandidateAlarmSources(NativeAlarmTransition transition) { var objectSegment = FirstSegment(transition.SourceObjectReference); @@ -3526,6 +3693,7 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers UnindexAlarmSource(sourceReference); _alarmSourceFilter.Remove(sourceReference); _alarmSourceFilterPredicate.Remove(sourceReference); + CancelAlarmResubscribeRetry(sourceReference); // Clear the in-flight marker so that if an adapter // subscribe is still in flight for this source, the late AlarmSubscribeCompleted // is recognized as orphaned (its guard checks _alarmSourceSubscribers, now empty) @@ -3547,24 +3715,89 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers _alarmSubscriptionIds.Clear(); _alarmReplay.Clear(); _alarmSubscribesInFlight.Clear(); - var self = Self; - var generation = _adapterGeneration; + // A fresh session re-issues every feed: retries armed against the previous one are moot + // and their backoff starts over. + foreach (var sourceRef in _alarmResubscribeInterval.Keys.ToList()) + CancelAlarmResubscribeRetry(sourceRef); foreach (var sourceRef in _alarmSourceSubscribers.Keys.ToList()) + IssueAlarmResubscribe(alarmable, sourceRef); + } + + /// + /// Issues one requester-less (ReplyTo == null) alarm-feed subscribe for + /// against — the reconnect + /// re-subscribe and its DCL-2 retry. + /// + private void IssueAlarmResubscribe(IAlarmSubscribableConnection alarmable, string sourceRef) + { + var self = Self; + var generation = _adapterGeneration; + var sr = sourceRef; + var filter = _alarmSourceFilter.GetValueOrDefault(sourceRef); + _alarmSubscribesInFlight.Add(sr); + alarmable.SubscribeAlarmsAsync(sr, filter, + t => self.Tell(new AlarmTransitionReceived(t, generation))) + .ContinueWith(task => task.IsCompletedSuccessfully + ? new AlarmSubscribeCompleted( + sr, true, task.Result, null, null, null, null, generation, alarmable) as object + : new AlarmSubscribeCompleted(sr, false, null, + task.Exception?.GetBaseException().Message ?? "Unknown error", + null, null, null, generation, alarmable)) + .PipeTo(self); + } + + // ── DCL-2: alarm re-subscribe retry ── + + /// + /// Next retry delay per alarm source whose requester-less re-subscribe failed. Same floor, + /// doubling and ceiling as the tag-resolution probe + /// ( → + /// ). + /// + private readonly Dictionary _alarmResubscribeInterval = new(); + + private static string AlarmResubscribeTimerKey(string sourceRef) => "alarm-resubscribe:" + sourceRef; + + private void ScheduleAlarmResubscribeRetry(string sourceRef) + { + if (!_alarmSourceSubscribers.ContainsKey(sourceRef)) + return; + + var delay = _alarmResubscribeInterval.TryGetValue(sourceRef, out var current) + ? current + : _options.TagResolutionRetryInterval; + _alarmResubscribeInterval[sourceRef] = NextTagResolutionInterval( + delay, _options.TagResolutionRetryInterval, _options.TagResolutionRetryMaxInterval); + Timers.StartSingleTimer(AlarmResubscribeTimerKey(sourceRef), + new RetryAlarmResubscribe(sourceRef, _adapterGeneration), delay); + _log.Info("[{0}] Alarm feed for source {1} will be re-subscribed in {2}", + _connectionName, sourceRef, delay); + } + + private void CancelAlarmResubscribeRetry(string sourceRef) + { + _alarmResubscribeInterval.Remove(sourceRef); + Timers.Cancel(AlarmResubscribeTimerKey(sourceRef)); + } + + private void HandleRetryAlarmResubscribe(RetryAlarmResubscribe msg) + { + // A retry armed against an earlier session is moot: the reconnect re-issued every feed. + if (msg.AdapterGeneration != _adapterGeneration) + return; + if (!_alarmSourceSubscribers.ContainsKey(msg.SourceReference)) { - var sr = sourceRef; - var filter = _alarmSourceFilter.GetValueOrDefault(sourceRef); - _alarmSubscribesInFlight.Add(sr); - alarmable.SubscribeAlarmsAsync(sr, filter, - t => self.Tell(new AlarmTransitionReceived(t, generation))) - .ContinueWith(task => task.IsCompletedSuccessfully - ? new AlarmSubscribeCompleted( - sr, true, task.Result, null, null, null, null, generation, alarmable) as object - : new AlarmSubscribeCompleted(sr, false, null, - task.Exception?.GetBaseException().Message ?? "Unknown error", - null, null, null, generation, alarmable)) - .PipeTo(self); + CancelAlarmResubscribeRetry(msg.SourceReference); + return; } + if (_alarmSubscriptionIds.ContainsKey(msg.SourceReference) + || _alarmSubscribesInFlight.Contains(msg.SourceReference) + || _adapter is not IAlarmSubscribableConnection alarmable) + return; + + _log.Info("[{0}] Retrying alarm feed subscribe for source {1}", _connectionName, msg.SourceReference); + IssueAlarmResubscribe(alarmable, msg.SourceReference); } /// Notifies alarm subscribers that the source feed is unavailable (connection lost). @@ -3593,9 +3826,40 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers /// swapped-out adapter can be dropped (). /// internal record AdapterDisconnected(int AdapterGeneration); - internal record TagValueReceived(string TagPath, TagValue Value, int AdapterGeneration); + /// + /// A tag value marshalled onto the actor thread. marks a value that + /// came from a seed READ rather than the live subscription (DCL-1): a seed is held until its + /// whole seed operation completes (up to ), + /// so it can be older than a live value the subscription has already delivered. + /// + internal record TagValueReceived(string TagPath, TagValue Value, int AdapterGeneration, SeedKind Seed = SeedKind.None); + + /// Origin of a (DCL-1). + internal enum SeedKind + { + /// A live subscription notification. + None, + + /// + /// A seed read for tags every interested instance was already registered for while the + /// subscription was live: the reconnect re-seed and the tag-resolution re-seed. Dropped + /// when the tag already delivered a live value in the current generation. + /// + Reseed, + + /// + /// The seed read of an initial . The requesting instance + /// may have joined a tag that was ALREADY live for another instance, so it never saw the + /// earlier live values; when the tag has delivered a live value in the current generation + /// the stale seed is replaced by that latest live value rather than dropped outright. + /// + InitialSubscribe, + } internal record RetryTagResolution; + /// DCL-2: backed-off retry of a failed requester-less alarm-feed re-subscribe. + internal record RetryAlarmResubscribe(string SourceReference, int AdapterGeneration); + /// Coalescing-timer tick for the tag-quality counter push. internal record QualityFlushTick; diff --git a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/MxGatewayDataConnection.cs b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/MxGatewayDataConnection.cs index 063f0e7a..84dcd39e 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/MxGatewayDataConnection.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/MxGatewayDataConnection.cs @@ -370,7 +370,10 @@ public class MxGatewayDataConnection // ONE gateway round trip per batch (SubscribeBulk = AddItem + Advise per tag in a // single worker pass) instead of the historical 2 RPCs per tag. var session = Volatile.Read(ref _session); - var outcomes = await _client!.SubscribeBulkAsync(tagPaths, cancellationToken); + // Dereference the session's client ONCE (DCL-4); results from a session that ended + // mid-call are not registered (the `current` check below). + var client = _client!; + var outcomes = await client.SubscribeBulkAsync(tagPaths, cancellationToken); var current = session == Volatile.Read(ref _session); var results = new List(outcomes.Count); foreach (var outcome in outcomes) diff --git a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/OpcUaDataConnection.cs b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/OpcUaDataConnection.cs index 279e8caf..8baa823f 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/OpcUaDataConnection.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/OpcUaDataConnection.cs @@ -215,10 +215,13 @@ public class OpcUaDataConnection IReadOnlyList tagPaths, SubscriptionCallback callback, CancellationToken cancellationToken = default) { EnsureConnected(); + // Dereference the session's client ONCE (DCL-4): a reconnect swaps _client, and a call + // must run entirely against the client it started on. + var client = _client!; // ONE shared callback for the whole batch — the client hands back the node id // (== tag path for OPC UA), so no per-tag closure is needed. - var outcomes = await _client!.CreateSubscriptionsAsync( + var outcomes = await client.CreateSubscriptionsAsync( tagPaths, (nodeId, value, timestamp, statusCode) => { @@ -445,23 +448,33 @@ public class OpcUaDataConnection } /// - public Task BrowseChildrenAsync( + public async Task BrowseChildrenAsync( string? parentNodeId, string? continuationToken = null, CancellationToken cancellationToken = default) - => _client!.BrowseChildrenAsync(parentNodeId, continuationToken, cancellationToken); + { + // async so a not-connected adapter FAULTS the task instead of throwing synchronously + // (DCL-6): a freshly swapped failover adapter has no client until the reconnect timer + // fires, and the old `_client!` dereference threw a NullReferenceException on the actor + // thread, so the caller got no reply at all. + var client = _client + ?? throw new ConnectionNotConnectedException("OPC UA client is not connected."); + return await client.BrowseChildrenAsync(parentNodeId, continuationToken, cancellationToken); + } /// - public Task SearchAddressSpaceAsync( + public async Task SearchAddressSpaceAsync( string query, int maxDepth, int maxResults, CancellationToken cancellationToken = default) { // Guard connection state with the typed ConnectionNotConnectedException so // the site-side handler can map it uniformly (mirrors BrowseChildrenAsync, // whose underlying client throws the same type when the session is down). - if (_client == null || !_client.IsConnected) + // async so the guard faults the task rather than throwing synchronously (DCL-6). + var client = _client; + if (client == null || !client.IsConnected) throw new ConnectionNotConnectedException("OPC UA client is not connected."); - return _client.SearchAddressSpaceAsync(query, maxDepth, maxResults, cancellationToken); + return await client.SearchAddressSpaceAsync(query, maxDepth, maxResults, cancellationToken); } private void StopHeartbeatMonitor() diff --git a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/OpcUaValueBoundary.cs b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/OpcUaValueBoundary.cs index 11aecf01..665d935c 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/OpcUaValueBoundary.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/OpcUaValueBoundary.cs @@ -56,6 +56,26 @@ internal static class OpcUaValueBoundary internal static DateTime ToClrTimestamp(DateTimeUtc value) => value == DateTimeUtc.MinValue ? DateTime.MinValue : value.ToDateTime(); + /// + /// The timestamp to stamp on a value read or notified from the server: the SOURCE timestamp + /// when present, else the SERVER timestamp, else now (DCL-7). A connection configured for + /// TimestampsToReturn = Server gets no source timestamp at all, and a server may omit it + /// on notifications; taking SourceTimestamp unconditionally stamped such values + /// 0001-01-01T00:00:00Z, which was stored, streamed and shown until the tag next changed. + /// One helper for both the read and the notification path. + /// + /// The DataValue's source timestamp. + /// The DataValue's server timestamp. + /// The effective UTC timestamp, never . + internal static DateTime EffectiveTimestamp(DateTimeUtc source, DateTimeUtc server) + { + var fromSource = ToClrTimestamp(source); + if (fromSource != DateTime.MinValue) + return fromSource; + var fromServer = ToClrTimestamp(server); + return fromServer != DateTime.MinValue ? fromServer : DateTime.UtcNow; + } + /// /// The SDK value to write for a CLR payload, with SDK 1.5's new Variant(object) /// semantics: a byte[] is a ByteString scalar, other supported scalars and diff --git a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealMxGatewayClient.cs b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealMxGatewayClient.cs index 7e0f0261..c96e74e7 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealMxGatewayClient.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealMxGatewayClient.cs @@ -47,6 +47,20 @@ public sealed class RealMxGatewayClient : IMxGatewayClient // completed. A faulted advise is evicted so the next write retries. private readonly ConcurrentDictionary> _supervisoryAdvised = new(); + /// + /// Cancelled on . The SHARED supervisory-advise task runs under + /// this (plus ), never under the token of + /// whichever caller happened to create it (DCL-9). + /// + private readonly CancellationTokenSource _lifetime = new(); + + /// + /// Upper bound on one shared supervisory advise. The gateway session has no command + /// deadline of its own yet, so without a bound a hung advise would wedge every later + /// caller for that handle; a timed-out advise is evicted and the next caller retries. + /// + internal static readonly TimeSpan SharedSupervisoryAdviseTimeout = TimeSpan.FromSeconds(60); + // With no configured MXAccess write-user this connection behaves as a // supervisory client: every advise defaults to AdviseSupervisory so writes are // accepted. A configured write-user keeps the prior plain-advise behaviour. @@ -517,6 +531,7 @@ public sealed class RealMxGatewayClient : IMxGatewayClient /// A task that represents the asynchronous operation. public async ValueTask DisposeAsync() { + _lifetime.Cancel(); if (_session is not null) await _session.DisposeAsync().ConfigureAwait(false); if (_client is not null) await _client.DisposeAsync().ConfigureAwait(false); if (_galaxy is not null) await _galaxy.DisposeAsync().ConfigureAwait(false); @@ -633,27 +648,46 @@ public sealed class RealMxGatewayClient : IMxGatewayClient /// builds every other command). The result is remembered per handle; a failure is /// not cached so the next attempt retries rather than wedging the item permanently. /// - private async Task EnsureSupervisoryAdvisedAsync(int handle, CancellationToken ct) + internal async Task EnsureSupervisoryAdvisedAsync(int handle, CancellationToken ct) { // GetOrAdd + Lazy runs the advise at most once per handle; concurrent // callers await the same Task and so never reach WriteBulk before it // completes (default Lazy is thread-safe, factory runs once). + // + // DCL-9: the shared task must NOT capture the creating caller's token — a write's 30 s + // deadline firing would cancel the advise a concurrent, deadline-free subscribe is also + // awaiting, failing that subscribe as a tag-resolution error. The shared advise runs under + // the client lifetime (bounded by SharedSupervisoryAdviseTimeout); each caller applies its + // OWN token to its wait only. var advise = _supervisoryAdvised.GetOrAdd( handle, - h => new Lazy(() => AdviseSupervisoryCoreAsync(h, ct))); + h => new Lazy(() => RunSharedSupervisoryAdviseAsync(h))); try { - await advise.Value.ConfigureAwait(false); + await advise.Value.WaitAsync(ct).ConfigureAwait(false); } catch { - // Evict the faulted entry (only if it's still the one we awaited) so the - // next write retries rather than caching a transient advise failure. - _supervisoryAdvised.TryRemove(new KeyValuePair>(handle, advise)); + // Evict a faulted/cancelled SHARED entry (only if it's still the one we awaited) so + // the next call retries rather than caching a transient advise failure. A caller that + // merely stopped waiting on its own token leaves the shared advise running for the + // others. + if (advise.Value.IsFaulted || advise.Value.IsCanceled) + _supervisoryAdvised.TryRemove(new KeyValuePair>(handle, advise)); throw; } } + private async Task RunSharedSupervisoryAdviseAsync(int handle) + { + using var cts = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token); + cts.CancelAfter(SharedSupervisoryAdviseTimeout); + await (AdviseCoreOverride ?? AdviseSupervisoryCoreAsync)(handle, cts.Token).ConfigureAwait(false); + } + + /// Test seam: replaces the gateway round trip of one supervisory advise. + internal Func? AdviseCoreOverride { get; set; } + private async Task AdviseSupervisoryCoreAsync(int handle, CancellationToken ct) { var reply = await _session!.InvokeAsync( diff --git a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealOpcUaClient.cs b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealOpcUaClient.cs index 4de0230d..f325591c 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealOpcUaClient.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealOpcUaClient.cs @@ -772,7 +772,7 @@ public class RealOpcUaClient : IOpcUaClient // SDK 2: DataValue is a struct; restore the SDK 1.5 CLR payload shapes. var dataValue = notification.Value; var value = OpcUaValueBoundary.ToClr(dataValue.WrappedValue); - var timestamp = OpcUaValueBoundary.ToClrTimestamp(dataValue.SourceTimestamp); + var timestamp = OpcUaValueBoundary.EffectiveTimestamp(dataValue.SourceTimestamp, dataValue.ServerTimestamp); var statusCode = dataValue.StatusCode.Code; if (_callbacks.TryGetValue(handle, out var cb)) @@ -962,11 +962,29 @@ public class RealOpcUaClient : IOpcUaClient HandleAlarmEvent(handle, sourceNodeId, efl, onTransition); }; - await _applyGate.RunAsync(async () => + try { - eventShard.AddItem(item); - await eventShard.ApplyChangesAsync(cancellationToken); - }, cancellationToken); + await _applyGate.RunAsync(async () => + { + eventShard.AddItem(item); + await eventShard.ApplyChangesAsync(cancellationToken); + }, cancellationToken); + } + catch + { + await DiscardFailedAlarmItemAsync(handle, eventShard, item); + throw; + } + + // DCL-3: ApplyChangesAsync does NOT throw for a per-item create failure — the server's + // verdict is on the item's status, exactly as on the data path. An unknown node, a node + // that is not an event notifier or a rejected event filter used to be recorded as a live + // feed (SubscribeAlarmsResponse Success) that never delivers anything. + if (AlarmItemCreateError(item) is { } createError) + { + await DiscardFailedAlarmItemAsync(handle, eventShard, item); + throw new ServiceResultException(createError); + } _alarmItems[handle] = item; // Replay currently-active conditions as a Snapshot…SnapshotComplete sequence. @@ -974,6 +992,42 @@ public class RealOpcUaClient : IOpcUaClient return handle; } + /// + /// The server's per-item verdict on an alarm event monitored item after + /// ApplyChangesAsync: the bad when the create was rejected, + /// else null (DCL-3). + /// + internal static ServiceResult? AlarmItemCreateError(MonitoredItem item) + { + var error = item.Status?.Error; + return error != null && ServiceResult.IsBad(error) ? error : null; + } + + /// + /// Unwinds a half-created alarm feed: removes the item from the event shard (best effort — + /// a dead session must not mask the original failure) and drops the per-handle bookkeeping + /// created up front. + /// + private async Task DiscardFailedAlarmItemAsync(string handle, Subscription eventShard, MonitoredItem item) + { + try + { + await _applyGate.RunAsync(async () => + { + eventShard.RemoveItem(item); + await eventShard.ApplyChangesAsync(CancellationToken.None); + }, CancellationToken.None); + } + catch (Exception ex) + { + _logger.LogDebug(ex, "Removing a failed alarm event item from the event shard failed (ignored)."); + } + + _alarmInRefresh.TryRemove(handle, out _); + _alarmSnapshotIds.TryRemove(handle, out _); + _alarmLastState.TryRemove(handle, out _); + } + /// public async Task RemoveAlarmSubscriptionAsync(string subscriptionHandle, CancellationToken cancellationToken = default) { @@ -1555,7 +1609,8 @@ public class RealOpcUaClient : IOpcUaClient var result = results[i]; outcomes[index] = new OpcUaReadOutcome( nodeId, OpcUaValueBoundary.ToClr(result.WrappedValue), - OpcUaValueBoundary.ToClrTimestamp(result.SourceTimestamp), result.StatusCode.Code, null); + OpcUaValueBoundary.EffectiveTimestamp(result.SourceTimestamp, result.ServerTimestamp), + result.StatusCode.Code, null); } else { diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/AlarmActor.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/AlarmActor.cs index ccab92a2..9347a7be 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/AlarmActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/AlarmActor.cs @@ -33,8 +33,11 @@ namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Actors; /// /// Supervision: Resume on exception (from the Instance Actor). This actor has no children. /// -public class AlarmActor : ReceiveActor +public class AlarmActor : ReceiveActor, IWithTimers { + /// + public ITimerScheduler Timers { get; set; } = null!; + private readonly string _alarmName; private readonly string _instanceName; private readonly IActorRef _instanceActor; @@ -171,6 +174,15 @@ public class AlarmActor : ReceiveActor private readonly Queue<(DateTimeOffset Timestamp, double Value)> _rateOfChangeWindow = new(); private readonly TimeSpan _rateOfChangeWindowDuration; + /// + /// SRT-3: the newest sample folded into the rate window, and the wall-clock instant it was + /// processed — so the window-expiry tick can tell how far (in the samples' own time base) + /// the window has advanced since a value that has simply stopped changing. + /// + private (DateTimeOffset Timestamp, double Value, DateTimeOffset ProcessedAtUtc)? _rateLastSample; + + private const string RateWindowTimerKey = "rate-window"; + private int _executionCounter; /// Initializes a new and configures message handlers for the alarm. @@ -266,6 +278,9 @@ public class AlarmActor : ReceiveActor // Handle a faulted off-dispatcher evaluation task (N2) — clears in-flight // instead of stranding the alarm trigger with an unhandled Status.Failure. Receive(HandleExpressionEvalFailed); + + // SRT-3: a RateOfChange window that ages out while the value holds re-evaluates. + Receive(_ => HandleRateWindowTick()); } /// @@ -350,6 +365,9 @@ public class AlarmActor : ReceiveActor }; ApplyTriggeredState(isTriggered, observedSource); + + if (_triggerType == AlarmTriggerType.RateOfChange) + ScheduleRateWindowExpiry(); } catch (Exception ex) { @@ -586,27 +604,9 @@ public class AlarmActor : ReceiveActor // Add to window _rateOfChangeWindow.Enqueue((timestamp, numericValue)); + _rateLastSample = (timestamp, numericValue, DateTimeOffset.UtcNow); - // Remove old entries outside the window - var cutoff = timestamp - _rateOfChangeWindowDuration; - while (_rateOfChangeWindow.Count > 0 && _rateOfChangeWindow.Peek().Timestamp < cutoff) - { - _rateOfChangeWindow.Dequeue(); - } - - if (_rateOfChangeWindow.Count < 2) return false; - - var oldest = _rateOfChangeWindow.Peek(); - var timeDelta = (timestamp - oldest.Timestamp).TotalSeconds; - if (timeDelta <= 0) return false; - - var signedRate = (numericValue - oldest.Value) / timeDelta; - return config.Direction switch - { - RateOfChangeDirection.Rising => signedRate > config.ThresholdPerSecond, - RateOfChangeDirection.Falling => -signedRate > config.ThresholdPerSecond, - _ => Math.Abs(signedRate) > config.ThresholdPerSecond - }; + return EvaluateRateWindow(config, timestamp, numericValue); } catch { @@ -614,13 +614,97 @@ public class AlarmActor : ReceiveActor } } + /// + /// Prunes the rate window to and evaluates the rate from the oldest + /// surviving sample to at . Fewer than two + /// samples in the window ⇒ not triggered. + /// + private bool EvaluateRateWindow(RateOfChangeEvalConfig config, DateTimeOffset now, double currentValue) + { + // Remove old entries outside the window + var cutoff = now - _rateOfChangeWindowDuration; + while (_rateOfChangeWindow.Count > 0 && _rateOfChangeWindow.Peek().Timestamp < cutoff) + { + _rateOfChangeWindow.Dequeue(); + } + + if (_rateOfChangeWindow.Count < 2) return false; + + var oldest = _rateOfChangeWindow.Peek(); + var timeDelta = (now - oldest.Timestamp).TotalSeconds; + if (timeDelta <= 0) return false; + + var signedRate = (currentValue - oldest.Value) / timeDelta; + return config.Direction switch + { + RateOfChangeDirection.Rising => signedRate > config.ThresholdPerSecond, + RateOfChangeDirection.Falling => -signedRate > config.ThresholdPerSecond, + _ => Math.Abs(signedRate) > config.ThresholdPerSecond + }; + } + + /// + /// SRT-3 (2026-12-02 review): tag subscriptions report on CHANGE, so a value that steps and + /// then holds produces no further sample, and the window — pruned only when a sample arrived — + /// used to keep the alarm Active indefinitely although the rate had been 0 since the step. + /// While the window holds two or more samples, a single-shot tick is armed for the moment its + /// oldest sample ages out; the tick re-evaluates with the value held flat since the newest + /// sample. Each new sample re-arms it (the timer key replaces any pending tick). + /// + private void ScheduleRateWindowExpiry() + { + if (_rateOfChangeWindow.Count < 2 || _rateLastSample is not { } last) + { + Timers.Cancel(RateWindowTimerKey); + return; + } + + // In the samples' own time base the oldest sample leaves the window at + // oldest + window; it was `last.Timestamp` when the newest sample was processed. + // +10 ms because the prune keeps a sample exactly AT the cutoff. + var dueIn = _rateOfChangeWindow.Peek().Timestamp + _rateOfChangeWindowDuration - last.Timestamp + - (DateTimeOffset.UtcNow - last.ProcessedAtUtc) + + TimeSpan.FromMilliseconds(10); + if (dueIn < TimeSpan.Zero) dueIn = TimeSpan.Zero; + Timers.StartSingleTimer(RateWindowTimerKey, RateWindowTick.Instance, dueIn); + } + + private void HandleRateWindowTick() + { + if (_evalConfig is not RateOfChangeEvalConfig config || _rateLastSample is not { } last) + return; + try + { + // "Now" in the samples' time base: the newest sample's timestamp advanced by the wall + // time since it was processed. The value has been flat at last.Value since then. + var now = last.Timestamp + (DateTimeOffset.UtcNow - last.ProcessedAtUtc); + ApplyTriggeredState(EvaluateRateWindow(config, now, last.Value), sourceExecutionId: null); + ScheduleRateWindowExpiry(); + } + catch (Exception ex) + { + _healthCollector?.IncrementAlarmError(); + _logger.LogError(ex, "Alarm {Alarm} rate-window re-evaluation error on {Instance}", _alarmName, _instanceName); + } + } + + /// SRT-3: the RateOfChange window-expiry tick. + internal sealed class RateWindowTick + { + public static readonly RateWindowTick Instance = new(); + private RateWindowTick() { } + } + /// /// Evaluates the compiled trigger expression against the current attribute /// snapshot, returning the resulting bool. This bool feeds the existing /// binary Normal↔Active state path — the alarm is active while true. A - /// throwing, non-bool, or timed-out expression is treated as false (logged - /// as an alarm error) so that the state machine still runs — an Active - /// alarm correctly clears if the expression starts throwing. + /// non-bool result is an evaluated false. A THROWING or TIMED-OUT evaluation + /// is "unknown", not false (2026-12-02 review SRT-2): it is logged (node log, + /// alarm-error counter, a rate-limited site event) and the alarm KEEPS its + /// current state. Coercing it to false cleared an Active alarm on a single slow + /// evaluation under load, then re-raised it — with a second on-trigger run — on + /// the next successful one, for a condition that never cleared. /// private void StartExpressionEvaluation() { @@ -656,7 +740,7 @@ public class AlarmActor : ReceiveActor // compile-checked pre-deploy. var state = await expression.RunAsync( new TriggerExpressionGlobals(snapshot), cancellationToken: cts.Token); - return state.ReturnValue is bool b && b; + return (bool?)(state.ReturnValue is bool b && b); } finally { @@ -666,14 +750,11 @@ public class AlarmActor : ReceiveActor catch (Exception ex) { // OperationCanceledException (timeout, INCLUDING one that fired while still - // waiting on the gate) falls through here too and is treated as false. - // _healthCollector (Interlocked) and _logger are thread-safe, so this catch - // is safe off the actor thread. - _healthCollector?.IncrementAlarmError(); - _logger.LogError(ex, - "Alarm {Alarm} trigger expression evaluation failed on {Instance}; treated as false", - _alarmName, _instanceName); - return false; + // waiting on the gate) falls through here too. The outcome is UNKNOWN (null), + // never false (SRT-2). ReportEvalError touches only thread-safe members, so this + // catch is safe off the actor thread. + ReportEvalError(ex); + return null; } finally { @@ -694,7 +775,9 @@ public class AlarmActor : ReceiveActor _evalInFlight = false; try { - ApplyTriggeredState(msg.Result, msg.SourceExecutionId); + // Unknown (the evaluation threw or timed out): keep the current state (SRT-2). + if (msg.Result is { } result) + ApplyTriggeredState(result, msg.SourceExecutionId); } catch (Exception ex) { @@ -708,18 +791,37 @@ public class AlarmActor : ReceiveActor /// /// Applies a faulted off-dispatcher evaluation task (N2): logs the fault, then - /// delegates to the false result (per the class contract — a throwing expression - /// is treated as false so the state machine still runs, an Active alarm clears) - /// which clears in-flight and drains any pending evaluation. Without this the - /// alarm trigger would be permanently parked with _evalInFlight stuck true. + /// delegates to the UNKNOWN result (SRT-2 — the alarm keeps its state), which clears + /// in-flight and drains any pending evaluation. Without this the alarm trigger would + /// be permanently parked with _evalInFlight stuck true. /// private void HandleExpressionEvalFailed(ExpressionEvalFailed msg) + { + ReportEvalError(msg.Cause); + HandleExpressionEvalResult(new ExpressionEvalResult(null, msg.SourceExecutionId)); + } + + /// One "evaluation failed" site event per minute per alarm (SRT-2). + private readonly EventRateLimiter _evalErrorEvents = new(TimeSpan.FromMinutes(1)); + + /// + /// Records a failed/timed-out trigger-expression evaluation: alarm-error counter and node log + /// every time, a site_events Warning at most once a minute. Thread-safe (called from the + /// off-dispatcher evaluation task). + /// + private void ReportEvalError(Exception ex) { _healthCollector?.IncrementAlarmError(); - _logger.LogError(msg.Cause, - "Alarm {Alarm} trigger-expression evaluation task faulted on {Instance}; treated as false", + _logger.LogError(ex, + "Alarm {Alarm} trigger expression evaluation failed on {Instance}; alarm state unchanged", _alarmName, _instanceName); - HandleExpressionEvalResult(new ExpressionEvalResult(false, msg.SourceExecutionId)); + if (_evalErrorEvents.TryAcquire(out var suppressed)) + { + var note = suppressed > 0 ? $" ({suppressed} more failure(s) since the last event)" : string.Empty; + LogAlarmEvent("Warning", + $"Alarm '{_alarmName}' on '{_instanceName}': trigger expression could not be evaluated " + + $"({ex.GetType().Name}: {ex.Message}); alarm state left unchanged{note}"); + } } /// @@ -1032,7 +1134,9 @@ public class AlarmActor : ReceiveActor /// to the execution that actually wrote the value it evaluated — not to a /// later change that arrived while the evaluation was in flight. /// - private sealed record ExpressionEvalResult(bool Result, Guid? SourceExecutionId = null); + /// The truth value, or null when the evaluation threw or timed out (SRT-2: keep state). + /// Writer of the newest value in the evaluated snapshot. + private sealed record ExpressionEvalResult(bool? Result, Guid? SourceExecutionId = null); /// /// Piped back to self when the off-dispatcher evaluation TASK itself faults diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/DeploymentManagerActor.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/DeploymentManagerActor.cs index 7fdb1b5b..02bfb357 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/DeploymentManagerActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/DeploymentManagerActor.cs @@ -3423,7 +3423,14 @@ public class DeploymentManagerActor : ReceiveActor, IWithTimers // Flow Debugger (design 2026-09-05 §5.2): the trace flag rides beside the parent id. Trace: request.Trace); var sender = Sender; - instanceActor.Ask(scriptCall, TimeSpan.FromSeconds(30)) + // SRT-13: wait as long as the TARGET SCRIPT may run — its resolved execution timeout + // (enqueue-anchored, so the run replies by then even if it queued) plus the + // stuck-script grace and a small margin — not a hard-coded 30 s. A 120 s handshake + // script used to fail its inbound caller at 30 s while it ran on and completed its + // device writes, so a retrying caller ran the handshake twice. + RoutedCallTimeoutAsync(instanceActor, request.ScriptName) + .ContinueWith(timeout => instanceActor.Ask(scriptCall, timeout.Result)) + .Unwrap() .ContinueWith(t => { if (t.IsCompletedSuccessfully) @@ -3466,6 +3473,30 @@ public class DeploymentManagerActor : ReceiveActor, IWithTimers } } + /// Slack on top of a routed script's own timeout before the routed Ask gives up. + internal static readonly TimeSpan RoutedCallMargin = TimeSpan.FromSeconds(5); + + /// + /// SRT-13: the routed-call Ask timeout for — its resolved execution + /// timeout plus the stuck-script grace and . Falls back to the + /// site default timeout when the instance cannot answer (never faults). + /// + private Task RoutedCallTimeoutAsync(IActorRef instanceActor, string scriptName) => + RoutedCallTimeoutAsync(instanceActor, scriptName, _options); + + /// + internal static Task RoutedCallTimeoutAsync(IActorRef instanceActor, string scriptName, SiteRuntimeOptions options) + { + var slack = TimeSpan.FromMilliseconds(Math.Max(0, options.StuckScriptGraceMs)) + RoutedCallMargin; + var fallback = TimeSpan.FromSeconds(options.ScriptExecutionTimeoutSeconds) + slack; + return instanceActor + .Ask( + new InstanceActor.GetScriptExecutionTimeout(scriptName), TimeSpan.FromSeconds(5)) + .ContinueWith(t => t.IsCompletedSuccessfully && t.Result.Timeout is { } scriptTimeout + ? scriptTimeout + slack + : fallback, TaskScheduler.Default); + } + /// /// Projects a routed script's return value to a cross-process-serializable plain /// CLR graph ( / / diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/EventRateLimiter.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/EventRateLimiter.cs new file mode 100644 index 00000000..edb09009 --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/EventRateLimiter.cs @@ -0,0 +1,39 @@ +namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Actors; + +/// +/// Thread-safe "at most one per interval" gate for an operational site event that a failure +/// path could otherwise emit on every occurrence — e.g. a trigger expression that times out on +/// every attribute change during a burst (2026-12-02 review SRT-2). The node log and the health +/// counter still record every occurrence; only the site_events row is rate-limited. +/// +internal sealed class EventRateLimiter +{ + private readonly long _intervalMs; + private long _nextAllowedMs = long.MinValue; + private int _suppressed; + + /// Creates a limiter that admits one event per . + /// Minimum spacing between admitted events. + public EventRateLimiter(TimeSpan interval) => _intervalMs = (long)interval.TotalMilliseconds; + + /// + /// True when an event may be emitted now; the caller then emits it, naming + /// occurrences that were dropped since the previous one. + /// + /// Occurrences suppressed since the last admitted event. + /// Whether the event is admitted. + public bool TryAcquire(out int suppressedSinceLast) + { + var now = Environment.TickCount64; + var next = Interlocked.Read(ref _nextAllowedMs); + if (now >= next && Interlocked.CompareExchange(ref _nextAllowedMs, now + _intervalMs, next) == next) + { + suppressedSinceLast = Interlocked.Exchange(ref _suppressed, 0); + return true; + } + + Interlocked.Increment(ref _suppressed); + suppressedSinceLast = 0; + return false; + } +} diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs index 9b554c6e..e5f6e24f 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs @@ -153,6 +153,16 @@ public class InstanceActor : ReceiveActor internal sealed record StaticOverridesFlushed(IActorRef Actor, Exception? Error); + /// + /// SRT-13: asks for a script's resolved execution timeout (per-script override, else the + /// site default) so a routed inbound call waits as long as the script is allowed to run + /// instead of a hard-coded 30 s. + /// + internal sealed record GetScriptExecutionTimeout(string ScriptName); + + /// Reply to ; null when the script is unknown. + internal sealed record ScriptExecutionTimeoutReply(TimeSpan? Timeout); + /// /// Cached string forms of — the TagValueUpdate ingest path calls this once or twice per update, so a /// static lookup replaces repeated reflection. @@ -329,6 +339,16 @@ public class InstanceActor : ReceiveActor // Defaults to 100 ms, mirroring NativeAlarmActor's persistFlushInterval (P4). _staticOverrideFlushInterval = staticOverrideFlushInterval ?? TimeSpan.FromMilliseconds(100); _staticStateResetGate = staticStateResetGate; + // SRT-12: the first static-override flush is ordered AFTER the redeploy reset. A value + // script on the new instance can write a static attribute within the first ~100 ms; its + // flush ran on its own connection with no ordering against the (slower, lock-contended) + // clear, so the clear could land afterwards and delete it — in memory but not on disk, + // silently reverted by the next restart. The reset's own fault is ignored here (the + // deploy fails on it through its persistence join). + if (staticStateResetGate != null) + _staticOverridePersistTail = staticStateResetGate.ContinueWith( + static _ => { }, CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); _configuration = configuration; @@ -391,6 +411,7 @@ public class InstanceActor : ReceiveActor // Handle script call requests — route to appropriate Script Actor (Ask pattern) Receive(HandleScriptCallRequest); + Receive(HandleGetScriptExecutionTimeout); // Handle attribute value changes from DCL (Tell pattern) Receive(HandleAttributeValueChanged); @@ -769,6 +790,15 @@ public class InstanceActor : ReceiveActor if (!_overridesLoaded) _staticWritesBeforeOverrideLoad.Add(command.AttributeName); + // SRT-11: a successful write refreshes the stored quality and timestamp with the value. + // A List attribute loaded Bad (malformed default/override) used to stay Bad for the + // actor's lifetime — GetAttribute, the Debug View snapshot and a requireGoodQuality + // waiter all saw Bad while the stream said Good — and a static attribute had no stored + // timestamp at all, so every snapshot stamped it "now". + var writtenAt = DateTimeOffset.UtcNow; + _attributeQualities[command.AttributeName] = "Good"; + _attributeTimestamps[command.AttributeName] = writtenAt; + // Publish attribute change to stream and notify children var changed = new AttributeValueChanged( _instanceUniqueName, @@ -776,7 +806,7 @@ public class InstanceActor : ReceiveActor command.AttributeName, command.Value, "Good", - DateTimeOffset.UtcNow, + writtenAt, // (ParentExecutionId tag-cascade): carry the writing // execution's id onto the change so a child Alarm Actor this write // trips can chain its on-trigger script run under the writer. Null for @@ -1077,6 +1107,32 @@ public class InstanceActor : ReceiveActor /// Routes script call requests to the appropriate Script Actor. /// Uses Ask pattern. /// + /// + /// SRT-12: the native-alarm rehydration read, chained behind + /// when this start is a (re)deploy; null (the actor reads directly) on every other start. + /// + private Task>? GatedNativeAlarmRead(string sourceCanonicalName) + { + if (_staticStateResetGate == null) + return null; + var storage = _storage; + var instanceName = _instanceUniqueName; + return _staticStateResetGate + .ContinueWith(_ => storage.GetNativeAlarmsAsync(instanceName, sourceCanonicalName), + CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default) + .Unwrap(); + } + + private void HandleGetScriptExecutionTimeout(GetScriptExecutionTimeout request) + { + var script = _configuration?.Scripts.FirstOrDefault(s => s.CanonicalName == request.ScriptName); + Sender.Tell(new ScriptExecutionTimeoutReply(script is null + ? null + : TimeSpan.FromSeconds(script.ExecutionTimeoutSeconds is { } perScript && perScript > 0 + ? perScript + : _options.ScriptExecutionTimeoutSeconds))); + } + private void HandleScriptCallRequest(ScriptCallRequest request) { if (_scriptActors.TryGetValue(request.ScriptName, out var scriptActor)) @@ -1415,11 +1471,16 @@ public class InstanceActor : ReceiveActor private void HandleConnectionQualityChanged(ConnectionQualityChanged qualityChanged) { - _logger.LogWarning("Connection {Connection} quality changed to {Quality} for instance {Instance}", - qualityChanged.ConnectionName, qualityChanged.Quality, _instanceUniqueName); + if (qualityChanged.Quality == QualityCode.Good) + _logger.LogInformation("Connection {Connection} restored for instance {Instance}", + qualityChanged.ConnectionName, _instanceUniqueName); + else + _logger.LogWarning("Connection {Connection} quality changed to {Quality} for instance {Instance}", + qualityChanged.ConnectionName, qualityChanged.Quality, _instanceUniqueName); // Lever 1 (2026-08-28): a connection returning to Good is the Instance Actor's - // only restore signal (the DCL re-subscribes transparently). If our own subscribe + // only restore signal (the DCL re-subscribes transparently; it sends Good when the + // connection re-enters Connected — SRT-6, WP3 task 3.8). If our own subscribe // on it is still unconfirmed, retry at the floor now rather than in up to // TagSubscribeRetryMaxIntervalMs — recovery must be prompt. Timer != null ⇔ the // subscribe is unconfirmed (it is only nulled by a Success); if a request is in @@ -1436,6 +1497,12 @@ public class InstanceActor : ReceiveActor ArmTagSubscribeWatchdog(qualityChanged.ConnectionName, subState); } + // Good is a restore signal ONLY (decided 2026-12-03, SRT-6): it must NOT stamp the + // bound attributes Good with their last-known values — those values are from before + // the outage, and the device has not re-reported yet. Per-tag quality comes back + // through the DCL's re-subscribe and re-seed as ordinary TagValueUpdates. + if (qualityChanged.Quality == QualityCode.Good) return; + if (_configuration == null) return; // Mark all attributes bound to this connection with the new quality @@ -2297,6 +2364,11 @@ public class InstanceActor : ReceiveActor } var nativeKind = ResolveNativeKind(nativeSource.ConnectionName); + // SRT-12: on a (re)deploy the native-alarm rehydration read is chained behind the + // reset gate too — not only the override load — so the successor can only observe the + // CLEARED native_alarm_state, never re-emit the predecessor's conditions (stale alarms + // from an old binding that no snapshot would ever reconcile if the source is down). + var rehydrationRead = GatedNativeAlarmRead(nativeSource.CanonicalName); var props = Props.Create(() => new NativeAlarmActor( nativeSource, _instanceUniqueName, @@ -2306,7 +2378,9 @@ public class InstanceActor : ReceiveActor _options, _logger, nativeKind, - _serviceProvider)); + _serviceProvider, + null, + rehydrationRead)); var actorRef = TryCreateChild( props, $"native-alarm-{nativeSource.CanonicalName}", "Native alarm source", nativeSource.CanonicalName); diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/ScriptActor.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/ScriptActor.cs index 86c5b664..d09108b9 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/ScriptActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/ScriptActor.cs @@ -366,7 +366,8 @@ public class ScriptActor : ReceiveActor, IWithTimers /// to date — a Conditional's truth value, an Expression's last result (evaluated, never fired) — /// so the NEXT real change is judged against the real value: no spurious edge from the replay, /// and no missed edge afterwards. A WhileTrue trigger whose condition already holds is seeded - /// true without starting its re-fire timer; it fires on its next false→true edge. + /// true WITH its re-fire timer running but without the immediate edge run (2026-12-02 review + /// SRT-4 — it used to lose its periodic re-fire until the condition went false and back). /// private void HandleAttributeValueSeed(Messages.AttributeValueSeed seed) { @@ -376,7 +377,10 @@ public class ScriptActor : ReceiveActor, IWithTimers if (_triggerConfig is ConditionalTriggerConfig conditional && conditional.AttributeName == changed.AttributeName) { - _conditionState = EvaluateCondition(conditional, changed.Value); + var seeded = EvaluateCondition(conditional, changed.Value); + if (conditional.Mode == TriggerMode.WhileTrue) + AdoptWhileTrueFromSeed(seeded, _conditionState); + _conditionState = seeded; } else if (_triggerConfig is ExpressionTriggerConfig) { @@ -441,7 +445,7 @@ public class ScriptActor : ReceiveActor, IWithTimers // compile-checked pre-deploy. var state = await expression.RunAsync( new TriggerExpressionGlobals(snapshot), cancellationToken: cts.Token); - return state.ReturnValue is bool b && b; + return (bool?)(state.ReturnValue is bool b && b); } finally { @@ -451,12 +455,15 @@ public class ScriptActor : ReceiveActor, IWithTimers catch (Exception ex) { // OperationCanceledException (timeout, INCLUDING a timeout that fired while - // still waiting on the gate) falls through here too and is treated as false. + // still waiting on the gate) falls through here too. The outcome is UNKNOWN + // (null), never false (2026-12-02 review SRT-2): coercing it to false stopped a + // WhileTrue timer / re-armed an OnTrue edge, so the next successful evaluation + // fired an extra run for a condition that never went false. // LogExpressionError touches only thread-safe members (_healthCollector - // Interlocked, _logger, DI-resolved singleton logger) so it is safe off the - // actor thread. + // Interlocked, _logger, DI-resolved singleton logger, the rate limiter) so it is + // safe off the actor thread. LogExpressionError(ex); - return false; + return null; } finally { @@ -476,17 +483,22 @@ public class ScriptActor : ReceiveActor, IWithTimers private void HandleExpressionEvalResult(ExpressionEvalResult msg) { _evalInFlight = false; - if (_triggerConfig is ExpressionTriggerConfig exprConfig) + // Unknown (the evaluation threw or timed out): adopt nothing, fire nothing (SRT-2). + if (_triggerConfig is ExpressionTriggerConfig exprConfig && msg.Result is { } result) { if (msg.SeedOnly) { - // 01/SR-U1: a seed adopts the truth value and never fires. + // 01/SR-U1: a seed adopts the truth value and never fires — but a WhileTrue + // trigger it leaves true keeps re-firing on its cadence (SRT-4), exactly as it + // did before the restart that made this a seed. + if (exprConfig.Mode == TriggerMode.WhileTrue) + AdoptWhileTrueFromSeed(result, _lastExpressionResult); } else if (exprConfig.Mode == TriggerMode.WhileTrue) - HandleWhileTrueTransition(msg.Result, _lastExpressionResult); - else if (msg.Result && !_lastExpressionResult) + HandleWhileTrueTransition(result, _lastExpressionResult); + else if (result && !_lastExpressionResult) TrySpawnExecution(null); - _lastExpressionResult = msg.Result; + _lastExpressionResult = result; } if (_evalPending) { @@ -497,29 +509,34 @@ public class ScriptActor : ReceiveActor, IWithTimers /// /// Applies a faulted off-dispatcher evaluation task (N2): logs the fault via the - /// existing error path (which also increments the health counter), then reuses the - /// false-result path — clearing in-flight, applying the false edge, and draining any - /// pending evaluation — so a transient scheduler fault cannot permanently park the trigger. - /// A faulted SEED evaluation (review 2026-10-21 follow-up L4) carries no truth value at all: - /// it only clears in-flight and drains the pending evaluation, adopting nothing — replaying it - /// as a real false stopped a running WhileTrue timer, and even as a seeded false it would make - /// the next true evaluation look like a fresh edge and fire spuriously. + /// existing error path (which also increments the health counter), then clears in-flight + /// and drains any pending evaluation, so a transient scheduler fault cannot permanently + /// park the trigger. A faulted evaluation carries no truth value at all and adopts nothing + /// (review 2026-10-21 follow-up L4 for seeds; 2026-12-02 review SRT-2 for real changes) — + /// replaying it as a false stopped a running WhileTrue timer, and made the next true + /// evaluation look like a fresh edge and fire spuriously. /// private void HandleExpressionEvalFailed(ExpressionEvalFailed msg) { + // A faulted evaluation — seed or real — carries no truth value: clear in-flight, drain + // the pending evaluation, adopt nothing (SRT-2; the seed case was already so, L4). LogExpressionError(msg.Cause); - if (!msg.SeedOnly) - { - HandleExpressionEvalResult(new ExpressionEvalResult(false)); - return; - } + HandleExpressionEvalResult(new ExpressionEvalResult(null, msg.SeedOnly)); + } - _evalInFlight = false; - if (_evalPending) - { - _evalPending = false; - StartExpressionEvaluation(_evalPendingSeedOnly); - } + /// + /// SRT-4 (2026-12-02 review): a seed that leaves a WhileTrue trigger's condition TRUE starts + /// the periodic re-fire timer WITHOUT the immediate edge run (a seed never fires — 01/SR-U1); + /// one that leaves it false stops it. Before this, a WhileTrue script whose condition was + /// adopted from a persisted static override (failover, restart, disable/enable) never + /// re-fired again until the condition went false and back to true. + /// + private void AdoptWhileTrueFromSeed(bool nowTrue, bool wasTrue) + { + if (nowTrue && !wasTrue) + StartWhileTrueTimer(); + else if (!nowTrue && wasTrue) + StopWhileTrueTimer(); } /// @@ -586,13 +603,23 @@ public class ScriptActor : ReceiveActor, IWithTimers private void LogExpressionError(Exception ex) { _healthCollector?.IncrementScriptError(); - var errorMsg = $"Trigger expression for script '{_scriptName}' on instance '{_instanceName}' failed: {ex.Message}"; - _logger.LogError(ex, "Trigger expression evaluation failed: {Script} on {Instance}", _scriptName, _instanceName); + _logger.LogError(ex, "Trigger expression evaluation failed: {Script} on {Instance}; trigger state unchanged", + _scriptName, _instanceName); + // The site_events row is rate-limited (SRT-2): a burst that times out every evaluation + // would otherwise mint one Error row per attribute change. + if (!_evalErrorEvents.TryAcquire(out var suppressed)) + return; + var note = suppressed > 0 ? $" ({suppressed} more failure(s) since the last event)" : string.Empty; + var errorMsg = $"Trigger expression for script '{_scriptName}' on instance '{_instanceName}' failed: {ex.Message}; " + + $"trigger state left unchanged{note}"; _ = _serviceProvider?.GetService()?.LogEventAsync( "script", "Error", _instanceName, $"ScriptActor:{_scriptName}", errorMsg, ex.ToString()); } + /// One "trigger expression failed" site event per minute per script (SRT-2). + private readonly EventRateLimiter _evalErrorEvents = new(TimeSpan.FromMinutes(1)); + /// /// Attempts to spawn a script execution, respecting MinTimeBetweenRuns. /// @@ -952,7 +979,9 @@ public class ScriptActor : ReceiveActor, IWithTimers /// carries the boolean truth value so the OnTrue/WhileTrue edge logic runs on /// the actor thread. /// - private sealed record ExpressionEvalResult(bool Result, bool SeedOnly = false); + /// The truth value, or null when the evaluation threw or timed out (SRT-2: adopt nothing). + /// Whether this evaluation only seeds the edge state (01/SR-U1). + private sealed record ExpressionEvalResult(bool? Result, bool SeedOnly = false); /// /// Piped back to self when the off-dispatcher evaluation TASK itself faults diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/ScriptRunLauncher.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/ScriptRunLauncher.cs index ff0f0ebc..8335a589 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/ScriptRunLauncher.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/ScriptRunLauncher.cs @@ -281,18 +281,16 @@ internal static class ScriptRunLauncher var emitPerRunEvents = ScriptRunEventPolicy.ShouldEmitPerRun(effectiveOptions, instanceName, scriptName); var runStopwatch = Stopwatch.StartNew(); - // Identify the worker this body is holding, so the watchdog can detach and - // replace it if the body wedges. Read in the FIRST synchronous segment — a script - // that later hops threads on an await no longer holds this worker, and the run-stamp - // guard in TryDetachWorker will (correctly) refuse to detach it. - var workerSlot = ScriptExecutionScheduler.CurrentWorkerSlot; - var workerRunStamp = workerSlot is { } slot ? executionScheduler.CurrentRunStamp(slot) : 0L; + // Track the worker this body is holding — not just in this first segment but after + // every await (SRT-1): each continuation runs on whichever worker dequeues it, under a + // new run stamp, so the watchdog reads the LATEST (slot, stamp) when it fires. + var workerTracker = ScriptRunWorkerTracker.Begin(executionScheduler); IDisposable? logScope = null; var completed = 0; ArmStuckScriptWatchdog( cts, options, logger, siteEventLogger, executionScheduler, - workerSlot, workerRunStamp, timeout, + workerTracker, timeout, () => Volatile.Read(ref completed) != 0, $"Script '{scriptName}' on instance '{instanceName}'", instanceName, $"ScriptActor:{scriptName}"); @@ -480,7 +478,11 @@ internal static class ScriptRunLauncher // Notify the owning ScriptActor of completion (also releases its in-flight slot). completionTarget.Tell(new ScriptActor.ScriptExecutionCompleted(scriptName, true, null)); } - catch (OperationCanceledException) + // Only the run's OWN deadline is a timeout (SRT-10). Any other cancellation — an HTTP + // client's internal timeout, a script's own CancellationTokenSource, a cancelled read — + // falls through to the general failure path below with its real exception and stack, + // instead of being reported as "timed out after N s" for a run that lasted 5 s. + catch (OperationCanceledException) when (cts.IsCancellationRequested) { healthCollector?.IncrementScriptError(); summaryRecorder?.RecordTimedOut(instanceName, scriptName, runStopwatch.ElapsedMilliseconds); @@ -714,18 +716,16 @@ internal static class ScriptRunLauncher var scriptName = $"AlarmActor:{alarmName}"; var runStopwatch = Stopwatch.StartNew(); - // Identify the worker this body is holding, so the - // stuck-script watchdog can detach and replace it if the body wedges — same - // mechanism, same gauge, as the instance-script path. Read in the FIRST synchronous - // segment, before any await. - var workerSlot = ScriptExecutionScheduler.CurrentWorkerSlot; - var workerRunStamp = workerSlot is { } slot ? executionScheduler.CurrentRunStamp(slot) : 0L; + // Track the worker this body is holding, so the stuck-script watchdog can detach and + // replace it if the body wedges — same mechanism, same gauge, as the instance-script + // path, and likewise followed across awaits (SRT-1). + var workerTracker = ScriptRunWorkerTracker.Begin(executionScheduler); IDisposable? logScope = null; var completed = 0; ArmStuckScriptWatchdog( cts, options, logger, siteEventLogger, executionScheduler, - workerSlot, workerRunStamp, timeout, + workerTracker, timeout, () => Volatile.Read(ref completed) != 0, $"Alarm on-trigger script for '{alarmName}' on instance '{instanceName}'", instanceName, scriptName); @@ -802,7 +802,8 @@ internal static class ScriptRunLauncher summaryRecorder?.RecordCompleted(instanceName, scriptName, runStopwatch.ElapsedMilliseconds); completionTarget.Tell(new AlarmActor.AlarmExecutionCompleted(alarmName, true)); } - catch (OperationCanceledException) + // Only the run's own deadline is a timeout (SRT-10); see RunScriptAsync. + catch (OperationCanceledException) when (cts.IsCancellationRequested) { healthCollector?.IncrementScriptError(); summaryRecorder?.RecordTimedOut(instanceName, scriptName, runStopwatch.ElapsedMilliseconds); @@ -854,8 +855,7 @@ internal static class ScriptRunLauncher ILogger logger, ISiteEventLogger? siteEventLogger, ScriptExecutionScheduler scheduler, - int? workerSlot, - long workerRunStamp, + ScriptRunWorkerTracker workerTracker, TimeSpan timeout, Func isCompleted, string subject, @@ -871,6 +871,8 @@ internal static class ScriptRunLauncher var stuckMsg = $"{subject} exceeded its {timeout.TotalSeconds:F0}s timeout and is STILL EXECUTING — " + "its dedicated script-execution thread is blocked (cooperative cancellation not observed)."; + // The worker the run holds NOW — after any number of awaits (SRT-1). + var (workerSlot, workerRunStamp) = workerTracker.Snapshot(); var outcome = workerSlot is { } slot ? scheduler.TryDetachWorker(slot, workerRunStamp) : WorkerDetachOutcome.NotRunning; diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/ScriptRunWorkerTracker.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/ScriptRunWorkerTracker.cs new file mode 100644 index 00000000..cbf08159 --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/ScriptRunWorkerTracker.cs @@ -0,0 +1,111 @@ +namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts; + +/// +/// Tracks WHICH script-execution worker a run is holding right now, for the stuck-script +/// watchdog (2026-12-02 review SRT-1). +/// +/// The launcher used to capture (slot, runStamp) once, in the run's first synchronous +/// segment. But a script's await continuation is a NEW task queued back onto the scheduler, +/// dequeued by whichever worker is free under a NEW run stamp — so once the script had awaited +/// anything (practically every script reads an attribute before doing I/O), the watchdog's +/// captured pair no longer matched, TryDetachWorker answered NotRunning, and a +/// worker wedged in blocking I/O was never detached or replaced. +/// +/// +/// The run's tracker flows with its through an +/// whose change callback fires every time a piece of the run starts +/// (context restored on a thread) or stops (context reverted) executing. On start it records the +/// current thread's worker slot and that worker's current run stamp; on stop it clears them if +/// that worker was the recorded one. A run blocked inside a continuation therefore keeps the +/// latest (slot, stamp) of the worker it is actually blocking, while a run parked in an +/// await (holding no thread) reads as "not on a worker". +/// +/// +internal sealed class ScriptRunWorkerTracker +{ + private static readonly AsyncLocal Current = new(OnContextChanged); + + private readonly ScriptExecutionScheduler _scheduler; + private readonly object _gate = new(); + private int _slot = -1; + private long _stamp; + + private ScriptRunWorkerTracker(ScriptExecutionScheduler scheduler) => _scheduler = scheduler; + + /// + /// Starts tracking the calling run: records the worker the caller is on (if any) and installs + /// the tracker in the run's execution context so every later continuation updates it. Call in + /// the run's first synchronous segment. + /// + /// The scheduler whose workers run this script. + /// The run's tracker. + public static ScriptRunWorkerTracker Begin(ScriptExecutionScheduler scheduler) + { + var tracker = new ScriptRunWorkerTracker(scheduler); + tracker.OnEnter(); + Current.Value = tracker; + return tracker; + } + + /// + /// The worker the run is executing on right now, as (slot, runStamp); a null slot when + /// the run holds no script-execution worker (parked in an await, or on another thread). + /// + /// The latest observed worker slot and its run stamp. + public (int? Slot, long RunStamp) Snapshot() + { + lock (_gate) + return _slot >= 0 ? (_slot, _stamp) : (null, 0L); + } + + private static void OnContextChanged(AsyncLocalValueChangedArgs args) + { + // Only thread switches matter; the explicit set in Begin already recorded the worker. + if (!args.ThreadContextChanged) + return; + try + { + if (args.PreviousValue is { } leaving && !ReferenceEquals(leaving, args.CurrentValue)) + leaving.OnLeave(); + if (args.CurrentValue is { } entering && !ReferenceEquals(entering, args.PreviousValue)) + entering.OnEnter(); + } + catch + { + // Never let diagnostics bookkeeping fault an execution-context switch. + } + } + + private void OnEnter() + { + // Only a script-execution worker is recorded. The run's execution context also flows to + // threads that hold no worker — a thread-pool continuation, or the watchdog's own + // timer callback, which captured the context when it was registered — and those must + // NOT erase the worker a still-running segment is blocking. A stale record is harmless: + // OnLeave clears it when that worker's segment ends, and TryDetachWorker re-checks the + // run stamp before detaching anything. + if (ScriptExecutionScheduler.CurrentWorkerSlot is not { } slot) + return; + var stamp = _scheduler.CurrentRunStamp(slot); + if (stamp == 0) + return; + lock (_gate) + { + _slot = slot; + _stamp = stamp; + } + } + + private void OnLeave() + { + var slot = ScriptExecutionScheduler.CurrentWorkerSlot; + lock (_gate) + { + if (slot is { } s && s == _slot) + { + _slot = -1; + _stamp = 0; + } + } + } +} diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/ScriptRuntimeContext.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/ScriptRuntimeContext.cs index 51243bbd..480914b8 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/ScriptRuntimeContext.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/ScriptRuntimeContext.cs @@ -728,7 +728,10 @@ public class ScriptRuntimeContext // ScadaBridge#56: the Instance Actor logs under this run's id while serving it. SourceExecutionId: _executionId); - var response = await _instanceActor.Ask(request, _askTimeout).ConfigureAwait(false); + // SRT-9: the run's deadline token cancels the wait, so a run parked here takes the timeout + // path at its deadline instead of sailing past it (Roslyn only observes the token between + // top-level statements). + var response = await _instanceActor.Ask(request, _askTimeout, _scriptTimeoutToken).ConfigureAwait(false); if (!response.Found) { @@ -940,7 +943,8 @@ public class ScriptRuntimeContext { // Ask — mutation serialized through the Instance Actor mailbox; the reply // carries the device-write outcome for data-connected attributes. - response = await _instanceActor.Ask(command, _askTimeout).ConfigureAwait(false); + // SRT-9: bounded by the run's deadline too (a data-sourced write waits out the DCL Ask). + response = await _instanceActor.Ask(command, _askTimeout, _scriptTimeoutToken).ConfigureAwait(false); } catch (Exception ex) when (sw is not null) { @@ -1217,7 +1221,9 @@ public class ScriptRuntimeContext Trace: _isTraced); // Ask the Instance Actor, which routes to the appropriate Script Actor - var result = await _instanceActor.Ask(request, _askTimeout).ConfigureAwait(false); + // SRT-9: the CALLER's deadline cancels the wait — a nested script that outlives the caller's + // budget no longer lets the caller carry on past its timeout and be recorded as completed. + var result = await _instanceActor.Ask(request, _askTimeout, _scriptTimeoutToken).ConfigureAwait(false); if (!result.Success) { @@ -1313,7 +1319,9 @@ public class ScriptRuntimeContext // threaded so NotifyTarget.Send can stamp it onto NotificationSubmit. _sourceNode, // Flow Debugger: the NotifySend row rides the inline collector (null when untraced). - traceSink: _traceSink); + traceSink: _traceSink, + // SRT-8: Notify.Status's central query is bounded by the run's deadline. + scriptTimeoutToken: _scriptTimeoutToken); /// /// Read-only access to the instance's CURRENT alarm conditions (MES alarm-status API @@ -2678,6 +2686,16 @@ public class ScriptRuntimeContext private readonly TimeSpan _askTimeout; private readonly ILogger _logger; + /// SRT-8: the run's deadline; cancels the central status query. + private readonly CancellationToken _scriptTimeoutToken; + + /// + /// SRT-8: ceiling on the central round trip of — it is a point read, + /// and the script's whole execution budget (_askTimeout) is far too long to wait + /// when central is unreachable. + /// + internal static readonly TimeSpan CentralStatusQueryTimeout = TimeSpan.FromSeconds(10); + /// /// The per-execution id for this script run, stamped /// into AuditEvent.ExecutionId on the NotifySend row. @@ -2730,6 +2748,7 @@ public class ScriptRuntimeContext /// Optional identifier of the parent execution (for routed calls). /// Optional cluster node identifier (node-a/node-b) for audit stamping. /// Flow Debugger inline collector — receives the same Send hands to the writer; null when untraced. + /// The run's deadline; cancels the central status query (SRT-8). // Parameter ordering: executionId sits immediately after the ILogger, // consistent with the other audit-threaded ctors. parentExecutionId is // a trailing optional param. @@ -2745,8 +2764,10 @@ public class ScriptRuntimeContext IAuditWriter? auditWriter = null, Guid? parentExecutionId = null, string? sourceNode = null, - Action? traceSink = null) + Action? traceSink = null, + CancellationToken scriptTimeoutToken = default) { + _scriptTimeoutToken = scriptTimeoutToken; _storeAndForward = storeAndForward; _siteCommunicationActor = siteCommunicationActor; _siteId = siteId; @@ -2789,12 +2810,13 @@ public class ScriptRuntimeContext /// /// Queries the delivery status of a previously-sent notification. /// - /// The query is issued to central via the site communication actor. While the - /// notification is still buffered in the site Store-and-Forward Engine — central - /// has no row for it yet (Found: false) but the buffer still holds the id — - /// the status is reported as the site-local Forwarding state. If central - /// has a row, its status is mapped through verbatim. If central does not know the - /// id and it is not buffered locally, the status is Unknown. + /// While the notification is still buffered in the site Store-and-Forward Engine it is + /// answered site-locally as Forwarding — checked FIRST (2026-12-02 review SRT-8), + /// so the common "central unreachable, still buffered" case never waits on central. + /// Otherwise the query goes to central (bounded by + /// and the run's deadline) and a central row's status is mapped through verbatim. If central + /// does not know the id (or cannot be reached) and it is not buffered, the status is + /// Unknown. /// /// The notification identifier returned from Send. /// The delivery status of the notification. @@ -2804,19 +2826,24 @@ public class ScriptRuntimeContext throw new InvalidOperationException( "Notification status query is not available — site communication actor not wired"); + // Site-local first: still in the buffer ⇒ in transit, whatever central knows. + if (await TryBufferedStatusAsync(notificationId).ConfigureAwait(false) is { } forwarding) + return forwarding; + var correlationId = Guid.NewGuid().ToString(); var query = new NotificationStatusQuery(correlationId, notificationId); + var centralTimeout = _askTimeout < CentralStatusQueryTimeout ? _askTimeout : CentralStatusQueryTimeout; NotificationStatusResponse response; try { response = await _siteCommunicationActor - .Ask(query, _askTimeout).ConfigureAwait(false); + .Ask(query, centralTimeout, _scriptTimeoutToken).ConfigureAwait(false); } - catch (Exception ex) + catch (Exception ex) when (!_scriptTimeoutToken.IsCancellationRequested) { - // Central could not be reached. Fall through to the buffer check: if the - // notification is still in the local S&F buffer it is Forwarding. + // Central could not be reached. Re-check the buffer: the notification may have + // been enqueued by a sweep race between the local check and here. _logger.LogWarning(ex, "Notification status query for {NotificationId} did not reach central", notificationId); @@ -2831,20 +2858,21 @@ public class ScriptRuntimeContext response.Status, response.RetryCount, response.LastError, response.DeliveredAt); } - // Central has no row. If the notification is still buffered at the site it - // is in transit — report the site-local Forwarding state. Otherwise it is - // genuinely unknown (never sent, or already forwarded and central lost it). - if (_storeAndForward != null) - { - var buffered = await _storeAndForward.GetMessageByIdAsync(notificationId).ConfigureAwait(false); - if (buffered != null) - { - return new NotificationDeliveryStatus( - "Forwarding", buffered.RetryCount, buffered.LastError, DeliveredAt: null); - } - } + // Central has no row. Re-check the buffer (the forwarder may have re-buffered it + // meanwhile); otherwise it is genuinely unknown (never sent, or already forwarded + // and central lost it). + return await TryBufferedStatusAsync(notificationId).ConfigureAwait(false) + ?? new NotificationDeliveryStatus("Unknown", 0, null, null); + } - return new NotificationDeliveryStatus("Unknown", 0, null, null); + private async Task TryBufferedStatusAsync(string notificationId) + { + if (_storeAndForward == null) + return null; + var buffered = await _storeAndForward.GetMessageByIdAsync(notificationId).ConfigureAwait(false); + return buffered == null + ? null + : new NotificationDeliveryStatus("Forwarding", buffered.RetryCount, buffered.LastError, DeliveredAt: null); } } diff --git a/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardService.cs b/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardService.cs index 6d1ebd04..bec02b88 100644 --- a/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardService.cs @@ -916,7 +916,9 @@ public class StoreAndForwardService // rather than burning a full timeout per remaining message. // Skipped rows keep their RetryCount/LastAttemptAt untouched. var outcome = await RetryMessageAsync(message); - if (outcome == RetryOutcome.TransientFailure) + if (outcome is RetryOutcome.TransientFailure + or RetryOutcome.DeliveredNotRemoved + or RetryOutcome.StorageFailure) return; } } @@ -939,8 +941,47 @@ public class StoreAndForwardService /// short-circuit a (category, target) lane after its first transient /// failure. = no attempt was made (no handler, or the /// row's status changed under a concurrent apply); its RetryCount is untouched. + /// = the handler succeeded but the buffer row could + /// not be deleted (SF-2); = the handler answered but the + /// resulting status write failed. Both leave the row Pending with its counters + /// untouched and stop the lane for this sweep, like a transient failure. /// - internal enum RetryOutcome { Delivered, Parked, TransientFailure, Skipped } + internal enum RetryOutcome { Delivered, Parked, TransientFailure, Skipped, DeliveredNotRemoved, StorageFailure } + + /// Attempts the post-delivery delete; how many times before giving up. + internal const int DeliveredRemoveAttempts = 3; + + /// + /// Deletes a delivered message's buffer row, retrying a transient storage error (e.g. + /// SQLITE_BUSY on the shared LocalDb file) a few times. Returns false — after + /// logging an error — when every attempt failed; never throws. + /// + private async Task TryRemoveDeliveredMessageAsync(StoreAndForwardMessage message) + { + for (var attempt = 1; ; attempt++) + { + try + { + await _storage.RemoveMessageAsync(message.Id); + return true; + } + catch (Exception ex) when (attempt < DeliveredRemoveAttempts) + { + _logger.LogWarning(ex, + "Delivered message {MessageId} could not be removed from the buffer (attempt {Attempt}/{Max}); retrying", + message.Id, attempt, DeliveredRemoveAttempts); + await Task.Delay(TimeSpan.FromMilliseconds(50 * attempt)); + } + catch (Exception ex) + { + _logger.LogError(ex, + "Message {MessageId} was DELIVERED to {Target} but could not be removed from the buffer after {Max} attempts; " + + "it stays pending and will be delivered again on the next due sweep", + message.Id, message.Target, DeliveredRemoveAttempts); + return false; + } + } + } private async Task RetryMessageAsync(StoreAndForwardMessage message) { @@ -957,19 +998,35 @@ public class StoreAndForwardService var attemptStartUtc = DateTime.UtcNow; var attemptStopwatch = System.Diagnostics.Stopwatch.StartNew(); + // SF-2: the try covers the delivery attempt ONLY. Bookkeeping after the handler + // has answered (the row delete on success, the park on a permanent failure) is a + // storage operation, not a delivery outcome — a SQLITE_BUSY / disk-full there used + // to land in the transient catch below, which counted a retry against a call that + // had SUCCEEDED and could park it (an operator Retry then re-sent it). + bool success; + Exception? deliveryFailure = null; try { - var success = await handler(message); - attemptStopwatch.Stop(); - if (success) - { - await _storage.RemoveMessageAsync(message.Id); - Interlocked.Decrement(ref _bufferedCount); - RaiseActivity("Delivered", message.Category, - $"Delivered to {message.Target} after {message.RetryCount} retries"); + success = await handler(message); + } + catch (Exception ex) + { + success = false; + deliveryFailure = ex; + } + attemptStopwatch.Stop(); - // Terminal Delivered observer notification — the audit - // bridge maps this to Attempted + CachedResolve(Delivered). + if (deliveryFailure is null && success) + { + if (!await TryRemoveDeliveredMessageAsync(message)) + { + // Delivered, but the row is still Pending in the buffer, so the next due + // sweep will deliver it again (downstream idempotency is the caller's + // responsibility). RetryCount is NOT incremented and the row is NOT parked. + // The lane stops here so the rows behind it are not delivered ahead of the + // (re-)delivery of this one — per-target FIFO holds even for the duplicate. + RaiseActivity("Delivered", message.Category, + $"Delivered to {message.Target} after {message.RetryCount} retries (buffer delete failed; will re-deliver)"); await PostObserverNotification( message, CachedCallAttemptOutcome.Delivered, @@ -977,15 +1034,47 @@ public class StoreAndForwardService httpStatus: null, occurredAtUtc: attemptStartUtc, durationMs: (int)attemptStopwatch.ElapsedMilliseconds); - return RetryOutcome.Delivered; + return RetryOutcome.DeliveredNotRemoved; } + Interlocked.Decrement(ref _bufferedCount); + RaiseActivity("Delivered", message.Category, + $"Delivered to {message.Target} after {message.RetryCount} retries"); + + // Terminal Delivered observer notification — the audit + // bridge maps this to Attempted + CachedResolve(Delivered). + await PostObserverNotification( + message, + CachedCallAttemptOutcome.Delivered, + lastError: null, + httpStatus: null, + occurredAtUtc: attemptStartUtc, + durationMs: (int)attemptStopwatch.ElapsedMilliseconds); + return RetryOutcome.Delivered; + } + + if (deliveryFailure is null) + { // Permanent failure on retry — park immediately. message.Status = StoreAndForwardMessageStatus.Parked; message.LastAttemptAt = DateTimeOffset.UtcNow; message.LastError = "Permanent failure (handler returned false)"; - var parked = await _storage.UpdateMessageIfStatusAsync( - message, StoreAndForwardMessageStatus.Pending); + bool parked; + try + { + parked = await _storage.UpdateMessageIfStatusAsync( + message, StoreAndForwardMessageStatus.Pending); + } + catch (Exception storageEx) + { + // A storage failure writing the park is not a delivery failure: leave the + // row Pending with its counters untouched; the next due sweep re-attempts + // it (and parks it then). Stop the lane, as for any unresolved head. + _logger.LogError(storageEx, + "Message {MessageId} to {Target} failed permanently but the park could not be written; it stays pending", + message.Id, message.Target); + return RetryOutcome.StorageFailure; + } if (!parked) { _logger.LogDebug( @@ -1008,9 +1097,10 @@ public class StoreAndForwardService durationMs: (int)attemptStopwatch.ElapsedMilliseconds); return RetryOutcome.Parked; } - catch (Exception ex) + + // The handler threw: a transient delivery failure. { - attemptStopwatch.Stop(); + var ex = deliveryFailure; // Transient failure — increment retry, check max message.RetryCount++; message.LastAttemptAt = DateTimeOffset.UtcNow; diff --git a/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardStorage.cs b/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardStorage.cs index 8b3b008f..bbb000f3 100644 --- a/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardStorage.cs +++ b/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardStorage.cs @@ -187,10 +187,13 @@ public class StoreAndForwardStorage } /// - /// Gets all messages that are due for retry (Pending status, last attempt older than retry interval). + /// Gets the messages that are due for retry (Pending status, last attempt older than retry + /// interval), restricted per (category, target) lane to the due rows that are not + /// preceded by an older still-pending, not-yet-due row of the same lane — a lane never + /// passes its own backing-off head (SF-1). /// /// Maximum number of messages to return, or 0 for no limit. - /// A task that resolves to the list of messages due for retry, ordered by creation time ascending. + /// A task that resolves to the eligible messages, ordered by lane rank then creation time (enqueue order within each lane). public async Task> GetMessagesForRetryAsync(int limit = 0) { await using var connection = OpenConnection(); @@ -199,38 +202,41 @@ public class StoreAndForwardStorage const string cols = @"id, category, target, payload_json, retry_count, max_retries, retry_interval_ms, created_at, last_attempt_at, status, last_error, origin_instance, execution_id, source_script, parent_execution_id"; - const string due = @"status = @pending - AND (last_attempt_at_ms IS NULL + const string dueExpr = @"(last_attempt_at_ms IS NULL OR retry_interval_ms = 0 OR (@nowMs - last_attempt_at_ms) >= retry_interval_ms)"; - if (limit > 0) - { - // Page FAIRLY across (category, target) lanes: rank each due row within its - // lane (oldest-first) and take the page by rank, so one dead target holding - // hundreds of due rows contributes one row per "round" like every other - // lane instead of owning the whole page. Within a lane rank order == created_at - // order, so per-target FIFO is preserved for the service's GroupBy. - cmd.CommandText = $@" + // Per-target FIFO (SF-1). Due-ness is decided PER LANE, not per row: the window + // runs over EVERY pending row of a (category, target) lane in enqueue order + // (created_at, rowid as the same-instant tie-break), and `blocked_by` counts the + // not-yet-due rows at or before each row. Only the lane prefix with + // blocked_by = 0 is eligible, so a younger row can never be handed out while an + // older row of the same lane is still pending but backing off — previously the + // head's failure pushed ITS last_attempt_at forward while the rows behind it + // kept their older stamps, so a later sweep delivered B before A. It also means + // a dead target is probed once per head retry interval rather than by whichever + // staggered row happened to come due on each sweep. + // + // The page is then taken FAIRLY across lanes by lane rank (review 2026-10-21 + // 02/C2): one dead target holding hundreds of rows contributes one row per + // "round" like every other lane instead of owning the whole page. Within a lane + // rank order == enqueue order, preserved by the service's stable GroupBy. + cmd.CommandText = $@" SELECT {cols} FROM ( SELECT {cols}, - ROW_NUMBER() OVER (PARTITION BY category, target ORDER BY created_at ASC) AS lane_rank + ROW_NUMBER() OVER lane AS lane_rank, + SUM(CASE WHEN {dueExpr} THEN 0 ELSE 1 END) OVER lane AS blocked_by FROM sf_messages - WHERE {due} + WHERE status = @pending + WINDOW lane AS (PARTITION BY category, target ORDER BY created_at ASC, rowid ASC + ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) ) - ORDER BY lane_rank ASC, created_at ASC - LIMIT @limit"; + WHERE blocked_by = 0 + ORDER BY lane_rank ASC, created_at ASC" + + (limit > 0 ? "\n LIMIT @limit" : string.Empty); + if (limit > 0) cmd.Parameters.AddWithValue("@limit", limit); - } - else - { - cmd.CommandText = $@" - SELECT {cols} - FROM sf_messages - WHERE {due} - ORDER BY created_at ASC"; - } cmd.Parameters.AddWithValue("@pending", (int)StoreAndForwardMessageStatus.Pending); cmd.Parameters.AddWithValue("@nowMs", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); diff --git a/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Types/AttributeValueCodecTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Types/AttributeValueCodecTests.cs index 4c8e736b..d714bf22 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Types/AttributeValueCodecTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Types/AttributeValueCodecTests.cs @@ -324,4 +324,89 @@ public class AttributeValueCodecTests public void CoerceEnumerable_ThrowsOnUnsupportedElementType() => Assert.Throws( () => AttributeValueCodec.CoerceEnumerable(new object[] { new byte[] { 1 } }, DataType.Binary)); + + // ── CMN-3: non-finite floating-point list elements ── + + /// A double list holding NaN/±Infinity encodes (no throw) and round-trips. + [Fact] + public void RoundTrip_DoubleList_NonFinite() + { + var json = AttributeValueCodec.Encode( + new List { double.NaN, double.PositiveInfinity, double.NegativeInfinity, 1.5 }); + var back = (IList)AttributeValueCodec.Decode(json, DataType.List, DataType.Double)!; + Assert.True(double.IsNaN(back[0])); + Assert.Equal(double.PositiveInfinity, back[1]); + Assert.Equal(double.NegativeInfinity, back[2]); + Assert.Equal(1.5, back[3]); + } + + /// A float list holding NaN/±Infinity encodes (no throw) and round-trips. + [Fact] + public void RoundTrip_FloatList_NonFinite() + { + var json = AttributeValueCodec.Encode( + new List { float.NaN, float.PositiveInfinity, float.NegativeInfinity }); + var back = (IList)AttributeValueCodec.Decode(json, DataType.List, DataType.Float)!; + Assert.True(float.IsNaN(back[0])); + Assert.Equal(float.PositiveInfinity, back[1]); + Assert.Equal(float.NegativeInfinity, back[2]); + } + + // ── CMN-4: scalar DateTime wire form ── + + /// A UTC scalar DateTime encodes as ISO-8601 round-trip and keeps sub-second precision and Kind. + [Fact] + public void Encode_ScalarUtcDateTime_RoundTripsWithSubSecondPrecision() + { + var dt = new DateTime(2026, 6, 15, 13, 45, 30, 123, DateTimeKind.Utc).AddTicks(4567); + var encoded = AttributeValueCodec.Encode(dt)!; + Assert.Equal("2026-06-15T13:45:30.1234567Z", encoded); + + var back = DateTime.Parse(encoded, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); + Assert.Equal(dt, back); + Assert.Equal(DateTimeKind.Utc, back.Kind); + } + + /// An Unspecified-kind scalar DateTime is taken as UTC (all timestamps are UTC system-wide). + [Fact] + public void Encode_ScalarUnspecifiedDateTime_IsStampedUtc() => + Assert.Equal("2026-06-15T13:45:30.0000000Z", + AttributeValueCodec.Encode(new DateTime(2026, 6, 15, 13, 45, 30, DateTimeKind.Unspecified))); + + /// The scalar DateTime encoding is culture-independent. + [Fact] + public void Encode_ScalarDateTime_IsInvariant() + { + var original = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = new CultureInfo("de-DE"); + Assert.Equal("2026-06-15T13:45:30.5000000Z", + AttributeValueCodec.Encode(new DateTime(2026, 6, 15, 13, 45, 30, 500, DateTimeKind.Utc))); + } + finally + { + CultureInfo.CurrentCulture = original; + } + } + + /// A scalar DateTimeOffset encodes as ISO-8601 round-trip, preserving the offset. + [Fact] + public void Encode_ScalarDateTimeOffset_IsIso8601() => + Assert.Equal("2026-06-15T13:45:30.2500000+00:00", + AttributeValueCodec.Encode(new DateTimeOffset(2026, 6, 15, 13, 45, 30, 250, TimeSpan.Zero))); + + /// + /// Compatibility read: a List element in the pre-CMN-4 scalar form (invariant general + /// format) still decodes next to an element in the new ISO form. + /// + [Fact] + public void Decode_DateTimeList_AcceptsOldAndNewScalarForms() + { + var back = (IList)AttributeValueCodec.Decode( + "[\"06/15/2026 13:45:30\",\"2026-06-15T13:45:30.1230000Z\"]", + DataType.List, DataType.DateTime)!; + Assert.Equal(new DateTime(2026, 6, 15, 13, 45, 30), back[0]); + Assert.Equal(new DateTime(2026, 6, 15, 13, 45, 30, 123, DateTimeKind.Utc), back[1]); + } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Types/DynamicJsonElementTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Types/DynamicJsonElementTests.cs index c2f2f696..5f67f839 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Types/DynamicJsonElementTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Types/DynamicJsonElementTests.cs @@ -205,4 +205,54 @@ public class DynamicJsonElementTests Assert.Throws( () => { var _ = obj.items[idx]; }); } + + // ── CMN-10: JSON null converts to null for nullable targets ── + + private static ConvertBinder ConvertTo(Type t) => + (ConvertBinder)Microsoft.CSharp.RuntimeBinder.Binder.Convert( + Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags.ConvertExplicit, t, typeof(DynamicJsonElementTests)); + + /// A JSON null converts to a null string (not "" and not a binder failure). + [Fact] + public void TryConvert_StringTarget_OnJsonNull_ReturnsNull() + { + var wrapper = new DynamicJsonElement(JsonDocument.Parse("null").RootElement); + Assert.True(wrapper.TryConvert(ConvertTo(typeof(string)), out var result)); + Assert.Null(result); + } + + /// A JSON null converts to a null int?. + [Fact] + public void TryConvert_NullableIntTarget_OnJsonNull_ReturnsNull() + { + var wrapper = new DynamicJsonElement(JsonDocument.Parse("null").RootElement); + Assert.True(wrapper.TryConvert(ConvertTo(typeof(int?)), out var result)); + Assert.Null(result); + } + + /// A JSON null cannot convert to a non-nullable value type: the binder reports failure. + [Fact] + public void TryConvert_IntTarget_OnJsonNull_ReportsFailure() + { + var wrapper = new DynamicJsonElement(JsonDocument.Parse("null").RootElement); + Assert.False(wrapper.TryConvert(ConvertTo(typeof(int)), out _)); + } + + /// A JSON number converts through Nullable<T>'s underlying type. + [Fact] + public void TryConvert_NullableIntTarget_OnNumber_ReturnsValue() + { + var wrapper = new DynamicJsonElement(JsonDocument.Parse("42").RootElement); + Assert.True(wrapper.TryConvert(ConvertTo(typeof(int?)), out var result)); + Assert.Equal(42, result); + } + + /// End to end through the dynamic binder: (string) and (int?) casts of a JSON-null wrapper yield null. + [Fact] + public void DynamicCast_OnJsonNullWrapper_YieldsNull() + { + dynamic wrapper = new DynamicJsonElement(JsonDocument.Parse("null").RootElement); + Assert.Null((string?)wrapper); + Assert.Null((int?)wrapper); + } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Actors/DataConnectionDisconnectedBrowseTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Actors/DataConnectionDisconnectedBrowseTests.cs new file mode 100644 index 00000000..74416d57 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Actors/DataConnectionDisconnectedBrowseTests.cs @@ -0,0 +1,77 @@ +using Akka.Actor; +using Akka.TestKit.Xunit2; +using NSubstitute; +using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Protocol; +using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services; +using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management; +using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Actors; +using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters; +using ZB.MOM.WW.ScadaBridge.HealthMonitoring; + +namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Actors; + +/// +/// DCL-6 (2026-12-02 review, WP3 task 3.4): browse/search while the connection has no session must +/// REPLY with a typed ConnectionNotConnected failure. An adapter that threw synchronously +/// (before returning a task) escaped the actor's faulted-task mapping, so the node-browser dialog +/// waited out its whole Ask timeout and the site logged a "threw exception, resuming" warning. +/// +public class DataConnectionDisconnectedBrowseTests : TestKit +{ + private readonly ISiteHealthCollector _health = Substitute.For(); + private readonly IDataConnectionFactory _factory = Substitute.For(); + + private readonly DataConnectionOptions _options = new() + { + ReconnectInterval = TimeSpan.FromSeconds(30), + WriteTimeout = TimeSpan.FromSeconds(5), + }; + + /// An adapter that throws synchronously still yields a typed reply, in the Connecting state. + [Fact] + public void SynchronousThrowWhileConnecting_RepliesConnectionNotConnected() + { + var adapter = Substitute.For(); + // Never connects: the actor stays in Connecting. + adapter.ConnectAsync(Arg.Any>(), Arg.Any()) + .Returns(new TaskCompletionSource().Task); + ((IBrowsableDataConnection)adapter) + .BrowseChildrenAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns>(_ => throw new ConnectionNotConnectedException("not connected")); + ((IAddressSpaceSearchable)adapter) + .SearchAddressSpaceAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns>(_ => throw new ConnectionNotConnectedException("not connected")); + + var actor = Sys.ActorOf(Props.Create(() => new DataConnectionActor( + "conn", adapter, _options, _health, _factory, "OpcUa"))); + + actor.Tell(new SearchAddressSpaceCommand("conn", "Tag", 5, 100)); + var search = ExpectMsg(TimeSpan.FromSeconds(5)); // pre-fix: no reply + Assert.Equal(BrowseFailureKind.ConnectionNotConnected, search.Failure?.Kind); + + actor.Tell(new BrowseNodeCommand("conn", null)); + var browse = ExpectMsg(TimeSpan.FromSeconds(5)); + Assert.Equal(BrowseFailureKind.ConnectionNotConnected, browse.Failure?.Kind); + } + + /// The OPC UA adapter with no client yet faults the task (typed) instead of throwing. + [Fact] + public async Task OpcUaAdapterWithoutClient_FaultsTheTask_WithTypedException() + { + var clientFactory = Substitute.For(); + await using var adapter = new OpcUaDataConnection(clientFactory, + Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance); + + // Calling the method must not throw synchronously (pre-fix: NullReferenceException / + // ConnectionNotConnectedException thrown before a task existed) — it returns a faulted task. + Task browse; + try { browse = adapter.BrowseChildrenAsync(null); } + catch (Exception ex) { throw new Xunit.Sdk.XunitException($"Browse threw synchronously: {ex.GetType().Name}"); } + await Assert.ThrowsAsync(() => browse); + + Task search; + try { search = adapter.SearchAddressSpaceAsync("x", 3, 10); } + catch (Exception ex) { throw new Xunit.Sdk.XunitException($"Search threw synchronously: {ex.GetType().Name}"); } + await Assert.ThrowsAsync(() => search); + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Actors/DataConnectionReconfigureTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Actors/DataConnectionReconfigureTests.cs index 155edaf2..181b3063 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Actors/DataConnectionReconfigureTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Actors/DataConnectionReconfigureTests.cs @@ -188,6 +188,8 @@ public class DataConnectionReconfigureTests : TestKit ExpectMsg(TimeSpan.FromSeconds(5)); AwaitCondition(() => Subscribed(newAdapter), TimeSpan.FromSeconds(5)); + // Re-entering Connected tells the subscriber Good (SRT-6 restore signal). + ExpectMsg(m => m.Quality == QualityCode.Good, TimeSpan.FromSeconds(5)); ExpectNoMsg(TimeSpan.FromMilliseconds(300)); oldCallback!("sensor/temp", new TagValue(999, QualityCode.Good, DateTimeOffset.UtcNow)); diff --git a/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Actors/DataConnectionResubscribeLoopTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Actors/DataConnectionResubscribeLoopTests.cs new file mode 100644 index 00000000..cad06189 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Actors/DataConnectionResubscribeLoopTests.cs @@ -0,0 +1,182 @@ +using System.Collections.Concurrent; +using Akka.Actor; +using Akka.TestKit.Xunit2; +using NSubstitute; +using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Protocol; +using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services; +using ZB.MOM.WW.ScadaBridge.Commons.Messages.DataConnection; +using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums; +using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Actors; +using ZB.MOM.WW.ScadaBridge.HealthMonitoring; + +namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Actors; + +/// +/// DCL-4 (2026-12-02 review, WP3 task 3.3): the reconnect re-subscribe loop is bound to its +/// session. A loop whose chunk wedged across a reconnect must stop when that session ends instead +/// of carrying on with its remaining chunks against the SAME adapter's NEW client (duplicate +/// monitored items / gateway subscribes whose stale-generation results were dropped unreleased). +/// +[Collection("DataConnectionManagerActor")] +public class DataConnectionResubscribeLoopTests : TestKit +{ + private readonly ISiteHealthCollector _health = Substitute.For(); + private readonly IDataConnectionFactory _factory = Substitute.For(); + + private readonly DataConnectionOptions _options = new() + { + ReconnectInterval = TimeSpan.FromMilliseconds(100), + TagResolutionRetryInterval = TimeSpan.FromSeconds(30), + WriteTimeout = TimeSpan.FromSeconds(5), + SeedReadMaxAttempts = 1, + SeedReadRetryDelay = TimeSpan.FromMilliseconds(10), + SubscribeBatchSize = 1, + SubscribeBatchDelay = TimeSpan.Zero + }; + + private void AwaitConnectedCount(string name, int count) => + AwaitCondition(() => _health.ReceivedCalls().Count(c => + c.GetMethodInfo().Name == nameof(ISiteHealthCollector.UpdateConnectionHealth) && + c.GetArguments() is [string n, ConnectionHealth reported, ..] && + n == name && reported == ConnectionHealth.Connected) >= count, + TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(10)); + + /// The wedged loop from the dead session issues no further chunks once its session ends. + [Fact] + public void ResubscribeLoopFromAnEndedSession_StopsAtItsWedgedChunk() + { + const string name = "resub-loop-cancel"; + var adapter = new HangableAdapter(); + var config = new Dictionary { ["Endpoint"] = "opc.tcp://plc:4840" }; + var actor = Sys.ActorOf(Props.Create(() => + new DataConnectionActor(name, adapter, _options, _health, _factory, "OpcUa", config, null, 3)), name); + AwaitConnectedCount(name, 1); + + var instance = CreateTestProbe(); + instance.Send(actor, new SubscribeTagsRequest("c1", "inst1", name, ["A", "B", "C"], DateTimeOffset.UtcNow)); + instance.FishForMessage(m => m.Success, TimeSpan.FromSeconds(5)); + + // Session 2: the re-subscribe loop's FIRST chunk wedges. + var wedged = adapter.HangNextCall(); + adapter.RaiseDisconnected(); + AwaitConnectedCount(name, 2); + AwaitCondition(() => wedged.Started, TimeSpan.FromSeconds(5)); + + // The tags the wedged session-2 loop had NOT reached yet. + var notReached = new[] { "A", "B", "C" }.Except(wedged.Tags).ToList(); + Assert.Equal(2, notReached.Count); + + // Session 3: a fresh loop re-subscribes every tag. + adapter.RaiseDisconnected(); + AwaitConnectedCount(name, 3); + AwaitCondition(() => notReached.All(t => adapter.CallsFor(t) == 2), + TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(10)); + + // The wedged chunk finally returns (the old client's operation timeout). + wedged.Fail(new TimeoutException("old session's operation timed out")); + + // Pre-fix the session-2 loop carried on: its remaining chunks were issued a THIRD time. + var deadline = DateTime.UtcNow + TimeSpan.FromMilliseconds(500); + while (DateTime.UtcNow < deadline) + { + foreach (var tag in notReached) + Assert.Equal(2, adapter.CallsFor(tag)); + Thread.Sleep(20); + } + } + + /// A held subscribe call. + internal sealed class HeldCall + { + private readonly TaskCompletionSource> _tcs = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public volatile bool Started; + + public IReadOnlyList Tags { get; set; } = []; + + public Task> Task => _tcs.Task; + + public void Fail(Exception ex) => _tcs.SetException(ex); + } + + /// Batch adapter that succeeds at once, except for one call the test chooses to hold. + internal sealed class HangableAdapter : IDataConnection, IBatchSubscribableConnection + { + private readonly ConcurrentQueue _subscribedTags = new(); + private HeldCall? _holdNext; + private int _handle; + + public ConnectionHealth Status { get; private set; } = ConnectionHealth.Disconnected; + + public event Action? Disconnected; + + public int CallsFor(string tag) => _subscribedTags.Count(t => t == tag); + + public HeldCall HangNextCall() + { + var held = new HeldCall(); + Volatile.Write(ref _holdNext, held); + return held; + } + + public void RaiseDisconnected() + { + Status = ConnectionHealth.Disconnected; + Disconnected?.Invoke(); + } + + public Task ConnectAsync(IDictionary connectionDetails, CancellationToken cancellationToken = default) + { + Status = ConnectionHealth.Connected; + return System.Threading.Tasks.Task.CompletedTask; + } + + public Task DisconnectAsync(CancellationToken cancellationToken = default) => System.Threading.Tasks.Task.CompletedTask; + + public Task> SubscribeBatchAsync( + IReadOnlyList tagPaths, SubscriptionCallback callback, CancellationToken cancellationToken = default) + { + foreach (var tag in tagPaths) + _subscribedTags.Enqueue(tag); + + if (Interlocked.Exchange(ref _holdNext, null) is { } held) + { + held.Tags = tagPaths.ToList(); + held.Started = true; + return held.Task; + } + + return System.Threading.Tasks.Task.FromResult>(tagPaths + .Select(t => new TagSubscribeResult(t, true, $"h{Interlocked.Increment(ref _handle)}", null)) + .ToList()); + } + + public Task UnsubscribeBatchAsync(IReadOnlyList subscriptionIds, CancellationToken cancellationToken = default) => + System.Threading.Tasks.Task.CompletedTask; + + public Task SubscribeAsync(string tagPath, SubscriptionCallback callback, CancellationToken cancellationToken = default) => + throw new NotSupportedException("batch-capable adapter"); + + public Task UnsubscribeAsync(string subscriptionId, CancellationToken cancellationToken = default) => + System.Threading.Tasks.Task.CompletedTask; + + public Task ReadAsync(string tagPath, CancellationToken cancellationToken = default) => + System.Threading.Tasks.Task.FromResult(new ReadResult(false, null, "no value")); + + public Task> ReadBatchAsync( + IEnumerable tagPaths, CancellationToken cancellationToken = default) => + System.Threading.Tasks.Task.FromResult>( + new Dictionary()); + + public Task WriteAsync(string tagPath, object? value, CancellationToken cancellationToken = default) => + System.Threading.Tasks.Task.FromResult(new WriteResult(true, null)); + + public Task> WriteBatchAsync( + IDictionary values, CancellationToken cancellationToken = default) => + System.Threading.Tasks.Task.FromResult>( + values.ToDictionary(kv => kv.Key, _ => new WriteResult(true, null))); + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Actors/DataConnectionRetryGapTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Actors/DataConnectionRetryGapTests.cs new file mode 100644 index 00000000..21850772 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Actors/DataConnectionRetryGapTests.cs @@ -0,0 +1,138 @@ +using Akka.Actor; +using Akka.TestKit.Xunit2; +using NSubstitute; +using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Protocol; +using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services; +using ZB.MOM.WW.ScadaBridge.Commons.Messages.DataConnection; +using ZB.MOM.WW.ScadaBridge.Commons.Types.Alarms; +using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums; +using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Actors; +using ZB.MOM.WW.ScadaBridge.HealthMonitoring; + +namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Actors; + +/// +/// WP3 task 3.2 (2026-12-02 review): failures on the reconnect paths that used to leave a feed or +/// a tag in NO retry set. +/// +/// DCL-2 — a requester-less alarm re-subscribe that fails after a reconnect is retried on +/// a backed-off timer. +/// DCL-8 — a connection-level failure row in a re-subscribe batch puts the tag into the +/// resolution retry set instead of only logging it. +/// +/// +[Collection("DataConnectionManagerActor")] +public class DataConnectionRetryGapTests : TestKit +{ + private readonly ISiteHealthCollector _health = Substitute.For(); + private readonly IDataConnectionFactory _factory = Substitute.For(); + + private readonly DataConnectionOptions _options = new() + { + ReconnectInterval = TimeSpan.FromMilliseconds(100), + TagResolutionRetryInterval = TimeSpan.FromMilliseconds(200), + TagResolutionRetryMaxInterval = TimeSpan.FromSeconds(1), + WriteTimeout = TimeSpan.FromSeconds(5), + SeedReadMaxAttempts = 1, + SeedReadRetryDelay = TimeSpan.FromMilliseconds(10), + SubscribeBatchDelay = TimeSpan.Zero + }; + + private void AwaitConnectedCount(string name, int count) => + AwaitCondition(() => _health.ReceivedCalls().Count(c => + c.GetMethodInfo().Name == nameof(ISiteHealthCollector.UpdateConnectionHealth) && + c.GetArguments() is [string n, ConnectionHealth reported, ..] && + n == name && reported == ConnectionHealth.Connected) >= count, + TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(10)); + + private static NativeAlarmTransition AlarmRaise(string source) => + new(source + ".Hi", source, "AnalogLimit.Hi", AlarmTransitionKind.Raise, + new AlarmConditionState(true, false, null, AlarmShelveState.Unshelved, false, 500), + "Process", "hi", "hi", "", "", null, DateTimeOffset.UtcNow, "92", "90"); + + /// + /// DCL-2: after a reconnect the DCL re-issues the alarm feed itself (no requester). That + /// re-subscribe fails once (e.g. an nsu= namespace the restarted server has not loaded + /// yet); the DCL must retry it, and transitions from the retried feed must reach the instance. + /// Pre-fix the failure was only logged and the source stayed silent until the next reconnect. + /// + [Fact] + public void FailedAlarmResubscribeAfterReconnect_IsRetried() + { + const string name = "alarm-resub-retry"; + var adapter = Substitute.For(); + adapter.ConnectAsync(Arg.Any>(), Arg.Any()) + .Returns(Task.CompletedTask); + var calls = 0; + AlarmTransitionCallback? latest = null; + ((IAlarmSubscribableConnection)adapter) + .SubscribeAlarmsAsync(Arg.Any(), Arg.Any(), + Arg.Any(), Arg.Any()) + .Returns(ci => + { + var n = Interlocked.Increment(ref calls); + if (n == 2) + return Task.FromException(new InvalidOperationException("namespace not loaded yet")); + latest = (AlarmTransitionCallback)ci[2]; + return Task.FromResult($"alarm-sub-{n}"); + }); + + var actor = Sys.ActorOf(Props.Create(() => new DataConnectionActor( + name, adapter, _options, _health, _factory, "OpcUa")), name); + AwaitConnectedCount(name, 1); + + var instance = CreateTestProbe(); + instance.Send(actor, new SubscribeAlarmsRequest("c", "inst", name, "Tank01", null, DateTimeOffset.UtcNow)); + instance.ExpectMsg(m => m.Success, TimeSpan.FromSeconds(5)); + + adapter.Disconnected += Raise.Event(); + AwaitConnectedCount(name, 2); + + // Call 2 (the reconnect re-subscribe) failed; the retry is call 3. + AwaitCondition(() => Volatile.Read(ref calls) >= 3, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(20)); + + // The retried feed is live: a transition reaches the instance. + AwaitCondition(() => latest != null, TimeSpan.FromSeconds(5)); + AwaitAssert(() => + { + latest!(AlarmRaise("Tank01")); + instance.FishForMessage( + u => u.Transition.SourceObjectReference == "Tank01", TimeSpan.FromMilliseconds(500)); + }, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(100)); + } + + /// + /// DCL-8: a reconnect re-subscribe chunk fails with a connection-level exception while the + /// session stays up (no Disconnected). The tag must land in the resolution retry set and + /// be re-subscribed by the probe; pre-fix it sat in no retry set — Bad until an unrelated + /// reconnect. + /// + [Fact] + public void ConnectionLevelFailureRowInResubscribe_IsRetriedByTheResolutionProbe() + { + const string name = "resub-connlevel"; + const string tag = "sensor/temp"; + var adapter = new DataConnectionSameAdapterReconnectTests.GatedAdapter(); + var config = new Dictionary { ["Endpoint"] = "opc.tcp://plc:4840" }; + var actor = Sys.ActorOf(Props.Create(() => + new DataConnectionActor(name, adapter, _options, _health, _factory, "OpcUa", config, null, 3)), name); + AwaitConnectedCount(name, 1); + + var instance = CreateTestProbe(); + instance.Send(actor, new SubscribeTagsRequest("c1", "inst1", name, [tag], DateTimeOffset.UtcNow)); + adapter.AwaitCall(0).Complete(tag, "h0"); + instance.FishForMessage(m => m.Success, TimeSpan.FromSeconds(5)); + + adapter.RaiseDisconnected(); + AwaitConnectedCount(name, 2); + + // The re-subscribe chunk fails at connection level; the session itself stays healthy. + adapter.AwaitCall(1).Fail(new InvalidOperationException("transient transport fault")); + + // The resolution probe re-issues the tag (pre-fix: never). + adapter.AwaitCall(2).Complete(tag, "h2"); + AwaitCondition(() => actor.Ask( + new DataConnectionActor.GetHealthReport(), TimeSpan.FromSeconds(1)).Result.ResolvedTags == 1, + TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(20)); + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Actors/DataConnectionSeedOrderingTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Actors/DataConnectionSeedOrderingTests.cs new file mode 100644 index 00000000..249ea875 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Actors/DataConnectionSeedOrderingTests.cs @@ -0,0 +1,258 @@ +using System.Collections.Concurrent; +using Akka.Actor; +using Akka.TestKit.Xunit2; +using NSubstitute; +using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Protocol; +using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services; +using ZB.MOM.WW.ScadaBridge.Commons.Messages.DataConnection; +using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums; +using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Actors; +using ZB.MOM.WW.ScadaBridge.HealthMonitoring; + +namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Actors; + +/// +/// DCL-1 (2026-12-02 review, WP3 task 3.1): a seed read is held until its whole seed operation +/// completes, while the subscription is already live, so a seed can arrive AFTER a newer live value. +/// Decided rule: a seed for a tag that has already delivered a live value in the current subscribe +/// generation never overwrites it. Also covers SRT-6 / task 3.8 — the connection actor tells its +/// subscribers ConnectionQualityChanged(Good) when it re-enters Connected. +/// +[Collection("DataConnectionManagerActor")] +public class DataConnectionSeedOrderingTests : TestKit +{ + private const string Tag = "Mixer.State"; + private const string OtherTag = "Mixer.Speed"; + + private readonly ISiteHealthCollector _health = Substitute.For(); + private readonly IDataConnectionFactory _factory = Substitute.For(); + + private readonly DataConnectionOptions _options = new() + { + ReconnectInterval = TimeSpan.FromMilliseconds(100), + TagResolutionRetryInterval = TimeSpan.FromSeconds(30), + WriteTimeout = TimeSpan.FromSeconds(5), + SeedReadMaxAttempts = 1, + SeedReadRetryDelay = TimeSpan.FromMilliseconds(10), + SubscribeBatchDelay = TimeSpan.Zero + }; + + private IActorRef CreateConnectionActor(string name, SeedGatedAdapter adapter) + { + var config = new Dictionary { ["Endpoint"] = "opc.tcp://plc:4840" }; + return Sys.ActorOf(Props.Create(() => + new DataConnectionActor( + name, adapter, _options, _health, _factory, "OpcUa", config, null, 3)), name); + } + + private void AwaitConnectedCount(string name, int count) => + AwaitCondition(() => _health.ReceivedCalls().Count(c => + c.GetMethodInfo().Name == nameof(ISiteHealthCollector.UpdateConnectionHealth) && + c.GetArguments() is [string n, ConnectionHealth reported, ..] && + n == name && reported == ConnectionHealth.Connected) >= count, + TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(10)); + + private static TagValue Good(object value) => new(value, QualityCode.Good, DateTimeOffset.UtcNow); + + /// + /// Initial subscribe: the live "Running" arrives while the seed read is still out; the seed + /// then returns the older "Idle". The instance must end on "Running" — the stale seed is + /// replaced by the latest live value (pre-fix it regressed the attribute to "Idle", Good). + /// + [Fact] + public void InitialSubscribe_SeedArrivingAfterLiveValue_DoesNotRegressIt() + { + const string name = "seed-initial"; + var adapter = new SeedGatedAdapter(); + var actor = CreateConnectionActor(name, adapter); + AwaitConnectedCount(name, 1); + + var seedGate = adapter.GateNextRead(); + var instance = CreateTestProbe(); + instance.Send(actor, new SubscribeTagsRequest("c1", "inst1", name, [Tag], DateTimeOffset.UtcNow)); + + // The subscription is live before the seed read returns. + adapter.AwaitCallback(Tag)(Tag, Good("Running")); + var live = instance.ExpectMsg(TimeSpan.FromSeconds(5)); + Assert.Equal("Running", live.Value); + + // The seed read (taken before the change) now completes with the older value. + seedGate.Release(new Dictionary { [Tag] = "Idle" }); + instance.ExpectMsg(r => r.Success, TimeSpan.FromSeconds(5)); + var afterSeed = instance.ExpectMsg(TimeSpan.FromSeconds(5)); + Assert.Equal("Running", afterSeed.Value); // pre-fix: "Idle" + } + + /// + /// A seed for a tag that has delivered NO live value is still delivered — the seed is the + /// only value a static tag will ever produce. + /// + [Fact] + public void InitialSubscribe_SeedForTagWithNoLiveValue_IsDelivered() + { + const string name = "seed-static"; + var adapter = new SeedGatedAdapter(); + var actor = CreateConnectionActor(name, adapter); + AwaitConnectedCount(name, 1); + + var seedGate = adapter.GateNextRead(); + var instance = CreateTestProbe(); + instance.Send(actor, new SubscribeTagsRequest("c1", "inst1", name, [Tag], DateTimeOffset.UtcNow)); + adapter.AwaitCallback(Tag); + + seedGate.Release(new Dictionary { [Tag] = "Idle" }); + instance.ExpectMsg(r => r.Success, TimeSpan.FromSeconds(5)); + Assert.Equal("Idle", instance.ExpectMsg(TimeSpan.FromSeconds(5)).Value); + } + + /// + /// Reconnect: the re-subscribe goes live and delivers "Running" while the re-seed is still out; + /// the re-seed then returns "Idle" for that tag (dropped) and a value for a tag that has not + /// re-reported (delivered). The connection also signals Good on re-entering Connected (3.8). + /// + [Fact] + public void Reconnect_ReseedArrivingAfterLiveValue_IsDropped_AndGoodIsSignalled() + { + const string name = "seed-reconnect"; + var adapter = new SeedGatedAdapter(); + var actor = CreateConnectionActor(name, adapter); + AwaitConnectedCount(name, 1); + + var instance = CreateTestProbe(); + instance.Send(actor, new SubscribeTagsRequest("c1", "inst1", name, [Tag, OtherTag], DateTimeOffset.UtcNow)); + instance.ExpectMsg(r => r.Success, TimeSpan.FromSeconds(5)); + adapter.ClearCallbacks(); + + var reseedGate = adapter.GateNextRead(); + adapter.RaiseDisconnected(); + var bad = instance.ExpectMsg(TimeSpan.FromSeconds(5)); + Assert.Equal(QualityCode.Bad, bad.Quality); + AwaitConnectedCount(name, 2); + var good = instance.ExpectMsg(TimeSpan.FromSeconds(5)); + Assert.Equal(QualityCode.Good, good.Quality); // pre-fix: Good was never sent + + // The new subscription delivers a live change before the re-seed returns. + adapter.AwaitCallback(Tag)(Tag, Good("Running")); + Assert.Equal("Running", instance.ExpectMsg(TimeSpan.FromSeconds(5)).Value); + + reseedGate.Release(new Dictionary { [Tag] = "Idle", [OtherTag] = 7 }); + + // OtherTag never re-reported live, so its seed is delivered; Tag's seed must not be. + var seen = new List(); + instance.FishForMessage(u => + { + seen.Add(u); + return u.TagPath == OtherTag; + }, TimeSpan.FromSeconds(5)); + instance.ExpectNoMsg(TimeSpan.FromMilliseconds(300)); + Assert.DoesNotContain(seen, u => u.TagPath == Tag); // pre-fix: Tag = "Idle" + Assert.Equal(7, seen.Single(u => u.TagPath == OtherTag).Value); + } + + /// One held ReadBatchAsync call. + internal sealed class ReadGate + { + private readonly TaskCompletionSource> _tcs = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public Task> Values => _tcs.Task; + + public void Release(Dictionary values) => _tcs.SetResult(values); + } + + /// + /// Batch-capable adapter whose subscribes succeed at once (capturing each tag's live + /// callback) and whose seed reads can be held until the test releases them. + /// + internal sealed class SeedGatedAdapter : IDataConnection, IBatchSubscribableConnection + { + private readonly ConcurrentDictionary _callbacks = new(); + private readonly ConcurrentQueue _readGates = new(); + private int _handle; + + public ConnectionHealth Status { get; private set; } = ConnectionHealth.Disconnected; + + public event Action? Disconnected; + + public ReadGate GateNextRead() + { + var gate = new ReadGate(); + _readGates.Enqueue(gate); + return gate; + } + + public void ClearCallbacks() => _callbacks.Clear(); + + public SubscriptionCallback AwaitCallback(string tag) + { + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(5); + while (DateTime.UtcNow < deadline) + { + if (_callbacks.TryGetValue(tag, out var cb)) + return cb; + Thread.Sleep(10); + } + + throw new TimeoutException($"No subscription for {tag}."); + } + + public void RaiseDisconnected() + { + Status = ConnectionHealth.Disconnected; + Disconnected?.Invoke(); + } + + public Task ConnectAsync(IDictionary connectionDetails, CancellationToken cancellationToken = default) + { + Status = ConnectionHealth.Connected; + return Task.CompletedTask; + } + + public Task DisconnectAsync(CancellationToken cancellationToken = default) => Task.CompletedTask; + + public Task> SubscribeBatchAsync( + IReadOnlyList tagPaths, SubscriptionCallback callback, CancellationToken cancellationToken = default) + { + var rows = new List(); + foreach (var tag in tagPaths) + { + _callbacks[tag] = callback; + rows.Add(new TagSubscribeResult(tag, true, $"h{Interlocked.Increment(ref _handle)}", null)); + } + return Task.FromResult>(rows); + } + + public Task UnsubscribeBatchAsync(IReadOnlyList subscriptionIds, CancellationToken cancellationToken = default) => + Task.CompletedTask; + + public Task SubscribeAsync(string tagPath, SubscriptionCallback callback, CancellationToken cancellationToken = default) => + throw new NotSupportedException("batch-capable adapter"); + + public Task UnsubscribeAsync(string subscriptionId, CancellationToken cancellationToken = default) => Task.CompletedTask; + + public Task ReadAsync(string tagPath, CancellationToken cancellationToken = default) => + Task.FromResult(new ReadResult(false, null, "no value")); + + public async Task> ReadBatchAsync( + IEnumerable tagPaths, CancellationToken cancellationToken = default) + { + var values = _readGates.TryDequeue(out var gate) + ? await gate.Values + : new Dictionary(); + return tagPaths + .Where(values.ContainsKey) + .ToDictionary(t => t, t => new ReadResult(true, + new TagValue(values[t], QualityCode.Good, DateTimeOffset.UtcNow), null)); + } + + public Task WriteAsync(string tagPath, object? value, CancellationToken cancellationToken = default) => + Task.FromResult(new WriteResult(true, null)); + + public Task> WriteBatchAsync( + IDictionary values, CancellationToken cancellationToken = default) => + Task.FromResult>( + values.ToDictionary(kv => kv.Key, _ => new WriteResult(true, null))); + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/OpcUaValueBoundaryTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/OpcUaValueBoundaryTests.cs index 63bdaf33..7f35202c 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/OpcUaValueBoundaryTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/OpcUaValueBoundaryTests.cs @@ -92,4 +92,33 @@ public class OpcUaValueBoundaryTests Assert.Throws(() => OpcUaValueBoundary.ToVariant(new object())); Assert.Throws(() => OpcUaValueBoundary.ToVariant(new int[2, 2])); } + + /// DCL-7: the source timestamp wins when present. + [Fact] + public void EffectiveTimestamp_PrefersTheSourceTimestamp() + { + var source = new DateTime(2026, 11, 12, 10, 30, 0, DateTimeKind.Utc); + var server = source.AddSeconds(2); + Assert.Equal(source, OpcUaValueBoundary.EffectiveTimestamp(source, server)); + } + + /// + /// DCL-7: with TimestampsToReturn = Server (or a server that omits it) there is no source + /// timestamp — fall back to the server timestamp, never 0001-01-01. + /// + [Fact] + public void EffectiveTimestamp_FallsBackToTheServerTimestamp() + { + var server = new DateTime(2026, 11, 12, 10, 30, 2, DateTimeKind.Utc); + Assert.Equal(server, OpcUaValueBoundary.EffectiveTimestamp(DateTimeUtc.MinValue, server)); + } + + /// DCL-7: with neither timestamp, the value is stamped now rather than DateTime.MinValue. + [Fact] + public void EffectiveTimestamp_WithNeither_IsNow() + { + var before = DateTime.UtcNow; + var ts = OpcUaValueBoundary.EffectiveTimestamp(DateTimeUtc.MinValue, DateTimeUtc.MinValue); + Assert.InRange(ts, before, DateTime.UtcNow); + } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/RealMxGatewaySharedAdviseTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/RealMxGatewaySharedAdviseTests.cs new file mode 100644 index 00000000..91d1221b --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/RealMxGatewaySharedAdviseTests.cs @@ -0,0 +1,58 @@ +using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters; + +namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Adapters; + +/// +/// DCL-9 (2026-12-02 review, WP3 task 3.3): the per-handle supervisory advise is shared by every +/// concurrent caller, so it must not run under the token of whichever caller created it. A write +/// whose deadline fires must not cancel the advise a concurrent, deadline-free subscribe awaits. +/// +public class RealMxGatewaySharedAdviseTests +{ + /// The first caller's cancellation fails only that caller; the shared advise completes for the second. + [Fact] + public async Task FirstCallersCancellation_DoesNotCancelTheSharedAdvise() + { + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var coreCalls = 0; + CancellationToken coreToken = default; + var client = new RealMxGatewayClient(null) + { + AdviseCoreOverride = async (_, ct) => + { + Interlocked.Increment(ref coreCalls); + coreToken = ct; + await release.Task.WaitAsync(ct); + }, + }; + + using var writeDeadline = new CancellationTokenSource(); + var write = client.EnsureSupervisoryAdvisedAsync(42, writeDeadline.Token); + var subscribe = client.EnsureSupervisoryAdvisedAsync(42, CancellationToken.None); + + writeDeadline.Cancel(); + await Assert.ThrowsAnyAsync(() => write); + Assert.False(coreToken.IsCancellationRequested); // pre-fix: the shared advise was cancelled + + release.SetResult(); + await subscribe.WaitAsync(TimeSpan.FromSeconds(5)); // pre-fix: OperationCanceledException + Assert.Equal(1, coreCalls); // advise-once still holds + } + + /// A faulted shared advise is evicted so the next caller retries it. + [Fact] + public async Task FaultedSharedAdvise_IsRetriedByTheNextCaller() + { + var coreCalls = 0; + var client = new RealMxGatewayClient(null) + { + AdviseCoreOverride = (_, _) => Interlocked.Increment(ref coreCalls) == 1 + ? Task.FromException(new InvalidOperationException("gateway busy")) + : Task.CompletedTask, + }; + + await Assert.ThrowsAsync(() => client.EnsureSupervisoryAdvisedAsync(7, CancellationToken.None)); + await client.EnsureSupervisoryAdvisedAsync(7, CancellationToken.None); + Assert.Equal(2, coreCalls); + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/RealOpcUaAlarmItemStatusTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/RealOpcUaAlarmItemStatusTests.cs new file mode 100644 index 00000000..3dbc2b20 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/RealOpcUaAlarmItemStatusTests.cs @@ -0,0 +1,45 @@ +using System.Reflection; +using Opc.Ua; +using Opc.Ua.Client; +using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters; + +namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Adapters; + +/// +/// DCL-3 (2026-12-02 review, WP3 task 3.2): ApplyChangesAsync does not throw for a +/// per-item create failure, so the alarm path must read the event item's status — as the data +/// path already does — instead of recording a rejected item as a live feed. +/// +public class RealOpcUaAlarmItemStatusTests +{ +#pragma warning disable CS0618 // the parameterless MonitoredItem ctor is fine for a status-only probe + private static MonitoredItem NewItem() => new(); +#pragma warning restore CS0618 + + // MonitoredItemStatus.SetError is not public; the SDK calls it when the server rejects a create. + private static void SetError(MonitoredItem item, ServiceResult error) => + typeof(MonitoredItemStatus) + .GetMethod("SetError", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)! + .Invoke(item.Status, [error]); + + /// A rejected create (e.g. BadNodeIdUnknown) is reported as the item's error. + [Fact] + public void RejectedItem_ReportsTheBadStatus() + { + var item = NewItem(); + SetError(item, new ServiceResult(StatusCodes.BadNodeIdUnknown)); + + var error = RealOpcUaClient.AlarmItemCreateError(item); + + Assert.NotNull(error); + Assert.Equal(StatusCodes.BadNodeIdUnknown, error!.StatusCode.Code); + } + + /// An item with no error (created) is not reported. + [Fact] + public void CreatedItem_ReportsNoError() + { + var item = NewItem(); + Assert.Null(RealOpcUaClient.AlarmItemCreateError(item)); + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/DataConnectionActorAlarmIndexTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/DataConnectionActorAlarmIndexTests.cs index e0b63bcc..94290dde 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/DataConnectionActorAlarmIndexTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/DataConnectionActorAlarmIndexTests.cs @@ -13,9 +13,11 @@ namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests; /// /// The alarm subscriber first-segment bucket index must make EXACTLY the routing -/// decisions the previous linear scan made. The expectation in each case is computed with -/// the original rule (plain StartsWith against every subscribed source), so the -/// test pins equivalence rather than restating the new implementation. +/// decisions a linear scan over every subscribed source makes. The expectation in each case +/// is computed with an independent oracle — since the 2026-12-02 review (DCL-5) the rule is +/// "the reference is the source itself or lies beneath it at a separator", no longer a raw +/// string StartsWith that let Tank1 receive Tank10's alarms — so the test +/// pins equivalence rather than restating the implementation. /// public class DataConnectionActorAlarmIndexTests : TestKit { @@ -37,9 +39,10 @@ public class DataConnectionActorAlarmIndexTests : TestKit private static readonly (string SourceRef, string SourceObjectRef)[] Transitions = [ - ("Area1.Tank1.Hi", "Area1.Tank1"), // Area1 (residue) + Area1.Tank - ("Area1.Tank1.Sub.Hi", "Area1.Tank1.Sub"), // + Area1.Tank1.Sub - ("Area1X.Pump.Hi", "Area1X.Pump"), // sub-segment prefix: Area1 ONLY + ("Area1.Tank1.Hi", "Area1.Tank1"), // Area1 (residue) ONLY — "Area1.Tank" is a sibling, not a parent (DCL-5) + ("Area1.Tank1.Sub.Hi", "Area1.Tank1.Sub"), // Area1 + Area1.Tank1.Sub + ("Area1.Tank.Hi", "Area1.Tank"), // Area1 + Area1.Tank + ("Area1X.Pump.Hi", "Area1X.Pump"), // sub-segment prefix of Area1: nobody (DCL-5) ("Area2.Tank9.Hi", "Area2.Tank9"), // Area2.Tank only ("Zone.A.Hi", "Zone.A"), // nobody ]; @@ -49,10 +52,12 @@ public class DataConnectionActorAlarmIndexTests : TestKit new AlarmConditionState(true, false, null, AlarmShelveState.Unshelved, false, 500), "Process", "hi", "hi", "", "", null, DateTimeOffset.UtcNow, "92", "90"); - /// The ORIGINAL linear-scan rule, kept here as the oracle. + /// The linear-scan oracle: the source itself, or a descendant at a '.' separator. private static bool LinearScanMatches(string sourceRef, string transitionSourceRef, string transitionSourceObjectRef) => - transitionSourceObjectRef.StartsWith(sourceRef, StringComparison.Ordinal) - || transitionSourceRef.StartsWith(sourceRef, StringComparison.Ordinal); + Under(transitionSourceObjectRef, sourceRef) || Under(transitionSourceRef, sourceRef); + + private static bool Under(string reference, string source) => + reference == source || reference.StartsWith(source + ".", StringComparison.Ordinal); /// Verifies that the bucket index routes exactly as the previous linear scan did. [Fact] @@ -164,7 +169,59 @@ public class DataConnectionActorAlarmIndexTests : TestKit Thread.Sleep(200); Assert.NotNull(cb); - cb!(Transition("Area1.Tank1.Hi", "Area1.Tank1")); + cb!(Transition("Area1.Tank.Hi", "Area1.Tank")); probe.ExpectNoMsg(TimeSpan.FromMilliseconds(300)); } + + /// + /// DCL-5: sibling sources whose names share a prefix (ns=2;s=Tank1 / ns=2;s=Tank10, + /// MxGateway Pump1 / Pump10) must not receive each other's alarms. Pre-fix every + /// Tank10 transition was also delivered to — and mirrored by — the Tank1 instance. + /// + [Theory] + [InlineData("ns=2;s=Tank1", "ns=2;s=Tank10")] + [InlineData("Pump1", "Pump10")] + public void SiblingSourcesSharingAPrefix_DoNotReceiveEachOthersAlarms(string shortSource, string longSource) + { + AlarmTransitionCallback? cb = null; + var adapter = Substitute.For(); + adapter.ConnectAsync(Arg.Any>(), Arg.Any()) + .Returns(Task.CompletedTask); + ((IAlarmSubscribableConnection)adapter) + .SubscribeAlarmsAsync(Arg.Any(), Arg.Any(), + Arg.Do(c => cb = c), Arg.Any()) + .Returns(ci => Task.FromResult("alarm-" + ci.ArgAt(0))); + + var actor = Sys.ActorOf(Props.Create(() => new DataConnectionActor( + "conn", adapter, _options, _health, _factory, "OpcUa"))); + + var shortProbe = CreateTestProbe(); + var longProbe = CreateTestProbe(); + actor.Tell(new SubscribeAlarmsRequest("c1", "inst-short", "conn", shortSource, null, DateTimeOffset.UtcNow), shortProbe.Ref); + shortProbe.ExpectMsg(m => m.Success, TimeSpan.FromSeconds(5)); + actor.Tell(new SubscribeAlarmsRequest("c2", "inst-long", "conn", longSource, null, DateTimeOffset.UtcNow), longProbe.Ref); + longProbe.ExpectMsg(m => m.Success, TimeSpan.FromSeconds(5)); + + cb!(Transition(longSource + ".Hi", longSource)); + longProbe.ExpectMsg(TimeSpan.FromSeconds(5)); + shortProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(300)); // pre-fix: delivered here too + + // The short source still gets its own alarms. + cb!(Transition(shortSource + ".Hi", shortSource)); + shortProbe.ExpectMsg(TimeSpan.FromSeconds(5)); + } + + /// The separator-aware containment rule behind alarm routing. + [Theory] + [InlineData("Tank1", "Tank1", true)] + [InlineData("Tank1.Hi", "Tank1", true)] + [InlineData("Area/Tank1", "Area", true)] + [InlineData("Tank10", "Tank1", false)] + [InlineData("Tank10.Hi", "Tank1", false)] + [InlineData("ns=2;s=Tank10", "ns=2;s=Tank1", false)] + [InlineData("Area1.Tank", "Area1.", true)] + [InlineData("anything", "", true)] + [InlineData("Tank", "Tank1", false)] + public void IsUnderAlarmSource_IsSeparatorAware(string reference, string source, bool expected) => + Assert.Equal(expected, DataConnectionActor.IsUnderAlarmSource(reference, source)); } diff --git a/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/DataConnectionActorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/DataConnectionActorTests.cs index e9bbd4f9..b4f15de2 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/DataConnectionActorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/DataConnectionActorTests.cs @@ -1476,6 +1476,8 @@ public class DataConnectionActorTests : TestKit AwaitCondition(() => backupAdapter.ReceivedCalls().Any(c => c.GetMethodInfo().Name == "SubscribeAsync"), TimeSpan.FromSeconds(5)); + // Re-entering Connected on the backup tells the subscriber Good (SRT-6 restore signal). + ExpectMsg(m => m.Quality == QualityCode.Good, TimeSpan.FromSeconds(5)); await Task.Delay(300); // actor is Connected on backup // Drain any value updates produced by the re-subscribe path. diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/AlarmActorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/AlarmActorTests.cs index a9d23741..cf9c842f 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/AlarmActorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/AlarmActorTests.cs @@ -352,6 +352,45 @@ public class AlarmActorTests : TestKit, IDisposable Assert.Equal(AlarmState.Active, msg.State); } + /// + /// SRT-3: a value that steps and then HOLDS produces no further sample (subscriptions report on + /// change). The alarm must clear once the step ages out of the window — pre-fix it stayed + /// Active indefinitely although the rate had been 0 since the step. + /// + [Fact] + public void AlarmActor_RateOfChange_ClearsWhenTheValueStopsChanging() + { + var instanceProbe = CreateTestProbe(); + // 10 units/sec threshold, 1 sec window. + var alarm = SpawnRocAlarm(RocConfig(10, 1, "either"), instanceProbe); + + var t0 = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); + alarm.Tell(PressureSample(0, t0)); + alarm.Tell(PressureSample(100, t0.AddMilliseconds(500))); // 200 units/sec → Active + Assert.Equal(AlarmState.Active, instanceProbe.ExpectMsg(TimeSpan.FromSeconds(5)).State); + + // No further sample: the 0 leaves the window ~0.5 s later and the alarm clears on its own. + var cleared = instanceProbe.ExpectMsg(TimeSpan.FromSeconds(5)); + Assert.Equal(AlarmState.Normal, cleared.State); + } + + /// SRT-3: while the value keeps changing fast, the window tick does not clear the alarm. + [Fact] + public void AlarmActor_RateOfChange_StaysActiveWhileTheValueKeepsChangingFast() + { + var instanceProbe = CreateTestProbe(); + var alarm = SpawnRocAlarm(RocConfig(10, 1, "either"), instanceProbe); + + var t0 = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); + alarm.Tell(PressureSample(0, t0)); + alarm.Tell(PressureSample(100, t0.AddMilliseconds(500))); + Assert.Equal(AlarmState.Active, instanceProbe.ExpectMsg(TimeSpan.FromSeconds(5)).State); + + // A second steep step re-arms the tick; the rate over the window stays above threshold. + alarm.Tell(PressureSample(200, t0.AddMilliseconds(900))); + instanceProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(300)); + } + /// Verifies that an either-direction rate-of-change alarm activates on a rapid fall. [Fact] public void AlarmActor_RateOfChange_Either_ActivatesOnRapidFall() @@ -1153,4 +1192,40 @@ public class AlarmActorTests : TestKit, IDisposable var change = instanceProbe.ExpectMsg(TimeSpan.FromSeconds(10)); Assert.Equal(AlarmState.Active, change.State); } + + /// + /// SRT-2: a failed/timed-out expression evaluation is "unknown" and leaves an Active alarm + /// Active. Pre-fix it was coerced to false: Active → Normal on the failure, then Normal → + /// Active (and a second on-trigger run) on the next successful evaluation. + /// + [Fact] + public void ExpressionEvalFailure_LeavesAnActiveAlarmActive() + { + var expr = CompileRawTriggerExpression("Attributes[\"A\"]?.ToString() == \"1\""); + var alarmConfig = new ResolvedAlarm + { + CanonicalName = "ExprKeepAlarm", + TriggerType = "Expression", + TriggerConfiguration = "{\"expression\":\"Attributes[\\\"A\\\"]?.ToString() == \\\"1\\\"\"}", + PriorityLevel = 1 + }; + var instanceProbe = CreateTestProbe(); + var alarm = ActorOf(Props.Create(() => new AlarmActor( + "ExprKeepAlarm", "Pump1", instanceProbe.Ref, alarmConfig, + null, _sharedLibrary, _options, + NullLogger.Instance, expr))); + + alarm.Tell(new AttributeValueChanged("Pump1", "A", "A", "1", "Good", DateTimeOffset.UtcNow)); + Assert.Equal(AlarmState.Active, instanceProbe.ExpectMsg(TimeSpan.FromSeconds(10)).State); + + // One evaluation cannot be completed (timeout under load / task fault). + alarm.Tell(new AlarmActor.ExpressionEvalFailed(new TimeoutException("eval timed out"))); + // The condition still holds; then it genuinely clears. + alarm.Tell(new AttributeValueChanged("Pump1", "A", "A", "1", "Good", DateTimeOffset.UtcNow)); + alarm.Tell(new AttributeValueChanged("Pump1", "A", "A", "0", "Good", DateTimeOffset.UtcNow)); + + // Exactly one transition — the genuine clear. Pre-fix: Normal (the failure), Active, Normal. + Assert.Equal(AlarmState.Normal, instanceProbe.ExpectMsg(TimeSpan.FromSeconds(10)).State); + instanceProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); + } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/DeploymentManagerRouteTraceTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/DeploymentManagerRouteTraceTests.cs index 5ddc0260..a13f63d3 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/DeploymentManagerRouteTraceTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/DeploymentManagerRouteTraceTests.cs @@ -163,4 +163,38 @@ public class DeploymentManagerRouteTraceTests : TestKit, IDisposable var read = ExpectMsg(TimeSpan.FromSeconds(10)); Assert.Equal("Hand", read.Values["Mode"]?.ToString()); } + + /// + /// SRT-13: a routed inbound call waits as long as the TARGET script may run — its resolved + /// timeout (per-script override, else the site default) plus the stuck-script grace and a + /// margin — instead of a hard-coded 30 s that failed a 120 s handshake script's caller while the + /// script ran on. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task RoutedCallTimeout_FollowsTheTargetScriptsTimeout() + { + var options = new SiteRuntimeOptions { ScriptExecutionTimeoutSeconds = 30, StuckScriptGraceMs = 1000 }; + var config = new FlattenedConfiguration + { + InstanceUniqueName = "Handshake", + Scripts = + [ + new ResolvedScript { CanonicalName = "Slow", Code = "return 1;", ExecutionTimeoutSeconds = 120 }, + new ResolvedScript { CanonicalName = "Default", Code = "return 1;" }, + ], + }; + var instance = ActorOf(Props.Create(() => new InstanceActor( + "Handshake", JsonSerializer.Serialize(config), _storage, _compilationService, _sharedScriptLibrary, + null, options, NullLogger.Instance))); + + var slack = TimeSpan.FromSeconds(1) + DeploymentManagerActor.RoutedCallMargin; + Assert.Equal(TimeSpan.FromSeconds(120) + slack, + await DeploymentManagerActor.RoutedCallTimeoutAsync(instance, "Slow", options)); // pre-fix: 30 s flat + Assert.Equal(TimeSpan.FromSeconds(30) + slack, + await DeploymentManagerActor.RoutedCallTimeoutAsync(instance, "Default", options)); + // Unknown script: the site default (the instance replies "not found" on the call itself). + Assert.Equal(TimeSpan.FromSeconds(30) + slack, + await DeploymentManagerActor.RoutedCallTimeoutAsync(instance, "Missing", options)); + } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorRedeployGateTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorRedeployGateTests.cs new file mode 100644 index 00000000..4814b6b5 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorRedeployGateTests.cs @@ -0,0 +1,142 @@ +using System.Text.Json; +using Akka.Actor; +using Akka.TestKit.Xunit2; +using Microsoft.Extensions.Logging.Abstractions; +using ZB.MOM.WW.ScadaBridge.Commons.Messages.DataConnection; +using ZB.MOM.WW.ScadaBridge.Commons.Messages.DebugView; +using ZB.MOM.WW.ScadaBridge.Commons.Messages.Instance; +using ZB.MOM.WW.ScadaBridge.Commons.Types.Alarms; +using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums; +using ZB.MOM.WW.ScadaBridge.Commons.Types.Flattening; +using ZB.MOM.WW.ScadaBridge.SiteRuntime.Actors; +using ZB.MOM.WW.ScadaBridge.SiteRuntime.Persistence; +using ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts; +using ZB.MOM.WW.ScadaBridge.TestSupport; + +namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests.Actors; + +/// +/// SRT-12 (2026-12-02 review, WP3 task 3.10): the redeploy reset gate (clear static overrides, +/// then clear native alarms) must cover the successor's whole start, not just its override load — +/// the native-alarm rehydration read and the first static-override flush are ordered behind it too. +/// +public class InstanceActorRedeployGateTests : TestKit, IDisposable +{ + private readonly SiteStorageService _storage; + private readonly ScriptCompilationService _compilationService; + private readonly SharedScriptLibrary _sharedScriptLibrary; + private readonly SiteRuntimeOptions _options = new(); + private readonly TestLocalDb _localDb; + + /// Creates a temporary LocalDb-backed site storage and the script services the actor needs. + public InstanceActorRedeployGateTests() + { + _localDb = TestLocalDb.CreateTemp("instance-redeploy-gate"); + _storage = new SiteStorageService(_localDb.Db, NullLogger.Instance); + _storage.InitializeAsync().GetAwaiter().GetResult(); + _compilationService = new ScriptCompilationService(NullLogger.Instance); + _sharedScriptLibrary = new SharedScriptLibrary(_compilationService, NullLogger.Instance); + } + + /// + void IDisposable.Dispose() + { + Shutdown(); + var path = _localDb.Path; + _localDb.Dispose(); + TestLocalDb.DeleteFiles(path); + } + + private IActorRef CreateGated(string name, FlattenedConfiguration config, IActorRef? dcl, Task gate) => + ActorOf(Props.Create(() => new InstanceActor( + name, JsonSerializer.Serialize(config), _storage, _compilationService, _sharedScriptLibrary, + null, _options, NullLogger.Instance, dcl, null, null, null, gate))); + + /// Holds true for the whole window (polling, not a blind sleep). + private static async Task AssertHoldsFor(Func> holds, TimeSpan window, string because) + { + var deadline = DateTime.UtcNow + window; + while (DateTime.UtcNow < deadline) + { + Assert.True(await holds(), because); + await Task.Delay(50); + } + } + + /// + /// The successor's first static-override flush lands only after the reset: a write made while + /// the (slow) clear is still pending must survive it. Pre-fix the flush committed within + /// ~100 ms, the delayed clear then deleted it, and the next restart silently reverted it. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task FirstStaticFlush_IsOrderedAfterTheResetGate() + { + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var config = new FlattenedConfiguration + { + InstanceUniqueName = "GateFlush", + Attributes = [new ResolvedAttribute { CanonicalName = "Mode", Value = "Auto", DataType = "String" }], + }; + var actor = CreateGated("GateFlush", config, null, gate.Task); + + actor.Tell(new SetStaticAttributeCommand("w1", "GateFlush", "Mode", "Manual", DateTimeOffset.UtcNow)); + Assert.True(ExpectMsg().Success); + + // While the reset is pending, nothing may reach the table (pre-fix: committed at ~100 ms). + await AssertHoldsFor( + async () => (await _storage.GetStaticOverridesAsync("GateFlush")).Count == 0, + TimeSpan.FromMilliseconds(500), "a static flush committed ahead of the redeploy reset"); + + // The reset runs, then the gate opens: the write lands after it and survives. + await _storage.ClearStaticOverridesAsync("GateFlush"); + gate.SetResult(); + await AwaitAssertAsync(async () => + { + var stored = await _storage.GetStaticOverridesAsync("GateFlush"); + Assert.Equal("Manual", stored.GetValueOrDefault("Mode")); + }, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(50)); + } + + /// + /// The native-alarm rehydration read is chained behind the gate, so the successor can only see + /// the CLEARED table. Pre-fix NativeAlarmActor read native_alarm_state directly in PreStart and + /// re-emitted the predecessor's conditions (stale alarms from an old binding). + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task NativeAlarmRehydration_IsOrderedAfterTheResetGate() + { + // The predecessor left an active condition behind. + await _storage.UpsertNativeAlarmAsync("GateNative", "Pressure", "T01.Hi", + JsonSerializer.Serialize(new AlarmConditionState(true, false, null, AlarmShelveState.Unshelved, false, 800)), + DateTimeOffset.UtcNow); + + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var config = new FlattenedConfiguration + { + InstanceUniqueName = "GateNative", + NativeAlarmSources = + [ + new ResolvedNativeAlarmSource + { + CanonicalName = "Pressure", ConnectionName = "Opc", SourceReference = "ns=2;s=T01" + } + ], + }; + var dcl = CreateTestProbe(); + var actor = CreateGated("GateNative", config, dcl.Ref, gate.Task); + dcl.ExpectMsg(TimeSpan.FromSeconds(5)); + + // The reset clears the table, THEN the gate opens. + await Task.Delay(200); // give a pre-fix (ungated) PreStart read every chance to win the race + await _storage.ClearNativeAlarmsForInstanceAsync("GateNative"); + gate.SetResult(); + + await AssertHoldsFor(async () => + { + var snap = await actor.Ask(new SubscribeDebugViewRequest("GateNative", "c"), TimeSpan.FromSeconds(3)); + return !snap.AlarmStates.Any(a => a.SourceReference == "T01.Hi" && !a.IsConfiguredPlaceholder); + }, TimeSpan.FromSeconds(1), "the predecessor's native alarm was rehydrated"); + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorTests.cs index 1351c0a2..72dd97e8 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorTests.cs @@ -233,6 +233,42 @@ public class InstanceActorTests : TestKit, IDisposable Assert.Equal("100.0", getResponse.Value?.ToString()); } + /// + /// SRT-11: a successful static write refreshes the stored quality and timestamp. A List + /// attribute whose config default fails to decode loads Bad; a later valid write used to fix + /// the value but leave GetAttribute (and the Debug View, and requireGoodQuality waiters) on Bad + /// for the actor's lifetime while the stream said Good. + /// + [Fact] + public void InstanceActor_StaticWrite_RefreshesQualityAndTimestamp() + { + var config = new FlattenedConfiguration + { + InstanceUniqueName = "PumpListFix", + Attributes = + [ + new ResolvedAttribute + { + CanonicalName = "Recipe", Value = "[not json", DataType = "List", ElementDataType = "Int32" + } + ] + }; + var actor = CreateInstanceActor("PumpListFix", config); + + actor.Tell(new GetAttributeRequest("q0", "PumpListFix", "Recipe", DateTimeOffset.UtcNow)); + Assert.Equal("Bad", ExpectMsg().Quality); // malformed default + + var before = DateTimeOffset.UtcNow; + actor.Tell(new SetStaticAttributeCommand("w1", "PumpListFix", "Recipe", "[1,2,3]", DateTimeOffset.UtcNow)); + Assert.True(ExpectMsg().Success); + + actor.Tell(new GetAttributeRequest("q1", "PumpListFix", "Recipe", DateTimeOffset.UtcNow)); + var after = ExpectMsg(); + Assert.Equal("Good", after.Quality); // pre-fix: "Bad" + Assert.Equal(new List { 1, 2, 3 }, Assert.IsType>(after.Value)); + Assert.True(after.Timestamp >= before, $"timestamp {after.Timestamp} not refreshed by the write"); + } + /// Verifies that setting a static attribute persists it to SQLite. /// A task that represents the asynchronous operation. [Fact] @@ -1638,6 +1674,34 @@ public class InstanceActorTests : TestKit, IDisposable Assert.True(sw.Elapsed < TimeSpan.FromMilliseconds(1000), $"retry took {sw.Elapsed} — backoff not reset"); } + /// + /// SRT-6 / WP3 task 3.8: the DCL's ConnectionQualityChanged(Good) on reconnect is a + /// restore signal only. It must NOT stamp the bound attributes Good with their pre-outage + /// last-known values — they stay Bad until the device re-reports through a TagValueUpdate. + /// + [Fact] + public void ConnectionBackToGood_DoesNotStampBoundAttributesGood() + { + var (instance, dclProbe) = CreateInstanceWithDataSourcedAttribute(new SiteRuntimeOptions()); + dclProbe.ExpectMsg(); + + instance.Tell(new TagValueUpdate("conn-1", "ns=2;s=Motor.Temp", 42, QualityCode.Good, DateTimeOffset.UtcNow)); + instance.Tell(new ConnectionQualityChanged("conn-1", QualityCode.Bad, DateTimeOffset.UtcNow)); + instance.Tell(new ConnectionQualityChanged("conn-1", QualityCode.Good, DateTimeOffset.UtcNow)); + + instance.Tell(new GetAttributeRequest("q1", "Sub-1", "Motor.Temp", DateTimeOffset.UtcNow)); + var stillBad = ExpectMsg(TimeSpan.FromSeconds(5)); + Assert.Equal("Bad", stillBad.Quality); // pre-fix: "Good" + Assert.Equal(42, stillBad.Value); + + // The device re-reports: quality returns through the ordinary value path. + instance.Tell(new TagValueUpdate("conn-1", "ns=2;s=Motor.Temp", 43, QualityCode.Good, DateTimeOffset.UtcNow)); + instance.Tell(new GetAttributeRequest("q2", "Sub-1", "Motor.Temp", DateTimeOffset.UtcNow)); + var good = ExpectMsg(TimeSpan.FromSeconds(5)); + Assert.Equal("Good", good.Quality); + Assert.Equal(43, good.Value); + } + /// Verifies that a late reply for a failed and re-issued request is ignored. [Fact] public void LateReplyForFailedAndReissuedRequest_IsIgnored() diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/ScriptActorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/ScriptActorTests.cs index f2a6f224..39ebce55 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/ScriptActorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/ScriptActorTests.cs @@ -616,6 +616,75 @@ public class ScriptActorTests : TestKit, IDisposable instance.ExpectMsg(TimeSpan.FromSeconds(2)); } + /// + /// SRT-2: a REAL (non-seed) evaluation that faults or times out is "unknown", not false. Pre-fix + /// it stopped the running WhileTrue timer (and the next true evaluation fired a spurious edge run). + /// + [Fact] + public void ScriptActor_ExpressionWhileTrue_FaultedRealEval_DoesNotStopReFiring() + { + var triggerExpr = CompileTriggerExpression("Attributes[\"Active\"]?.ToString() == \"yes\""); + var (actor, instance) = CreateTriggeredActor( + "ExprRealFault", + "Expression", + "{\"expression\":\"Attributes[\\\"Active\\\"]?.ToString() == \\\"yes\\\"\",\"mode\":\"WhileTrue\"}", + TimeSpan.FromMilliseconds(300), + triggerExpr); + + actor.Tell(Change("Active", "yes")); + instance.ExpectMsg(TimeSpan.FromSeconds(2)); // edge fire + instance.ExpectMsg(TimeSpan.FromSeconds(2)); // tick 1 + + actor.Tell(new ScriptActor.ExpressionEvalFailed(new TimeoutException("eval timed out"))); + + // Nothing real said the condition went false: the timer keeps re-firing (pre-fix: stopped). + instance.ExpectMsg(TimeSpan.FromSeconds(2)); + instance.ExpectMsg(TimeSpan.FromSeconds(2)); + } + + /// + /// SRT-4: a Conditional WhileTrue trigger whose condition is adopted TRUE from a seed (a + /// persisted static override after failover/restart) re-fires on its cadence — without the + /// immediate edge run a seed never makes. Pre-fix it never fired again. + /// + [Fact] + public void ScriptActor_ConditionalWhileTrue_SeededTrue_StartsReFiringWithoutAnEdgeRun() + { + var (actor, instance) = CreateTriggeredActor( + "CondSeed", + "Conditional", + "{\"attributeName\":\"Temp\",\"operator\":\">\",\"threshold\":50,\"mode\":\"WhileTrue\"}", + TimeSpan.FromMilliseconds(300)); + + var sw = System.Diagnostics.Stopwatch.StartNew(); + actor.Tell(new ZB.MOM.WW.ScadaBridge.SiteRuntime.Messages.AttributeValueSeed(Change("Temp", "100"))); + + instance.ExpectMsg(TimeSpan.FromSeconds(3)); // pre-fix: never + // The first run is a TIMER tick (≥ one 300 ms interval), not an immediate edge run. + Assert.True(sw.Elapsed >= TimeSpan.FromMilliseconds(250), $"first run after {sw.Elapsed} — seed fired an edge run"); + instance.ExpectMsg(TimeSpan.FromSeconds(3)); // and it keeps re-firing + } + + /// SRT-4: the Expression twin — a seed-only evaluation that is true starts the WhileTrue timer. + [Fact] + public void ScriptActor_ExpressionWhileTrue_SeededTrue_StartsReFiringWithoutAnEdgeRun() + { + var triggerExpr = CompileTriggerExpression("Attributes[\"Active\"]?.ToString() == \"yes\""); + var (actor, instance) = CreateTriggeredActor( + "ExprSeed", + "Expression", + "{\"expression\":\"Attributes[\\\"Active\\\"]?.ToString() == \\\"yes\\\"\",\"mode\":\"WhileTrue\"}", + TimeSpan.FromMilliseconds(300), + triggerExpr); + + var sw = System.Diagnostics.Stopwatch.StartNew(); + actor.Tell(new ZB.MOM.WW.ScadaBridge.SiteRuntime.Messages.AttributeValueSeed(Change("Active", "yes"))); + + instance.ExpectMsg(TimeSpan.FromSeconds(3)); // pre-fix: never + Assert.True(sw.Elapsed >= TimeSpan.FromMilliseconds(250), $"first run after {sw.Elapsed} — seed fired an edge run"); + instance.ExpectMsg(TimeSpan.FromSeconds(3)); + } + /// Verifies that an on-true expression trigger fires once per false-to-true edge. [Fact] public void ScriptActor_ExpressionOnTrue_FiresOncePerFalseToTrueEdge() diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/StuckScriptWatchdogTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/StuckScriptWatchdogTests.cs index d0a9c082..d43852c4 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/StuckScriptWatchdogTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/StuckScriptWatchdogTests.cs @@ -127,6 +127,93 @@ public class StuckScriptWatchdogTests : TestKit, IDisposable Assert.Equal(1, scheduler.MaximumConcurrencyLevel); } + /// + /// SRT-1: a script that AWAITS before it wedges. Its continuation runs on whichever worker + /// dequeues it, under a new run stamp, so the (slot, stamp) captured in the first synchronous + /// segment no longer matches; pre-fix the watchdog answered NotRunning and never detached the + /// worker the continuation was actually blocking. Nearly every real script awaits an attribute + /// read before doing its I/O. + /// + [Fact] + public void ScriptWedgedAfterAnAwait_StillDetachesTheWorkerItIsBlocking() + { + using var scheduler = new ScriptExecutionScheduler(1); + var siteLog = new FakeSiteEventLogger(); + var options = WatchdogOptions(); + + var wedged = BuildScriptActor("AwaitThenWedge", CompileRaw( + "await Task.Delay(20); " + + "ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests.Actors.WatchdogHooks.Gate.Wait(); return null;"), + options, scheduler, new SingleServiceProvider(siteLog)); + wedged.Tell(new ScriptCallRequest("AwaitThenWedge", null, 0, "corr-await"), ActorRefs.NoSender); + + AwaitAssert( + () => Assert.Equal(1, scheduler.DetachedThreadCount), // pre-fix: stays 0 + TimeSpan.FromSeconds(15)); + AwaitAssert( + () => Assert.Contains(siteLog.OfType("script"), r => + r.Message.Contains("AwaitThenWedge") && r.Message.Contains("DETACHED")), + TimeSpan.FromSeconds(5)); + + // The replacement worker serves new work while the continuation stays wedged. + var healthy = BuildScriptActor("HealthyAfterAwait", CompileRaw("return 3;"), options, scheduler, null); + var caller = CreateTestProbe(); + healthy.Tell(new ScriptCallRequest("HealthyAfterAwait", null, 0, "corr-h"), caller.Ref); + Assert.True(caller.ExpectMsg(TimeSpan.FromSeconds(15)).Success); + + WatchdogHooks.Gate.Release(); + AwaitAssert(() => Assert.Equal(0, scheduler.DetachedThreadCount), TimeSpan.FromSeconds(15)); + } + + /// + /// SRT-10: a cancellation that is NOT the run's own deadline (an HTTP client's internal + /// timeout, a script's own token) is a failure with its real message — not "timed out after + /// N s" for a run that never reached its timeout. + /// + [Fact] + public void ForeignCancellation_IsReportedAsAFailure_NotATimeout() + { + using var scheduler = new ScriptExecutionScheduler(1); + var options = new SiteRuntimeOptions { ScriptExecutionTimeoutSeconds = 60, StuckScriptGraceMs = 200, MaxScriptCallDepth = 10 }; + + var actor = BuildScriptActor("OwnCancel", CompileRaw( + "throw new System.OperationCanceledException(\"upstream request was cancelled\");"), + options, scheduler, null); + var caller = CreateTestProbe(); + actor.Tell(new ScriptCallRequest("OwnCancel", null, 0, "corr-cancel"), caller.Ref); + + var result = caller.ExpectMsg(TimeSpan.FromSeconds(15)); + Assert.False(result.Success); + Assert.DoesNotContain("timed out", result.ErrorMessage); // pre-fix: "timed out after 60s" + Assert.Contains("upstream request was cancelled", result.ErrorMessage); + } + + /// + /// SRT-9: a script parked in Instance.CallScript past its own deadline takes the timeout + /// path AT the deadline. Pre-fix the Ask was bounded only by the full script timeout measured + /// from the call (and ignored the deadline token), so the run sailed past its deadline and + /// then failed with an Ask timeout — or, had the callee answered, carried on and completed. + /// + [Fact] + public void ScriptParkedInCallScript_TimesOutAtItsDeadline() + { + using var scheduler = new ScriptExecutionScheduler(1); + var options = new SiteRuntimeOptions { ScriptExecutionTimeoutSeconds = 2, StuckScriptGraceMs = 200, MaxScriptCallDepth = 10 }; + + // The instance (a silent probe) never answers the nested call. + var actor = BuildScriptActor("Caller", CompileRaw( + "await Task.Delay(1000); await Instance.CallScript(\"Callee\"); return 1;"), + options, scheduler, null); + var caller = CreateTestProbe(); + var sw = System.Diagnostics.Stopwatch.StartNew(); + actor.Tell(new ScriptCallRequest("Caller", null, 0, "corr-nested"), caller.Ref); + + var result = caller.ExpectMsg(TimeSpan.FromSeconds(10)); + Assert.False(result.Success); + Assert.Contains("timed out", result.ErrorMessage); // pre-fix: "failed: ... Timeout ..." at ~3 s + Assert.True(sw.Elapsed < TimeSpan.FromMilliseconds(2900), $"timed out after {sw.Elapsed}"); + } + /// Verifies that at the detach cap no further replacement is started and an error event is emitted. [Fact] public void AtTheDetachCap_NoFurtherReplacementIsStarted_AndAnErrorEventIsEmitted() diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/TriggerEvalStarvationTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/TriggerEvalStarvationTests.cs index 8e064a84..b666d452 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/TriggerEvalStarvationTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/TriggerEvalStarvationTests.cs @@ -136,9 +136,12 @@ public class TriggerEvalStarvationTests : TestKit, IDisposable /// /// GROUP 2 — the evaluation deadline is measured from ENQUEUE, so time spent waiting on a /// saturated burns the same budget. With the gate fully - /// occupied for the whole assertion window, a queued evaluation must still resolve (as - /// false) at its timeout rather than stalling indefinitely — and the trigger must drain - /// rather than park, so the next change still evaluates. + /// occupied for the whole assertion window, a queued evaluation must still resolve at its + /// timeout rather than stalling indefinitely — and the trigger must drain rather than park, + /// so the next change still evaluates. Since the 2026-12-02 review (SRT-2) a timed-out + /// evaluation is "unknown": it resolves WITHOUT changing the alarm's state (it used to be + /// coerced to false and clear the alarm), and reports a rate-limited site event — that event + /// is the proof it resolved at its deadline. /// /// A task that represents the asynchronous operation. [Fact] @@ -147,6 +150,8 @@ public class TriggerEvalStarvationTests : TestKit, IDisposable using var scheduler = new ScriptExecutionScheduler(1); using var evalGate = new TriggerEvalGate(1); var options = new SiteRuntimeOptions { TriggerEvalTimeoutSeconds = 1 }; + var siteLog = new TestSupport.FakeSiteEventLogger(); + IServiceProvider services = new TestSupport.SingleServiceProvider(siteLog); var instanceProbe = CreateTestProbe(); var alarm = ActorOf(Props.Create(() => new AlarmActor( @@ -155,11 +160,11 @@ public class TriggerEvalStarvationTests : TestKit, IDisposable { CanonicalName = "ExprAlarm", TriggerType = "Expression", - TriggerConfiguration = "{\"expression\":\"true\"}", + TriggerConfiguration = "{\"expression\":\"Attributes[\\\"A\\\"]?.ToString() != \\\"0\\\"\"}", PriorityLevel = 500 }, null, _sharedLibrary, options, NullLogger.Instance, - CompileTriggerExpression("true"), null, null, null, null, scheduler, evalGate))); + CompileTriggerExpression("Attributes[\"A\"]?.ToString() != \"0\""), null, null, services, null, scheduler, evalGate))); // 1. Free gate: the expression evaluates true and the alarm raises. alarm.Tell(new AttributeValueChanged("Inst1", "A", "A", 1, "Good", DateTimeOffset.UtcNow)); @@ -171,23 +176,27 @@ public class TriggerEvalStarvationTests : TestKit, IDisposable Assert.Equal(0, evalGate.AvailablePermits); // 3. The next evaluation can never acquire the gate. Its deadline was armed at - // enqueue, so it cancels at ~1 s, is treated as false, and clears the alarm. - // Previously the clock started at dequeue, so this would hang forever. + // enqueue, so it cancels at ~1 s and resolves as UNKNOWN: the alarm stays Active and a + // site event reports the failed evaluation. Previously the clock started at dequeue, + // so this would hang forever (and before SRT-2 it cleared the alarm). var stopwatch = Stopwatch.StartNew(); - alarm.Tell(new AttributeValueChanged("Inst1", "A", "A", 2, "Good", DateTimeOffset.UtcNow)); - var cleared = instanceProbe.ExpectMsg(TimeSpan.FromSeconds(10)); + alarm.Tell(new AttributeValueChanged("Inst1", "A", "A", 0, "Good", DateTimeOffset.UtcNow)); + AwaitAssert(() => Assert.Contains(siteLog.OfType("alarm"), e => + e.Message.Contains("could not be evaluated", StringComparison.Ordinal)), + TimeSpan.FromSeconds(10), TimeSpan.FromMilliseconds(50)); stopwatch.Stop(); - Assert.Equal(AlarmState.Normal, cleared.State); Assert.True(stopwatch.Elapsed < TimeSpan.FromSeconds(6), $"queued evaluation took {stopwatch.Elapsed} to resolve — the deadline is not enqueue-anchored"); Assert.Equal(0, evalGate.AvailablePermits); // still held: it genuinely never ran + instanceProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(200)); // no state change from an unknown result - // 4. Not parked: releasing the gate and sending another change evaluates again. + // 4. Not parked: releasing the gate and sending another change evaluates again — the + // genuine false now clears the alarm. evalGate.Release(); - alarm.Tell(new AttributeValueChanged("Inst1", "A", "A", 3, "Good", DateTimeOffset.UtcNow)); - var reRaised = instanceProbe.ExpectMsg(TimeSpan.FromSeconds(10)); - Assert.Equal(AlarmState.Active, reRaised.State); + alarm.Tell(new AttributeValueChanged("Inst1", "A", "A", 0, "Good", DateTimeOffset.UtcNow)); + var cleared = instanceProbe.ExpectMsg(TimeSpan.FromSeconds(10)); + Assert.Equal(AlarmState.Normal, cleared.State); } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Scripts/NotifyHelperTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Scripts/NotifyHelperTests.cs index ca280820..fb909325 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Scripts/NotifyHelperTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Scripts/NotifyHelperTests.cs @@ -276,10 +276,14 @@ public class NotifyHelperTests : TestKit, IAsyncLifetime, IDisposable Assert.Null(payload!.SourceScript); } - /// Verifies that status, when still buffered at site, reports forwarding. + /// + /// Verifies that status, when still buffered at site, reports forwarding — answered + /// site-locally WITHOUT asking central (2026-12-02 review SRT-8: it used to ask central first, + /// with the script's whole execution timeout, exactly when central is unreachable). + /// /// A task that represents the asynchronous operation. [Fact] - public async Task Status_WhenStillBufferedAtSite_ReportsForwarding() + public async Task Status_WhenStillBufferedAtSite_ReportsForwarding_WithoutAskingCentral() { var commProbe = CreateTestProbe(); var notify = CreateHelper(commProbe.Ref); @@ -287,20 +291,32 @@ public class NotifyHelperTests : TestKit, IAsyncLifetime, IDisposable // Enqueue but never let it forward — the message stays buffered at the site. var notificationId = await notify.To("Operators").Send("Pump alarm", "Pump 3 tripped"); - var statusTask = notify.Status(notificationId); + // Nobody answers on the central side: the call must still return promptly. + var status = await notify.Status(notificationId).WaitAsync(TimeSpan.FromSeconds(2)); - // The status query goes to central; central has no row for an un-forwarded - // notification, so it answers Found: false. - var query = await commProbe.ExpectMsgAsync(); - Assert.Equal(notificationId, query.NotificationId); - commProbe.Reply(new NotificationStatusResponse( - query.CorrelationId, Found: false, Status: "Unknown", - RetryCount: 0, LastError: null, DeliveredAt: null)); - - var status = await statusTask; - - // Found: false AND still in the site S&F buffer → the site-local Forwarding state. Assert.Equal("Forwarding", status.Status); + commProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(200)); // pre-fix: a NotificationStatusQuery + } + + /// + /// SRT-8: the central query is bounded by the run's deadline token — a run whose deadline + /// fires while central is silent takes the timeout path rather than waiting out the Ask. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Status_CentralQuery_IsCancelledByTheRunDeadline() + { + var commProbe = CreateTestProbe(); + using var deadline = new CancellationTokenSource(); + var notify = new ScriptRuntimeContext.NotifyHelper( + _saf, commProbe.Ref, "site-7", "Plant.Pump3", null, TimeSpan.FromSeconds(30), + NullLogger.Instance, Guid.NewGuid(), scriptTimeoutToken: deadline.Token); + + var statusTask = notify.Status("not-buffered-id"); + await commProbe.ExpectMsgAsync(); + deadline.Cancel(); + + await Assert.ThrowsAnyAsync(() => statusTask.WaitAsync(TimeSpan.FromSeconds(5))); } /// Verifies that status, when central reports delivered, maps the central response. diff --git a/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardServiceTests.cs b/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardServiceTests.cs index bbb1c465..9dca8b06 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardServiceTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardServiceTests.cs @@ -842,6 +842,105 @@ public class StoreAndForwardServiceTests : IAsyncLifetime, IDisposable Assert.Equal(1, maxConcurrent); // one (category,target) lane: strictly sequential } + // ── SF-1: per-target FIFO across sweeps ── + + private async Task ExecSqlAsync(string sql) + { + await using var conn = _localDb.Db.CreateConnection(); + await using var cmd = conn.CreateCommand(); + cmd.CommandText = sql; + await cmd.ExecuteNonQueryAsync(); + } + + /// Back-dates a buffered row's last attempt so it is due on the next sweep. + private Task MakeDueAsync(string id) => ExecSqlAsync( + $"UPDATE sf_messages SET last_attempt_at_ms = {DateTimeOffset.UtcNow.AddMinutes(-5).ToUnixTimeMilliseconds()} WHERE id = '{id}'"); + + /// + /// SF-1 (the review's exact scenario): A then B to one target. The head A fails, so its + /// last attempt moves to now while B keeps its older stamp. On the next sweep B is due and + /// A is not — pre-fix B was delivered first and A's later delivery overwrote B's newer + /// value. The lane must wait for its head. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task RetrySweep_YoungerRow_NeverPassesBackingOffHead() + { + var delivered = new List(); + var targetUp = false; + _service.RegisterDeliveryHandler(StoreAndForwardCategory.CachedDbWrite, msg => + { + if (!targetUp) throw new TimeoutException("Mes down"); + delivered.Add(msg.Id); + return Task.FromResult(true); + }); + + await _service.EnqueueAsync(StoreAndForwardCategory.CachedDbWrite, "Mes", "{}", + attemptImmediateDelivery: false, retryInterval: TimeSpan.FromSeconds(30), messageId: "A"); + await _service.EnqueueAsync(StoreAndForwardCategory.CachedDbWrite, "Mes", "{}", + attemptImmediateDelivery: false, retryInterval: TimeSpan.FromSeconds(30), messageId: "B"); + await MakeDueAsync("A"); + await MakeDueAsync("B"); + + // Sweep 1: A is attempted and fails (its last attempt is now "now"); B is skipped. + await _service.RetryPendingMessagesAsync(); + Assert.Empty(delivered); + + // The target recovers. B is still due by its own stamp, A is not. + targetUp = true; + await _service.RetryPendingMessagesAsync(); + Assert.Empty(delivered); // pre-fix: ["B"] + + // Once the head is due, the lane drains in enqueue order. + await MakeDueAsync("A"); + await _service.RetryPendingMessagesAsync(); + Assert.Equal(new[] { "A", "B" }, delivered); + } + + // ── SF-2: storage failure after a successful delivery ── + + /// + /// SF-2: the handler succeeded but the row delete fails. The delivery must not be counted + /// as a failed retry (pre-fix: RetryCount++ and, on the last allowed retry, Parked — an + /// operator Retry then re-sent a call that had succeeded). The row stays Pending with its + /// counters untouched, and the lane stops so the younger row is not delivered ahead of + /// the head's re-delivery. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task RetrySweep_DeleteFailsAfterDelivery_IsNotCountedAsFailure() + { + var delivered = new List(); + _service.RegisterDeliveryHandler(StoreAndForwardCategory.ExternalSystem, msg => + { + delivered.Add(msg.Id); + return Task.FromResult(true); + }); + await _service.EnqueueAsync(StoreAndForwardCategory.ExternalSystem, "api", "{}", + attemptImmediateDelivery: false, retryInterval: TimeSpan.Zero, maxRetries: 1, messageId: "head"); + await _service.EnqueueAsync(StoreAndForwardCategory.ExternalSystem, "api", "{}", + attemptImmediateDelivery: false, retryInterval: TimeSpan.Zero, maxRetries: 1, messageId: "next"); + + await ExecSqlAsync( + "CREATE TRIGGER fail_delete BEFORE DELETE ON sf_messages BEGIN SELECT RAISE(ABORT, 'disk I/O error'); END;"); + + await _service.RetryPendingMessagesAsync(); + + Assert.Equal(new[] { "head" }, delivered); // lane stopped after the head + var head = await _service.GetMessageByIdAsync("head"); + Assert.NotNull(head); + Assert.Equal(StoreAndForwardMessageStatus.Pending, head!.Status); // pre-fix: Parked + Assert.Equal(0, head.RetryCount); // pre-fix: 1 + Assert.Null(head.LastError); + + // Storage recovers: the head is re-delivered (at-least-once) and the lane drains in order. + await ExecSqlAsync("DROP TRIGGER fail_delete;"); + await _service.RetryPendingMessagesAsync(); + Assert.Equal(new[] { "head", "head", "next" }, delivered); + Assert.Null(await _service.GetMessageByIdAsync("head")); + Assert.Null(await _service.GetMessageByIdAsync("next")); + } + private static void InterlockedMax(ref int target, int value) { int current; diff --git a/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardStorageTests.cs b/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardStorageTests.cs index d55c495e..6851f5aa 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardStorageTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardStorageTests.cs @@ -135,18 +135,23 @@ public class StoreAndForwardStorageTests : IAsyncLifetime, IDisposable { // Exercise the julianday elapsed-time comparison with a // non-zero retry interval. A message attempted just now must NOT be due; one - // attempted long ago must be due. + // attempted long ago must be due. Each row is its own (category, target) lane: + // within ONE lane a not-due older row would hold back the rows behind it (SF-1, + // covered by GetMessagesForRetry_RowBehindNotDueHead_IsNotReturned). var notDue = CreateMessage("notdue", StoreAndForwardCategory.ExternalSystem); + notDue.Target = "lane-notdue"; notDue.RetryIntervalMs = (long)TimeSpan.FromHours(1).TotalMilliseconds; notDue.LastAttemptAt = DateTimeOffset.UtcNow; await _storage.EnqueueAsync(notDue); var due = CreateMessage("due", StoreAndForwardCategory.ExternalSystem); + due.Target = "lane-due"; due.RetryIntervalMs = (long)TimeSpan.FromMinutes(5).TotalMilliseconds; due.LastAttemptAt = DateTimeOffset.UtcNow.AddHours(-2); await _storage.EnqueueAsync(due); var neverAttempted = CreateMessage("never", StoreAndForwardCategory.ExternalSystem); + neverAttempted.Target = "lane-never"; neverAttempted.RetryIntervalMs = (long)TimeSpan.FromHours(1).TotalMilliseconds; neverAttempted.LastAttemptAt = null; await _storage.EnqueueAsync(neverAttempted); @@ -853,6 +858,60 @@ public class StoreAndForwardStorageTests : IAsyncLifetime, IDisposable Assert.Equal("a000", dead[0]); } + /// + /// SF-1: due-ness is per lane. A younger row whose own stamp is due must not be returned + /// while an older pending row of the SAME lane is still backing off; another lane is + /// unaffected. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task GetMessagesForRetry_RowBehindNotDueHead_IsNotReturned() + { + var now = DateTimeOffset.UtcNow; + var head = NewMsg("head", StoreAndForwardMessageStatus.Pending, now.AddMinutes(-10)); + head.LastAttemptAt = now; // just failed: not due for 30 s + var behind = NewMsg("behind", StoreAndForwardMessageStatus.Pending, now.AddMinutes(-9)); + behind.LastAttemptAt = now.AddMinutes(-5); // due by its own stamp + var other = NewMsg("other", StoreAndForwardMessageStatus.Pending, now.AddMinutes(-8)); + other.Target = "other-target"; + other.LastAttemptAt = now.AddMinutes(-5); + await _storage.EnqueueAsync(head); + await _storage.EnqueueAsync(behind); + await _storage.EnqueueAsync(other); + + foreach (var limit in new[] { 0, 500 }) + { + var ids = (await _storage.GetMessagesForRetryAsync(limit)).Select(m => m.Id).ToList(); + Assert.Equal(new[] { "other" }, ids); // pre-fix: behind, other + } + } + + /// + /// SF-1: an older PARKED row does not block its lane (only pending rows hold a lane), and + /// a due head releases the rows behind it in enqueue order. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task GetMessagesForRetry_ParkedOlderRow_DoesNotBlockLane() + { + var now = DateTimeOffset.UtcNow; + var parked = NewMsg("parked", StoreAndForwardMessageStatus.Parked, now.AddMinutes(-10)); + parked.LastAttemptAt = now; + var a = NewMsg("a", StoreAndForwardMessageStatus.Pending, now.AddMinutes(-9)); + a.LastAttemptAt = now.AddMinutes(-5); + var b = NewMsg("b", StoreAndForwardMessageStatus.Pending, now.AddMinutes(-8)); + b.LastAttemptAt = now.AddMinutes(-5); + var c = NewMsg("c", StoreAndForwardMessageStatus.Pending, now.AddMinutes(-7)); + c.LastAttemptAt = now; // not due: blocks nothing older, holds itself back + await _storage.EnqueueAsync(parked); + await _storage.EnqueueAsync(a); + await _storage.EnqueueAsync(b); + await _storage.EnqueueAsync(c); + + var ids = (await _storage.GetMessagesForRetryAsync(500)).Select(m => m.Id).ToList(); + Assert.Equal(new[] { "a", "b" }, ids); + } + // ReplaceAll_SwapsTheEntireBuffer_Atomically was DELETED with ReplaceAllAsync in // LocalDb Phase 2, and deliberately not replaced. It asserted a destructive // delete-all-then-insert-all, which was the standby's anti-entropy apply: a resync