perf(ablegacy): #1073 memoise the read plan per ordered reference list (bounded, dropped on reinit/shutdown, refusals applied at use)
This commit is contained in:
@@ -378,3 +378,7 @@ and the UI authoring flow.
|
||||
- **Native heap is invisible to the GC.** As with AB CIP, libplctag's native heap does not show up in CLR allocation figures; watch whole-process RSS and use `ReinitializeAsync` to recycle libplctag handles. (`IDriver.GetMemoryFootprint()` was deleted as unconsumed in Gitea #525.)
|
||||
- **PCCC reconnect is more expensive than CIP** — legacy PLCs have no connection multiplexing, so the resilience pipeline should use longer backoff than for AB CIP (see [docs/v2/driver-specs.md §4](../v2/driver-specs.md)).
|
||||
- **Single-element addressing today** — a PCCC file is inherently an array (an N7 file is up to 256 words), but the current tag surface addresses one element per tag; range-spanning tags must be enumerated element-by-element until multi-element addressing lands.
|
||||
|
||||
## Read-plan cache (#1073)
|
||||
|
||||
`ReadAsync` memoises its plan (resolution, per-device bucketing, coalesced-block planning) per EXACT ordered reference list, up to 64 lists per device-table generation (a full cache is cleared). The cache is dropped on every initialise and teardown, so a config change re-plans. The plan is cached as if no block were refused; the device's current refused-block memory is applied at use time. Reads containing an unresolved reference are not cached.
|
||||
|
||||
@@ -101,7 +101,7 @@ public sealed partial class AbLegacyDriver
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private List<ReadUnit> PlanReadUnits(DeviceState device, List<ReadItem> items)
|
||||
private List<ReadUnit> PlanReadUnits(DeviceState device, List<ReadItem> items, bool applyRefusals = true)
|
||||
{
|
||||
if (_options.CoalesceReads == false || items.Count < 2) return [.. items.Select(i => new ReadUnit(i, null))];
|
||||
|
||||
@@ -138,7 +138,7 @@ public sealed partial class AbLegacyDriver
|
||||
}
|
||||
var count = run[^1].Parsed.WordNumber - start + 1;
|
||||
var block = new CoalescedBlock(letter, file, start, count, type, run);
|
||||
if (run.Count < 2 || device.RefusedBlocks.ContainsKey(block.Key))
|
||||
if (run.Count < 2 || (applyRefusals && device.RefusedBlocks.ContainsKey(block.Key)))
|
||||
units.AddRange(run.Select(r => new ReadUnit(r, null)));
|
||||
else
|
||||
units.Add(new ReadUnit(null, block));
|
||||
@@ -148,6 +148,132 @@ public sealed partial class AbLegacyDriver
|
||||
return units;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies the device's CURRENT refused-block memory to a cached plan (#1073). The cache holds the plan as if no
|
||||
/// block were refused, because the memory grows while the plan lives; a refused block becomes its members as singles
|
||||
/// in place — exactly what <see cref="PlanReadUnits"/> emits when it already knows the refusal.
|
||||
/// </summary>
|
||||
private static List<ReadUnit> ApplyRefusedBlocks(DeviceState device, List<ReadUnit> units)
|
||||
{
|
||||
if (device.RefusedBlocks.IsEmpty) return units;
|
||||
List<ReadUnit>? expanded = null;
|
||||
for (var i = 0; i < units.Count; i++)
|
||||
{
|
||||
if (units[i].Block is { } b && device.RefusedBlocks.ContainsKey(b.Key))
|
||||
{
|
||||
expanded ??= [.. units.Take(i)];
|
||||
expanded.AddRange(b.Members.Select(m => new ReadUnit(m, null)));
|
||||
}
|
||||
else expanded?.Add(units[i]);
|
||||
}
|
||||
return expanded ?? units;
|
||||
}
|
||||
|
||||
/// <summary>The planned, device-bucketed form of one read's reference list (#1073).</summary>
|
||||
private sealed record ReadPlan((int Index, uint Status)[] Unresolved, DevicePlan[] Devices);
|
||||
|
||||
/// <summary>One device's units, planned with no block refusal applied (see <see cref="ApplyRefusedBlocks"/>).</summary>
|
||||
private sealed record DevicePlan(DeviceState Device, List<ReadUnit> Units);
|
||||
|
||||
/// <summary>Distinct reference lists cached per device-table generation; a full cache is cleared (a poll loop reads a
|
||||
/// handful of fixed shapes — a cache this large means ad-hoc reads, which must not grow it without bound).</summary>
|
||||
internal const int MaxCachedReadPlans = 64;
|
||||
|
||||
/// <summary>Plans built (cache misses) since construction — test seam.</summary>
|
||||
internal int ReadPlanBuilds => Volatile.Read(ref _readPlanBuilds);
|
||||
private int _readPlanBuilds;
|
||||
|
||||
/// <summary>Plans currently cached — test seam.</summary>
|
||||
internal int CachedReadPlanCount => _readPlans?.Plans.Count ?? 0;
|
||||
|
||||
private volatile ReadPlanCache? _readPlans;
|
||||
|
||||
/// <summary>
|
||||
/// One device-table generation's plans. Valid only while <see cref="Devices"/> is still the published table, which
|
||||
/// every initialise and teardown replaces (and nulls the field), so a config change always re-plans. The key is the
|
||||
/// EXACT ordered reference list, not an order-insensitive set: a plan carries each reference's result-array index,
|
||||
/// so a reordered list needs different indices, and a poll/subscription re-reads the same list in the same order.
|
||||
/// </summary>
|
||||
private sealed class ReadPlanCache(Dictionary<string, DeviceState> devices)
|
||||
{
|
||||
public Dictionary<string, DeviceState> Devices { get; } = devices;
|
||||
public System.Collections.Concurrent.ConcurrentDictionary<string[], ReadPlan> Plans { get; } = new(RefListComparer.Instance);
|
||||
}
|
||||
|
||||
private sealed class RefListComparer : IEqualityComparer<string[]>
|
||||
{
|
||||
public static readonly RefListComparer Instance = new();
|
||||
public bool Equals(string[]? x, string[]? y) => x is not null && y is not null && x.AsSpan().SequenceEqual(y);
|
||||
public int GetHashCode(string[] o)
|
||||
{
|
||||
var h = new HashCode();
|
||||
foreach (var r in o) h.Add(r, StringComparer.Ordinal);
|
||||
return h.ToHashCode();
|
||||
}
|
||||
}
|
||||
|
||||
private ReadPlan GetReadPlan(Dictionary<string, DeviceState> devices, IReadOnlyList<string> references)
|
||||
{
|
||||
var cache = _readPlans;
|
||||
if (cache is null || !ReferenceEquals(cache.Devices, devices))
|
||||
_readPlans = cache = new ReadPlanCache(devices);
|
||||
var key = references.ToArray();
|
||||
if (cache.Plans.TryGetValue(key, out var hit)) return hit;
|
||||
var plan = BuildReadPlan(devices, key);
|
||||
Interlocked.Increment(ref _readPlanBuilds);
|
||||
// Only a plan with no Unresolved entries is cached: an unresolved reference may resolve later (a transient
|
||||
// equipment-tag parse), and caching would pin the Bad answer.
|
||||
if (plan.Unresolved.Length == 0)
|
||||
{
|
||||
if (cache.Plans.Count >= MaxCachedReadPlans) cache.Plans.Clear();
|
||||
cache.Plans[key] = plan;
|
||||
}
|
||||
return plan;
|
||||
}
|
||||
|
||||
/// <summary>The uncached planning step: resolve, classify and bucket every reference, then plan each device's units.</summary>
|
||||
internal string DescribeReadPlanForTest(IReadOnlyList<string> references, bool cached)
|
||||
{
|
||||
var plan = cached ? GetReadPlan(_devices, references) : BuildReadPlan(_devices, [.. references]);
|
||||
var parts = plan.Unresolved.Select(u => $"!{u.Index}:{u.Status}")
|
||||
.Concat(plan.Devices.SelectMany(d => ApplyRefusedBlocks(d.Device, d.Units).Select(u =>
|
||||
u.Block is { } b ? $"B[{b.Key};{string.Join(",", b.Members.Select(m => m.Index))}]" : $"S{u.Single!.Index}")));
|
||||
return string.Join("|", parts);
|
||||
}
|
||||
|
||||
private ReadPlan BuildReadPlan(Dictionary<string, DeviceState> devices, string[] references)
|
||||
{
|
||||
var unresolved = new List<(int, uint)>();
|
||||
var buckets = new Dictionary<DeviceState, List<ReadItem>>(ReferenceEqualityComparer.Instance);
|
||||
for (var i = 0; i < references.Length; i++)
|
||||
{
|
||||
var reference = references[i];
|
||||
if (!_resolver.TryResolve(reference, out var def) || !devices.TryGetValue(def.DeviceHostAddress, out var device))
|
||||
{
|
||||
unresolved.Add((i, AbLegacyStatusMapper.BadNodeIdUnknown));
|
||||
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))
|
||||
{
|
||||
unresolved.Add((i, AbLegacyStatusMapper.BadConfigurationError));
|
||||
continue;
|
||||
}
|
||||
var parsed = device.ParseAddress(def);
|
||||
if (parsed is null)
|
||||
{
|
||||
WarnMalformedOnce(device, def);
|
||||
unresolved.Add((i, AbLegacyStatusMapper.BadNodeIdUnknown));
|
||||
continue;
|
||||
}
|
||||
if (!buckets.TryGetValue(device, out var list)) buckets[device] = list = [];
|
||||
list.Add(new ReadItem(i, reference, def, parsed));
|
||||
}
|
||||
return new ReadPlan([.. unresolved],
|
||||
[.. buckets.Select(kv => new DevicePlan(kv.Key, PlanReadUnits(kv.Key, kv.Value, applyRefusals: false)))]);
|
||||
}
|
||||
|
||||
/// <summary>What a block read concluded; <see cref="Fallback"/> = read the members singly instead.</summary>
|
||||
private enum BlockOutcome { Done, Fallback }
|
||||
|
||||
|
||||
@@ -279,6 +279,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
_tagsByRawPath = tags;
|
||||
_configRejected = rejected;
|
||||
_devices = devices;
|
||||
_readPlans = null; // a config change re-plans (#1073)
|
||||
_resolver.Clear(); // drop transient parses made against the previous table
|
||||
if (options.Probe.Enabled && !string.IsNullOrWhiteSpace(options.Probe.ProbeAddress))
|
||||
{
|
||||
@@ -346,6 +347,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
}
|
||||
var retired = _devices.Values.ToList();
|
||||
_devices = new Dictionary<string, DeviceState>(StringComparer.OrdinalIgnoreCase);
|
||||
_readPlans = null;
|
||||
return (retired, _lifecycleEpoch);
|
||||
}
|
||||
}
|
||||
@@ -519,35 +521,12 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
var results = new DataValueSnapshot[fullReferences.Count];
|
||||
var devices = _devices; // one snapshot of the published table for the whole call
|
||||
|
||||
var buckets = new Dictionary<DeviceState, List<ReadItem>>(ReferenceEqualityComparer.Instance);
|
||||
for (var i = 0; i < fullReferences.Count; i++)
|
||||
{
|
||||
var reference = fullReferences[i];
|
||||
if (!_resolver.TryResolve(reference, out var def) || !devices.TryGetValue(def.DeviceHostAddress, out var device))
|
||||
{
|
||||
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 = device.ParseAddress(def);
|
||||
if (parsed is null)
|
||||
{
|
||||
WarnMalformedOnce(device, def);
|
||||
results[i] = new DataValueSnapshot(null, AbLegacyStatusMapper.BadNodeIdUnknown, null, now);
|
||||
continue;
|
||||
}
|
||||
if (!buckets.TryGetValue(device, out var list)) buckets[device] = list = [];
|
||||
list.Add(new ReadItem(i, reference, def, parsed));
|
||||
}
|
||||
if (buckets.Count == 0) return results;
|
||||
var plan = GetReadPlan(devices, fullReferences);
|
||||
foreach (var (index, status) in plan.Unresolved)
|
||||
results[index] = new DataValueSnapshot(null, status, null, now);
|
||||
if (plan.Devices.Length == 0) return results;
|
||||
|
||||
var passes = buckets.ToArray();
|
||||
var passes = plan.Devices;
|
||||
var outcomes = new DeviceReadOutcome[passes.Length];
|
||||
using (var window = new SemaphoreSlim(MaxConcurrentDevices, MaxConcurrentDevices))
|
||||
{
|
||||
@@ -563,7 +542,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
await window.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
outcomes[d] = await ReadDevicePassAsync(passes[d].Key, passes[d].Value, results, now, cancellationToken)
|
||||
outcomes[d] = await ReadDevicePassAsync(passes[d].Device, passes[d].Units, results, now, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
@@ -623,10 +602,10 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
|
||||
/// <summary>Reads one device's references in order, failing fast once the device is marked down.</summary>
|
||||
private async Task<DeviceReadOutcome> ReadDevicePassAsync(
|
||||
DeviceState device, List<ReadItem> items, DataValueSnapshot[] results, DateTime now, CancellationToken ct)
|
||||
DeviceState device, List<ReadUnit> units, DataValueSnapshot[] results, DateTime now, CancellationToken ct)
|
||||
{
|
||||
var outcome = new DeviceReadOutcome();
|
||||
var work = new Queue<ReadUnit>(PlanReadUnits(device, items));
|
||||
var work = new Queue<ReadUnit>(ApplyRefusedBlocks(device, units));
|
||||
while (work.TryDequeue(out var unit))
|
||||
{
|
||||
var members = unit.Block?.Members ?? [unit.Single!];
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Tests;
|
||||
|
||||
/// <summary>#1073: the read plan is memoised per exact ordered reference list, per device-table generation.</summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class AbLegacyReadPlanCacheTests
|
||||
{
|
||||
private const string Host = "ab://10.0.0.5/1,0";
|
||||
|
||||
private static AbLegacyDriver NewDriver(int tagCount = 4)
|
||||
{
|
||||
var tags = Enumerable.Range(0, tagCount)
|
||||
.Select(i => new AbLegacyTagDefinition($"T{i}", Host, $"N7:{i}", AbLegacyDataType.Int)).ToArray();
|
||||
var factory = new FakeAbLegacyTagFactory { Customise = p => new FakeAbLegacyTag(p) { Value = 1, ArrayValue = new short[64] } };
|
||||
return new AbLegacyDriver(new AbLegacyDriverOptions
|
||||
{
|
||||
Devices = [new AbLegacyDeviceOptions(Host)],
|
||||
RawTags = AbLegacyRawTags.Entries(tags),
|
||||
Probe = new AbLegacyProbeOptions { Enabled = false },
|
||||
}, "drv-plan", factory);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Same_reference_list_plans_once_and_a_different_order_is_a_separate_entry()
|
||||
{
|
||||
var drv = NewDriver();
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
|
||||
await drv.ReadAsync(["T0", "T1", "T2"], CancellationToken.None);
|
||||
await drv.ReadAsync(["T0", "T1", "T2"], CancellationToken.None);
|
||||
await drv.ReadAsync(["T0", "T1", "T2"], CancellationToken.None);
|
||||
drv.ReadPlanBuilds.ShouldBe(1);
|
||||
|
||||
var r = await drv.ReadAsync(["T2", "T1", "T0"], CancellationToken.None);
|
||||
drv.ReadPlanBuilds.ShouldBe(2); // indices differ, so order is part of the key
|
||||
drv.CachedReadPlanCount.ShouldBe(2);
|
||||
r.Count.ShouldBe(3);
|
||||
await drv.ShutdownAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Cached_plan_equals_an_uncached_plan_and_answers_identically()
|
||||
{
|
||||
var drv = NewDriver();
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
string[] refs = ["T3", "T0", "T1"];
|
||||
|
||||
var first = await drv.ReadAsync(refs, CancellationToken.None);
|
||||
var second = await drv.ReadAsync(refs, CancellationToken.None);
|
||||
|
||||
drv.DescribeReadPlanForTest(refs, cached: true).ShouldBe(drv.DescribeReadPlanForTest(refs, cached: false));
|
||||
drv.DescribeReadPlanForTest(refs, cached: true).ShouldContain("B[");
|
||||
second.Select(s => (s.Value, s.StatusCode)).ShouldBe(first.Select(s => (s.Value, s.StatusCode)));
|
||||
await drv.ShutdownAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Reinitialize_and_shutdown_drop_the_cache()
|
||||
{
|
||||
var drv = NewDriver();
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
await drv.ReadAsync(["T0", "T1"], CancellationToken.None);
|
||||
drv.CachedReadPlanCount.ShouldBe(1);
|
||||
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
drv.CachedReadPlanCount.ShouldBe(0);
|
||||
await drv.ReadAsync(["T0", "T1"], CancellationToken.None);
|
||||
drv.ReadPlanBuilds.ShouldBe(2); // re-planned against the new device table
|
||||
|
||||
await drv.ShutdownAsync(CancellationToken.None);
|
||||
drv.CachedReadPlanCount.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_cache_is_bounded()
|
||||
{
|
||||
var drv = NewDriver(tagCount: 2);
|
||||
await drv.InitializeAsync("{}", CancellationToken.None);
|
||||
for (var i = 1; i <= AbLegacyDriver.MaxCachedReadPlans * 2; i++)
|
||||
await drv.ReadAsync([.. Enumerable.Repeat("T0", i), "T1"], CancellationToken.None);
|
||||
drv.CachedReadPlanCount.ShouldBeLessThanOrEqualTo(AbLegacyDriver.MaxCachedReadPlans);
|
||||
await drv.ShutdownAsync(CancellationToken.None);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user