From 98dc4c24a14852944e2fda00f26ab178c79d1de4 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 16:28:04 -0500 Subject: [PATCH 1/2] refactor(sql): #1076 one shared Sql DriverConfig JSON options (Sql.Contracts SqlDriverConfigJson) for driver factory and deploy gate; parity test --- .../Validation/SqlTagDeployChecks.cs | 17 +--------- .../SqlDriverConfigJson.cs | 31 +++++++++++++++++++ .../SqlDriverFactoryExtensions.cs | 10 +----- .../SqlDriverConfigJsonParityTests.cs | 25 +++++++++++++++ 4 files changed, 58 insertions(+), 25 deletions(-) create mode 100644 src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts/SqlDriverConfigJson.cs create mode 100644 tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Tests/SqlDriverConfigJsonParityTests.cs diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/SqlTagDeployChecks.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/SqlTagDeployChecks.cs index 122c03927..0be75d713 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/SqlTagDeployChecks.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/SqlTagDeployChecks.cs @@ -109,21 +109,6 @@ public static class SqlTagDeployChecks /// Error code for a named query the Sql driver would refuse at construction (lmxopcua#1058). public const string NamedQueryInvalidCode = "SqlNamedQueryInvalid"; - /// - /// The driver factory's config reader options (SqlDriverFactoryExtensions.JsonOptions, which lives in the - /// driver assembly this one does not reference): case-insensitive, comments + trailing commas tolerated, unknown - /// members skipped, enums by name. Keep in step — a looser reader here could pass a blob the driver refuses. - /// - private static readonly JsonSerializerOptions SqlConfigJson = new() - { - PropertyNameCaseInsensitive = true, - PropertyNamingPolicy = JsonNamingPolicy.CamelCase, - ReadCommentHandling = JsonCommentHandling.Skip, - AllowTrailingCommas = true, - UnmappedMemberHandling = System.Text.Json.Serialization.JsonUnmappedMemberHandling.Skip, - Converters = { new System.Text.Json.Serialization.JsonStringEnumConverter() }, - }; - /// /// lmxopcua#1058 (#974 follow-up). The driver checks every queries entry with /// under its provider when it is constructed, and ONE refused query @@ -145,7 +130,7 @@ public static class SqlTagDeployChecks { var merged = DriverDeviceConfigMerger.Merge( driver.DriverConfig, devices.Select(d => new DriverDeviceConfigMerger.DeviceRow(d.Name, d.DeviceConfig)).ToList(), []); - dto = JsonSerializer.Deserialize(merged, SqlConfigJson); + dto = JsonSerializer.Deserialize(merged, SqlDriverConfigJson.Options); } catch (JsonException) { diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts/SqlDriverConfigJson.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts/SqlDriverConfigJson.cs new file mode 100644 index 000000000..b1d52a801 --- /dev/null +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts/SqlDriverConfigJson.cs @@ -0,0 +1,31 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts; + +/// +/// The ONE definition of how a Sql DriverConfig blob is read (lmxopcua#1076). The driver factory deserialises +/// with , and the deploy gate (SqlTagDeployChecks, which +/// cannot reference the driver assembly) uses the same instance, so the gate can never be looser or stricter than +/// the driver about what the JSON means. +/// +/// Case-insensitive property names, camelCase naming policy (so a write round-trips to the authored shape). +/// Comments and trailing commas tolerated. +/// Unknown members skipped — a blob authored against another schema version must not brick the driver. +/// Enums read as names or ordinals, always written as names (the enum-serialization guard). +/// +/// Treat as read-only: do not mutate after first use. +/// +public static class SqlDriverConfigJson +{ + /// Serializer options shared by the driver factory, the probe and the deploy gate. + public static readonly JsonSerializerOptions Options = new() + { + PropertyNameCaseInsensitive = true, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + ReadCommentHandling = JsonCommentHandling.Skip, + AllowTrailingCommas = true, + UnmappedMemberHandling = JsonUnmappedMemberHandling.Skip, + Converters = { new JsonStringEnumConverter() }, + }; +} diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql/SqlDriverFactoryExtensions.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql/SqlDriverFactoryExtensions.cs index 91bbda729..1a52950b4 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql/SqlDriverFactoryExtensions.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql/SqlDriverFactoryExtensions.cs @@ -47,15 +47,7 @@ public static class SqlDriverFactoryExtensions /// what makes a write round-trip to the authored shape. /// /// - internal static readonly JsonSerializerOptions JsonOptions = new() - { - PropertyNameCaseInsensitive = true, - PropertyNamingPolicy = JsonNamingPolicy.CamelCase, - ReadCommentHandling = JsonCommentHandling.Skip, - AllowTrailingCommas = true, - UnmappedMemberHandling = JsonUnmappedMemberHandling.Skip, - Converters = { new JsonStringEnumConverter() }, - }; + internal static readonly JsonSerializerOptions JsonOptions = SqlDriverConfigJson.Options; /// The serializer options, exposed so tests can assert the enum guard on a real round-trip. internal static JsonSerializerOptions JsonOptionsForTest => JsonOptions; diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Tests/SqlDriverConfigJsonParityTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Tests/SqlDriverConfigJsonParityTests.cs new file mode 100644 index 000000000..6c4e4113d --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Tests/SqlDriverConfigJsonParityTests.cs @@ -0,0 +1,25 @@ +using System.Text.Json; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts; + +namespace ZB.MOM.WW.OtOpcUa.Driver.Sql.Tests; + +/// lmxopcua#1076: the deploy gate and the driver read a Sql DriverConfig through ONE options instance. +public sealed class SqlDriverConfigJsonParityTests +{ + [Fact] + public void Driver_factory_and_deploy_gate_share_one_options_instance() + => ReferenceEquals(SqlDriverFactoryExtensions.JsonOptionsForTest, SqlDriverConfigJson.Options).ShouldBeTrue(); + + [Theory] + [InlineData("{\"provider\":\"Odbc\",\"queries\":{\"q\":{\"sql\":\"select 1\"}}}")] + [InlineData("{\"PROVIDER\":2, // c\n \"unknown\":1, \"queries\":{\"q\":{\"sql\":\"select 1\"},},}")] + public void Both_readers_parse_identically(string json) + { + var a = JsonSerializer.Deserialize(json, SqlDriverFactoryExtensions.JsonOptionsForTest)!; + var b = JsonSerializer.Deserialize(json, SqlDriverConfigJson.Options)!; + JsonSerializer.Serialize(a, SqlDriverConfigJson.Options).ShouldBe(JsonSerializer.Serialize(b, SqlDriverConfigJson.Options)); + a.Provider.ShouldBe(b.Provider); + } +} From 823030276581e04ffb70d0ab1c2d617c9879ffe9 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 16:30:13 -0500 Subject: [PATCH 2/2] perf(ablegacy): #1073 memoise the read plan per ordered reference list (bounded, dropped on reinit/shutdown, refusals applied at use) --- docs/drivers/AbLegacy.md | 4 + .../AbLegacyDriver.Coalescing.cs | 130 +++++++++++++++++- .../AbLegacyDriver.cs | 41 ++---- .../AbLegacyReadPlanCacheTests.cs | 87 ++++++++++++ 4 files changed, 229 insertions(+), 33 deletions(-) create mode 100644 tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Tests/AbLegacyReadPlanCacheTests.cs diff --git a/docs/drivers/AbLegacy.md b/docs/drivers/AbLegacy.md index c7ed9cf62..351d2495a 100644 --- a/docs/drivers/AbLegacy.md +++ b/docs/drivers/AbLegacy.md @@ -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. diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy/AbLegacyDriver.Coalescing.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy/AbLegacyDriver.Coalescing.cs index 285e006fc..9af09443c 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy/AbLegacyDriver.Coalescing.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy/AbLegacyDriver.Coalescing.cs @@ -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. /// - private List PlanReadUnits(DeviceState device, List items) + private List PlanReadUnits(DeviceState device, List 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; } + /// + /// 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 emits when it already knows the refusal. + /// + private static List ApplyRefusedBlocks(DeviceState device, List units) + { + if (device.RefusedBlocks.IsEmpty) return units; + List? 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; + } + + /// The planned, device-bucketed form of one read's reference list (#1073). + private sealed record ReadPlan((int Index, uint Status)[] Unresolved, DevicePlan[] Devices); + + /// One device's units, planned with no block refusal applied (see ). + private sealed record DevicePlan(DeviceState Device, List Units); + + /// 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). + internal const int MaxCachedReadPlans = 64; + + /// Plans built (cache misses) since construction — test seam. + internal int ReadPlanBuilds => Volatile.Read(ref _readPlanBuilds); + private int _readPlanBuilds; + + /// Plans currently cached — test seam. + internal int CachedReadPlanCount => _readPlans?.Plans.Count ?? 0; + + private volatile ReadPlanCache? _readPlans; + + /// + /// One device-table generation's plans. Valid only while 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. + /// + private sealed class ReadPlanCache(Dictionary devices) + { + public Dictionary Devices { get; } = devices; + public System.Collections.Concurrent.ConcurrentDictionary Plans { get; } = new(RefListComparer.Instance); + } + + private sealed class RefListComparer : IEqualityComparer + { + 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 devices, IReadOnlyList 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; + } + + /// The uncached planning step: resolve, classify and bucket every reference, then plan each device's units. + internal string DescribeReadPlanForTest(IReadOnlyList 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 devices, string[] references) + { + var unresolved = new List<(int, uint)>(); + var buckets = new Dictionary>(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)))]); + } + /// What a block read concluded; = read the members singly instead. private enum BlockOutcome { Done, Fallback } diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy/AbLegacyDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy/AbLegacyDriver.cs index 23b8f5c04..f7eb77140 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy/AbLegacyDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy/AbLegacyDriver.cs @@ -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(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>(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 /// Reads one device's references in order, failing fast once the device is marked down. private async Task ReadDevicePassAsync( - DeviceState device, List items, DataValueSnapshot[] results, DateTime now, CancellationToken ct) + DeviceState device, List units, DataValueSnapshot[] results, DateTime now, CancellationToken ct) { var outcome = new DeviceReadOutcome(); - var work = new Queue(PlanReadUnits(device, items)); + var work = new Queue(ApplyRefusedBlocks(device, units)); while (work.TryDequeue(out var unit)) { var members = unit.Block?.Members ?? [unit.Single!]; diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Tests/AbLegacyReadPlanCacheTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Tests/AbLegacyReadPlanCacheTests.cs new file mode 100644 index 000000000..8399906ed --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Tests/AbLegacyReadPlanCacheTests.cs @@ -0,0 +1,87 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport; + +namespace ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Tests; + +/// #1073: the read plan is memoised per exact ordered reference list, per device-table generation. +[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); + } +}