fix(abcip): #983 a dead device no longer stalls the multi-device read batch and logs once per outage (P-2, P-16)

Scheduler faults everything queued behind a failed channel exchange; per-device read
windows plus a per-call fault latch fail a dead device's remaining items fast; throttled
creates no longer throw+log per tag (one Warning per device per outage, Info on recovery).
This commit is contained in:
Joseph Doherty
2026-12-03 09:45:29 -05:00
parent 65fd71de7a
commit eff7775bca
5 changed files with 459 additions and 15 deletions
@@ -295,19 +295,34 @@ public sealed class RequestScheduler : IAsyncDisposable
private async Task ExecuteAsync(List<Pending> batch)
{
// True once the CHANNEL (not a reply parse / envelope check) failed: a connection-level fault.
var channelFailed = false;
async Task<ReadOnlyMemory<byte>> SendOnChannelAsync(ReadOnlyMemory<byte> request)
{
try
{
// Never a waiter's token (B2).
return await _channel.SendAsync(request, _stop.Token).ConfigureAwait(false);
}
catch (Exception) when (!_stop.IsCancellationRequested)
{
channelFailed = true;
throw;
}
}
try
{
if (batch.Count == 1)
{
// Never a waiter's token (B2).
var raw = await _channel.SendAsync(batch[0].Request, _stop.Token).ConfigureAwait(false);
var raw = await SendOnChannelAsync(batch[0].Request).ConfigureAwait(false);
batch[0].Succeed(CipReply.Parse(raw), this);
return;
}
var requests = new List<byte[]>(batch.Count);
foreach (var b in batch) requests.Add(b.Request);
var envelopeRaw = await _channel.SendAsync(MultipleServicePacket.Build(requests), _stop.Token).ConfigureAwait(false);
var envelopeRaw = await SendOnChannelAsync(MultipleServicePacket.Build(requests)).ConfigureAwait(false);
var envelope = CipReply.Parse(envelopeRaw);
if (envelope.Service != MultipleServiceCode)
throw new AbTransportException(AbStatus.BadReply, $"MSP reply carries service 0x{envelope.Service:X2}.");
@@ -325,14 +340,35 @@ public sealed class RequestScheduler : IAsyncDisposable
catch (AbTransportException ex)
{
foreach (var b in batch) b.Fail(ex, this);
if (channelFailed) FailQueued(ex);
}
catch (Exception ex)
{
var wrapped = new AbTransportException(AbStatus.BadConnection, $"CIP exchange failed: {ex.Message}", ex);
foreach (var b in batch) b.Fail(wrapped, this);
if (channelFailed) FailQueued(wrapped);
}
}
/// <summary>
/// P-2: the channel failed (timeout, closed session, failed open). Every request already queued behind
/// the failed batch would otherwise start its OWN attempt against the same dead peer, each paying a
/// timeout or a throttled re-open, so a 1000-tag device took N batches x timeout to give up. They are
/// faulted with the same exception now; a request submitted AFTER this point is a fresh attempt and
/// reopens the session as usual, so recovery is not delayed.
/// </summary>
/// <param name="error">The channel failure shared with every queued waiter.</param>
private void FailQueued(Exception error)
{
List<Pending> queued;
lock (_lock)
{
queued = [.. _queue];
_queue.Clear();
}
foreach (var q in queued) q.Fail(error, this);
}
/// <summary>
/// The error a waiter sees when the scheduler (i.e. its connection) goes away under it. Deliberately
/// NOT an <see cref="OperationCanceledException"/>: upstream treats OCE as "the caller unsubscribed"
@@ -911,13 +911,13 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
// and written once after the batch: an inline write to the shared _health field would race.
var maxConcurrent = ReadWindow;
var outcomes = new ReadOutcome[itemCount];
using var window = new SemaphoreSlim(maxConcurrent, maxConcurrent);
using var batch = new ReadBatch(maxConcurrent);
var tasks = new Task[itemCount];
for (var i = 0; i < itemCount; i++)
tasks[i] = RunItemAsync(i);
// Task.WhenAll completes only once EVERY item has finished (it does not short-circuit on the
// first fault), so disposing the window on the way out can never pull the semaphore out from
// first fault), so disposing the windows on the way out can never pull a semaphore out from
// under an item still waiting on it.
await Task.WhenAll(tasks).ConfigureAwait(false);
@@ -931,15 +931,97 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
{
if (slot < groups.Count)
{
outcomes[slot] = await ReadGroupAsync(groups[slot], results, now, window, cancellationToken)
outcomes[slot] = await ReadGroupAsync(groups[slot], results, now, batch, cancellationToken)
.ConfigureAwait(false);
NoteDeviceOutcome(groups[slot].ParentDefinition.DeviceHostAddress, outcomes[slot]);
}
else
{
var fb = fallbacks[slot - groups.Count];
outcomes[slot] = await ReadSingleAsync(
fb, fullReferences[fb.OriginalIndex], results, now, window, cancellationToken)
fb, fullReferences[fb.OriginalIndex], results, now, batch, cancellationToken)
.ConfigureAwait(false);
if (_resolver.TryResolve(fullReferences[fb.OriginalIndex], out var fbDef))
NoteDeviceOutcome(fbDef.DeviceHostAddress, outcomes[slot]);
}
}
}
/// <summary>
/// Per-<see cref="ReadAsync"/>-call state. (1) A read window PER DEVICE: every device has its own request
/// scheduler, so a shared window let one dead device's in-flight items hold every slot for a full timeout while
/// a healthy device's items waited behind them (P-2). (2) A per-device fault latch: the first connection-level
/// failure of a device in this call makes that device's remaining items fail fast, once they get their turn,
/// instead of each paying its own timeout / throttled re-open against the same dead peer.
/// </summary>
private sealed class ReadBatch(int windowSize) : IDisposable
{
private readonly System.Collections.Concurrent.ConcurrentDictionary<DeviceState, SemaphoreSlim> _windows = new();
private readonly System.Collections.Concurrent.ConcurrentDictionary<DeviceState, string> _faulted = new();
/// <summary>The bounded-parallel window for <paramref name="device"/>.</summary>
/// <param name="device">The device.</param>
/// <returns>The device's window.</returns>
public SemaphoreSlim WindowFor(DeviceState device) =>
_windows.GetOrAdd(device, _ => new SemaphoreSlim(windowSize, windowSize));
/// <summary>True when a connection-level failure of <paramref name="device"/> was already seen in this call.</summary>
/// <param name="device">The device.</param>
/// <param name="reason">The first failure's message.</param>
/// <returns><see langword="true"/> when the device is latched.</returns>
public bool IsFaulted(DeviceState device, out string reason)
{
if (_faulted.TryGetValue(device, out var r)) { reason = r; return true; }
reason = string.Empty;
return false;
}
/// <summary>Latches <paramref name="device"/> for the rest of this call (first reason wins).</summary>
/// <param name="device">The device.</param>
/// <param name="reason">The failure message.</param>
/// <returns><see langword="true"/> when this call latched the device (it was not latched yet).</returns>
public bool Latch(DeviceState device, string reason) => _faulted.TryAdd(device, reason);
/// <inheritdoc />
public void Dispose()
{
foreach (var w in _windows.Values) w.Dispose();
}
}
/// <summary>
/// Resets a device's outage-log state when one of its reads proved it reachable (a read that succeeded or
/// was answered with a refusal), logging one Info that carries the suppressed-warning count (P-16).
/// </summary>
private void NoteDeviceOutcome(string deviceHostAddress, ReadOutcome outcome)
{
if (outcome.State != DriverState.Healthy && !outcome.Answered) return;
if (!_devicesByRoutingKey.TryGetValue(deviceHostAddress, out var device)) return;
if (device.EndOutage(out var suppressed))
_logger.LogInformation(
"AbCip device {Device} is reachable again; {Suppressed} per-read failure warning(s) were suppressed during the outage",
deviceHostAddress, suppressed);
}
/// <summary>
/// Logs a per-read comms failure at Warning ONCE per device per outage (with the exception), and at Debug for
/// every further one: a dead 1000-tag device used to emit ~1000 Warnings with stack traces per poll (P-16).
/// </summary>
private void LogReadFault(DeviceState device, Exception? ex, string message, params object?[] args)
{
if (device.TryBeginOutageWarning())
{
// Logged once per outage; every further failure is Debug until the device answers again.
if (ex is null) _logger.LogWarning(message, args);
else _logger.LogWarning(ex, message, args);
}
else
{
device.CountSuppressedWarning();
if (_logger.IsEnabled(LogLevel.Debug))
{
if (ex is null) _logger.LogDebug(message, args);
else _logger.LogDebug(ex, message, args);
}
}
}
@@ -1042,7 +1124,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
private async Task<ReadOutcome> ReadSingleAsync(
AbCipUdtReadFallback fb, string reference, DataValueSnapshot[] results, DateTime now,
SemaphoreSlim window, CancellationToken ct)
ReadBatch batch, CancellationToken ct)
{
if (!_resolver.TryResolve(reference, out var def))
{
@@ -1069,6 +1151,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
var runtime = await EnsureTagRuntimeAsync(device, def, ct).ConfigureAwait(false);
// Window slot only now that the runtime exists (see ReadAsync); a wait that throws never acquired.
var window = batch.WindowFor(device);
await window.WaitAsync(ct).ConfigureAwait(false);
// Serialise Read → GetStatus → Decode against the shared runtime — the cached libplctag
// Tag handle is not concurrency-safe and GetStatus returns the LAST op's status.
@@ -1078,6 +1161,16 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
await opLock.WaitAsync(ct).ConfigureAwait(false);
try
{
// P-2: an earlier item of THIS call already proved the device's connection dead — fail fast
// instead of paying another timeout, and drop the handle so the next poll goes through the
// cold-create backoff rather than the wire.
if (batch.IsFaulted(device, out var latched))
{
EvictRuntime(device, def.Name);
results[fb.OriginalIndex] = new DataValueSnapshot(null, AbCipStatusMapper.BadCommunicationError, null, now);
return ReadOutcome.Degraded(latched);
}
await runtime.ReadAsync(ct).ConfigureAwait(false);
var status = runtime.GetStatus();
@@ -1110,11 +1203,13 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
EvictRuntime(device, def.Name);
results[fb.OriginalIndex] = new DataValueSnapshot(null,
AbCipStatusMapper.MapStatus(status), null, now);
_logger.LogWarning(
var statusMessage = $"transport status {status} reading {reference}";
if (AbCipRefusals.IsConnectionFault(status)) batch.Latch(device, statusMessage);
LogReadFault(device, null,
"AbCip read returned non-zero transport status {Status} for tag {Tag} on device {Device}; " +
"evicting cached runtime so next call re-creates it",
status, reference, def.DeviceHostAddress);
return ReadOutcome.Degraded($"transport status {status} reading {reference}");
return ReadOutcome.Degraded(statusMessage);
}
var tagPath = AbCipTagPath.TryParse(def.TagPath);
@@ -1207,6 +1302,17 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
results[fb.OriginalIndex] = new DataValueSnapshot(null, AbCipStatusMapper.BadCommunicationError, null, now);
return ReadOutcome.None;
}
catch (ConnectionThrottledException throttled)
{
// P-16: the device's connect backoff window is open — an expected state, not a per-tag event. No
// eviction (nothing cached) and no stack trace; one Warning per device per outage (shared with the
// failure that opened the window), Debug after.
results[fb.OriginalIndex] = new DataValueSnapshot(null, AbCipStatusMapper.BadCommunicationError, null, now);
LogReadFault(device, null,
"AbCip reads on device {Device} are throttled while its connect backoff window is open: {Reason}",
def.DeviceHostAddress, throttled.Message);
return ReadOutcome.Degraded(throttled.Message);
}
catch (Exception ex)
{
// Transport exception — evict so the next read creates a fresh handle. An AbTransportException
@@ -1215,7 +1321,8 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
EvictRuntime(device, def.Name);
results[fb.OriginalIndex] = new DataValueSnapshot(null,
AbCipStatusMapper.MapException(ex), null, now);
_logger.LogWarning(ex,
if (AbCipRefusals.IsConnectionFault(ex)) batch.Latch(device, ex.Message);
LogReadFault(device, ex,
"AbCip read transport exception for tag {Tag} on device {Device}",
reference, def.DeviceHostAddress);
return ReadOutcome.Degraded(ex.Message);
@@ -1230,7 +1337,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
/// per-tag fallback list are unaffected.
/// </summary>
private async Task<ReadOutcome> ReadGroupAsync(
AbCipUdtReadGroup group, DataValueSnapshot[] results, DateTime now, SemaphoreSlim window, CancellationToken ct)
AbCipUdtReadGroup group, DataValueSnapshot[] results, DateTime now, ReadBatch batch, CancellationToken ct)
{
var parent = group.ParentDefinition;
@@ -1245,6 +1352,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
var runtime = await EnsureTagRuntimeAsync(device, parent, ct).ConfigureAwait(false);
// Window slot only now that the runtime exists (see ReadAsync); a wait that throws never acquired.
var window = batch.WindowFor(device);
await window.WaitAsync(ct).ConfigureAwait(false);
// Serialise the whole-UDT Read → GetStatus → per-member DecodeValueAt against the shared
// parent runtime — the members decode from that one handle's buffer.
@@ -1254,6 +1362,14 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
await opLock.WaitAsync(ct).ConfigureAwait(false);
try
{
// P-2: see ReadSingleAsync — an earlier item of this call already proved the connection dead.
if (batch.IsFaulted(device, out var latched))
{
EvictRuntime(device, parent.Name);
StampGroupStatus(group, results, now, AbCipStatusMapper.BadCommunicationError);
return ReadOutcome.Degraded(latched);
}
await runtime.ReadAsync(ct).ConfigureAwait(false);
var status = runtime.GetStatus();
@@ -1278,11 +1394,13 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
EvictRuntime(device, parent.Name);
var mapped = AbCipStatusMapper.MapStatus(status);
StampGroupStatus(group, results, now, mapped);
_logger.LogWarning(
var statusMessage = $"transport status {status} reading UDT {group.ParentName}";
if (AbCipRefusals.IsConnectionFault(status)) batch.Latch(device, statusMessage);
LogReadFault(device, null,
"AbCip whole-UDT read returned non-zero transport status {Status} for parent {Parent} " +
"on device {Device}; {MemberCount} member values stamped with mapped status",
status, group.ParentName, parent.DeviceHostAddress, group.Members.Count);
return ReadOutcome.Degraded($"transport status {status} reading UDT {group.ParentName}");
return ReadOutcome.Degraded(statusMessage);
}
foreach (var member in group.Members)
@@ -1344,11 +1462,21 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
StampGroupStatus(group, results, now, AbCipStatusMapper.BadCommunicationError);
return ReadOutcome.None;
}
catch (ConnectionThrottledException throttled)
{
// P-16: see ReadSingleAsync — a throttled create is not a per-parent Warning.
StampGroupStatus(group, results, now, AbCipStatusMapper.BadCommunicationError);
LogReadFault(device, null,
"AbCip reads on device {Device} are throttled while its connect backoff window is open: {Reason}",
parent.DeviceHostAddress, throttled.Message);
return ReadOutcome.Degraded(throttled.Message);
}
catch (Exception ex)
{
EvictRuntime(device, parent.Name);
StampGroupStatus(group, results, now, AbCipStatusMapper.MapException(ex));
_logger.LogWarning(ex,
if (AbCipRefusals.IsConnectionFault(ex)) batch.Latch(device, ex.Message);
LogReadFault(device, ex,
"AbCip whole-UDT read transport exception for parent {Parent} on device {Device}",
group.ParentName, parent.DeviceHostAddress);
return ReadOutcome.Degraded(ex.Message);
@@ -2438,6 +2566,30 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
/// </para>
/// </summary>
public SemaphoreSlim ConnectGate { get; } = new(1, 1);
private int _outageWarned;
private int _suppressedWarnings;
/// <summary>
/// True for the FIRST per-read failure of an outage (the caller logs it at Warning); false for every
/// further one until <see cref="EndOutage"/> (P-16).
/// </summary>
/// <returns><see langword="true"/> when the caller should log at Warning.</returns>
public bool TryBeginOutageWarning() => Interlocked.CompareExchange(ref _outageWarned, 1, 0) == 0;
/// <summary>Counts one failure that was logged below Warning because the outage was already announced.</summary>
public void CountSuppressedWarning() => Interlocked.Increment(ref _suppressedWarnings);
/// <summary>Ends the outage: the device answered. Returns whether one was open, and how many warnings it suppressed.</summary>
/// <param name="suppressed">The suppressed-warning count of the outage that ended.</param>
/// <returns><see langword="true"/> when an outage was open.</returns>
public bool EndOutage(out int suppressed)
{
suppressed = 0;
if (Interlocked.Exchange(ref _outageWarned, 0) == 0) return false;
suppressed = Interlocked.Exchange(ref _suppressedWarnings, 0);
return true;
}
/// <summary>Gets or sets the current host state of this device.</summary>
public HostState HostState { get; set; } = HostState.Unknown;
/// <summary>Gets or sets the UTC timestamp when the host state was last changed.</summary>
@@ -28,6 +28,31 @@ internal static class AbCipRefusals
or AbStatus.NotAllowed or AbStatus.TooLarge or AbStatus.TooSmall or AbStatus.TypeMismatch
or AbStatus.Unsupported;
/// <summary>
/// True when <paramref name="status"/> proves the CONNECTION failed (timeout, closed / unreachable session,
/// aborted open) rather than one tag: every other tag on the same device would fail the same way (P-2).
/// </summary>
/// <param name="status">The transport status.</param>
/// <returns><see langword="true"/> for a connection-level fault.</returns>
public static bool IsConnectionFault(AbStatus status) => status is AbStatus.Timeout or AbStatus.BadConnection
or AbStatus.Abort;
/// <summary>True when <paramref name="status"/> (an <see cref="AbStatus"/> value) is a connection-level fault.</summary>
/// <param name="status">The runtime status word.</param>
/// <returns><see langword="true"/> for a connection-level fault.</returns>
public static bool IsConnectionFault(int status) => IsConnectionFault((AbStatus)status);
/// <summary>True when <paramref name="ex"/> is a connection-level failure (see <see cref="IsConnectionFault(AbStatus)"/>).</summary>
/// <param name="ex">The exception.</param>
/// <returns><see langword="true"/> for a connection-level fault.</returns>
public static bool IsConnectionFault(Exception ex) => ex switch
{
AbCipLocalRefusalException => false,
AbTransportException ate => IsConnectionFault(ate.Status),
System.Net.Sockets.SocketException or IOException or TimeoutException => true,
_ => false,
};
/// <summary>True when <paramref name="status"/> (an <see cref="AbStatus"/> value) is a device refusal.</summary>
/// <param name="status">The runtime status word.</param>
/// <returns><see langword="true"/> for a deterministic device refusal.</returns>
@@ -200,6 +200,31 @@ public sealed class RequestSchedulerTests
(await s.SendAsync(Req(8, 3), CancellationToken.None).WaitAsync(Timeout, Ct)).GeneralStatus.ShouldBe((byte)0);
}
[Fact]
public async Task Channel_failure_faults_everything_queued_behind_it_without_further_attempts()
{
// P-2: a dead peer used to cost one timeout / throttled re-open PER queued batch.
var ch = new FakeCipChannel(maxRequestBytes: 64); // small budget: 200 requests would be many batches
await using var s = new RequestScheduler(ch, allowPacking: true);
var a = await HoldFirstAsync(s, ch, Req(8, 0));
var boom = new AbTransportException(AbStatus.Timeout, "reply timeout");
ch.Respond = _ => Task.FromException<byte[]>(boom);
var queued = Enumerable.Range(1, 200).Select(i => s.SendAsync(Req(8, (byte)i), CancellationToken.None)).ToList();
s.QueuedCount.ShouldBe(200);
ch.Gate!.SetResult();
(await Should.ThrowAsync<AbTransportException>(() => a.WaitAsync(Timeout, Ct))).ShouldBeSameAs(boom);
foreach (var q in queued)
(await Should.ThrowAsync<AbTransportException>(() => q.WaitAsync(Timeout, Ct))).ShouldBeSameAs(boom);
ch.SentCount.ShouldBe(1); // only the in-flight exchange ever reached the dead channel
s.QueuedCount.ShouldBe(0);
// Positive control: a request submitted AFTER the failure is a fresh attempt (recovery is not delayed).
ch.Respond = ch.DefaultRespond;
(await s.SendAsync(Req(8, 9), CancellationToken.None).WaitAsync(Timeout, Ct)).GeneralStatus.ShouldBe((byte)0);
ch.SentCount.ShouldBe(2);
}
[Fact]
public async Task A_non_transport_channel_exception_is_wrapped_and_shared_by_the_batch()
{
@@ -0,0 +1,206 @@
using Microsoft.Extensions.Logging;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport;
using ZB.MOM.WW.OtOpcUa.Driver.AbCip;
namespace ZB.MOM.WW.OtOpcUa.Driver.AbCip.Tests;
/// <summary>
/// Review 2026-12-02 P-2 / P-16 (#983): one dead device in a multi-device read must not stall the healthy ones
/// (warm handles used to bypass every backoff; each of N tags paid its own timeout), and a dead device must not
/// log one Warning with a stack trace per tag per poll.
/// </summary>
[Trait("Category", "Unit")]
public sealed class AbCipDeadDeviceBatchTests
{
private const string DevA = "ab://10.0.0.5/1,0";
private const string DevB = "ab://10.0.0.6/1,0";
/// <summary>A warm tag on a dead device: the read takes a while, then times out like a real session.</summary>
private sealed class SlowTimeoutTag(AbCipTagCreateParams p) : FakeAbCipTag(p)
{
public override async Task ReadAsync(CancellationToken cancellationToken)
{
await base.ReadAsync(cancellationToken);
await Task.Delay(300, cancellationToken);
throw new AbTransportException(AbStatus.Timeout, "reply timeout");
}
}
private static AbCipDriverOptions TwoDeviceOptions(int bTags, int window = 8)
{
var defs = new List<AbCipTagDefinition>();
for (var i = 0; i < bTags; i++) defs.Add(new AbCipTagDefinition($"B{i}", DevB, $"B{i}", AbCipDataType.DInt));
defs.Add(new AbCipTagDefinition("A0", DevA, "A0", AbCipDataType.DInt));
return new AbCipDriverOptions
{
Devices = [new AbCipDeviceOptions(DevA), new AbCipDeviceOptions(DevB)],
RawTags = AbCipRawTags.From([.. defs]),
Probe = new AbCipProbeOptions { Enabled = false },
MaxConcurrentReads = window,
};
}
/// <summary>
/// Device B has 200 WARM runtimes that all time out (300 ms each). The first window's worth fail on the wire;
/// the rest fail fast on the batch's fault latch, and device A (listed last) is read Good regardless.
/// </summary>
[Fact]
public async Task A_dead_device_with_warm_handles_costs_one_window_of_timeouts_not_one_per_tag()
{
var bCreates = 0;
var factory = new FakeAbCipTagFactory
{
Customise = p =>
{
if (p.Gateway != "10.0.0.6") return new FakeAbCipTag(p) { Value = 1 };
Interlocked.Increment(ref bCreates);
return new FakeAbCipTag(p) { Value = 2 };
},
};
var drv = new AbCipDriver(TwoDeviceOptions(bTags: 200), "abcip-dead", factory);
await drv.InitializeAsync("{}", CancellationToken.None);
string[] refs = [.. Enumerable.Range(0, 200).Select(i => $"B{i}"), "A0"];
// Warm every runtime while the device is healthy.
(await drv.ReadAsync(refs, CancellationToken.None)).ShouldAllBe(s => s.StatusCode == AbCipStatusMapper.Good);
bCreates.ShouldBe(200);
// The device dies mid-run: the cached (warm) handles now fail like a dead session.
foreach (var tag in factory.Tags.Where(t => t.Key.StartsWith('B')).Select(t => t.Value))
{
tag.ThrowOnRead = true;
tag.Exception = new AbTransportException(AbStatus.Timeout, "reply timeout");
}
var sw = System.Diagnostics.Stopwatch.StartNew();
var r = await drv.ReadAsync(refs, CancellationToken.None);
sw.Stop();
r[200].StatusCode.ShouldBe(AbCipStatusMapper.Good); // device A answered
r[200].Value.ShouldBe(1);
r.Take(200).ShouldAllBe(s => s.StatusCode != AbCipStatusMapper.Good);
// The in-flight window's worth carry the wire's own status (timeout); everything behind it the latch's.
r.Take(200).Count(s => s.StatusCode == AbCipStatusMapper.BadCommunicationError).ShouldBeGreaterThanOrEqualTo(192);
// Only the items that were in flight (<= window) ever reached the wire; the rest were latched out.
var bReads = factory.Tags.Where(t => t.Key.StartsWith('B')).Sum(t => t.Value.ReadCount) - 200; // minus the warm-up
bReads.ShouldBeLessThanOrEqualTo(8);
bReads.ShouldBeGreaterThan(0); // positive control: the failure did reach the wire
}
/// <summary>Same shape with a real delay per failed read: the whole call must cost ~one timeout, not 200/8 of them.</summary>
[Fact]
public async Task The_whole_call_costs_about_one_timeout_and_a_healthy_device_is_not_blocked()
{
var factory = new FakeAbCipTagFactory
{
Customise = p => p.Gateway == "10.0.0.6" ? new SlowTimeoutTag(p) : new FakeAbCipTag(p) { Value = 1 },
};
var drv = new AbCipDriver(TwoDeviceOptions(bTags: 200), "abcip-dead2", factory);
await drv.InitializeAsync("{}", CancellationToken.None);
string[] refs = [.. Enumerable.Range(0, 200).Select(i => $"B{i}"), "A0"];
var sw = System.Diagnostics.Stopwatch.StartNew();
var r = await drv.ReadAsync(refs, CancellationToken.None);
sw.Stop();
r[200].StatusCode.ShouldBe(AbCipStatusMapper.Good);
// Unfixed: 25 windows x 300 ms = 7.5 s. Fixed: one 300 ms window (generous bound for slow CI).
sw.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(3));
r.Take(200).ShouldAllBe(s => s.StatusCode != AbCipStatusMapper.Good);
}
/// <summary>
/// After the failed call the dead device's handles are evicted, so the next poll re-creates cold: ONE
/// single-flight attempt reaches the wire, fails, opens the backoff window, and the other 19 tags (and every
/// later poll) are throttled without touching it. Once the window passes a recovered device reads Good.
/// </summary>
[Fact]
public async Task The_next_poll_of_a_dead_device_makes_one_attempt_then_throttles_and_recovery_still_works()
{
var down = false;
var bCreates = 0;
var factory = new FakeAbCipTagFactory
{
Customise = p =>
{
if (p.Gateway != "10.0.0.6") return new FakeAbCipTag(p) { Value = 1 };
Interlocked.Increment(ref bCreates);
return down
? new FakeAbCipTag(p) { ThrowOnInitialize = true, Exception = new AbTransportException(AbStatus.Timeout, "connect timeout") }
: new FakeAbCipTag(p) { Value = 2 };
},
};
var drv = new AbCipDriver(TwoDeviceOptions(bTags: 20), "abcip-dead3", factory);
await drv.InitializeAsync("{}", CancellationToken.None);
string[] refs = [.. Enumerable.Range(0, 20).Select(i => $"B{i}"), "A0"];
await drv.ReadAsync(refs, CancellationToken.None);
bCreates.ShouldBe(20);
down = true;
foreach (var tag in factory.Tags.Where(t => t.Key.StartsWith('B')).Select(t => t.Value))
{
tag.ThrowOnRead = true;
tag.Exception = new AbTransportException(AbStatus.Timeout, "reply timeout");
}
await drv.ReadAsync(refs, CancellationToken.None); // warm failures; handles evicted
bCreates.ShouldBe(20);
var r = await drv.ReadAsync(refs, CancellationToken.None); // cold: one real attempt, rest throttled
bCreates.ShouldBe(21);
r.Take(20).ShouldAllBe(s => s.StatusCode != AbCipStatusMapper.Good);
r[20].StatusCode.ShouldBe(AbCipStatusMapper.Good);
await drv.ReadAsync(refs, CancellationToken.None); // inside the window: nothing re-created
bCreates.ShouldBe(21);
// Recovery once the window passes.
down = false;
await Task.Delay(TimeSpan.FromMilliseconds(1300), TestContext.Current.CancellationToken);
r = await drv.ReadAsync(refs, CancellationToken.None);
r.ShouldAllBe(s => s.StatusCode == AbCipStatusMapper.Good);
await drv.DisposeAsync();
}
/// <summary>P-16: a dead device with 100 cold tags polled 10 times logs at most a couple of Warnings, not 1000.</summary>
[Fact]
public async Task A_dead_device_logs_one_warning_per_outage_not_one_per_tag_per_poll()
{
var logger = new AbCipLoggingTests.CapturingLogger<AbCipDriver>();
var fail = true;
var factory = new FakeAbCipTagFactory
{
Customise = p => new FakeAbCipTag(p)
{
ThrowOnInitialize = fail,
Exception = new AbTransportException(AbStatus.Timeout, "connect timeout"),
Value = 3,
},
};
var defs = Enumerable.Range(0, 100)
.Select(i => new AbCipTagDefinition($"T{i}", DevA, $"T{i}", AbCipDataType.DInt)).ToArray();
var drv = new AbCipDriver(new AbCipDriverOptions
{
Devices = [new AbCipDeviceOptions(DevA)],
RawTags = AbCipRawTags.From(defs),
Probe = new AbCipProbeOptions { Enabled = false },
}, "abcip-log", factory, logger: logger);
await drv.InitializeAsync("{}", CancellationToken.None);
string[] refs = [.. defs.Select(d => d.Name)];
for (var i = 0; i < 10; i++)
(await drv.ReadAsync(refs, CancellationToken.None)).ShouldAllBe(s => s.StatusCode != AbCipStatusMapper.Good);
var warnings = logger.Entries.Where(e => e.Level == LogLevel.Warning && e.Message.Contains(DevA)).ToList();
warnings.Count.ShouldBeLessThanOrEqualTo(2);
warnings.Count.ShouldBeGreaterThanOrEqualTo(1); // positive control: the outage IS announced
// Recovery ends the outage with one Info carrying the suppressed count, and re-arms the Warning.
fail = false;
await Task.Delay(TimeSpan.FromMilliseconds(1300), TestContext.Current.CancellationToken);
(await drv.ReadAsync(refs, CancellationToken.None)).ShouldAllBe(s => s.StatusCode == AbCipStatusMapper.Good);
logger.Entries.Count(e => e.Level == LogLevel.Information && e.Message.Contains("reachable again")).ShouldBe(1);
await drv.DisposeAsync();
}
}