fix(abcip): #983 RMW lock keying + whole-word lock, bit selector 0-63, interval floors, cycle guard on struct type, browse surfaces transport faults (P-23 a-e)

This commit is contained in:
Joseph Doherty
2026-12-03 09:55:25 -05:00
parent c5c31a1671
commit 7d6cf97fdd
8 changed files with 295 additions and 15 deletions
@@ -1602,7 +1602,22 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
// Serialise Encode → Write → GetStatus against the shared runtime — the same cached
// Tag handle may be in use by a concurrent ReadAsync or poll loop.
var opLock = device.GetRuntimeLock(def.Name);
await opLock.WaitAsync(cancellationToken).ConfigureAwait(false);
// P-23a: a whole-word write to an integer tag shares the read-modify-write lock of its bit writers
// (`Flags.3`): both address the same controller word through DIFFERENT runtimes, so without it a bit
// RMW's read-then-write could land over a whole-word write made between them (lost update).
var hostLock = arrayElements is null && parsedPath is { BitIndex: null } && IsIntegerHostType(def.DataType)
? device.GetRmwLock(parsedPath.ToLibplctagName())
: null;
if (hostLock is not null) await hostLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
await opLock.WaitAsync(cancellationToken).ConfigureAwait(false);
}
catch
{
hostLock?.Release();
throw;
}
int status;
uint? refusal;
int size;
@@ -1633,6 +1648,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
finally
{
opLock.Release();
hostLock?.Release();
}
if (refusal is { } refused)
@@ -1823,6 +1839,11 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
}
}
/// <summary>True for the integer types a bit selector (<c>Tag.n</c>) can address, i.e. a possible RMW host.</summary>
private static bool IsIntegerHostType(AbCipDataType type) => type is AbCipDataType.SInt or AbCipDataType.USInt
or AbCipDataType.Int or AbCipDataType.UInt or AbCipDataType.DInt or AbCipDataType.UDInt
or AbCipDataType.LInt or AbCipDataType.ULInt;
/// <summary>
/// Read-modify-write one bit within an integer parent (SINT / INT / DINT / LINT — Logix allows <c>.n</c> on
/// each). Creates / reuses a parallel parent runtime (distinct from the bit-selector handle) + serialises
@@ -2228,7 +2249,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
() => capturedDiscoveredFolder.Folder(fullName, discovered.Name));
var anyEmitted = await FanOutDiscoveredUdtMembersAsync(
udtFolder, device.HostAddress, fullName, shape, discovered.ReadOnly,
depth: 1, emitted, visited: [discovered.Name], cancellationToken)
depth: 1, emitted, visited: [StructKey(discovered.TemplateInstanceId, discovered.Name)], cancellationToken)
.ConfigureAwait(false);
if (anyEmitted) continue; // expanded — don't emit the placeholder Variable
// Empty shape (no usable atomic leaf): degrade to a single Variable below.
@@ -2341,6 +2362,18 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
return size == width * Math.Max(1, def.ElementCount) ? null : AbCipStatusMapper.BadTypeMismatch;
}
/// <summary>
/// The cycle-guard key of a struct on the fan-out path: its template instance id when the controller supplied
/// one (identity of the struct TYPE), else its name (seeded / test shapes carry none). Keying on the member
/// NAME alone skipped a legitimate member whose nested type happened to contain a member of the same name
/// (P-23d) — only a true re-entry of the same struct type is cyclic.
/// </summary>
/// <param name="templateInstanceId">The struct's CIP template instance id, if known.</param>
/// <param name="name">The member / tag name, the fallback key.</param>
/// <returns>The guard key.</returns>
private static string StructKey(uint? templateInstanceId, string name) =>
templateInstanceId is { } id ? $"tpl:{id}" : $"name:{name}";
/// <summary>
/// Recursively fan a controller-discovered UDT shape out into Variable nodes — one per
/// ATOMIC leaf — under the folder produced by <paramref name="folder"/>. Mirrors the
@@ -2416,7 +2449,8 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
// live a level deeper, so the cap is checked against depth + 1.
if (member.ArrayLength > 1) continue;
if (depth + 1 > MaxUdtDepth) continue;
if (!visited.Add(member.Name)) continue; // cyclic UDT reference — stop here
var structKey = StructKey(member.NestedTemplateId, member.Name);
if (!visited.Add(structKey)) continue; // cyclic UDT reference (same struct TYPE already on this path) — stop here
if (nested is not null)
{
// Materialise the nested sub-folder lazily under the parent folder (itself lazy),
@@ -2430,7 +2464,7 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
.ConfigureAwait(false);
anyEmitted |= nestedEmitted;
}
visited.Remove(member.Name);
visited.Remove(structKey);
continue;
}
}
@@ -2638,7 +2672,10 @@ public sealed class AbCipDriver : IDriver, IReadable, IWritable, ITagDiscovery,
public System.Collections.Concurrent.ConcurrentDictionary<string, IAbCipTagRuntime> ParentRuntimes { get; } =
new(StringComparer.OrdinalIgnoreCase);
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, SemaphoreSlim> _rmwLocks = new();
// OrdinalIgnoreCase like ParentRuntimes: `Flags.3` and `FLAGS.4` share one parent runtime, so they must share
// its lock (P-23a — a case-sensitive key gave them two locks over one handle: a lost update).
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, SemaphoreSlim> _rmwLocks =
new(StringComparer.OrdinalIgnoreCase);
/// <summary>Gets or creates a semaphore for coordinating RMW (read-modify-write) operations on a parent tag.</summary>
/// <param name="parentTagName">The name of the parent tag.</param>
@@ -98,7 +98,7 @@ public static class AbCipDriverFactoryExtensions
Probe = new AbCipProbeOptions
{
Enabled = dto.Probe?.Enabled ?? true,
Interval = TimeSpan.FromMilliseconds(dto.Probe?.IntervalMs ?? 5_000),
Interval = IntervalOrDefault(dto.Probe?.IntervalMs, 5_000),
Timeout = PositiveTimeoutOrDefault(dto.Probe?.TimeoutMs, 2_000),
ProbeTagPath = dto.Probe?.ProbeTagPath,
},
@@ -111,7 +111,7 @@ public static class AbCipDriverFactoryExtensions
EnableControllerBrowse = dto.EnableControllerBrowse ?? false,
BrowsePageDelay = TimeSpan.FromMilliseconds(Math.Max(0, dto.BrowsePageDelayMs ?? 5)),
EnableAlarmProjection = dto.EnableAlarmProjection ?? false,
AlarmPollInterval = TimeSpan.FromMilliseconds(dto.AlarmPollIntervalMs ?? 1_000),
AlarmPollInterval = IntervalOrDefault(dto.AlarmPollIntervalMs, 1_000),
EnableDeclarationOnlyUdtGrouping = dto.EnableDeclarationOnlyUdtGrouping ?? false,
MaxConcurrentReads = dto.MaxConcurrentReads ?? 8,
};
@@ -131,6 +131,19 @@ public static class AbCipDriverFactoryExtensions
private static TimeSpan PositiveTimeoutOrDefault(int? ms, int defaultMs) =>
TimeSpan.FromMilliseconds(ms is int v and > 0 ? v : defaultMs);
/// <summary>Floor on a loop interval (probe / alarm poll): 0 would hot-loop against the PLC, a negative value makes <c>Task.Delay</c> throw out of the loop (P-23c).</summary>
internal const int MinIntervalMs = 100;
/// <summary>
/// Maps an operator-supplied loop interval (ms): null ⇒ <paramref name="defaultMs"/>, anything below
/// <see cref="MinIntervalMs"/> (zero, negative) is clamped up to it.
/// </summary>
/// <param name="ms">The operator-supplied interval in milliseconds, or null.</param>
/// <param name="defaultMs">The default applied when <paramref name="ms"/> is null.</param>
/// <returns>An interval of at least <see cref="MinIntervalMs"/>.</returns>
private static TimeSpan IntervalOrDefault(int? ms, int defaultMs) =>
TimeSpan.FromMilliseconds(Math.Max(MinIntervalMs, ms ?? defaultMs));
// tagName null = a driver-level (or device-level) config field: the error text names the driver config,
// not a tag. Never pass a placeholder like "device" as tagName — it renders as "tag 'device'".
private static T ParseEnum<T>(string? raw, string? tagName, string driverInstanceId, string field,
@@ -87,7 +87,7 @@ public sealed record AbCipTagPath(
int? bitIndex = null;
if (parts.Count >= 2 && int.TryParse(parts[^1], out var maybeBit)
&& maybeBit is >= 0 and <= 31
&& maybeBit is >= 0 and <= 63
&& !parts[^1].Contains('['))
{
bitIndex = maybeBit;
@@ -57,10 +57,13 @@ internal sealed class SymbolListingEnumerator : IAbCipTagEnumerator
.ConfigureAwait(false);
}
catch (OperationCanceledException) { throw; }
catch (Exception)
catch (Exception ex) when (!AbCipRefusals.IsConnectionFault(ex))
{
// A refusal (the controller answered "no" for this program) or a listing that cannot be read: skip it.
continue;
}
// A connection-level fault (timeout, closed session, I/O) is NOT "this program is unreadable" — the rest of
// the listing would be silently missing with no log (P-23e) — so it propagates and the browse reports it.
foreach (var tag in CipSymbolObjectDecoder.Decode(programBuffer, programScope: program))
yield return tag;
@@ -357,6 +357,46 @@ public sealed class AbCipDriverDiscoveryTests
builder.Folders.ShouldContain(f => f.BrowseName == "Motor1.Status");
}
/// <summary>
/// Review 2026-12-02 P-23d (#983): the fan-out's cycle guard keyed on member NAME, so a UDT tag <c>Status</c>
/// whose nested type has a member also called <c>Status</c> was skipped as "cyclic" and never appeared in browse.
/// Keyed on the struct TYPE (template id) it is emitted; a true re-entry of the same template id stays cut.
/// </summary>
[Fact]
public async Task A_nested_member_that_shares_its_parents_name_is_not_mistaken_for_a_cycle()
{
const string device = "ab://10.0.0.5/1,0";
const uint outerTemplateId = 0x2A;
const uint innerTemplateId = 0x123;
var builder = new RecordingBuilder();
var enumeratorFactory = new FakeEnumeratorFactory(
new AbCipDiscoveredTag("Status", null, AbCipDataType.Structure, ReadOnly: false,
TemplateInstanceId: outerTemplateId));
var templateReaderFactory = new IdKeyedTemplateReaderFactory
{
Templates =
{
[outerTemplateId] = BuildSimpleTemplate("OuterUdt", 12,
("Speed", 0xCA, 0, 0),
("Status", (ushort)(0x8000 | innerTemplateId), 0, 8)), // same NAME as the tag, different TYPE
[innerTemplateId] = BuildSimpleTemplate("InnerUdt", 4, ("Code", 0xC4, 0, 0)),
},
};
var drv = new AbCipDriver(new AbCipDriverOptions
{
Devices = [new AbCipDeviceOptions(device)],
EnableControllerBrowse = true,
}, "drv-1", enumeratorFactory: enumeratorFactory, templateReaderFactory: templateReaderFactory);
await drv.InitializeAsync("{}", CancellationToken.None);
await drv.DiscoverAsync(builder, CancellationToken.None);
var names = builder.Variables.Select(v => v.Info.FullName).ToList();
names.ShouldContain("Status.Speed"); // positive control: the parent fanned out
names.ShouldContain("Status.Status.Code"); // the same-named nested member is no longer dropped
}
/// <summary>
/// A discovered Structure whose shape cannot be resolved degrades to the prior single
/// Variable behavior (no regression): one Variable under the Discovered folder keyed by
@@ -66,4 +66,33 @@ public sealed class AbCipProgramScopeEnumerationTests
tags.ShouldContain(t => t.Name == "WW_InCycle");
}
/// <summary>
/// P-23e (#983): a connection-level failure reading a program's listing used to be swallowed with no log,
/// silently dropping the program (and everything after it) from browse. It must surface; a device refusal
/// still skips just that program.
/// </summary>
[Fact]
public async Task A_timeout_reading_a_program_listing_surfaces_but_a_refusal_skips_the_program()
{
var controllerListing = Convert.FromHexString(ControllerListing);
using var timesOut = new SymbolListingEnumerator((_, name, _) => name == "@tags"
? Task.FromResult(controllerListing)
: Task.FromException<byte[]>(new ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport.AbTransportException(
ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport.AbStatus.Timeout, "listing timeout")));
await Should.ThrowAsync<ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport.AbTransportException>(async () =>
{
await foreach (var _ in timesOut.EnumerateAsync(Params, TestContext.Current.CancellationToken)) { }
});
// Positive control: the same shape with a device REFUSAL yields the controller tags and does not throw.
using var refused = new SymbolListingEnumerator((_, name, _) => name == "@tags"
? Task.FromResult(controllerListing)
: Task.FromException<byte[]>(new ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport.AbTransportException(
ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport.AbStatus.NotFound, "no such program")));
var tags = new List<AbCipDiscoveredTag>();
await foreach (var t in refused.EnumerateAsync(Params, TestContext.Current.CancellationToken)) tags.Add(t);
tags.ShouldContain(t => t.Name == "WW_InCycle");
}
}
@@ -0,0 +1,144 @@
using System.Collections.Concurrent;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.AbCip;
namespace ZB.MOM.WW.OtOpcUa.Driver.AbCip.Tests;
/// <summary>Review 2026-12-02 P-23 (#983) AbCip items a and c (b, d and e live beside the path, discovery and enumeration tests).</summary>
[Trait("Category", "Unit")]
public sealed class AbCipReviewP23Tests
{
private const string Device = "ab://10.0.0.5/1,0";
/// <summary>A parent whose read takes a moment, so an unlocked read-modify-write interleaves with a sibling.</summary>
private sealed class SlowReadParent(AbCipTagCreateParams p, ConcurrentQueue<string>? log = null) : FakeAbCipTag(p)
{
private object? _snapshot;
// A real read captures the controller's word when it is READ; the decode that follows sees that snapshot, not
// whatever a later write made of it. Without this the fake hides every lost update.
public override async Task ReadAsync(CancellationToken cancellationToken)
{
await base.ReadAsync(cancellationToken);
_snapshot = Value;
log?.Enqueue("rmw-read");
await Task.Delay(80, cancellationToken);
}
public override object? DecodeValue(AbCipDataType type, int? bitIndex) => _snapshot;
public override Task WriteAsync(CancellationToken cancellationToken)
{
log?.Enqueue("rmw-write");
return base.WriteAsync(cancellationToken);
}
}
/// <summary>
/// P-23a: <c>Flags.3</c> and <c>FLAGS.4</c> share one case-insensitive parent runtime, so they must share its
/// read-modify-write lock. With a case-sensitive lock table each took its own and one update was lost.
/// </summary>
[Fact]
public async Task Bit_writes_whose_parent_names_differ_only_by_case_both_land()
{
var factory = new FakeAbCipTagFactory { Customise = p => new SlowReadParent(p) { Value = 0 } };
var drv = new AbCipDriver(new AbCipDriverOptions
{
Devices = [new AbCipDeviceOptions(Device)],
RawTags = AbCipRawTags.From(
new AbCipTagDefinition("A", Device, "Flags.3", AbCipDataType.Bool),
new AbCipTagDefinition("B", Device, "FLAGS.4", AbCipDataType.Bool)),
Probe = new AbCipProbeOptions { Enabled = false },
}, "abcip-rmw-case", factory);
await drv.InitializeAsync("{}", CancellationToken.None);
var results = await Task.WhenAll(
drv.WriteAsync([new WriteRequest("A", true)], CancellationToken.None),
drv.WriteAsync([new WriteRequest("B", true)], CancellationToken.None));
results.ShouldAllBe(r => r.Single().StatusCode == AbCipStatusMapper.Good);
Convert.ToInt32(factory.Tags["Flags"].Value).ShouldBe((1 << 3) | (1 << 4)); // neither update lost
}
/// <summary>
/// P-23a: a whole-word write to the parent goes through a different runtime than the bit RMW's, so it must take
/// the same lock — or it lands between the RMW's read and write and is overwritten by the stale read-back.
/// </summary>
[Fact]
public async Task A_whole_word_write_never_lands_between_a_bit_RMWs_read_and_write()
{
var log = new ConcurrentQueue<string>();
var creates = 0;
var factory = new FakeAbCipTagFactory
{
Customise = p =>
{
// 1st create = the bit write's parent runtime, 2nd = the whole-word tag's own runtime.
var n = Interlocked.Increment(ref creates);
return n == 1
? new SlowReadParent(p, log) { Value = 0 }
: new LoggingWholeWord(p, log) { Value = 0 };
},
};
var drv = new AbCipDriver(new AbCipDriverOptions
{
Devices = [new AbCipDeviceOptions(Device)],
RawTags = AbCipRawTags.From(
new AbCipTagDefinition("Bit", Device, "Flags.3", AbCipDataType.Bool),
new AbCipTagDefinition("Word", Device, "Flags", AbCipDataType.DInt)),
Probe = new AbCipProbeOptions { Enabled = false },
}, "abcip-rmw-whole", factory);
await drv.InitializeAsync("{}", CancellationToken.None);
// Warm both runtimes (1 = parent, 2 = whole), then clear the log and race them.
await drv.WriteAsync([new WriteRequest("Bit", true)], CancellationToken.None);
await drv.WriteAsync([new WriteRequest("Word", 7)], CancellationToken.None);
log.Clear();
var rmw = drv.WriteAsync([new WriteRequest("Bit", false)], CancellationToken.None);
var deadline = DateTime.UtcNow.AddSeconds(5);
while (!log.Contains("rmw-read") && DateTime.UtcNow < deadline) await Task.Delay(1, TestContext.Current.CancellationToken);
var whole = drv.WriteAsync([new WriteRequest("Word", 9)], CancellationToken.None);
await Task.WhenAll(rmw, whole);
log.ToArray().ShouldBe(["rmw-read", "rmw-write", "whole-write"]);
}
private sealed class LoggingWholeWord(AbCipTagCreateParams p, ConcurrentQueue<string> log) : FakeAbCipTag(p)
{
public override Task WriteAsync(CancellationToken cancellationToken)
{
log.Enqueue("whole-write");
return base.WriteAsync(cancellationToken);
}
}
/// <summary>P-23c: a zero / negative probe or alarm interval hot-looped (0) or threw out of the loop (negative).</summary>
[Theory]
[InlineData(0)]
[InlineData(-5)]
[InlineData(10)]
public void Probe_and_alarm_intervals_are_clamped_to_a_floor(int ms)
{
var json = $$"""{"devices":[{"hostAddress":"{{Device}}"}],"probe":{"intervalMs":{{ms}}},"alarmPollIntervalMs":{{ms}}}""";
var o = AbCipDriverFactoryExtensions.ParseOptions("drv-1", json);
o.Probe.Interval.ShouldBe(TimeSpan.FromMilliseconds(AbCipDriverFactoryExtensions.MinIntervalMs));
o.AlarmPollInterval.ShouldBe(TimeSpan.FromMilliseconds(AbCipDriverFactoryExtensions.MinIntervalMs));
}
/// <summary>Positive control: an interval at or above the floor, and an absent one, are untouched.</summary>
[Fact]
public void Intervals_at_or_above_the_floor_and_absent_ones_are_untouched()
{
var o = AbCipDriverFactoryExtensions.ParseOptions("drv-1",
$$"""{"devices":[{"hostAddress":"{{Device}}"}],"probe":{"intervalMs":250},"alarmPollIntervalMs":1500}""");
o.Probe.Interval.ShouldBe(TimeSpan.FromMilliseconds(250));
o.AlarmPollInterval.ShouldBe(TimeSpan.FromMilliseconds(1500));
var d = AbCipDriverFactoryExtensions.ParseOptions("drv-1", $$"""{"devices":[{"hostAddress":"{{Device}}"}]}""");
d.Probe.Interval.ShouldBe(TimeSpan.FromSeconds(5));
d.AlarmPollInterval.ShouldBe(TimeSpan.FromSeconds(1));
}
}
@@ -85,13 +85,27 @@ public sealed class AbCipTagPathTests
p.ToLibplctagName().ShouldBe("Motor.Status.12");
}
/// <summary>Verifies that bit index 32 is rejected as out of range.</summary>
[Fact]
public void Bit_index_32_rejected_out_of_range()
/// <summary>
/// P-23b (#983): a LINT host has 64 bits, so the selector accepts 0..63 (it used to stop at 31 and
/// <c>MyLint.40</c> was a malformed tag). The per-host width check refuses a bit the host does not have.
/// </summary>
[Theory]
[InlineData("Flags.31", 31)]
[InlineData("Flags.32", 32)]
[InlineData("MyLint.40", 40)]
[InlineData("Flags.63", 63)]
public void Bit_index_up_to_63_is_a_bit_selector(string path, int bit)
{
// 32 exceeds the DINT bit width — treated as a member name rather than bit selector,
// which fails ident validation and returns null.
AbCipTagPath.TryParse("Flags.32").ShouldBeNull();
var p = AbCipTagPath.TryParse(path);
p.ShouldNotBeNull();
p.BitIndex.ShouldBe(bit);
}
/// <summary>Verifies that bit index 64 is rejected as out of range (a member name that fails ident validation).</summary>
[Fact]
public void Bit_index_64_rejected_out_of_range()
{
AbCipTagPath.TryParse("Flags.64").ShouldBeNull();
}
/// <summary>Verifies that program scope with members, subscript, and bit index parses correctly.</summary>