From 6adfc9f44909d2c1467235eec3e7baed46311860 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:49:57 -0500 Subject: [PATCH] fix(dcl): seeds never overwrite a newer live value; Good on reconnect resets only the subscribe backoff (DCL-1, SRT-6, WP3 tasks 3.1 + 3.8) 3.1: seed values are flagged on TagValueReceived; a reconnect/resolution re-seed for a tag that already delivered a live value in the current adapter generation is dropped, an initial-subscribe seed is replaced by the latest live value (a joining instance may have missed earlier live values). 3.8: the connection actor tells subscribers ConnectionQualityChanged(Good) on re-entering Connected; InstanceActor's Good branch only resets the Lever-1 backoff and no longer stamps bound attributes Good. --- .../Component-DataConnectionLayer.md | 2 +- docs/requirements/Component-SiteRuntime.md | 2 +- .../Actors/DataConnectionActor.cs | 113 +++++++- .../Actors/InstanceActor.cs | 17 +- .../Actors/DataConnectionReconfigureTests.cs | 2 + .../Actors/DataConnectionSeedOrderingTests.cs | 258 ++++++++++++++++++ .../DataConnectionActorTests.cs | 2 + .../Actors/InstanceActorTests.cs | 28 ++ 8 files changed, 411 insertions(+), 13 deletions(-) create mode 100644 tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Actors/DataConnectionSeedOrderingTests.cs diff --git a/docs/requirements/Component-DataConnectionLayer.md b/docs/requirements/Component-DataConnectionLayer.md index ccf6e6a5..9407dbd6 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 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). **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. diff --git a/docs/requirements/Component-SiteRuntime.md b/docs/requirements/Component-SiteRuntime.md index 9689308a..319325f7 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). diff --git a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Actors/DataConnectionActor.cs b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Actors/DataConnectionActor.cs index 64ddc575..aea38159 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Actors/DataConnectionActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Actors/DataConnectionActor.cs @@ -1260,6 +1260,7 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers ReSubscribeAllAlarms(); BecomeConnected(); + PushConnectionRestored(); } else { @@ -1970,7 +1971,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)); } } @@ -2633,7 +2634,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) { @@ -2819,6 +2820,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() @@ -2993,7 +3015,7 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers { 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 +3063,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 +3101,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 +3140,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 +3151,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 +3165,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(); } @@ -3593,7 +3662,35 @@ 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; /// Coalescing-timer tick for the tag-quality counter push. diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs index 9b554c6e..4a3bf268 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs @@ -1415,11 +1415,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 +1441,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 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/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/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/InstanceActorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorTests.cs index 1351c0a2..f656ad5e 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorTests.cs @@ -1638,6 +1638,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()