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:
Joseph Doherty
2026-12-03 15:06:28 -05:00
parent 870f7b28dd
commit eb859fda52
2 changed files with 221 additions and 26 deletions
@@ -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>=&gt;</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();
}
}
}