From fecb178efae4e68aa2cc9b021ba6fd0ff73b07f9 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 17:23:40 -0500 Subject: [PATCH] =?UTF-8?q?perf(grpc-data):=20A3=20L2=20in-process=20memor?= =?UTF-8?q?y=20harness=20(1,000=20imported=20conditions,=20one=20mapping)?= =?UTF-8?q?=20+=20MaxImportedConditionBytes=20from=20the=20measurement=20(?= =?UTF-8?q?205,665=20B=20=C3=97=202,500)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Configuration/DataConnectionOptions.cs | 4 +- .../ProjectedConditionAccess.cs | 15 ++- ...ImportedConditionMemoryMeasurementTests.cs | 95 +++++++++++++++++++ 3 files changed, 108 insertions(+), 6 deletions(-) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMemoryMeasurementTests.cs diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs index 3dedbbd93..2be47ff68 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs @@ -21,8 +21,8 @@ public sealed class DataConnectionOptions public long MaxTransportBytes { get; set; } = 64 * 1024 * 1024; /// A3 (§5.5): imported-condition node budget per consumer node (2,500 × 49 worst-case nodes per condition). public int MaxImportedConditionNodes { get; set; } = 122_500; - /// A3 (§5.5): imported-condition memory budget per consumer node (≈ 2,500 × 157 KiB; provisional until L2). - public long MaxImportedConditionBytes { get; set; } = 400L * 1024 * 1024; + /// A3 (§5.5): imported-condition memory budget per consumer node (§9.3 L2: measured 205,665 B/condition × 2,500 ≈ 490 MiB). + public long MaxImportedConditionBytes { get; set; } = ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ProjectedConditionOptions.DefaultMaxImportedConditionBytes; public long MaxPendingBytes { get; set; } = 1024 * 1024; public TimeSpan MaxSessionLifetime { get; set; } = TimeSpan.FromHours(1); /// A2b: remote condition-method operations the origin remembers at once for duplicate protection (all principals). diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs index 482d45f2a..9aeb14f49 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs @@ -40,18 +40,25 @@ public sealed class DeployedConditionMappings : IProjectedConditionMappings /// A3 host limits (§5.5 "Budget"). /// How long a connection's condition items stay open after the last event item goes (default 30 s). /// Per consumer node (default 122,500 = 2,500 × 49). -/// Per consumer node (default 400 MiB; provisional until L2). +/// Per consumer node (default = L2-measured × 2,500 ≈ 490 MiB). /// Pause before re-opening an ended condition stream. public sealed record ProjectedConditionOptions(TimeSpan Linger, int MaxImportedConditionNodes, long MaxImportedConditionBytes, TimeSpan ReconnectDelay) { /// Counted, not estimated (plan §5.5 table): the worst case per condition. public const int NodesPerCondition = 49; - /// Measured retained managed size per condition (≈ 157 KiB, SDK 2.0.1). - public const long BytesPerCondition = 160_997; + /// + /// Retained managed bytes per imported condition, measured by the A3 L2 harness (1,000 conditions in one mapping on a + /// running SDK 2.0.1 server: node + children + ids + registry/indexes + EventId registry + verdict cache; X0's + /// node-only harness measured 160,997). The managed-heap figure is used: it is higher than the working-set growth. + /// + public const long BytesPerCondition = 205_665; + + /// §9.3 L2: the host byte cap = measured per-condition bytes × 2,500 (the host condition cap). + public const long DefaultMaxImportedConditionBytes = BytesPerCondition * 2_500; public static ProjectedConditionOptions Default { get; } = - new(TimeSpan.FromSeconds(30), 122_500, 400L * 1024 * 1024, TimeSpan.FromSeconds(1)); + new(TimeSpan.FromSeconds(30), 122_500, DefaultMaxImportedConditionBytes, TimeSpan.FromSeconds(1)); } /// Why a condition-bearing mapping is not contributing conditions. diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMemoryMeasurementTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMemoryMeasurementTests.cs new file mode 100644 index 000000000..8a3ca14f8 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMemoryMeasurementTests.cs @@ -0,0 +1,95 @@ +using System.Diagnostics; +using System.Security.Cryptography; +using Opc.Ua; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests; + +/// +/// §9.3 L2 (A3 exit, m-T7) in-process measurement harness: consumer memory with 1,000 imported conditions in ONE mapping, +/// materialised through the real of a running SDK server — condition nodes and their +/// instance-scoped children, ids, the registry and its folder/notifier indexes, the verdict cache and the EventId registry +/// (every condition reports one event, filling its N6 slot) — plus the updates the runtime keeps per key (records + infos). +/// Opt-in: OTOPCUA_A3_L2=1 (it forces full GCs and is not a unit gate). Pass criterion: working-set growth ≤ 200 MiB. +/// +[Trait("Feature", "GrpcData"), Trait("Phase", "A3"), Trait("Category", "Perf")] +public sealed class ImportedConditionMemoryMeasurementTests +{ + private const string Connection = "conn-l2"; + private const string Mapping = "map-l2"; + private const int Conditions = 1_000; + + [Fact] + public async Task L2_one_thousand_imported_conditions_in_one_mapping_grow_the_working_set_by_at_most_200_MiB() + { + if (Environment.GetEnvironmentVariable("OTOPCUA_A3_L2") != "1") Assert.Skip("Set OTOPCUA_A3_L2=1 to run the A3 L2 memory measurement."); + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3-l2", encrypted: false, ct); + var nm = rig.Nm; + nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); + var parent = nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; + var root = new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant"); + nm.TryEnsureProjectedAnchor(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(Mapping, root), parent, + "remote", "Plant/remote", Mapping, 1, () => true), out _).ShouldBeTrue(); + var access = new ImportedConditionEventWireTests.FakeConditionAccess(); + access.Allowed.Add(ServerEventRig.KeyPrincipal); + nm.ProjectedConditionAccess = access; + + var (heap0, ws0) = Measure(); + var keys = Enumerable.Range(0, Conditions).Select(i => KeyOf("l2-" + i)).ToArray(); + var first = keys.Select((k, i) => Update(k, i, 3, active: true, acked: false)).ToList(); + var sw = Stopwatch.StartNew(); + nm.ApplyConditions(first); + var materialise = sw.Elapsed; + first.Clear(); + var (heapMid, _) = Measure(); + // One more transition each: every condition reports an event (consumer-minted EventId in its N6 registry). + var second = keys.Select((k, i) => Update(k, i, 4, active: true, acked: true)).ToList(); + sw.Restart(); + nm.ApplyConditions(second); + var transition = sw.Elapsed; + nm.ImportedConditionCount.ShouldBe(Conditions); + // Exercise the verdict cache once per condition (one identity). + var identity = new Security.RoleCarryingUserIdentity(new UserNameIdentityToken { UserName = "apikey" }, [], ServerEventRig.KeyPrincipal, + "k", null, null); + foreach (var k in keys) + nm.AuthorizeImportedCondition(identity, Core.Abstractions.OpcUaOperation.Read, nm.ImportedConditionNodeId(Connection, k)).ShouldBeTrue(); + + var (heap1, ws1) = Measure(); + GC.KeepAlive(second); + var heapGrowth = heap1 - heap0; + var wsGrowth = ws1 - ws0; + var line = $"L2: {Conditions} conditions, one mapping: managed heap +{heapGrowth / 1048576.0:F1} MiB ({heapGrowth / Conditions:N0} B/condition; after materialise {(heapMid - heap0) / Conditions:N0}), " + + $"working set +{wsGrowth / 1048576.0:F1} MiB ({wsGrowth / Conditions:N0} B/condition); materialise {materialise.TotalMilliseconds:F0} ms, " + + $"transition {transition.TotalMilliseconds:F0} ms; events reported {nm.ImportedEventsReported}"; + TestContext.Current.TestOutputHelper?.WriteLine(line); + if (Environment.GetEnvironmentVariable("OTOPCUA_A3_MEASURE_OUT") is { Length: > 0 } outPath) File.AppendAllText(outPath, line + Environment.NewLine); + wsGrowth.ShouldBeLessThanOrEqualTo(200L * 1024 * 1024); + } + + private static (long Heap, long WorkingSet) Measure() + { + for (var i = 0; i < 3; i++) { GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true); GC.WaitForPendingFinalizers(); } + using var process = Process.GetCurrentProcess(); + process.Refresh(); + return (GC.GetTotalMemory(forceFullCollection: true), process.WorkingSet64); + } + + private static string KeyOf(string seed) => + Convert.ToBase64String(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(seed))).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + + private static ImportedConditionUpdate Update(string key, int index, long version, bool active, bool acked) + { + var path = $"Plant/dev{index / 10}/HR{index}"; + var view = new DataView(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", path), DataRealm.Raw, null, 0, path); + var placements = new[] { new ImportedConditionPlacement(Mapping, DataRealm.Raw, view, "Plant/remote", path["Plant/".Length..]) }; + var info = new DataConditionInfo("http://opcfoundation.org/UA/:AlarmConditionType", $"HR{index}", DataConditionSourceKind.Native, + [view], (uint)DataConditionMethodSets.Native); + var state = new DataConditionState(key, version, false, true, info, active, acked, true, true, 0, 500, $"HR{index} high", + StatusCodes.Good.Code, null, 0, DateTimeOffset.UtcNow, true, new DataActivationMarker("inc", 1)); + return new ImportedConditionUpdate(Connection, state, info, placements, "Plant/remote/" + placements[0].RelativePath); + } +}