fix(abcip): #983 review — per-call device latch only on real connection failures; never evict handles that were not attempted

- On libplctag each tag is its own request with its own timeout: one tag's Timeout latched
  the whole device for the call, failing (and evicting) every later sibling. The latch now
  fires on BadConnection/Abort/socket-IO failures always, and on Timeout only on the native
  transport, where a reply timeout faults the device's one shared channel
  (AbCipRefusals.LatchesDevice).
- Items latched out were never attempted: their handles are kept (evicting re-created, and
  for a sole lease holder re-Forward-Opened, each one next poll). The failed item's handle is
  still evicted, and a throttled cold create now latches the device so kept warm handles
  fail fast instead of each paying a timeout.
- AbCipDeadDeviceBatchTests recovery leg: the device's kept warm handles answer again.
This commit is contained in:
Joseph Doherty
2026-12-03 12:03:14 -05:00
parent 7374fdd0e4
commit 84a0226bfa
5 changed files with 181 additions and 14 deletions
+1 -1
View File
@@ -517,7 +517,7 @@ UDT-typed tags found in the walk.
## Operational Notes
- **A dead device does not stall the others, and logs once (#983, review 2026-12-02 P-2/P-16).** Three layers: (1) the native request scheduler faults everything queued behind a failed *channel* exchange (timeout / closed session / failed open) with the same exception — it used to start one fresh attempt per queued batch, ~N/20 timeouts for a 1000-tag device; a request submitted afterwards is a fresh attempt, so recovery is not delayed; (2) `ReadAsync` keeps one read window **per device** and a per-call fault latch — the first connection-level failure of a device (`Timeout`/`BadConnection`/`Abort`, not a device refusal) makes that device's remaining items fail fast `BadCommunicationError` and evicts their handles, so the next poll goes through the cold-create backoff instead of the wire; (3) per-read comms failures log one Warning **per device per outage** (Debug after), a throttled create no longer logs per tag, and the first success logs one Info with the suppressed count. The latch is deliberately per call and does not open the connect backoff itself: a transient single failure must still re-create the handle on the next read (`AbCipDriverCodeReviewRegressionTests`).
- **A dead device does not stall the others, and logs once (#983, review 2026-12-02 P-2/P-16).** Three layers: (1) the native request scheduler faults everything queued behind a failed *channel* exchange (timeout / closed session / failed open) with the same exception — it used to start one fresh attempt per queued batch, ~N/20 timeouts for a 1000-tag device; a request submitted afterwards is a fresh attempt, so recovery is not delayed; (2) `ReadAsync` keeps one read window **per device** and a per-call fault latch — the first connection-level failure of a device (`BadConnection`/`Abort`, a socket/IO failure, and on the **native** transport a `Timeout` — which faults the device's one shared channel; not a device refusal) makes that device's remaining items fail fast `BadCommunicationError`. #983 review: a **libplctag** `Timeout` does NOT latch — each libplctag tag is its own request with its own timeout, so one slow tag used to fail every later sibling of the call; and the latched-out items' handles are **kept** (they never reached the wire — evicting them re-created, and for a sole lease holder re-Forward-Opened, every one on the next poll). The failed item's own handle is evicted, so the next poll re-creates it through the cold-create backoff, and a throttled create latches the device too (its kept warm handles then fail fast instead of each paying a timeout); (3) per-read comms failures log one Warning **per device per outage** (Debug after), a throttled create no longer logs per tag, and the first success logs one Info with the suppressed count. The latch is deliberately per call and does not open the connect backoff itself: a transient single failure must still re-create the handle on the next read (`AbCipDriverCodeReviewRegressionTests`).
- **Whole BOOL-array reads count DWORDs (#983, P-13).** A Logix `BOOL[n]` is `ceil(n/32)` DWORDs (type `0xD3`) and a Read Tag's element count is in DWORDs; the native runtime now asks for that and, when the reply type is `0xC1` (one byte per BOOL, as `ab_server` answers), re-reads once with `n` and remembers it. **Not hardware-verified** — the unit evidence is a fake controller that refuses a 64-element read of `BOOL[64]`; the live gate is a whole read of a real `BOOL[64]`. Controller *browse* still maps symbol type `0xD3` to `Structure` (no hardware capture of the symbol-listing dims for a BOOL array exists), so browse-commit does not yet produce a correct Bool-array tag.
- **Bit selector 0..63; whole-word writes share the RMW lock (#983, P-23).** `Tag.n` accepts 0..63 (a LINT host); the width check refuses a bit the host does not have. A whole-word write to an integer tag takes the same per-parent lock as the bit read-modify-writes of `Tag.n` (case-insensitive, like the parent runtime table), so neither can land between the other's read and write. Probe / alarm-poll intervals are floored at 100 ms at config parse (0 hot-looped, negative killed the loop). The discovered-UDT cycle guard keys on the struct *type* (template id), not the member name, so a nested member sharing its parent's name is browsed. A connection-level fault reading a program's symbol listing now aborts the browse instead of silently dropping the program.
- **Native heap is invisible to the GC.** libplctag's native `Tag` heap does not show up in CLR allocation figures. Watch whole-process RSS, and use `ReinitializeAsync` (tears down + re-creates every device's libplctag handles) as the remediation for native-heap growth. (There is no per-driver footprint number to consult: `IDriver.GetMemoryFootprint()` was deleted as unconsumed in Gitea #525.)
@@ -244,6 +244,12 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
/// Describes the OPTION only: injected factories (tests) are used regardless.</summary>
public AbCipTransport EffectiveTransport => _transport;
/// <summary>
/// Whether a read TIMEOUT latches the device for the rest of a read call (#983 review): on the native transport
/// a reply timeout faults the device's one shared channel; on libplctag it is one tag's own request.
/// </summary>
private bool LatchesOnTimeout => _transport == AbCipTransport.Native;
// The transport chosen at construction (see the ctor); logged at every init so an operator can tell
// from the node log which stack serves this instance.
private readonly AbCipTransport _transport;
@@ -1170,11 +1176,12 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
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.
// instead of paying another timeout. The handle is KEPT (#983 review): this item never reached
// the wire, so nothing proves its handle bad, and evicting it re-created it (and, for a sole lease
// holder, re-Forward-Opened) on the next poll. The failed item itself was evicted; its cold
// re-create goes through the connect backoff, and a throttled create latches the device too.
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);
}
@@ -1212,7 +1219,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
results[fb.OriginalIndex] = new DataValueSnapshot(null,
AbCipStatusMapper.MapStatus(status), null, now);
var statusMessage = $"transport status {status} reading {reference}";
if (AbCipRefusals.IsConnectionFault(status)) batch.Latch(device, statusMessage);
if (AbCipRefusals.LatchesDevice(status, LatchesOnTimeout)) 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",
@@ -1316,6 +1323,9 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
// 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);
// The device's backoff window is open — a device-wide verdict: latch, so its warm handles behind this one
// fail fast instead of each paying a timeout on the wire (#983 review: they are no longer evicted).
batch.Latch(device, throttled.Message);
LogReadFault(device, null,
"AbCip reads on device {Device} are throttled while its connect backoff window is open: {Reason}",
def.DeviceHostAddress, throttled.Message);
@@ -1329,7 +1339,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
EvictRuntime(device, def.Name);
results[fb.OriginalIndex] = new DataValueSnapshot(null,
AbCipStatusMapper.MapException(ex), null, now);
if (AbCipRefusals.IsConnectionFault(ex)) batch.Latch(device, ex.Message);
if (AbCipRefusals.LatchesDevice(ex, LatchesOnTimeout)) batch.Latch(device, ex.Message);
LogReadFault(device, ex,
"AbCip read transport exception for tag {Tag} on device {Device}",
reference, def.DeviceHostAddress);
@@ -1373,7 +1383,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
// 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);
// Handle kept — never attempted (#983 review, see ReadSingleAsync).
StampGroupStatus(group, results, now, AbCipStatusMapper.BadCommunicationError);
return ReadOutcome.Degraded(latched);
}
@@ -1403,7 +1413,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
var mapped = AbCipStatusMapper.MapStatus(status);
StampGroupStatus(group, results, now, mapped);
var statusMessage = $"transport status {status} reading UDT {group.ParentName}";
if (AbCipRefusals.IsConnectionFault(status)) batch.Latch(device, statusMessage);
if (AbCipRefusals.LatchesDevice(status, LatchesOnTimeout)) 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",
@@ -1474,6 +1484,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
{
// P-16: see ReadSingleAsync — a throttled create is not a per-parent Warning.
StampGroupStatus(group, results, now, AbCipStatusMapper.BadCommunicationError);
batch.Latch(device, throttled.Message); // device-wide verdict — see ReadSingleAsync
LogReadFault(device, null,
"AbCip reads on device {Device} are throttled while its connect backoff window is open: {Reason}",
parent.DeviceHostAddress, throttled.Message);
@@ -1483,7 +1494,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
{
EvictRuntime(device, parent.Name);
StampGroupStatus(group, results, now, AbCipStatusMapper.MapException(ex));
if (AbCipRefusals.IsConnectionFault(ex)) batch.Latch(device, ex.Message);
if (AbCipRefusals.LatchesDevice(ex, LatchesOnTimeout)) batch.Latch(device, ex.Message);
LogReadFault(device, ex,
"AbCip whole-UDT read transport exception for parent {Parent} on device {Device}",
group.ParentName, parent.DeviceHostAddress);
@@ -53,6 +53,40 @@ internal static class AbCipRefusals
_ => false,
};
/// <summary>
/// True when a read failure with <paramref name="status"/> proves the DEVICE's connection dead for the rest of a
/// read call — the P-2 per-call latch (#983 review). <see cref="AbStatus.BadConnection"/> / <see cref="AbStatus.Abort"/>
/// always do. <see cref="AbStatus.Timeout"/> does only on the native transport, where every tag of a device shares
/// one channel and a reply timeout FAULTS that channel (<c>EncapsulationClient</c>); on libplctag each tag is its
/// own request with its own timeout, so one slow tag proves nothing about its siblings.
/// </summary>
/// <param name="status">The transport status.</param>
/// <param name="nativeTransport">Whether the device is served by the native transport.</param>
/// <returns><see langword="true"/> when the device should be latched for the rest of the call.</returns>
public static bool LatchesDevice(AbStatus status, bool nativeTransport) =>
status is AbStatus.BadConnection or AbStatus.Abort || (nativeTransport && status == AbStatus.Timeout);
/// <summary>The <see cref="int"/> status-word form of <see cref="LatchesDevice(AbStatus, bool)"/>.</summary>
/// <param name="status">The runtime status word.</param>
/// <param name="nativeTransport">Whether the device is served by the native transport.</param>
/// <returns><see langword="true"/> when the device should be latched for the rest of the call.</returns>
public static bool LatchesDevice(int status, bool nativeTransport) => LatchesDevice((AbStatus)status, nativeTransport);
/// <summary>
/// The exception form of <see cref="LatchesDevice(AbStatus, bool)"/>: a socket / IO / timeout exception is a
/// channel failure (only the native transport raises them).
/// </summary>
/// <param name="ex">The exception.</param>
/// <param name="nativeTransport">Whether the device is served by the native transport.</param>
/// <returns><see langword="true"/> when the device should be latched for the rest of the call.</returns>
public static bool LatchesDevice(Exception ex, bool nativeTransport) => ex switch
{
AbCipLocalRefusalException => false,
AbTransportException ate => LatchesDevice(ate.Status, nativeTransport),
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>
@@ -0,0 +1,120 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport;
using ZB.MOM.WW.OtOpcUa.Driver.AbCip;
namespace ZB.MOM.WW.OtOpcUa.Driver.AbCip.Tests;
/// <summary>
/// #983 review round: the P-2 per-call device fault latch fired on ANY timeout and evicted handles it never tried.
/// </summary>
[Trait("Category", "Unit")]
public sealed class AbCip983ReviewTests
{
private const string Dev = "ab://10.0.0.6/1,0";
private static AbCipDriverOptions Options(int tags, AbCipTransport transport) => new()
{
Devices = [new AbCipDeviceOptions(Dev)],
RawTags = AbCipRawTags.From([.. Enumerable.Range(0, tags).Select(i => new AbCipTagDefinition($"T{i}", Dev, $"T{i}", AbCipDataType.DInt))]),
Probe = new AbCipProbeOptions { Enabled = false },
MaxConcurrentReads = 1, // deterministic order: T0, T1, … one at a time
Transport = transport,
};
/// <summary>
/// On libplctag every tag is its own request with its own timeout: ONE tag timing out (a slow/large tag, a bad
/// element) proves nothing about its siblings. It used to latch the whole device for the call — every later
/// tag read BadCommunicationError without being tried, and was evicted.
/// </summary>
[Fact]
public async Task On_libplctag_one_tag_timeout_does_not_latch_the_device()
{
var creates = 0;
var factory = new FakeAbCipTagFactory
{
Customise = p =>
{
Interlocked.Increment(ref creates);
return new FakeAbCipTag(p) { Value = 5 };
},
};
var drv = new AbCipDriver(Options(10, AbCipTransport.Libplctag), "abcip-983-lib", factory);
await drv.InitializeAsync("{}", CancellationToken.None);
string[] refs = [.. Enumerable.Range(0, 10).Select(i => $"T{i}")];
(await drv.ReadAsync(refs, CancellationToken.None)).ShouldAllBe(s => s.StatusCode == AbCipStatusMapper.Good);
var slow = factory.Tags["T3"];
slow.ThrowOnRead = true;
slow.Exception = new AbTransportException(AbStatus.Timeout, "reply timeout");
var r = await drv.ReadAsync(refs, CancellationToken.None);
r[3].StatusCode.ShouldNotBe(AbCipStatusMapper.Good);
r.Where((_, i) => i != 3).ShouldAllBe(s => s.StatusCode == AbCipStatusMapper.Good);
factory.Tags.Where(t => t.Key != "T3").ShouldAllBe(t => t.Value.ReadCount == 2, "every sibling was actually read");
creates.ShouldBe(10, "no sibling handle was evicted");
await drv.DisposeAsync();
}
/// <summary>A libplctag connection-level status (BadConnection) still latches — the positive control for the above.</summary>
[Fact]
public async Task On_libplctag_a_bad_connection_still_latches()
{
var factory = new FakeAbCipTagFactory { Customise = p => new FakeAbCipTag(p) { Value = 5 } };
var drv = new AbCipDriver(Options(10, AbCipTransport.Libplctag), "abcip-983-lib2", factory);
await drv.InitializeAsync("{}", CancellationToken.None);
string[] refs = [.. Enumerable.Range(0, 10).Select(i => $"T{i}")];
await drv.ReadAsync(refs, CancellationToken.None);
foreach (var tag in factory.Tags.Values)
{
tag.ThrowOnRead = true;
tag.Exception = new AbTransportException(AbStatus.BadConnection, "session gone");
}
var r = await drv.ReadAsync(refs, CancellationToken.None);
r.ShouldAllBe(s => s.StatusCode != AbCipStatusMapper.Good);
factory.Tags.Values.Sum(t => t.ReadCount).ShouldBe(10 + 1, "only the first item reached the wire");
await drv.DisposeAsync();
}
/// <summary>
/// On the native transport a timeout faults the shared channel, so it latches — but the items latched out were
/// never attempted and their handles are fine: they must not be evicted (each eviction re-creates the handle
/// and, for a sole lease holder, re-Forward-Opens on the next poll).
/// </summary>
[Fact]
public async Task On_native_a_channel_timeout_latches_but_never_attempted_handles_are_kept()
{
var creates = 0;
var factory = new FakeAbCipTagFactory
{
Customise = p =>
{
Interlocked.Increment(ref creates);
return new FakeAbCipTag(p) { Value = 5 };
},
};
var drv = new AbCipDriver(Options(10, AbCipTransport.Native), "abcip-983-nat", factory);
await drv.InitializeAsync("{}", CancellationToken.None);
string[] refs = [.. Enumerable.Range(0, 10).Select(i => $"T{i}")];
await drv.ReadAsync(refs, CancellationToken.None);
var first = factory.Tags["T0"];
first.ThrowOnRead = true;
first.Exception = new AbTransportException(AbStatus.Timeout, "no reply");
var r = await drv.ReadAsync(refs, CancellationToken.None);
r.ShouldAllBe(s => s.StatusCode != AbCipStatusMapper.Good); // latched: the rest fail fast
factory.Tags.Where(t => t.Key != "T0").ShouldAllBe(t => t.Value.ReadCount == 1, "latched items never reached the wire");
// The channel recovers: only the ATTEMPTED (failed) handle is re-created.
first.ThrowOnRead = false;
await drv.ReadAsync(refs, CancellationToken.None);
creates.ShouldBeLessThanOrEqualTo(11);
await drv.DisposeAsync();
}
}
@@ -112,9 +112,10 @@ public sealed class AbCipDeadDeviceBatchTests
}
/// <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.
/// After the failed call the handles that reached the wire are evicted (the latched-out ones are kept — #983
/// review), so the next poll re-creates those cold: ONE single-flight attempt reaches the wire, fails, opens the
/// backoff window, the rest are throttled, and a throttled create latches the device so the kept warm handles
/// fail fast too. 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()
@@ -144,7 +145,7 @@ public sealed class AbCipDeadDeviceBatchTests
tag.ThrowOnRead = true;
tag.Exception = new AbTransportException(AbStatus.Timeout, "reply timeout");
}
await drv.ReadAsync(refs, CancellationToken.None); // warm failures; handles evicted
await drv.ReadAsync(refs, CancellationToken.None); // warm failures; the attempted handles evicted
bCreates.ShouldBe(20);
var r = await drv.ReadAsync(refs, CancellationToken.None); // cold: one real attempt, rest throttled
@@ -155,8 +156,9 @@ public sealed class AbCipDeadDeviceBatchTests
await drv.ReadAsync(refs, CancellationToken.None); // inside the window: nothing re-created
bCreates.ShouldBe(21);
// Recovery once the window passes.
// Recovery once the window passes: the device answers again, on its kept warm handles too.
down = false;
foreach (var tag in factory.Tags.Where(t => t.Key.StartsWith('B')).Select(t => t.Value)) tag.ThrowOnRead = false;
await Task.Delay(TimeSpan.FromMilliseconds(1300), TestContext.Current.CancellationToken);
r = await drv.ReadAsync(refs, CancellationToken.None);
r.ShouldAllBe(s => s.StatusCode == AbCipStatusMapper.Good);