perf(ablegacy): #1031 memoise the parsed address per authored tag; bound RMW gates and refusal log by the authored set; identity-checked single-tag eviction
This commit is contained in:
@@ -535,7 +535,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
results[i] = new DataValueSnapshot(null, AbLegacyStatusMapper.BadConfigurationError, null, now);
|
||||
continue;
|
||||
}
|
||||
var parsed = AbLegacyAddress.TryParse(def.Address, device.Options.PlcFamily);
|
||||
var parsed = device.ParseAddress(def);
|
||||
if (parsed is null)
|
||||
{
|
||||
WarnMalformedOnce(device, def);
|
||||
@@ -686,6 +686,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
{
|
||||
var def = item.Def;
|
||||
var reference = item.Reference;
|
||||
IAbLegacyTagRuntime? usedRuntime = null; // the handle this call actually used (identity-checked eviction)
|
||||
try
|
||||
{
|
||||
if (item.Parsed.IsIndirect)
|
||||
@@ -733,9 +734,10 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
return (OpVerdict.Neutral, null);
|
||||
}
|
||||
runtime = live;
|
||||
usedRuntime = live;
|
||||
await runtime.ReadAsync(ct).ConfigureAwait(false);
|
||||
status = runtime.GetStatus();
|
||||
var parsed = AbLegacyAddress.TryParse(def.Address, device.Options.PlcFamily);
|
||||
var parsed = device.ParseAddress(def);
|
||||
if (status != 0)
|
||||
value = null;
|
||||
else if (IsArrayTag(def))
|
||||
@@ -771,8 +773,9 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
WarnRefusalOnce(device, def, "read", $"unclassifiable reply {(AbStatus)status}", results[item.Index].StatusCode);
|
||||
return (OpVerdict.Opaque, $"unclassifiable reply {(AbStatus)status} reading {reference}");
|
||||
}
|
||||
// Evict the stale handle so the next call re-creates it (mirrors AbCip).
|
||||
EvictRuntime(device, def.Name);
|
||||
// Evict the stale handle so the next call re-creates it (mirrors AbCip) — identity-checked: a sibling
|
||||
// that reconnected under the gate after we released it must not lose its fresh handle.
|
||||
EvictUsedRuntime(device, def.Name, usedRuntime);
|
||||
if (!device.FirstNonZeroStatusLogged)
|
||||
{
|
||||
device.FirstNonZeroStatusLogged = true;
|
||||
@@ -828,7 +831,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Transport exception — evict so the next read creates a fresh handle (mirrors AbCip).
|
||||
EvictRuntime(device, def.Name);
|
||||
EvictUsedRuntime(device, def.Name, usedRuntime);
|
||||
results[item.Index] = new DataValueSnapshot(null, AbLegacyStatusMapper.BadCommunicationError, null, now);
|
||||
return (OpVerdict.Fault, ex.Message);
|
||||
}
|
||||
@@ -920,9 +923,10 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
continue;
|
||||
}
|
||||
|
||||
IAbLegacyTagRuntime? usedRuntime = null; // the handle this write actually used
|
||||
try
|
||||
{
|
||||
var parsed = AbLegacyAddress.TryParse(def.Address, device.Options.PlcFamily);
|
||||
var parsed = device.ParseAddress(def);
|
||||
|
||||
// A malformed address is a config error, not a comms fault (BadNodeIdUnknown, warned once per tag).
|
||||
if (parsed is null)
|
||||
@@ -1052,6 +1056,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
continue; // the index moved under us (N3): not written, no health evidence
|
||||
}
|
||||
runtime = live;
|
||||
usedRuntime = live;
|
||||
if (arrayValue is not null) runtime.EncodeArray(arrayFileType, arrayValue);
|
||||
else runtime.EncodeValue(def.DataType, parsed.BitIndex, w.Value);
|
||||
await runtime.WriteAsync(cancellationToken).ConfigureAwait(false);
|
||||
@@ -1064,7 +1069,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
|
||||
results[i] = new WriteResult(status == 0 ? AbLegacyStatusMapper.Good : AbLegacyStatusMapper.MapStatus(status));
|
||||
// A no-reply status evicts the stale handle so the next call re-creates it (mirrors AbCip).
|
||||
if (IsNoReply((AbStatus)status) && status != 0) EvictRuntime(device, def.Name);
|
||||
if (IsNoReply((AbStatus)status) && status != 0) EvictUsedRuntime(device, def.Name, usedRuntime);
|
||||
RecordWriteStatus(device, def, status, ref outcome);
|
||||
}
|
||||
catch (OperationCanceledException) { throw; }
|
||||
@@ -1111,7 +1116,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Transport exception — evict so the next write/read creates a fresh handle (mirrors AbCip).
|
||||
EvictRuntime(device, def.Name);
|
||||
EvictUsedRuntime(device, def.Name, usedRuntime);
|
||||
device.RecordCommsFault(Clock());
|
||||
results[i] = new WriteResult(AbLegacyStatusMapper.BadCommunicationError);
|
||||
outcome.FaultMessage ??= ex.Message;
|
||||
@@ -1371,14 +1376,12 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
device.IndirectLastParent[indirectName] = parentName;
|
||||
if (previous is not null && !string.Equals(previous, parentName, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var oldGate = device.GetRmwLock(previous);
|
||||
await oldGate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try { EvictParentRuntime(device, previous); } finally { oldGate.Release(); }
|
||||
var oldHold = await device.EnterRmwAsync(previous, ct).ConfigureAwait(false);
|
||||
try { EvictParentRuntime(device, previous); } finally { oldHold.Dispose(); }
|
||||
}
|
||||
}
|
||||
|
||||
var rmwLock = device.GetRmwLock(parentName);
|
||||
await rmwLock.WaitAsync(ct).ConfigureAwait(false);
|
||||
var rmwHold = await device.EnterRmwAsync(parentName, ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
var parentRuntime = await EnsureParentRuntimeAsync(device, parentName, ct).ConfigureAwait(false);
|
||||
@@ -1410,7 +1413,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
}
|
||||
finally
|
||||
{
|
||||
rmwLock.Release();
|
||||
rmwHold.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1501,8 +1504,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
|
||||
// A bit-addressed index reads its parent word and decodes the bit, like the RMW path does.
|
||||
var runtimeName = (inner with { BitIndex = null }).ToLibplctagName();
|
||||
var gate = device.GetRmwLock(runtimeName);
|
||||
await gate.WaitAsync(ct).ConfigureAwait(false);
|
||||
var gate = await device.EnterRmwAsync(runtimeName, ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
IAbLegacyTagRuntime runtime;
|
||||
@@ -1562,7 +1564,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
}
|
||||
finally
|
||||
{
|
||||
gate.Release();
|
||||
gate.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1741,7 +1743,11 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
private void WarnRefusalOnce(DeviceState device, AbLegacyTagDefinition def, string operation, string reason,
|
||||
uint status = AbLegacyStatusMapper.BadNotSupported)
|
||||
{
|
||||
if (!device.RefusalLogged.TryAdd($"{operation}:{def.Name}", 0)) return;
|
||||
// Keyed by the AUTHORED tag: an indirect resolution's name ("tag=>N7:42") changes with the index value, so
|
||||
// keying on it grew the set (and re-warned) per value a sweeping index took (review 2026-12-02 P-23, L7).
|
||||
var arrow = def.Name.IndexOf("=>", StringComparison.Ordinal);
|
||||
var authored = arrow > 0 ? def.Name[..arrow] : def.Name;
|
||||
if (!device.RefusalLogged.TryAdd($"{operation}:{authored}", 0)) return;
|
||||
// The status the operation is actually answered with (review 07 r0 M8) — not always BadNotSupported.
|
||||
_logger.LogWarning(
|
||||
"AbLegacy {Operation} refused (0x{Status:X8}). Driver={DriverInstanceId} Device={DeviceHostAddress} Reference={Reference} Address={Address} Reason={Reason}",
|
||||
@@ -1764,7 +1770,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
{
|
||||
if (device.Runtimes.TryGetValue(def.Name, out var existing)) return existing;
|
||||
|
||||
var parsed = AbLegacyAddress.TryParse(def.Address, device.Options.PlcFamily)
|
||||
var parsed = device.ParseAddress(def)
|
||||
?? throw new InvalidOperationException(
|
||||
$"AbLegacy tag '{def.Name}' has malformed Address '{def.Address}' for PLC family {device.Options.PlcFamily}.");
|
||||
var createParams = CreateParamsFor(device, def, parsed);
|
||||
@@ -1813,6 +1819,16 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Evicts the handle an operation used and saw fail — by identity when the operation got as far as holding one
|
||||
/// (a sibling's fresh reconnect is left alone), by name only when it failed before it held any (#1031).
|
||||
/// </summary>
|
||||
private static void EvictUsedRuntime(DeviceState device, string tagName, IAbLegacyTagRuntime? used)
|
||||
{
|
||||
if (used is not null) EvictRuntime(device, tagName, used);
|
||||
else EvictRuntime(device, tagName);
|
||||
}
|
||||
|
||||
/// <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
|
||||
@@ -1976,15 +1992,102 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
}
|
||||
}
|
||||
|
||||
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, SemaphoreSlim> _rmwLocks = new();
|
||||
internal sealed class RmwGate
|
||||
{
|
||||
public readonly SemaphoreSlim Semaphore = new(1, 1);
|
||||
public int Users; // holders + waiters, under _rmwGatesLock
|
||||
}
|
||||
|
||||
private readonly Dictionary<string, RmwGate> _rmwGates = new(StringComparer.Ordinal);
|
||||
private readonly object _rmwGatesLock = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets or creates the read-modify-write lock for the specified parent name.
|
||||
/// Takes the read-modify-write gate of a parent word. The gate is reference-counted (holders + waiters) and
|
||||
/// removed the moment its last user leaves, so a sweeping indirect bit-write index no longer leaves one
|
||||
/// <see cref="SemaphoreSlim"/> behind per word it ever resolved (review 2026-12-02 P-23, residual L7).
|
||||
/// Removal at zero users is safe: nobody holds or awaits the gate, so a later caller's fresh gate cannot
|
||||
/// race another RMW of the same word — the gate a waiter already counted on is never removed.
|
||||
/// </summary>
|
||||
/// <param name="parentName">The parent name.</param>
|
||||
/// <returns>The semaphore slim for the parent.</returns>
|
||||
public SemaphoreSlim GetRmwLock(string parentName) =>
|
||||
_rmwLocks.GetOrAdd(parentName, _ => new SemaphoreSlim(1, 1));
|
||||
/// <param name="parentName">The parent word's runtime key.</param>
|
||||
/// <param name="ct">Cancels the wait.</param>
|
||||
/// <returns>The held gate; dispose it to release.</returns>
|
||||
public async Task<RmwHold> EnterRmwAsync(string parentName, CancellationToken ct)
|
||||
{
|
||||
RmwGate gate;
|
||||
lock (_rmwGatesLock)
|
||||
{
|
||||
if (!_rmwGates.TryGetValue(parentName, out gate!)) _rmwGates[parentName] = gate = new RmwGate();
|
||||
gate.Users++;
|
||||
}
|
||||
try
|
||||
{
|
||||
await gate.Semaphore.WaitAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
Leave(parentName, gate);
|
||||
throw;
|
||||
}
|
||||
return new RmwHold(this, parentName, gate);
|
||||
}
|
||||
|
||||
private void Leave(string parentName, RmwGate gate)
|
||||
{
|
||||
lock (_rmwGatesLock)
|
||||
{
|
||||
if (--gate.Users == 0
|
||||
&& _rmwGates.TryGetValue(parentName, out var current) && ReferenceEquals(current, gate))
|
||||
_rmwGates.Remove(parentName);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A held read-modify-write gate; <see cref="Dispose"/> releases it (once).</summary>
|
||||
public sealed class RmwHold
|
||||
{
|
||||
private DeviceState? _owner;
|
||||
private readonly string _name;
|
||||
private readonly RmwGate _gate;
|
||||
|
||||
internal RmwHold(DeviceState owner, string name, RmwGate gate)
|
||||
{
|
||||
_owner = owner;
|
||||
_name = name;
|
||||
_gate = gate;
|
||||
}
|
||||
|
||||
/// <summary>Releases the gate; further calls are no-ops.</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
var owner = Interlocked.Exchange(ref _owner, null);
|
||||
if (owner is null) return;
|
||||
_gate.Semaphore.Release();
|
||||
owner.Leave(_name, _gate);
|
||||
}
|
||||
}
|
||||
|
||||
// Parsed address per AUTHORED tag (P-24): every poll used to re-parse each address two or three times.
|
||||
// Bounded by the authored tag set — an indirect resolution's synthetic name never enters it. A cached
|
||||
// entry is honoured only while it was parsed from the same address text and family.
|
||||
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, (string Address, AbLegacyPlcFamily Family, AbLegacyAddress? Parsed)> _parsedAddresses
|
||||
= new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>
|
||||
/// The parsed form of <paramref name="def"/>'s address under this device's PLC family, memoised per
|
||||
/// authored tag. A resolved indirect definition (its name carries <c>=></c>) is parsed afresh, uncached.
|
||||
/// </summary>
|
||||
/// <param name="def">The tag definition.</param>
|
||||
/// <returns>The parsed address, or <see langword="null"/> when it is malformed for the family.</returns>
|
||||
public AbLegacyAddress? ParseAddress(AbLegacyTagDefinition def)
|
||||
{
|
||||
var family = Options.PlcFamily;
|
||||
if (def.Name.Contains("=>", StringComparison.Ordinal)) return AbLegacyAddress.TryParse(def.Address, family);
|
||||
if (_parsedAddresses.TryGetValue(def.Name, out var c) && c.Family == family
|
||||
&& string.Equals(c.Address, def.Address, StringComparison.Ordinal))
|
||||
return c.Parsed;
|
||||
var parsed = AbLegacyAddress.TryParse(def.Address, family);
|
||||
_parsedAddresses[def.Name] = (def.Address, family, parsed);
|
||||
return parsed;
|
||||
}
|
||||
|
||||
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, SemaphoreSlim> _runtimeLocks = new();
|
||||
|
||||
@@ -2069,7 +2172,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
}
|
||||
|
||||
/// <summary>The number of per-key gates currently held (runtime + RMW). Tests only.</summary>
|
||||
internal int GateCount => _runtimeLocks.Count + _rmwLocks.Count;
|
||||
internal int GateCount { get { lock (_rmwGatesLock) return _runtimeLocks.Count + _rmwGates.Count; } }
|
||||
|
||||
/// <summary>Test seam: invoked with the runtime key just before an operation waits on its gate (after the
|
||||
/// handle was fetched), so a test can act at exactly that point instead of sleeping.</summary>
|
||||
@@ -2129,6 +2232,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
if (ParentRuntimes.TryRemove(key, out var r))
|
||||
try { r.Dispose(); } catch { /* best-effort */ }
|
||||
IndirectLastName.Clear();
|
||||
_parsedAddresses.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+91
@@ -156,4 +156,95 @@ public sealed class AbLegacyIndirectAddressingTests
|
||||
// Only the live resolution's handle (plus the index word's parent runtime) remains cached.
|
||||
state.Runtimes.Keys.Count(k => k.StartsWith("Ind=>", StringComparison.Ordinal)).ShouldBe(1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #1031 (review 2026-12-02 P-23, residual L7): an indirect BIT write resolves to a different parent word per
|
||||
/// index value, and each word used to leave its read-modify-write gate behind. The gates are reference-counted
|
||||
/// and dropped when their last user leaves, so the table does not grow with the index.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Sweeping_index_bit_writes_leave_no_rmw_gates_behind()
|
||||
{
|
||||
var (drv, f) = await NewDriverAsync(new AbLegacyTagDefinition("IndBit", Host, "N7:[N7:0]/3", AbLegacyDataType.Bit, Writable: true));
|
||||
short index = 10;
|
||||
f.Customise = p => new FakeAbLegacyTag(p) { Value = p.TagName == "N7:0" ? index : (short)0 };
|
||||
var state = drv.GetDeviceState(Host)!;
|
||||
|
||||
for (short i = 10; i < 60; i++)
|
||||
{
|
||||
index = i;
|
||||
if (f.Tags.TryGetValue("N7:0", out var idx)) idx.Value = i;
|
||||
(await drv.WriteAsync([new WriteRequest("IndBit", true)], CancellationToken.None))[0]
|
||||
.StatusCode.ShouldBe(AbLegacyStatusMapper.Good); // positive control: every sweep step really wrote
|
||||
}
|
||||
|
||||
// The sweep really touched many distinct words ...
|
||||
f.Tags.Keys.Count(k => k.StartsWith("N7:", StringComparison.Ordinal)).ShouldBeGreaterThan(10);
|
||||
// ... and no RMW gate outlives its last user (the runtime gates for the live resolution remain, bounded).
|
||||
state.GateCount.ShouldBeLessThan(6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_rmw_gate_serialises_users_of_one_word_and_is_removed_with_its_last_user()
|
||||
{
|
||||
var (drv, _) = await NewDriverAsync(new AbLegacyTagDefinition("T", Host, "N7:1", AbLegacyDataType.Int));
|
||||
var state = drv.GetDeviceState(Host)!;
|
||||
var baseline = state.GateCount;
|
||||
|
||||
var first = await state.EnterRmwAsync("N7:5", CancellationToken.None);
|
||||
state.GateCount.ShouldBe(baseline + 1);
|
||||
var second = state.EnterRmwAsync("N7:5", CancellationToken.None);
|
||||
await Task.Delay(50, TestContext.Current.CancellationToken);
|
||||
second.IsCompleted.ShouldBeFalse(); // serialised behind the holder
|
||||
|
||||
first.Dispose();
|
||||
first.Dispose(); // idempotent: must not release the waiter's turn twice
|
||||
var held = await second;
|
||||
state.GateCount.ShouldBe(baseline + 1); // still one gate: the waiter took over the same one
|
||||
var third = state.EnterRmwAsync("N7:5", CancellationToken.None);
|
||||
await Task.Delay(50, TestContext.Current.CancellationToken);
|
||||
third.IsCompleted.ShouldBeFalse(); // the double dispose did not free a second slot
|
||||
|
||||
held.Dispose();
|
||||
(await third).Dispose();
|
||||
state.GateCount.ShouldBe(baseline);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_cancelled_rmw_wait_does_not_leak_its_gate()
|
||||
{
|
||||
var (drv, _) = await NewDriverAsync(new AbLegacyTagDefinition("T", Host, "N7:1", AbLegacyDataType.Int));
|
||||
var state = drv.GetDeviceState(Host)!;
|
||||
var baseline = state.GateCount;
|
||||
var holder = await state.EnterRmwAsync("N7:9", CancellationToken.None);
|
||||
using var cts = new CancellationTokenSource();
|
||||
var waiting = state.EnterRmwAsync("N7:9", cts.Token);
|
||||
cts.Cancel();
|
||||
await Should.ThrowAsync<OperationCanceledException>(async () => await waiting);
|
||||
|
||||
holder.Dispose();
|
||||
state.GateCount.ShouldBe(baseline);
|
||||
}
|
||||
|
||||
/// <summary>#1031 P-24: an authored tag's address is parsed once, and re-parsed only when its text changes.</summary>
|
||||
[Fact]
|
||||
public async Task Authored_addresses_are_parsed_once_per_tag_and_reparsed_on_change()
|
||||
{
|
||||
var (drv, _) = await NewDriverAsync(new AbLegacyTagDefinition("T", Host, "N7:1", AbLegacyDataType.Int));
|
||||
var state = drv.GetDeviceState(Host)!;
|
||||
var def = new AbLegacyTagDefinition("T", Host, "N7:1", AbLegacyDataType.Int);
|
||||
|
||||
var a = state.ParseAddress(def);
|
||||
a.ShouldNotBeNull();
|
||||
ReferenceEquals(state.ParseAddress(def), a).ShouldBeTrue();
|
||||
|
||||
var changed = state.ParseAddress(def with { Address = "N7:2" });
|
||||
changed!.WordNumber.ShouldBe(2);
|
||||
state.ParseAddress(def with { Address = "not-an-address" }).ShouldBeNull(); // a malformed address caches too
|
||||
|
||||
// A resolved indirect definition (synthetic "tag=>concrete" name) never enters the cache.
|
||||
var resolved = def with { Name = "T=>N7:7", Address = "N7:7" };
|
||||
state.ParseAddress(resolved)!.WordNumber.ShouldBe(7);
|
||||
ReferenceEquals(state.ParseAddress(resolved), state.ParseAddress(resolved)).ShouldBeFalse();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user