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 string MappingB = "map-l2b";
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;
// Access first: a condition-bearing mapping's anchor folders are event notifiers from materialisation.
var access = new ImportedConditionEventWireTests.FakeConditionAccess();
access.Allowed.Add(ServerEventRig.KeyPrincipal);
nm.ProjectedConditionAccess = access;
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");
// A3b review S5: worst case — TWO placements per condition (two mappings, two folders it is wired into).
nm.TryEnsureProjectedAnchor(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(Mapping, root), parent,
"remote", "Plant/remote", Mapping, 1, () => true), out var anchorA).ShouldBeTrue();
nm.TryEnsureProjectedAnchor(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(MappingB, root), parent,
"remote-b", "Plant/remote-b", MappingB, 1, () => true), out var anchorB).ShouldBeTrue();
// Event items: the Server object and both placement folders, publishing OFF so the server-side queues hold their events.
using var session = await rig.ConnectAsync(anonymous: false, ct);
var subscription = new Opc.Ua.Client.Subscription(session.DefaultSubscription) { PublishingInterval = 1000, PublishingEnabled = false };
session.AddSubscription(subscription);
await subscription.CreateAsync(ct);
foreach (var source in new[] { ObjectIds.Server, Local(session, anchorA!.Value), Local(session, anchorB!.Value) })
{
var item = new Opc.Ua.Client.MonitoredItem(subscription.DefaultItem)
{
StartNodeId = source, AttributeId = Attributes.EventNotifier, QueueSize = 1000,
Filter = new EventFilter { SelectClauses = [new SimpleAttributeOperand(ObjectTypeIds.BaseEventType, new QualifiedName(BrowseNames.EventId)),
new SimpleAttributeOperand(ObjectTypeIds.BaseEventType, new QualifiedName(BrowseNames.Message))] },
};
subscription.AddItem(item);
}
await subscription.ApplyChangesAsync(ct);
subscription.MonitoredItems.All(m => ServiceResult.IsGood(m.Status.Error)).ShouldBeTrue("all three event items are admitted");
var (heap0, ws0) = Measure();
var totalMemory0 = GC.GetTotalMemory(forceFullCollection: true);
var keys = Enumerable.Range(0, Conditions).Select(i => KeyOf("l2-" + i)).ToArray();
// Runner state (worst case): the committed Live records AND a full re-snapshot Buffer of the same keys.
var live = keys.Select((k, i) => Update(k, i, 3, active: true, acked: false, sequence: 1)).ToList();
var sw = Stopwatch.StartNew();
nm.ApplyConditions(live);
var materialise = sw.Elapsed;
var (heapMid, _) = Measure();
// Every N6 EventId slot filled: RecentEventIds transitions per condition, each a reported event minting an EventId.
List buffer = [];
sw.Restart();
for (var t = 0; t < OpcUaServer.ProjectedConditionRegistry.RecentEventIds; t++)
{
buffer = keys.Select((k, i) => Update(k, i, 4 + t, active: true, acked: t % 2 == 0, sequence: (ulong)(2 + t / 2))).ToList();
nm.ApplyConditions(buffer);
}
var transition = sw.Elapsed;
nm.ImportedConditionCount.ShouldBe(Conditions);
var slots = nm.FindImportedConditionRecentEventCount(Connection, keys[0]);
slots.ShouldBe(OpcUaServer.ProjectedConditionRegistry.RecentEventIds, "every N6 slot is in use");
// 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();
var (reportedHeap0, reportedHeap1) = (totalMemory0, GC.GetTotalMemory(forceFullCollection: true));
GC.KeepAlive(live);
GC.KeepAlive(buffer);
GC.KeepAlive(subscription);
var heapGrowth = heap1 - heap0;
var wsGrowth = ws1 - ws0;
var line = $"L2 (worst case: 2 placements, {slots} EventId slots, 3 event items, Live+Buffer records): {Conditions} conditions: " +
$"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, " +
$"{OpcUaServer.ProjectedConditionRegistry.RecentEventIds} transitions {transition.TotalMilliseconds:F0} ms; events reported {nm.ImportedEventsReported}; " +
$"GC.GetTotalMemory delta (not used, see Measure) +{(reportedHeap1 - reportedHeap0) / 1048576.0:F1} MiB";
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);
heapGrowth.ShouldBeLessThanOrEqualTo(200L * 1024 * 1024, "the retained managed heap is under the same bound");
}
private static NodeId Local(Opc.Ua.Client.ISession session, NodeId serverId) =>
new(serverId.IdentifierAsString, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri));
///
/// Retained managed heap and settled working set after forced compacting GCs.
///
///
/// A3 review round 2: GC.GetTotalMemory is NOT the retained heap on this runtime (.NET 10, regions). In the same
/// process state it reported either +92 MiB or +218 MiB (bimodal, run to run) while GC.GetGCMemoryInfo's heap size
/// was 135.5 MB in both, and a heap dump of a "+218 MiB" run held 136 MB of objects in total (eeheap -gc: allocated
/// 136,318,696, committed 236,208,128) — the extra ~125 MiB was committed-but-free region space. The live heap is therefore
/// taken from the last full blocking GC's HeapSizeBytes − FragmentedBytes, and the working set is sampled until the GC
/// has decommitted those free regions (two samples 500 ms apart within 1 MiB, at most 10 s): the instant after the forced
/// GCs it still counts them (+214 MiB seen; +133 MiB two seconds later in the same run).
///
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(); }
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true);
var info = GC.GetGCMemoryInfo(GCKind.FullBlocking);
using var process = Process.GetCurrentProcess();
process.Refresh();
var ws = process.WorkingSet64;
var settle = Stopwatch.StartNew();
while (settle.Elapsed < TimeSpan.FromSeconds(10))
{
Thread.Sleep(500);
process.Refresh();
var next = process.WorkingSet64;
var stable = Math.Abs(next - ws) < 1024 * 1024;
ws = next;
if (stable) break;
}
return (info.HeapSizeBytes - info.FragmentedBytes, ws);
}
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, ulong sequence)
{
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..]),
new ImportedConditionPlacement(MappingB, DataRealm.Raw, view, "Plant/remote-b", 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", sequence));
return new ImportedConditionUpdate(Connection, state, info, placements, "Plant/remote/" + placements[0].RelativePath);
}
}