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.
This commit is contained in:
+2
@@ -188,6 +188,8 @@ public class DataConnectionReconfigureTests : TestKit
|
||||
ExpectMsg<ConnectionQualityChanged>(TimeSpan.FromSeconds(5));
|
||||
|
||||
AwaitCondition(() => Subscribed(newAdapter), TimeSpan.FromSeconds(5));
|
||||
// Re-entering Connected tells the subscriber Good (SRT-6 restore signal).
|
||||
ExpectMsg<ConnectionQualityChanged>(m => m.Quality == QualityCode.Good, TimeSpan.FromSeconds(5));
|
||||
ExpectNoMsg(TimeSpan.FromMilliseconds(300));
|
||||
|
||||
oldCallback!("sensor/temp", new TagValue(999, QualityCode.Good, DateTimeOffset.UtcNow));
|
||||
|
||||
+258
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <c>ConnectionQualityChanged(Good)</c> when it re-enters Connected.
|
||||
/// </summary>
|
||||
[Collection("DataConnectionManagerActor")]
|
||||
public class DataConnectionSeedOrderingTests : TestKit
|
||||
{
|
||||
private const string Tag = "Mixer.State";
|
||||
private const string OtherTag = "Mixer.Speed";
|
||||
|
||||
private readonly ISiteHealthCollector _health = Substitute.For<ISiteHealthCollector>();
|
||||
private readonly IDataConnectionFactory _factory = Substitute.For<IDataConnectionFactory>();
|
||||
|
||||
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<string, string> { ["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);
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
[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<TagValueUpdate>(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<string, object> { [Tag] = "Idle" });
|
||||
instance.ExpectMsg<SubscribeTagsResponse>(r => r.Success, TimeSpan.FromSeconds(5));
|
||||
var afterSeed = instance.ExpectMsg<TagValueUpdate>(TimeSpan.FromSeconds(5));
|
||||
Assert.Equal("Running", afterSeed.Value); // pre-fix: "Idle"
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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<string, object> { [Tag] = "Idle" });
|
||||
instance.ExpectMsg<SubscribeTagsResponse>(r => r.Success, TimeSpan.FromSeconds(5));
|
||||
Assert.Equal("Idle", instance.ExpectMsg<TagValueUpdate>(TimeSpan.FromSeconds(5)).Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
[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<SubscribeTagsResponse>(r => r.Success, TimeSpan.FromSeconds(5));
|
||||
adapter.ClearCallbacks();
|
||||
|
||||
var reseedGate = adapter.GateNextRead();
|
||||
adapter.RaiseDisconnected();
|
||||
var bad = instance.ExpectMsg<ConnectionQualityChanged>(TimeSpan.FromSeconds(5));
|
||||
Assert.Equal(QualityCode.Bad, bad.Quality);
|
||||
AwaitConnectedCount(name, 2);
|
||||
var good = instance.ExpectMsg<ConnectionQualityChanged>(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<TagValueUpdate>(TimeSpan.FromSeconds(5)).Value);
|
||||
|
||||
reseedGate.Release(new Dictionary<string, object> { [Tag] = "Idle", [OtherTag] = 7 });
|
||||
|
||||
// OtherTag never re-reported live, so its seed is delivered; Tag's seed must not be.
|
||||
var seen = new List<TagValueUpdate>();
|
||||
instance.FishForMessage<TagValueUpdate>(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);
|
||||
}
|
||||
|
||||
/// <summary>One held <c>ReadBatchAsync</c> call.</summary>
|
||||
internal sealed class ReadGate
|
||||
{
|
||||
private readonly TaskCompletionSource<Dictionary<string, object>> _tcs =
|
||||
new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
public Task<Dictionary<string, object>> Values => _tcs.Task;
|
||||
|
||||
public void Release(Dictionary<string, object> values) => _tcs.SetResult(values);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal sealed class SeedGatedAdapter : IDataConnection, IBatchSubscribableConnection
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, SubscriptionCallback> _callbacks = new();
|
||||
private readonly ConcurrentQueue<ReadGate> _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<string, string> connectionDetails, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Status = ConnectionHealth.Connected;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task DisconnectAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
|
||||
|
||||
public Task<IReadOnlyList<TagSubscribeResult>> SubscribeBatchAsync(
|
||||
IReadOnlyList<string> tagPaths, SubscriptionCallback callback, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var rows = new List<TagSubscribeResult>();
|
||||
foreach (var tag in tagPaths)
|
||||
{
|
||||
_callbacks[tag] = callback;
|
||||
rows.Add(new TagSubscribeResult(tag, true, $"h{Interlocked.Increment(ref _handle)}", null));
|
||||
}
|
||||
return Task.FromResult<IReadOnlyList<TagSubscribeResult>>(rows);
|
||||
}
|
||||
|
||||
public Task UnsubscribeBatchAsync(IReadOnlyList<string> subscriptionIds, CancellationToken cancellationToken = default) =>
|
||||
Task.CompletedTask;
|
||||
|
||||
public Task<string> 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<ReadResult> ReadAsync(string tagPath, CancellationToken cancellationToken = default) =>
|
||||
Task.FromResult(new ReadResult(false, null, "no value"));
|
||||
|
||||
public async Task<IReadOnlyDictionary<string, ReadResult>> ReadBatchAsync(
|
||||
IEnumerable<string> tagPaths, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var values = _readGates.TryDequeue(out var gate)
|
||||
? await gate.Values
|
||||
: new Dictionary<string, object>();
|
||||
return tagPaths
|
||||
.Where(values.ContainsKey)
|
||||
.ToDictionary(t => t, t => new ReadResult(true,
|
||||
new TagValue(values[t], QualityCode.Good, DateTimeOffset.UtcNow), null));
|
||||
}
|
||||
|
||||
public Task<WriteResult> WriteAsync(string tagPath, object? value, CancellationToken cancellationToken = default) =>
|
||||
Task.FromResult(new WriteResult(true, null));
|
||||
|
||||
public Task<IReadOnlyDictionary<string, WriteResult>> WriteBatchAsync(
|
||||
IDictionary<string, object?> values, CancellationToken cancellationToken = default) =>
|
||||
Task.FromResult<IReadOnlyDictionary<string, WriteResult>>(
|
||||
values.ToDictionary(kv => kv.Key, _ => new WriteResult(true, null)));
|
||||
|
||||
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -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<ConnectionQualityChanged>(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.
|
||||
|
||||
@@ -1638,6 +1638,34 @@ public class InstanceActorTests : TestKit, IDisposable
|
||||
Assert.True(sw.Elapsed < TimeSpan.FromMilliseconds(1000), $"retry took {sw.Elapsed} — backoff not reset");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SRT-6 / WP3 task 3.8: the DCL's <c>ConnectionQualityChanged(Good)</c> 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.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void ConnectionBackToGood_DoesNotStampBoundAttributesGood()
|
||||
{
|
||||
var (instance, dclProbe) = CreateInstanceWithDataSourcedAttribute(new SiteRuntimeOptions());
|
||||
dclProbe.ExpectMsg<SubscribeTagsRequest>();
|
||||
|
||||
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<GetAttributeResponse>(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<GetAttributeResponse>(TimeSpan.FromSeconds(5));
|
||||
Assert.Equal("Good", good.Quality);
|
||||
Assert.Equal(43, good.Value);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that a late reply for a failed and re-issued request is ignored.</summary>
|
||||
[Fact]
|
||||
public void LateReplyForFailedAndReissuedRequest_IsIgnored()
|
||||
|
||||
Reference in New Issue
Block a user