fix(ablegacy): #984 per-tag family-type rejection + gate, bit arrays sized in words, Bit write RMWs bit 0, T/C/R read coalescing, answered-refusal/gate-race/null-write fixes

P-5 Long on MicroLogix/PLC-5 is BadConfigurationError per tag (init no longer throws), deploy gate warns via family-aware Inspect.
P-14 Bit array wire read sized in 16-bit words. P-15 Bit without /n RMWs bit 0; Bit on non-bit file refused.
P-18 native T/C/R sub-elements coalesce into one whole-element block read.
P-23f local OutOfBounds/TooLarge no longer count as answers, element/file >65535 is malformed; g block read re-resolves under the gate with identity-checked eviction; h null scalar write BadTypeMismatch.
This commit is contained in:
Joseph Doherty
2026-12-03 09:47:13 -05:00
parent 65fd71de7a
commit a9bc103eea
10 changed files with 601 additions and 75 deletions
@@ -169,7 +169,7 @@ public sealed record AbLegacyAddress(
}
else
{
if (!int.TryParse(fileTail, out var fn) || fn < 0) return null;
if (!int.TryParse(fileTail, out var fn) || fn < 0 || fn > MaxWireField) return null;
fileNumber = fn;
}
}
@@ -192,7 +192,7 @@ public sealed record AbLegacyAddress(
indirectWord = ParseInner(wordPart[1..^1], profile);
if (indirectWord is null) return null;
}
else if (!TryParseIndex(wordPart, octal, out word) || word < 0) return null;
else if (!TryParseIndex(wordPart, octal, out word) || word < 0 || word > MaxWireField) return null;
int? bitIndex = null;
if (bitText is not null)
@@ -272,6 +272,21 @@ public sealed record AbLegacyAddress(
/// bit-addressable. 16-bit element files (N/B/I/O/S/A) permit bits 0..15; the 32-bit
/// L-file permits 0..31.
/// </summary>
/// <summary>
/// Largest file / element number a PCCC address field can carry (the 0xFF-escaped 16-bit form). A larger literal
/// can never reach the wire — the native encoder refuses it locally — so it is a malformed address (configuration
/// error), not a device refusal that proves a device is alive.
/// </summary>
internal const int MaxWireField = ushort.MaxValue;
/// <summary>
/// Whether <paramref name="letter"/> is a bit-addressable word file (N/B/I/O/S/A 16-bit, L 32-bit), i.e. one a
/// <c>/n</c> bit suffix is legal on and a bit-in-word read-modify-write applies to.
/// </summary>
/// <param name="letter">The file-type letter (upper case).</param>
/// <returns><see langword="true"/> for a bit-addressable word file.</returns>
public static bool IsBitAddressableFile(string letter) => MaxBitIndexFor(letter) >= 0;
private static int MaxBitIndexFor(string letter) => letter switch
{
"L" => 31,
@@ -24,6 +24,23 @@ public sealed record AbLegacyPlcFamilyProfile(
/// <summary>MicroLogix only: RTC / HSC / DLS / MMI / PTO / PWM / STI / EII / IOS / BHI function files.</summary>
bool SupportsFunctionFiles = false)
{
/// <summary>
/// Why <paramref name="type"/> cannot be authored on a device of this family (an L-file <c>Long</c> or ST-file
/// <c>String</c> the profile says the family does not ship), or <see langword="null"/> when it can. The single
/// authority the driver's per-tag rejection and the deploy gate both read.
/// </summary>
/// <param name="type">The authored data type.</param>
/// <param name="family">The device family the profile belongs to (for the message).</param>
/// <returns>The refusal reason, or <see langword="null"/>.</returns>
public string? UnsupportedDataTypeReason(AbLegacyDataType type, AbLegacyPlcFamily family) => type switch
{
AbLegacyDataType.Long when !SupportsLongFile =>
$"a Long (32-bit L-file) tag is not supported on a {family} device (the family does not support L-files).",
AbLegacyDataType.String when !SupportsStringFile =>
$"a String (ST-file) tag is not supported on a {family} device (the family does not support ST-files).",
_ => null,
};
/// <summary>Gets the profile for the specified PLC family.</summary>
/// <param name="family">The PLC family.</param>
/// <remarks>
@@ -177,6 +177,11 @@ public static class AbLegacyTagDefinitionFactory
{
if (AbLegacyAddress.Validate(accepted.Address, family) is { } addressError)
warnings.Add($"AbLegacy tag address: {addressError} The driver reads this tag as BadNodeIdUnknown.");
else if (family is { } fam
&& AbLegacyPlcFamilyProfile.ForFamily(fam).UnsupportedDataTypeReason(accepted.DataType, fam) is { } typeError)
// The same rule the driver applies per tag at init: the tag reads BadConfigurationError and the
// rest of the driver keeps running.
warnings.Add($"AbLegacy tag: {typeError} The driver reads this tag as BadConfigurationError.");
else if (accepted.ArrayLength is not null
&& ArrayFileMismatch(accepted.DataType, accepted.Address) is { } widthError)
warnings.Add(widthError);
@@ -1,6 +1,7 @@
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport;
using ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport.Pccc;
namespace ZB.MOM.WW.OtOpcUa.Driver.AbLegacy;
@@ -41,6 +42,16 @@ public sealed partial class AbLegacyDriver
private sealed record CoalescedBlock(
string FileLetter, int FileNumber, int Start, int Count, AbLegacyDataType ElementType, List<ReadItem> Members)
{
/// <summary>True for a Timer / Counter / Control block: whole 3-word (6-byte) elements are read and each member's
/// word / status bit is sliced out of them (<see cref="AbLegacyDataType.TimerElement"/> is the grouping marker).</summary>
public bool IsStructured => ElementType == AbLegacyDataType.TimerElement;
/// <summary>The type the block's buffer is decoded as: a structured element is read as its raw 16-bit words.</summary>
public AbLegacyDataType DecodeType => IsStructured ? AbLegacyDataType.Int : ElementType;
/// <summary>The number of <see cref="DecodeType"/> values the buffer holds.</summary>
public int DecodeCount => IsStructured ? Count * 3 : Count;
/// <summary>The runtime-cache key; distinct from any RawPath (RawPaths never contain '|').</summary>
public string Key => $"|block|{FileLetter}{FileNumber}:{Start}+{Count}";
@@ -52,10 +63,23 @@ public sealed partial class AbLegacyDriver
/// The element type a scalar tag is decoded from when it rides a coalesced block, or <see langword="null"/>
/// when the tag keeps the single-tag path.
/// </summary>
private static AbLegacyDataType? CoalescedElementType(ReadItem item)
private AbLegacyDataType? CoalescedElementType(DeviceState device, ReadItem item)
{
var a = item.Parsed;
if (a.IsIndirect || a.SubElement is not null || a.FileNumber is null || IsArrayTag(item.Def)) return null;
if (a.IsIndirect || a.FileNumber is null || IsArrayTag(item.Def)) return null;
// T / C / R sub-elements (T4:0.ACC / .PRE / .DN ...): one whole-element read returns every sub-element of every
// timer in a span, where each used to cost its own exchange (review 2026-12-02 P-18). Native transport only: its
// 6-byte element layout is what the wire captures pin; libplctag's multi-element T/C/R buffer layout is not
// verified here, so that stack keeps the per-sub-element reads it has always had. PLC-5 native reads are
// refused for every non-N file, so it never rides a block either.
if (a.SubElement is not null)
return _transport == AbLegacyTransport.Native
&& device.Profile.LibplctagPlcAttribute != "plc5"
&& a.FileLetter is "T" or "C" or "R"
&& item.Def.DataType is AbLegacyDataType.Int or AbLegacyDataType.AnalogInt or AbLegacyDataType.Bit
&& TrySubElement(a) is not null
? AbLegacyDataType.TimerElement
: null;
return (a.FileLetter, item.Def.DataType) switch
{
("N" or "B", AbLegacyDataType.Int or AbLegacyDataType.AnalogInt or AbLegacyDataType.Bit) => AbLegacyDataType.Int,
@@ -66,6 +90,13 @@ public sealed partial class AbLegacyDriver
};
}
/// <summary>The resolved word / status-bit position of a T/C/R sub-element address, or null if it names none.</summary>
private static PcccAddress? TrySubElement(AbLegacyAddress a)
{
try { return PcccAddress.WithSubElementName(a.FileLetter, a.FileNumber, a.WordNumber, a.SubElement!); }
catch (AbTransportException) { return null; }
}
/// <summary>
/// Plans a device pass: coalescable tags grouped per file into runs of nearby elements (a run of two or more
/// tags becomes a block), everything else a single unit. Block shapes the device refused before stay single.
@@ -78,7 +109,7 @@ public sealed partial class AbLegacyDriver
var groups = new Dictionary<(string Letter, int File, AbLegacyDataType Type), List<ReadItem>>();
foreach (var item in items)
{
if (CoalescedElementType(item) is not { } type)
if (CoalescedElementType(device, item) is not { } type)
{
units.Add(new ReadUnit(item, null));
continue;
@@ -90,7 +121,7 @@ public sealed partial class AbLegacyDriver
foreach (var ((letter, file, type), members) in groups)
{
var width = type == AbLegacyDataType.Int ? 2 : 4;
var width = type switch { AbLegacyDataType.Int => 2, AbLegacyDataType.TimerElement => 6, _ => 4 };
var maxElements = MaxCoalescedBytes / width;
var ordered = members.OrderBy(m => m.Parsed.WordNumber).ToList();
var run = new List<ReadItem> { ordered[0] };
@@ -132,10 +163,18 @@ public sealed partial class AbLegacyDriver
foreach (var m in block.Members) results[m.Index] = new DataValueSnapshot(null, status, null, now);
}
// The runtime this call actually used; every eviction below targets IT (identity-checked), never a fresh one a
// concurrent caller reconnected under the gate in the meantime.
IAbLegacyTagRuntime? used = null;
void EvictUsed()
{
if (used is not null) EvictRuntime(device, block.Key, used);
}
(BlockOutcome, OpVerdict, string?) Refused(string why)
{
// The handle is never kept for a refused shape (review 07 r0 M5): it may never be planned again.
EvictRuntime(device, block.Key);
EvictUsed();
// Every refusal falls back to per-member reads THIS pass, so each member gets its own answer and a bad
// member can never black out its neighbours. The shape is only REMEMBERED after a repeat — one refusal can
// be transient (program mode, a download in progress), two in a row are deterministic.
@@ -166,12 +205,30 @@ public sealed partial class AbLegacyDriver
int status;
Array? data = null;
var opLock = device.GetRuntimeLock(block.Key);
device.BeforeOperationGate?.Invoke(block.Key);
await opLock.WaitAsync(ct).ConfigureAwait(false);
try
{
// Re-resolve under the gate (as the single-tag path does): the handle fetched above may have been evicted
// and disposed by a sibling's failed call while this one waited, and reading it would fail every member as
// a comms fault (review 2026-12-02 P-23g).
if (!device.Runtimes.TryGetValue(block.Key, out var live))
{
live = device.IsRetired
? runtime
: await CreateSingleFlightAsync(
device, device.Runtimes, block.Key, () => _tagFactory.Create(createParams), ct).ConfigureAwait(false);
}
runtime = used = live;
await runtime.ReadAsync(ct).ConfigureAwait(false);
status = runtime.GetStatus();
if (status == 0) data = runtime.DecodeArray(block.ElementType, block.Count) as Array;
if (status == 0) data = runtime.DecodeArray(block.DecodeType, block.DecodeCount) as Array;
}
catch (Exception ex) when (ex is not OperationCanceledException and not ConnectionThrottledException)
{
// Evict while the gate is still held so a waiter never picks up the failed handle.
EvictUsed();
throw;
}
finally
{
@@ -184,11 +241,11 @@ public sealed partial class AbLegacyDriver
// to per-member reads; only a no-reply status fails the block's members together (review 07 r0 I1).
if (!IsNoReply((AbStatus)status))
return Refused($"device status {(AbStatus)status}");
EvictRuntime(device, block.Key);
EvictUsed();
FailAll(AbLegacyStatusMapper.MapStatus(status));
return (BlockOutcome.Done, OpVerdict.Fault, $"transport status {status} reading {block.StartName}+{block.Count}");
}
if (data is null || data.Length < block.Count)
if (data is null || data.Length < block.DecodeCount)
return Refused("the block decoded short");
foreach (var m in block.Members)
@@ -213,7 +270,7 @@ public sealed partial class AbLegacyDriver
}
catch (Exception ex)
{
EvictRuntime(device, block.Key);
EvictUsed();
FailAll(AbLegacyStatusMapper.BadCommunicationError);
return (BlockOutcome.Done, OpVerdict.Fault, ex.Message);
}
@@ -227,6 +284,20 @@ public sealed partial class AbLegacyDriver
{
var offset = m.Parsed.WordNumber - block.Start;
var bit = m.Parsed.BitIndex;
if (block.IsStructured)
{
// Mirrors the native single-tag DecodeValue of a T/C/R sub-element: a status bit decodes as that bit (bool for a
// Bit tag, 0/1 for a word-typed one); a word sub-element as its 16-bit value (a Bit tag reads bit 0).
var words16 = (short[])data;
var sub = TrySubElement(m.Parsed)!;
var w = words16[offset * 3 + sub.SubElement!.Value];
if (sub.Bit is int sb)
{
var v = ((ushort)w >> sb & 1) != 0;
return m.Def.DataType == AbLegacyDataType.Bit ? v : (object)(v ? 1 : 0);
}
return m.Def.DataType == AbLegacyDataType.Bit ? (w & 1) != 0 : (int)w;
}
switch (data)
{
case short[] words:
@@ -40,6 +40,10 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
// by reference alongside _devices (same build-and-swap rule).
private volatile Dictionary<string, AbLegacyTagDefinition> _tagsByRawPath = new(StringComparer.Ordinal);
// RawPath → why the tag is a per-tag configuration error (its data type is not available on its device's PLC
// family). Published with the tag table; such a tag answers BadConfigurationError on read and write.
private volatile Dictionary<string, string> _configRejected = new(StringComparer.Ordinal);
// Serialises every PUBLISH/RETIRE of the two tables with the lifecycle epoch. Never held across an await.
private readonly object _lifecycleLock = new();
@@ -187,6 +191,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
// is ever mutated.
var devices = new Dictionary<string, DeviceState>(StringComparer.OrdinalIgnoreCase);
var tags = new Dictionary<string, AbLegacyTagDefinition>(StringComparer.Ordinal);
var rejected = new Dictionary<string, string>(StringComparer.Ordinal);
try
{
// re-parse the supplied DriverConfig so a config change delivered through the IDriver
@@ -238,32 +243,30 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
_driverInstanceId, entry.RawPath, reason);
continue;
}
tags[entry.RawPath] = def with
var resolved = def with
{
WriteIdempotent = entry.WriteIdempotent,
DeviceHostAddress = ResolveDeviceHost(options, entry.DeviceName),
};
tags[entry.RawPath] = resolved;
// A data type the owning device's PLC family does not ship (an L-file Long on a MicroLogix, an ST-file
// String on a family without one) is THIS TAG's configuration error — it reads/writes
// BadConfigurationError and is reported in the skipped-tag ledger — never a reason to fault every other
// tag and device of the instance (review 2026-12-02 P-5). The deploy gate says the same thing earlier
// (AbLegacyTagDefinitionFactory.Inspect, family-aware) from the same profile authority.
if (devices.TryGetValue(resolved.DeviceHostAddress, out var deviceForTag)
&& deviceForTag.Profile.UnsupportedDataTypeReason(resolved.DataType, deviceForTag.Options.PlcFamily) is { } typeReason)
{
rejected[entry.RawPath] = typeReason;
_skippedTags.Skip(entry.RawPath, typeReason);
_logger.LogWarning(
"AbLegacy tag rejected for its device's PLC family; it will read BadConfigurationError. Driver={DriverInstanceId} RawPath={RawPath} Device={DeviceHostAddress} Reason={Reason}",
_driverInstanceId, entry.RawPath, resolved.DeviceHostAddress, typeReason);
}
}
_skippedTags.Commit();
// Validate tag types against their device's family profile. Long (32-bit integer)
// and String (ST-file) are not supported by all PCCC families; reject them early
// so a misconfigured tag fails at init time with a clear message rather than
// surfacing an opaque comms error at runtime.
foreach (var tag in tags.Values)
{
if (!devices.TryGetValue(tag.DeviceHostAddress, out var deviceForTag)) continue;
var profile = deviceForTag.Profile;
if (tag.DataType == AbLegacyDataType.Long && !profile.SupportsLongFile)
throw new InvalidOperationException(
$"Tag '{tag.Name}' is typed as Long but device '{tag.DeviceHostAddress}' " +
$"(family {deviceForTag.Options.PlcFamily}) does not support L-files.");
if (tag.DataType == AbLegacyDataType.String && !profile.SupportsStringFile)
throw new InvalidOperationException(
$"Tag '{tag.Name}' is typed as String but device '{tag.DeviceHostAddress}' " +
$"(family {deviceForTag.Options.PlcFamily}) does not support ST-files.");
}
// Publish, start the probe loops and go Healthy as ONE step under the lifecycle lock, and only if no
// teardown (or newer initialise) ran since this attempt began. Starting the loops inside the lock
// means a teardown that swaps this table out always sees their tasks and joins them.
@@ -274,6 +277,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
$"AbLegacy driver {_driverInstanceId} initialise was superseded by a shutdown or a newer initialise.");
_options = options;
_tagsByRawPath = tags;
_configRejected = rejected;
_devices = devices;
_resolver.Clear(); // drop transient parses made against the previous table
if (options.Probe.Enabled && !string.IsNullOrWhiteSpace(options.Probe.ProbeAddress))
@@ -338,6 +342,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
{
_lifecycleEpoch++;
_tagsByRawPath = new Dictionary<string, AbLegacyTagDefinition>(StringComparer.Ordinal);
_configRejected = new Dictionary<string, string>(StringComparer.Ordinal);
}
var retired = _devices.Values.ToList();
_devices = new Dictionary<string, DeviceState>(StringComparer.OrdinalIgnoreCase);
@@ -523,6 +528,13 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
results[i] = new DataValueSnapshot(null, AbLegacyStatusMapper.BadNodeIdUnknown, null, now);
continue;
}
// A tag whose data type its device's PLC family does not ship is a per-tag configuration error: answered
// without touching the wire or the device's health (already warned once at init).
if (_configRejected.ContainsKey(def.Name))
{
results[i] = new DataValueSnapshot(null, AbLegacyStatusMapper.BadConfigurationError, null, now);
continue;
}
var parsed = AbLegacyAddress.TryParse(def.Address, device.Options.PlcFamily);
if (parsed is null)
{
@@ -895,6 +907,18 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
results[i] = new WriteResult(AbLegacyStatusMapper.BadNodeIdUnknown);
continue;
}
if (_configRejected.ContainsKey(def.Name))
{
results[i] = new WriteResult(AbLegacyStatusMapper.BadConfigurationError);
continue;
}
// A null scalar value has no encoding: the runtimes' Convert.To* would write it as 0 / false / "" (review
// 2026-12-02 P-23h). Refused before any runtime — and so any init read — exists; the array path already does.
if (w.Value is null && !IsArrayTag(def))
{
results[i] = new WriteResult(AbLegacyStatusMapper.BadTypeMismatch);
continue;
}
try
{
@@ -991,9 +1015,22 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
// sub-element combined with a /N bit index, so their BitIndex is always null. NOTE: an Input-image (I) write is sent
// to the PLC like any other write — the device drives the input image from physical inputs and
// may reject it; we surface that real PCCC status rather than pre-rejecting at the driver.
else if (def.DataType == AbLegacyDataType.Bit && parsed.BitIndex is int bit)
//
// A Bit tag authored WITHOUT /n reads as bit 0 of its word (DecodeValue), so it WRITES as bit 0 too — through
// the same RMW. The old fall-through encoded the whole word as 0x0001 / 0x0000 and silently cleared the
// other 15 bits (review 2026-12-02 P-15). A Bit tag on a file with no bit layout (F, ST, T/C/R element
// without a sub-element, ...) has no sound write at all: refused BadNotSupported.
else if (def.DataType == AbLegacyDataType.Bit && parsed.SubElement is null
&& parsed.BitIndex is null && !AbLegacyAddress.IsBitAddressableFile(parsed.FileLetter))
{
var (code, raw) = await WriteBitInWordAsync(device, def, parsed, bit, w.Value, cancellationToken)
WarnRefusalOnce(device, def, "write",
$"a Bit tag on {parsed.FileLetter}-file '{def.Address}' has no bit to write; author the address with a /n bit index on a word file, or a status sub-element.");
results[i] = new WriteResult(AbLegacyStatusMapper.BadNotSupported);
continue;
}
else if (def.DataType == AbLegacyDataType.Bit && parsed.SubElement is null)
{
var (code, raw) = await WriteBitInWordAsync(device, def, parsed, parsed.BitIndex ?? 0, w.Value, cancellationToken)
.ConfigureAwait(false);
results[i] = new WriteResult(code);
RecordWriteStatus(device, def, raw, ref outcome);
@@ -1613,6 +1650,17 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
private static int EffectiveArrayLength(AbLegacyTagDefinition def) =>
def.ArrayLength is int len && len >= 1 ? Math.Min(len, AbLegacyArray.MaxElements) : 1;
/// <summary>
/// The element count the WIRE read / runtime buffer is sized for. Equal to <see cref="EffectiveArrayLength"/> for
/// every array except a <c>Bit</c> array: its <c>arrayLength</c> counts BITS, but the file is read in 16-bit
/// words, so 256 bits are 16 words — not 256 (16x the bytes, and a read past the end of a short file that the
/// PLC refuses forever; review 2026-12-02 P-14). The decode still takes <see cref="EffectiveArrayLength"/> bits.
/// </summary>
internal static int WireElementCount(AbLegacyTagDefinition def) =>
IsArrayTag(def) && def.DataType == AbLegacyDataType.Bit
? (EffectiveArrayLength(def) + 15) / 16
: EffectiveArrayLength(def);
/// <summary>
/// True for a deterministic refusal of the operation itself (<see cref="AbStatus.Unsupported"/>) — the
/// native runtime raises it BEFORE anything reaches the wire (status-bit writes, PLC-5 non-N reads and
@@ -1638,7 +1686,13 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
/// <returns><see langword="true"/> for an answered refusal.</returns>
internal static bool IsAnsweredRefusal(Exception ex) =>
ex is AbTransportException ate
&& (IsDeviceRefusal(ate.Status) || ate is AbDeviceReplyException { Status: AbStatus.Unsupported });
&& (ate is AbDeviceReplyException { Status: AbStatus.Unsupported }
// A refusal STATUS proves an answer only when the DEVICE sent it. The native transport raises the same
// OutOfBounds / TooLarge / TypeMismatch locally (an element number that does not fit a PCCC field, an oversize
// count, a short buffer) with no wire involved, and counting those as answers let one unreachable tag on a dead
// device keep resetting its fault streak (review 2026-12-02 P-23f). A libplctag status arrives wrapped (it has
// an inner exception) and always came back from the library's own exchange, so it still counts.
|| (IsDeviceRefusal(ate.Status) && (ate is AbDeviceReplyException || ate.InnerException is not null)));
/// <summary>
/// Initializes a freshly created runtime. A runtime whose init is refused locally is still KEPT: the
@@ -1703,7 +1757,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
LibplctagPlcAttribute: device.Profile.LibplctagPlcAttribute,
TagName: parsed.ToLibplctagName(),
Timeout: _options.Timeout,
ElementCount: EffectiveArrayLength(def));
ElementCount: WireElementCount(def));
private async Task<IAbLegacyTagRuntime> EnsureTagRuntimeAsync(
DeviceState device, AbLegacyTagDefinition def, CancellationToken ct)
@@ -1759,6 +1813,21 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
}
}
/// <summary>
/// <see cref="EvictRuntime(DeviceState, string)"/>, but only if the cached runtime for <paramref name="tagName"/>
/// is still <paramref name="expected"/> — the one the caller actually used and saw fail. Without the identity
/// check a caller evicting after it released the operation gate could dispose the FRESH runtime a waiting
/// sibling had just reconnected under that gate, failing the sibling mid-read as a comms fault (review
/// 2026-12-02 P-23g).
/// </summary>
private static void EvictRuntime(DeviceState device, string tagName, IAbLegacyTagRuntime expected)
{
if (device.Runtimes.TryRemove(new KeyValuePair<string, IAbLegacyTagRuntime>(tagName, expected)))
{
try { expected.Dispose(); } catch { /* best-effort */ }
}
}
/// <summary>
/// Synchronous teardown. Mirrors the body of
/// <see cref="ShutdownAsync"/> but never wraps the async path in
@@ -19,6 +19,7 @@ public static class AbLegacyStatusMapper
public const uint BadCommunicationError = 0x80050000u;
public const uint BadTimeout = 0x800A0000u;
public const uint BadTypeMismatch = 0x80740000u;
public const uint BadConfigurationError = 0x80890000u;
/// <summary>
/// Map the integer form of an <see cref="AbStatus"/> (what <see cref="IAbLegacyTagRuntime.GetStatus"/>