fix(abcip): #983 packed structure reads, non-blocking lease release, allocation trims, docs (P-24)
Structure reads of a known size pack into one MSP; browse/template lease release no longer blocks a thread-pool thread up to 2 s; scheduler packs with running totals; CipReply empty extended-status array shared. AbCip.md documents P-2/P-13/P-16/P-22/P-23/P-24.
This commit is contained in:
@@ -191,7 +191,7 @@ The driver has two interchangeable wire transports, selected by one `DriverConfi
|
||||
a held connection idling out, so this shape follows a controller restart / re-download or a network gap.
|
||||
- `ConnectionSize` / `Timeout` / `AllowPacking` are honoured per pooled connection, and the **first**
|
||||
driver/device to open a given device key wins — including a Test Connect probe on a fused `admin,driver`
|
||||
node (its connection carries the probe timeout). A later opener with different options is ignored and
|
||||
node (a Test Connect probe carries its own probe timeout). The driver's own probe loop leases with the DRIVER's `Timeout` and bounds only its wait with the probe timeout (#983 P-22: it used to lease with the probe's, so a short probe timeout became every data read's). A later opener with different options is ignored and
|
||||
logged once as a Warning (`DeviceSessionPool`). ⚠️ The device key compares the **host string**, so the
|
||||
same controller addressed by DNS name in one driver and by IP in another gets two connections and two
|
||||
Forward Open throttles (up to two opens per second); address a controller the same way everywhere. ControlLogix, GuardLogix and (since T21) CompactLogix default to 4002, a Large
|
||||
@@ -517,6 +517,9 @@ 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`).
|
||||
- **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.)
|
||||
- **Handle eviction on failure** — a non-zero libplctag status or a transport exception evicts the cached tag runtime so the next read/write re-creates a fresh handle, mirroring the probe loop's recreate-on-failure behaviour.
|
||||
- **Read statuses carry the libplctag cause** — a tag the controller does not have reads `BadNodeIdUnknown` (not `BadCommunicationError`), and it does **not** open the device's connect-backoff window (the controller answered; before this, one typo throttled every sibling tag on the device). A genuine connection failure still opens it.
|
||||
|
||||
@@ -39,7 +39,7 @@ public sealed record CipReply(byte Service, byte GeneralStatus, ushort[] Extende
|
||||
r.U8(); // reserved
|
||||
var general = r.U8();
|
||||
var extWords = r.U8();
|
||||
var ext = new ushort[extWords];
|
||||
var ext = extWords == 0 ? [] : new ushort[extWords];
|
||||
for (var i = 0; i < extWords; i++) ext[i] = r.U16();
|
||||
var data = raw[r.Position..];
|
||||
return new CipReply(service, general, ext, data);
|
||||
|
||||
@@ -19,6 +19,13 @@ public static class MultipleServicePacket
|
||||
return w.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>Exact byte size of an MSP carrying <paramref name="count"/> requests totalling <paramref name="totalRequestBytes"/>:
|
||||
/// the running-total form of <see cref="BuildSize(IReadOnlyList{int})"/>, so a packer need not keep a list.</summary>
|
||||
/// <param name="count">The number of embedded requests.</param>
|
||||
/// <param name="totalRequestBytes">The summed byte size of the embedded requests.</param>
|
||||
/// <returns>The total packet size in bytes.</returns>
|
||||
public static int BuildSize(int count, int totalRequestBytes) => HeaderSize + 2 + 2 * count + totalRequestBytes;
|
||||
|
||||
/// <summary>Exact byte size of an MSP carrying requests of the given sizes.</summary>
|
||||
/// <param name="requestSizes">The byte size of each embedded request.</param>
|
||||
/// <returns>The total packet size in bytes.</returns>
|
||||
|
||||
@@ -207,29 +207,28 @@ public sealed class RequestScheduler : IAsyncDisposable
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
var sizes = new List<int>();
|
||||
var replySizes = new List<int>();
|
||||
var replyBudget = _channel.MaxRequestBytes; // connections are symmetric: one size bounds both directions
|
||||
// Running totals, not lists: the packer used to rebuild two Lists per pump pass and re-sum them for every
|
||||
// candidate (quadratic under the queue lock, P-24).
|
||||
var requestBytes = 0;
|
||||
var replyBytes = 0;
|
||||
var maxRequestBytes = _channel.MaxRequestBytes;
|
||||
var replyBudget = maxRequestBytes; // connections are symmetric: one size bounds both directions
|
||||
while (_queue.First is { } n)
|
||||
{
|
||||
if (batch.Count > 0)
|
||||
{
|
||||
if (!_allowPacking || n.Value.Exclusive) break;
|
||||
sizes.Add(n.Value.Request.Length);
|
||||
replySizes.Add(n.Value.ExpectedReplyBytes);
|
||||
if (MultipleServicePacket.BuildSize(sizes) > _channel.MaxRequestBytes
|
||||
|| ReplyEnvelopeSize(replySizes) > replyBudget)
|
||||
var count = batch.Count + 1;
|
||||
if (MultipleServicePacket.BuildSize(count, requestBytes + n.Value.Request.Length) > maxRequestBytes
|
||||
|| ReplyEnvelopeSize(count, replyBytes + n.Value.ExpectedReplyBytes) > replyBudget)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// The first request always goes, even when it alone exceeds the limit: it is sent
|
||||
// bare, and callers that must fit (LogixTagClient) fragment before they get here.
|
||||
sizes.Add(n.Value.Request.Length);
|
||||
replySizes.Add(n.Value.ExpectedReplyBytes);
|
||||
}
|
||||
// The first request always goes, even when it alone exceeds the limit: it is sent
|
||||
// bare, and callers that must fit (LogixTagClient) fragment before they get here.
|
||||
requestBytes += n.Value.Request.Length;
|
||||
replyBytes += n.Value.ExpectedReplyBytes;
|
||||
batch.Add(n.Value);
|
||||
_queue.RemoveFirst();
|
||||
if (n.Value.Exclusive) break;
|
||||
@@ -248,6 +247,13 @@ public sealed class RequestScheduler : IAsyncDisposable
|
||||
return total;
|
||||
}
|
||||
|
||||
/// <summary>Running-total form of <see cref="ReplyEnvelopeSize(IReadOnlyList{int})"/>.</summary>
|
||||
/// <param name="count">The number of embedded replies.</param>
|
||||
/// <param name="totalReplyBytes">The summed expected size of the embedded replies.</param>
|
||||
/// <returns>The total size of the MSP reply in bytes.</returns>
|
||||
internal static int ReplyEnvelopeSize(int count, int totalReplyBytes) =>
|
||||
ReplyHeaderBytes + 2 + 2 * count + totalReplyBytes;
|
||||
|
||||
private async Task PumpAsync()
|
||||
{
|
||||
while (true)
|
||||
|
||||
@@ -158,18 +158,28 @@ internal sealed class NativeAbCipTagEnumeratorFactory : IAbCipTagEnumeratorFacto
|
||||
/// <summary>Bounded lease release shared by the native enumerator and template reader.</summary>
|
||||
internal static class NativeLease
|
||||
{
|
||||
/// <summary>Upper bound on waiting for the lease release (and its Forward Close).</summary>
|
||||
private static readonly TimeSpan DisposeWait = TimeSpan.FromSeconds(2);
|
||||
|
||||
/// <summary>Releases, waiting at most 2 s; never throws, whatever the release delegate does.</summary>
|
||||
/// <summary>
|
||||
/// Starts the lease release and returns WITHOUT waiting for its Forward Close; never throws, whatever the
|
||||
/// release delegate does (P-24: this used to block a thread-pool thread for up to 2 s per browse / template
|
||||
/// read, from an async iterator's <c>finally</c>). Nothing is lost by not waiting: the pool's release does its
|
||||
/// bookkeeping synchronously (ref-count drop, closing-chain registration) before its first await, so an
|
||||
/// acquire made the next instant still opens only after this close — the same guarantee
|
||||
/// <see cref="ConnectionLease.ReleaseInBackground"/> gives the tag runtimes.
|
||||
/// </summary>
|
||||
/// <param name="release">The delegate that releases the lease.</param>
|
||||
/// <param name="logger">The logger used to report a failed release.</param>
|
||||
public static void ReleaseBounded(Func<ValueTask> release, ILogger logger)
|
||||
{
|
||||
try { release().AsTask().Wait(DisposeWait); }
|
||||
Task teardown;
|
||||
try { teardown = release().AsTask(); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Releasing the native AbCip device lease failed.");
|
||||
return;
|
||||
}
|
||||
_ = teardown.ContinueWith(
|
||||
t => logger.LogWarning(t.Exception, "Releasing the native AbCip device lease failed."),
|
||||
CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously,
|
||||
TaskScheduler.Default);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,7 +207,7 @@ internal sealed class NativeAbCipTagRuntime : IAbCipTagRuntime
|
||||
var path = Path();
|
||||
try
|
||||
{
|
||||
var (type, handle, data) = await client.ReadAsync(path, _wireElements, cancellationToken, ExpectedElementBytes(_p.AuthoredType)).ConfigureAwait(false);
|
||||
var (type, handle, data) = await client.ReadAsync(path, _wireElements, cancellationToken, ReplyBytesPerElementHint()).ConfigureAwait(false);
|
||||
if (_isBoolArray && SettleWholeBoolArrayCount(type))
|
||||
{
|
||||
// The reply showed the OTHER layout than the one this read was sized for: discard it and ask again
|
||||
@@ -256,6 +256,21 @@ internal sealed class NativeAbCipTagRuntime : IAbCipTagRuntime
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The reply bytes per element the scheduler budgets this read at. A scalar's width is static; a Structure (or an
|
||||
/// unknown authored type, e.g. the probe) has none, which used to send EVERY such read alone — N UDT parents cost
|
||||
/// N round trips per poll instead of ~N/20 (P-24). Once one read has returned, its size is the hint. An
|
||||
/// under-estimate (the UDT grew in an online edit) is safe: the controller answers Partial and the client's
|
||||
/// fragment loop completes the read.
|
||||
/// </summary>
|
||||
/// <returns>Bytes per element, or 0 when nothing is known (the read is then sent alone).</returns>
|
||||
private int ReplyBytesPerElementHint()
|
||||
{
|
||||
var known = ExpectedElementBytes(_p.AuthoredType);
|
||||
if (known > 0 || _data.Length == 0) return known;
|
||||
return (_data.Length + _wireElements - 1) / _wireElements;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Re-sizes a whole BOOL-array read to the layout the reply TYPE showed: 0xD3 means packed DWORDs (count =
|
||||
/// ceil(n / 32)), 0xC1 means one byte per element (count = n, e.g. ab_server). Any other type is no evidence.
|
||||
|
||||
@@ -81,6 +81,33 @@ public sealed class NativeAbCipTagEnumeratorTests
|
||||
return tags;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// P-24 (#983): the lease release (a Forward Close) must not be waited on from the async iterator's
|
||||
/// <c>finally</c> — it used to block a thread-pool thread for up to 2 s per browse. A release that never
|
||||
/// completes must not delay the enumeration; it is still started exactly once.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_slow_lease_release_does_not_delay_the_enumeration()
|
||||
{
|
||||
var ch = Serve(new() { [""] = Entries(CipSymbolObjectRealControllerCaptureTests.WwInCycle) });
|
||||
var neverCloses = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var releases = 0;
|
||||
await using var sched = new RequestScheduler(ch, allowPacking: false);
|
||||
using var enumerator = new NativeAbCipTagEnumerator(_ =>
|
||||
(sched, () => { Interlocked.Increment(ref releases); return new ValueTask(neverCloses.Task); }));
|
||||
|
||||
var tags = new List<AbCipDiscoveredTag>();
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
await foreach (var t in enumerator.EnumerateAsync(Params, TestContext.Current.CancellationToken))
|
||||
tags.Add(t);
|
||||
sw.Stop();
|
||||
|
||||
tags.ShouldContain(t => t.Name == "WW_InCycle"); // positive control: it enumerated
|
||||
releases.ShouldBe(1);
|
||||
sw.Elapsed.ShouldBeLessThan(TimeSpan.FromMilliseconds(1500)); // unfixed: held for the 2 s DisposeWait
|
||||
neverCloses.SetResult();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Paged_controller_and_program_listings_decode_identically_to_the_captured_buffers()
|
||||
{
|
||||
|
||||
@@ -410,6 +410,33 @@ public sealed class NativeAbCipTagRuntimeTests
|
||||
bits.Select((b, i) => b == (i % 2 == 1)).ShouldAllBe(ok => ok); // byte i, not bit i
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// P-24 (#983): a Structure read has no static element width, so every one was sent alone (UnknownReply). After
|
||||
/// the first read the size is known and queued structure reads pack into one Multiple Service Packet.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Structure_reads_of_a_known_size_pack_into_one_MSP()
|
||||
{
|
||||
var udt = Convert.FromHexString("A002CE0F" + new string('1', 40)); // struct handle + 20 data bytes
|
||||
var ch = new FakeCipChannel { RespondPerService = req => Convert.FromHexString("D2000000").Concat(udt).ToArray() };
|
||||
using var rt = NativeAbCipTagRuntime.ForTest(ch, Params("Motor", AbCipDataType.Structure) with { AllowPacking = true });
|
||||
await rt.InitializeAsync(CancellationToken.None); // learns the size
|
||||
ch.SentCount.ShouldBe(1);
|
||||
|
||||
ch.Gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var a = rt.ReadAsync(CancellationToken.None);
|
||||
await ch.WaitForSendsAsync(2); // `a` is in flight; the next two queue behind it
|
||||
var b = rt.ReadAsync(CancellationToken.None);
|
||||
var c = rt.ReadAsync(CancellationToken.None);
|
||||
var d = rt.ReadAsync(CancellationToken.None);
|
||||
ch.Gate.SetResult();
|
||||
await Task.WhenAll(a, b, c, d).WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
|
||||
|
||||
ch.SentCount.ShouldBe(3); // init, a alone, ONE packed MSP for b + c + d
|
||||
ch.Sent[2][0].ShouldBe((byte)0x0A);
|
||||
FakeCipChannel.SplitMsp(ch.Sent[2]).Count.ShouldBe(3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_user_string_array_uses_the_buffer_derived_stride()
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user