Merge driver follow-ups A: Modbus RTU response correlation + cancel redial + rebuild e2e (#1029/#1055), MTConnect malformed-item BadDecodingError + cross-chunk condition severity (#1055/#1037), TwinCAT write fail-fast + retired-client reads (#1035), OpcUaClient skipped-tag ledger append + zone-qualified IPv6 probe (#1039)

This commit is contained in:
Joseph Doherty
2026-12-03 15:25:42 -05:00
28 changed files with 1137 additions and 38 deletions
@@ -826,6 +826,74 @@ public sealed class MTConnectObservationIndexTests
idx.Get("e").Value.ShouldBe("Normal");
}
private static MTConnectObservation CondCode(string state, string code, int second) =>
new("c", state, new DateTime(2026, 7, 24, 12, 0, second, DateTimeKind.Utc),
Condition: new MTConnectConditionDetail(null, code, null, null, null));
/// <summary>#1037: the value word comes from the tracker, so two codes in one chunk read the most severe, not the last.</summary>
[Fact]
public void With_a_tracker_two_codes_in_one_chunk_read_the_most_severe()
{
var idx = new MTConnectObservationIndex([new MTConnectTagDefinition("c", DriverDataType.String, MtCategory: "CONDITION")]);
var tracker = new MTConnectConditionTracker();
var chunk = new MTConnectStreamsResult(1L, 3L, 1L, [CondCode("Fault", "A", 0), CondCode("Warning", "B", 1)]);
tracker.Apply(chunk, baseline: false);
idx.Apply(chunk, baseline: false, tracker);
idx.Get("c").Value.ShouldBe("Fault");
// Control: with no tracker the per-document reconcile is last-wins (unchanged behaviour).
var bare = new MTConnectObservationIndex([new MTConnectTagDefinition("c", DriverDataType.String, MtCategory: "CONDITION")]);
bare.Apply(chunk);
bare.Get("c").Value.ShouldBe("Warning");
}
/// <summary>#1037: across chunks, a Warning on B does not mask A's Fault, and clearing A leaves B's Warning.</summary>
[Fact]
public void With_a_tracker_a_later_chunk_cannot_mask_a_still_active_fault()
{
var idx = new MTConnectObservationIndex([new MTConnectTagDefinition("c", DriverDataType.String, MtCategory: "CONDITION")]);
var tracker = new MTConnectConditionTracker();
void Feed(params MTConnectObservation[] o)
{
var doc = new MTConnectStreamsResult(1L, 3L, 1L, o);
tracker.Apply(doc, baseline: false);
idx.Apply(doc, baseline: false, tracker);
}
Feed(CondCode("Fault", "A", 0));
Feed(CondCode("Warning", "B", 1));
idx.Get("c").Value.ShouldBe("Fault");
Feed(CondCode("Normal", "A", 2));
idx.Get("c").Value.ShouldBe("Warning");
Feed(CondCode("Normal", "B", 3));
idx.Get("c").Value.ShouldBe("Normal");
Feed(CondCode("Fault", "A", 4));
Feed(new MTConnectObservation("c", "UNAVAILABLE", new DateTime(2026, 7, 24, 12, 0, 5, DateTimeKind.Utc),
Condition: new MTConnectConditionDetail(null, null, null, null, null)));
idx.Get("c").StatusCode.ShouldBe(BadNoCommunication);
}
/// <summary>#1055: a skipped observation that named its item turns it BadDecodingError; a valid one in the same document wins.</summary>
[Fact]
public void A_malformed_data_item_reads_BadDecodingError_and_a_valid_observation_replaces_it()
{
var idx = new MTConnectObservationIndex([Tag("x", DriverDataType.Int64), Tag("y", DriverDataType.Int64)]);
idx.Apply(new MTConnectStreamsResult(1L, 3L, 1L, [
new MTConnectObservation("x", "1", new DateTime(2026, 7, 24, 12, 0, 0, DateTimeKind.Utc)),
new MTConnectObservation("y", "1", new DateTime(2026, 7, 24, 12, 0, 0, DateTimeKind.Utc)),
]));
idx.Apply(new MTConnectStreamsResult(1L, 4L, 1L, [
new MTConnectObservation("y", "2", new DateTime(2026, 7, 24, 12, 0, 1, DateTimeKind.Utc)),
], null, 2, "bad", ["x", "y"]));
idx.Get("x").StatusCode.ShouldBe(0x80070000u);
idx.Get("y").Value.ShouldBe(2L);
idx.Get("y").StatusCode.ShouldBe(Good);
}
/// <summary>An active fault carries more information than "no value"; it outranks UNAVAILABLE.</summary>
[Fact]
public void An_active_fault_outranks_unavailable_within_one_apply()
@@ -232,4 +232,98 @@ public sealed class MTConnectReview20261202Tests
await driver.ShutdownAsync(Ct);
}
// ------------------------------------------------------------------------------ #1037 / #1055 follow-ups
private static MTConnectDriverOptions CondOpts() =>
new()
{
AgentUri = "http://fixture-agent:5000",
RequestTimeoutMs = 5000,
Tags =
[
new MTConnectTagDefinition("dev1_pos", DriverDataType.Float64),
new MTConnectTagDefinition("dev1_execution", DriverDataType.String),
new MTConnectTagDefinition("dev1_cond", DriverDataType.String, MtCategory: "CONDITION"),
],
};
private static MTConnectObservation CondObs(string state, string? code, int second) =>
new("dev1_cond", state, ObservedAt.AddSeconds(second),
Condition: new MTConnectConditionDetail(null, code, null, null, null));
/// <summary>
/// #1037. The condition item's plain value tag is derived from the tracker: a Warning on code B in a LATER chunk must not
/// mask the still-active Fault on code A, and clearing A then leaves B's Warning (not "Normal").
/// </summary>
[Fact]
public async Task A_condition_value_tag_keeps_the_most_severe_active_code_across_chunks()
{
var client = CannedAgentClient.FromFixtures();
var driver = new MTConnectDriver(CondOpts(), "mt1", _ => client);
var seen = Record(driver);
await driver.InitializeAsync("{}", Ct);
await driver.SubscribeAsync(["dev1_cond"], TimeSpan.FromMilliseconds(50), Ct);
string? Latest() => seen.Where(e => e.FullReference == "dev1_cond").Select(e => e.Snapshot.Value as string).LastOrDefault();
await client.PumpAsync(new(FixtureInstanceId, 109, 108, [CondObs("Fault", "A", 1)])).WaitAsync(Watchdog, Ct);
Latest().ShouldBe("Fault");
await client.PumpAsync(new(FixtureInstanceId, 110, 109, [CondObs("Warning", "B", 2)])).WaitAsync(Watchdog, Ct);
Latest().ShouldBe("Fault", "a Warning on code B must not mask code A's still-active Fault");
await client.PumpAsync(new(FixtureInstanceId, 111, 110, [CondObs("Normal", "A", 3)])).WaitAsync(Watchdog, Ct);
Latest().ShouldBe("Warning", "code B is still active");
await client.PumpAsync(new(FixtureInstanceId, 112, 111, [CondObs("Normal", "B", 4)])).WaitAsync(Watchdog, Ct);
Latest().ShouldBe("Normal");
await driver.ShutdownAsync(Ct);
}
/// <summary>#1037 / #1055: the SAME chunk carrying Fault(A) then Warning(B) reads Fault, not the last word.</summary>
[Fact]
public async Task Two_codes_in_one_chunk_read_the_most_severe_not_the_last()
{
var client = CannedAgentClient.FromFixtures();
var driver = new MTConnectDriver(CondOpts(), "mt1", _ => client);
var seen = Record(driver);
await driver.InitializeAsync("{}", Ct);
await driver.SubscribeAsync(["dev1_cond"], TimeSpan.FromMilliseconds(50), Ct);
await client.PumpAsync(new(FixtureInstanceId, 109, 108, [CondObs("Fault", "A", 1), CondObs("Warning", "B", 2)]))
.WaitAsync(Watchdog, Ct);
seen.Where(e => e.FullReference == "dev1_cond").Last().Snapshot.Value.ShouldBe("Fault");
await driver.ShutdownAsync(Ct);
}
/// <summary>
/// #1055. An observation skipped for an unparseable timestamp still names its item: the item must read
/// BadDecodingError instead of its last Good value standing forever, and recover on the next valid observation.
/// </summary>
[Fact]
public async Task A_malformed_observation_marks_its_item_BadDecodingError_until_the_next_valid_one()
{
var client = CannedAgentClient.FromFixtures();
var driver = new MTConnectDriver(Opts(), "mt1", _ => client);
var seen = Record(driver);
await driver.InitializeAsync("{}", Ct);
await driver.SubscribeAsync(["dev1_pos"], TimeSpan.FromMilliseconds(50), Ct);
await client.PumpAsync(Chunk(FixtureInstanceId, 108, 109, ("dev1_pos", "1.5"))).WaitAsync(Watchdog, Ct);
seen.Where(e => e.FullReference == "dev1_pos").Last().Snapshot.StatusCode.ShouldBe(Good);
await client.PumpAsync(new(FixtureInstanceId, 110, 109, [], null, 1, "timestamp", ["dev1_pos"])).WaitAsync(Watchdog, Ct);
seen.Where(e => e.FullReference == "dev1_pos").Last().Snapshot.StatusCode.ShouldBe(0x80070000u);
await client.PumpAsync(Chunk(FixtureInstanceId, 110, 111, ("dev1_pos", "2.5"))).WaitAsync(Watchdog, Ct);
var recovered = seen.Where(e => e.FullReference == "dev1_pos").Last().Snapshot;
recovered.StatusCode.ShouldBe(Good);
recovered.Value.ShouldBe(2.5d);
await driver.ShutdownAsync(Ct);
}
}
@@ -503,6 +503,20 @@ public sealed class MTConnectStreamsParseTests
result.InstanceId.ShouldBe(1L);
}
/// <summary>#1055: a skip that still names its item reports the id (so the index can mark it Bad); an id-less one cannot.</summary>
[Theory]
[InlineData("""<Position timestamp="2026-07-24T12:00:00Z">1</Position>""", null)] // no dataItemId: unattributable
[InlineData("""<Position dataItemId="p">1</Position>""", "p")] // no timestamp
[InlineData("""<Position dataItemId="p" timestamp="whenever">1</Position>""", "p")] // unparseable timestamp
public void Parse_reports_the_data_item_of_a_skipped_observation_when_it_names_one(string observationXml, string? expectedId)
{
var result = MTConnectStreamsParser.Parse(StreamsDocument($"""<Samples>{observationXml}</Samples>"""));
result.SkippedObservations.ShouldBe(1);
if (expectedId is null) result.MalformedDataItemIds.ShouldBeNull();
else result.MalformedDataItemIds.ShouldBe([expectedId]);
}
/// <summary>M-8 positive control: a clean document reports nothing skipped.</summary>
[Fact]
public void Parse_of_a_clean_document_reports_nothing_skipped()
@@ -175,4 +175,48 @@ public sealed class ModbusCallerCancelDesyncTests
(await transport.SendAsync(1, ReadPdu(9), ct)).ShouldBe(new byte[] { 0x03, 0x02, 0x00, 0x09 });
server.Accepted.ShouldBe(1, "the teardown must be tied to the cancelled exit, not to every call");
}
/// <summary>
/// #1055: with auto-reconnect OFF a caller-cancelled RTU transaction used to leave the transport dead (the
/// discarded socket was never re-dialled) until the 90 s watchdog re-initialised the driver. The discard was
/// ours, so one redial is owed; a real link fault under auto-reconnect OFF must still stay down.
/// </summary>
[Fact]
public async Task RtuOverTcp_AutoReconnectOff_caller_cancel_still_redials_for_the_next_read()
{
var ct = TestContext.Current.CancellationToken;
await using var server = new LateReplyServer(rtu: true);
await using var transport = new ModbusRtuOverTcpTransport("127.0.0.1", server.Port, TimeSpan.FromSeconds(5), autoReconnect: false);
await transport.ConnectAsync(ct);
using var cancel = new CancellationTokenSource();
var first = transport.SendAsync(1, ReadPdu(5), cancel.Token);
await server.FirstReceived.WaitAsync(TimeSpan.FromSeconds(5), ct);
await cancel.CancelAsync();
await Should.ThrowAsync<OperationCanceledException>(first);
server.ReleaseFirst();
(await transport.SendAsync(1, ReadPdu(9), ct)).ShouldBe(new byte[] { 0x03, 0x02, 0x00, 0x09 });
server.Accepted.ShouldBe(2);
}
[Fact]
public async Task RtuOverTcp_AutoReconnectOff_link_fault_stays_down_and_the_cancel_allowance_is_spent_once()
{
var ct = TestContext.Current.CancellationToken;
var server = new LateReplyServer(rtu: true);
await using var transport = new ModbusRtuOverTcpTransport("127.0.0.1", server.Port, TimeSpan.FromSeconds(5), autoReconnect: false);
await transport.ConnectAsync(ct);
using var cancel = new CancellationTokenSource();
var first = transport.SendAsync(1, ReadPdu(5), cancel.Token);
await server.FirstReceived.WaitAsync(TimeSpan.FromSeconds(5), ct);
await cancel.CancelAsync();
await Should.ThrowAsync<OperationCanceledException>(first);
// The device goes away: the one owed redial fails, and the next call must fail fast, not dial again.
await server.DisposeAsync();
await Should.ThrowAsync<SocketException>(transport.SendAsync(1, ReadPdu(9), ct));
await Should.ThrowAsync<ModbusTransportUnavailableException>(transport.SendAsync(1, ReadPdu(9), ct));
}
}
@@ -104,6 +104,56 @@ public sealed class ModbusRtuFramingTests
ex.Reason.ShouldBe(ModbusTransportDesyncException.DesyncReason.TruncatedFrame);
}
/// <summary>#1029: a CRC-valid reply from the right unit that answers a DIFFERENT function is a desync.</summary>
[Fact]
public async Task ReadResponse_response_function_code_not_matching_request_throws_desync()
{
var frame = ModbusCrc.Append(new byte[] { 0x01, 0x04, 0x02, 0x00, 0x0A }); // an FC04 reply...
await using var s = Canned(frame);
var ex = await Should.ThrowAsync<ModbusTransportDesyncException>(
ModbusRtuFraming.ReadResponsePduAsync(s, 0x01, TestContext.Current.CancellationToken,
new byte[] { 0x03, 0x00, 0x00, 0x00, 0x01 })); // ...to an FC03 request
ex.Reason.ShouldBe(ModbusTransportDesyncException.DesyncReason.ResponseMismatch);
}
/// <summary>#1029: a stale exception reply for another function must not become this request's ModbusException.</summary>
[Fact]
public async Task ReadResponse_exception_for_another_function_throws_desync_not_ModbusException()
{
var frame = ModbusCrc.Append(new byte[] { 0x01, 0x86, 0x02 }); // exception for FC06
await using var s = Canned(frame);
var ex = await Should.ThrowAsync<ModbusTransportDesyncException>(
ModbusRtuFraming.ReadResponsePduAsync(s, 0x01, TestContext.Current.CancellationToken,
new byte[] { 0x03, 0x00, 0x00, 0x00, 0x01 }));
ex.Reason.ShouldBe(ModbusTransportDesyncException.DesyncReason.ResponseMismatch);
}
/// <summary>#1029: a write echo for another address is a stale reply, not this write's acknowledgement.</summary>
[Theory]
[InlineData((byte)0x06, new byte[] { 0x06, 0x00, 0x08, 0x00, 0x2A })]
[InlineData((byte)0x10, new byte[] { 0x10, 0x00, 0x08, 0x00, 0x01 })]
public async Task ReadResponse_write_echo_with_other_address_throws_desync(byte fc, byte[] echo)
{
await using var s = Canned(ModbusCrc.Append(new byte[] { 0x01 }.Concat(echo).ToArray()));
var request = new byte[] { fc, 0x00, 0x07, 0x00, 0x2A };
var ex = await Should.ThrowAsync<ModbusTransportDesyncException>(
ModbusRtuFraming.ReadResponsePduAsync(s, 0x01, TestContext.Current.CancellationToken, request));
ex.Reason.ShouldBe(ModbusTransportDesyncException.DesyncReason.ResponseMismatch);
}
/// <summary>Positive control for the three above: the matching reply and a matching exception still pass.</summary>
[Fact]
public async Task ReadResponse_matching_request_is_accepted_and_matching_exception_still_surfaces()
{
var ct = TestContext.Current.CancellationToken;
await using (var s = Canned(ModbusCrc.Append(new byte[] { 0x01, 0x06, 0x00, 0x07, 0x00, 0x2A })))
(await ModbusRtuFraming.ReadResponsePduAsync(s, 0x01, ct, new byte[] { 0x06, 0x00, 0x07, 0x00, 0x2A }))
.ShouldBe(new byte[] { 0x06, 0x00, 0x07, 0x00, 0x2A });
await using (var s = Canned(ModbusCrc.Append(new byte[] { 0x01, 0x83, 0x02 })))
await Should.ThrowAsync<ModbusException>(
ModbusRtuFraming.ReadResponsePduAsync(s, 0x01, ct, new byte[] { 0x03, 0x00, 0x00, 0x00, 0x01 }));
}
/// <summary>
/// A read-only test double that dribbles its backing bytes out at most <c>chunk</c> at a time
/// per <see cref="ReadAsync(Memory{byte}, CancellationToken)"/> call, then returns 0 (EOF)
@@ -39,6 +39,17 @@ public sealed class ModbusRtuOverTcpTransportTests
TestContext.Current.CancellationToken));
}
/// <summary>#1029: the transport hands the request PDU to the deframer, so another request's reply is refused.</summary>
[Fact]
public async Task SendAsync_reply_to_a_different_function_is_a_desync()
{
var fake = new CapturingDuplexStream(ModbusCrc.Append(new byte[] { 0x01, 0x04, 0x02, 0x00, 0x0A }));
await using var transport = ModbusRtuOverTcpTransport.ForTest(fake, TimeSpan.FromSeconds(2));
var ex = await Should.ThrowAsync<ModbusTransportDesyncException>(
transport.SendAsync(0x01, new byte[] { 0x03, 0x00, 0x00, 0x00, 0x01 }, TestContext.Current.CancellationToken));
ex.Reason.ShouldBe(ModbusTransportDesyncException.DesyncReason.ResponseMismatch);
}
[Fact]
public async Task SendAsync_stalled_gateway_hits_per_op_deadline()
{
@@ -189,4 +189,59 @@ public sealed class OpcUaClientDriverProbeTests
}
finally { listener.Stop(); }
}
// ── #1039: zone-qualified IPv6 hosts reach the preflight with their zone ───────────────────────
/// <summary>
/// The preflight dials the host <see cref="OpcUaClientDriverProbe.ExtractTarget"/> returns. .NET's
/// <see cref="Uri.Host"/> drops an IPv6 zone index (#819), so a link-local <c>fe80::1%eth0</c> endpoint was dialled
/// zone-less — unroutable, a false "Connect failed" before any OPC UA traffic. The host must carry the zone.
/// </summary>
[Theory]
[InlineData("opc.tcp://[fe80::1%eth0]:4841", "fe80::1%eth0", 4841)]
[InlineData("opc.tcp://[fe80::1%4]:4841/Ua", "fe80::1%4", 4841)]
// RFC 6874's encoded delimiter is accepted and normalised to the '%' the socket layer wants.
[InlineData("opc.tcp://[fe80::1%25eth0]:4841", "fe80::1%eth0", 4841)]
[InlineData("opc.tcp://[fe80::1%eth0]", "fe80::1%eth0", 4840)]
// Positive controls: a zone-less literal and a name are unchanged.
[InlineData("opc.tcp://[::1]:4841", "::1", 4841)]
[InlineData("opc.tcp://plc-host:4841", "plc-host", 4841)]
public void The_preflight_target_keeps_an_IPv6_zone_index(string endpointUrl, string expectedHost, int expectedPort)
{
var (host, port, url) = OpcUaClientDriverProbe.ExtractTarget(new OpcUaClientDriverOptions { EndpointUrl = endpointUrl });
host.ShouldBe(expectedHost);
port.ShouldBe(expectedPort);
url.ShouldBe(endpointUrl);
}
/// <summary>
/// End to end: a zone-qualified loopback literal reaches the preflight's socket connect (a listener that accepts
/// then closes proves it dialled), so the failure is the discovery handshake, never "Connect failed".
/// <c>::1%0</c> is a numeric zone that is valid everywhere an IPv6 socket is.
/// </summary>
[Fact]
public async Task A_zone_qualified_IPv6_literal_endpoint_passes_the_tcp_preflight()
{
if (!Socket.OSSupportsIPv6) Assert.Skip("IPv6 is not available on this host.");
var listener = new TcpListener(IPAddress.IPv6Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
var testCt = TestContext.Current.CancellationToken;
var accepted = Task.Run(async () =>
{
try { using var c = await listener.AcceptTcpClientAsync(testCt); return true; }
catch { return false; }
}, testCt);
try
{
var result = await _probe.ProbeAsync(
$$"""{"EndpointUrl":"opc.tcp://[::1%0]:{{port}}"}""", TimeSpan.FromSeconds(5), testCt);
result.Ok.ShouldBeFalse("the listener is not an OPC UA server");
result.Message.ShouldNotBeNull().ShouldNotContain("Connect failed", Case.Insensitive);
(await accepted.WaitAsync(TimeSpan.FromSeconds(5), testCt)).ShouldBeTrue("the preflight reached the listener");
}
finally { listener.Stop(); }
}
}
@@ -164,6 +164,35 @@ public sealed class OpcUaClientReview1202FindingsTests
log.Entries.Where(e => e.Level == LogLevel.Warning).ShouldHaveSingleItem().Message.ShouldContain("2 of the subscribed");
}
/// <summary>
/// #1039: the same refusals ride the skipped-tag report (so /hosts shows them without the log), once per path even
/// when the subscribe is retried; a re-initialise's rebuild clears them. Positive control: nothing is reported
/// before any refusal.
/// </summary>
[Fact]
public void Subscribe_time_refusals_are_added_to_the_skipped_tag_report_once_per_path()
{
var (drv, _) = NewConnectedDriver();
using var _ = drv;
drv.RecordSkippedTags(NamespaceMap.FromTable(new NamespaceTable(), Tags));
drv.GetSkippedTags().ShouldNotBeNull().SkippedCount.ShouldBe(0);
var handle = drv.AddSubscriptionForTest([SpeedRef]);
OpcUaClientDriver.RejectedItem[] refused =
[new("Plant/dev/Gone", 0x80340000u, "the server refused the monitored item (0x80340000)")];
drv.ReportRejectedItems(handle, refused);
drv.ReportRejectedItems(handle, refused); // the host retries the subscribe every health tick
var report = drv.GetSkippedTags().ShouldNotBeNull();
report.SkippedCount.ShouldBe(1);
report.Sample.ShouldHaveSingleItem().RawPath.ShouldBe("Plant/dev/Gone");
report.Sample[0].Reason.ShouldContain("refused");
report.AuthoredCount.ShouldBe(1);
drv.RecordSkippedTags(NamespaceMap.FromTable(new NamespaceTable(), Tags)); // re-initialise
drv.GetSkippedTags()!.SkippedCount.ShouldBe(0);
}
// ── G-13 ─────────────────────────────────────────────────────────────────────────────────────────────────────
private static readonly Dictionary<string, string> TripIndex = new() { ["ns=3;s=Alarms.Trip1"] = "Plant/opc/plc/Trip1" };
@@ -709,4 +709,160 @@ public sealed class TwinCATReview20261202Tests
factory.Clients.ShouldContain(c => c.LastConnectTimeout == TimeSpan.FromSeconds(8));
await drv.ShutdownAsync(Ct);
}
// ======================= #1035 — write fail-fast + retired-client read =======================
/// <summary>A client for one silent AMS target that waits <see cref="Delay"/> per write, then answers BadTimeout.</summary>
private sealed class SilentWriteFake(string silentNetId, TimeSpan delay, bool targetAnswersProbe) : FakeTwinCATClient
{
private int _silentWrites;
public int SilentWrites => Volatile.Read(ref _silentWrites);
private bool Silent => ConnectedAddress?.NetId == silentNetId;
public override async Task<uint> WriteValueAsync(
string symbolPath, TwinCATDataType type, int? bitIndex, object? value, CancellationToken ct)
{
if (!Silent) return await base.WriteValueAsync(symbolPath, type, bitIndex, value, ct);
Interlocked.Increment(ref _silentWrites);
await Task.Delay(delay, ct);
return TwinCATStatusMapper.BadTimeout;
}
public override Task<bool> ProbeAsync(CancellationToken ct) =>
Silent && !targetAnswersProbe ? Task.FromResult(false) : base.ProbeAsync(ct);
}
private static (TwinCATDriver drv, List<SilentWriteFake> clients, TwinCATTagDefinition[] tags) SilentWriteDriver(
TimeSpan delay, bool targetAnswersProbe)
{
var clients = new List<SilentWriteFake>();
var factory = new FakeTwinCATClientFactory();
factory.Customise = () =>
{
var c = new SilentWriteFake("5.23.91.23.1.1", delay, targetAnswersProbe);
lock (clients) clients.Add(c);
return c;
};
var tags = TagsOn(HostA, "A", 10)
.Append(new TwinCATTagDefinition("B0", HostB, "MAIN.B0", TwinCATDataType.DInt)).ToArray();
tags = [.. tags.Select(t => t with { Writable = true })];
var drv = new TwinCATDriver(new TwinCATDriverOptions
{
Devices = [new TwinCATDeviceOptions(HostA), new TwinCATDeviceOptions(HostB)],
RawTags = TwinCATRawTags.Entries(tags),
Probe = NoProbe,
Timeout = TimeSpan.FromSeconds(2),
}, "drv-1035", factory);
return (drv, clients, tags);
}
/// <summary>
/// #1035: a write batch to a device that stopped answering paid the timeout once PER WRITE (reads got the P-3 fail-fast,
/// writes did not). Now the first comms failure is checked against the device's ADS state and the rest of that
/// device's writes in the call answer BadCommunicationError with no wire attempt; another device's write is unaffected.
/// </summary>
[Fact]
public async Task A_silent_device_costs_one_write_timeout_per_call_not_one_per_write()
{
var delay = TimeSpan.FromMilliseconds(300);
var (drv, clients, tags) = SilentWriteDriver(delay, targetAnswersProbe: false);
await drv.InitializeAsync("{}", Ct);
var sw = Stopwatch.StartNew();
var results = await drv.WriteAsync([.. tags.Select(t => new WriteRequest(t.Name, 5))], Ct);
sw.Stop();
sw.Elapsed.ShouldBeLessThan(delay * 5, "A's writes must short-circuit after the first comms failure");
clients.Sum(c => c.SilentWrites).ShouldBe(1, "one wire attempt on the silent device per call");
results.Take(10).ShouldAllBe(r => IsComms(r.StatusCode));
results[10].StatusCode.ShouldBe(TwinCATStatusMapper.Good, "the healthy device's write goes out");
drv.GetHealth().State.ShouldBe(DriverState.Degraded);
await drv.ShutdownAsync(Ct);
}
/// <summary>
/// #1035 positive control: a write that times out on a device that STILL answers its state read is that one write's
/// fault — its siblings are still attempted (the short-circuit is reserved for a device that is gone).
/// </summary>
[Fact]
public async Task A_write_timeout_on_a_device_that_still_answers_does_not_short_circuit_its_siblings()
{
var (drv, clients, tags) = SilentWriteDriver(TimeSpan.FromMilliseconds(20), targetAnswersProbe: true);
await drv.InitializeAsync("{}", Ct);
var results = await drv.WriteAsync([.. tags.Take(10).Select(t => new WriteRequest(t.Name, 5))], Ct);
clients.Sum(c => c.SilentWrites).ShouldBe(10, "every sibling is still attempted on a live device");
results.ShouldAllBe(r => r.StatusCode == TwinCATStatusMapper.BadTimeout);
await drv.ShutdownAsync(Ct);
}
/// <summary>A device whose connect fails: the first write pays it, the throttled rest do not even try.</summary>
[Fact]
public async Task A_device_that_cannot_connect_fails_the_rest_of_the_batch_without_further_attempts()
{
var factory = new FakeTwinCATClientFactory();
factory.Customise = () => new FakeTwinCATClient { ThrowOnConnect = true };
var tags = TagsOn(HostA, "A", 6).Select(t => t with { Writable = true }).ToArray();
var drv = NewDriver(factory, NoProbe, native: false, null, [HostA], tags);
await drv.InitializeAsync("{}", Ct);
var results = await drv.WriteAsync([.. tags.Select(t => new WriteRequest(t.Name, 1))], Ct);
results.ShouldAllBe(r => r.StatusCode == TwinCATStatusMapper.BadCommunicationError);
factory.Clients.Count.ShouldBe(1, "one connect attempt; the rest of the batch failed fast");
await drv.ShutdownAsync(Ct);
}
private static bool IsComms(uint status) =>
status is TwinCATStatusMapper.BadCommunicationError or TwinCATStatusMapper.BadTimeout;
/// <summary>
/// #1035: a read already in flight when the symbol table is invalidated used to finish on the retired client and
/// publish its stale-offset value at Good. It is now discarded and re-read on a fresh client.
/// </summary>
[Fact]
public async Task A_read_in_flight_when_the_client_is_retired_is_re_read_on_a_fresh_client()
{
var factory = GenerationalFactory();
var drv = NewDriver(factory, NoProbe, native: false, null, [HostA],
new TwinCATTagDefinition("X", HostA, "MAIN.X", TwinCATDataType.DInt));
await drv.InitializeAsync("{}", Ct);
(await drv.ReadAsync(["X"], Ct))[0].Value.ShouldBe(111);
var first = factory.Clients[0];
first.BlockRead = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var inFlight = drv.ReadAsync(["X"], Ct);
await Task.Delay(100, Ct);
inFlight.IsCompleted.ShouldBeFalse("the read must be wedged in the wire call");
first.FireSymbolVersionChanged(); // a program change retires the client mid-read
first.BlockRead!.SetResult();
var after = (await inFlight.WaitAsync(TimeSpan.FromSeconds(5), Ct))[0];
after.StatusCode.ShouldBe(TwinCATStatusMapper.Good);
after.Value.ShouldBe(211, "the retired client's 111 must be discarded, not published");
factory.Clients.Count.ShouldBe(2);
await drv.ShutdownAsync(Ct);
}
/// <summary>Positive control for the above: with no invalidation the in-flight read keeps its value and no reconnect happens.</summary>
[Fact]
public async Task A_read_in_flight_with_no_invalidation_keeps_its_client_and_value()
{
var factory = GenerationalFactory();
var drv = NewDriver(factory, NoProbe, native: false, null, [HostA],
new TwinCATTagDefinition("X", HostA, "MAIN.X", TwinCATDataType.DInt));
await drv.InitializeAsync("{}", Ct);
(await drv.ReadAsync(["X"], Ct))[0].Value.ShouldBe(111);
factory.Clients[0].BlockRead = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var inFlight = drv.ReadAsync(["X"], Ct);
await Task.Delay(100, Ct);
factory.Clients[0].BlockRead!.SetResult();
(await inFlight.WaitAsync(TimeSpan.FromSeconds(5), Ct))[0].Value.ShouldBe(111);
factory.Clients.Count.ShouldBe(1);
await drv.ShutdownAsync(Ct);
}
}