From 82cf7fe1552b2027086b6e35f4a6149ab2e39609 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 23:24:24 -0500 Subject: [PATCH] =?UTF-8?q?test(grpc-data):=20A4=20L1=20harness=20?= =?UTF-8?q?=E2=80=94=20origin=20SnapshotConditions=20Lock=20hold=20with=20?= =?UTF-8?q?1,000=20conditions=20while=20publishing=20(opt-in=20OTOPCUA=5FL?= =?UTF-8?q?1=3D1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude --- ...nditionSnapshotLockHoldMeasurementTests.cs | 120 ++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ConditionSnapshotLockHoldMeasurementTests.cs diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ConditionSnapshotLockHoldMeasurementTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ConditionSnapshotLockHoldMeasurementTests.cs new file mode 100644 index 000000000..b8dd2807d --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ConditionSnapshotLockHoldMeasurementTests.cs @@ -0,0 +1,120 @@ +using System.Diagnostics; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests; + +/// +/// Plan §9.3 L1 (measured in A4; A1 did not record it): the origin's SnapshotConditions Lock hold inside a +/// running SDK server with 1,000 conditions in scope while "drivers publish" (two threads writing variable values and alarm +/// transitions through the node manager's own WriteValue / WriteAlarmCondition, which take Lock). +/// Pass: hold p99 ≤ 10 ms and no publish delayed > 50 ms during a snapshot. Opt-in (OTOPCUA_L1=1): it is a timing +/// measurement, not a unit test. +/// +/// +/// The hold is measured from INSIDE Lock: the hook +/// marks the start of the off-Lock key enumeration's end, and runs +/// right after the hold is released; the interval is therefore an UPPER bound of the hold (it also contains the slice's +/// list allocation and the lock acquisition wait). 1,000 conditions = one hold at DefaultMaxConditionsPerHold. +/// +[Trait("Feature", "GrpcData")] +[Trait("Phase", "A4")] +[Trait("Category", "Perf")] +public sealed class ConditionSnapshotLockHoldMeasurementTests : IDisposable +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + private readonly string _pkiRoot = Path.Combine(Path.GetTempPath(), $"otopcua-l1-{Guid.NewGuid():N}"); + + [Fact] + public async Task L1_snapshot_lock_hold_with_1000_conditions_while_publishing() + { + Assert.SkipUnless(Environment.GetEnvironmentVariable("OTOPCUA_L1") == "1", "opt-in timing harness (OTOPCUA_L1=1)"); + var started = await OpcUaHostStart.StartAsync( + port => new OpcUaApplicationHost( + new OpcUaApplicationHostOptions + { + ApplicationName = "OtOpcUa.L1", ApplicationUri = $"urn:OtOpcUa.L1:{Guid.NewGuid():N}", OpcUaPort = port, + PublicHostname = "localhost", PkiStoreRoot = _pkiRoot, + }, + Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance), + () => new OtOpcUaSdkServer(), Ct); + var nm = started.Server.NodeManager!; + nm.ConditionStateSink = new RecordingConditionSink(); + const int Conditions = 1000, Variables = 500; + for (var d = 0; d < 10; d++) + { + var device = $"Plant/dev{d}"; + nm.EnsureFolder(device, null, $"dev{d}", AddressSpaceRealm.Raw); + for (var i = 0; i < Conditions / 10; i++) + nm.MaterialiseAlarmCondition($"{device}/Alarm{i}", device, $"Alarm{i}", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true); + for (var i = 0; i < Variables / 10; i++) + nm.EnsureVariable($"{device}/Tag{i}", device, $"Tag{i}", "Double", false, AddressSpaceRealm.Raw); + } + nm.CompleteAddressSpaceApply(); + + long enumerated = 0; + var holds = new List(); + nm.OnConditionSnapshotKeysEnumerated = () => Volatile.Write(ref enumerated, Stopwatch.GetTimestamp()); + nm.OnConditionSnapshotHold = count => + { + count.ShouldBe(Conditions); + holds.Add(Stopwatch.GetElapsedTime(Volatile.Read(ref enumerated)).TotalMilliseconds); + }; + + using var stop = new CancellationTokenSource(); + var publishLatencies = new List[2] { [], [] }; + var publishers = Enumerable.Range(0, 2).Select(p => Task.Run(() => + { + var random = new Random(p); + var n = 0; + while (!stop.IsCancellationRequested) + { + var device = $"Plant/dev{random.Next(10)}"; + var t = Stopwatch.GetTimestamp(); + if (p == 0) nm.WriteValue($"{device}/Tag{random.Next(Variables / 10)}", (double)n++, 0, DateTime.UtcNow, AddressSpaceRealm.Raw); + else nm.WriteAlarmCondition($"{device}/Alarm{random.Next(Conditions / 10)}", + new AlarmConditionSnapshot(Active: (n++ & 1) == 0, Acknowledged: false, Confirmed: true, Enabled: true, + Shelving: AlarmShelvingKind.Unshelved, Severity: 700, Message: "hi", StatusCode: OpcUaStatus.Good, ConditionClass: null), + DateTime.UtcNow, AddressSpaceRealm.Raw); + publishLatencies[p].Add(Stopwatch.GetElapsedTime(t).TotalMilliseconds); + Thread.SpinWait(2000); + } + })).ToArray(); + + for (var i = 0; i < 20; i++) nm.SnapshotConditions((_, _) => true); // warm-up + holds.Clear(); + foreach (var list in publishLatencies) lock (list) { } + const int Samples = 500; + for (var i = 0; i < Samples; i++) + { + nm.SnapshotConditions((_, _) => true); + await Task.Delay(2, Ct); + } + stop.Cancel(); + await Task.WhenAll(publishers); + + static double P(List xs, double q) { var s = xs.OrderBy(x => x).ToArray(); return s[Math.Clamp((int)Math.Ceiling(q * s.Length) - 1, 0, s.Length - 1)]; } + var writes = publishLatencies[0]; + var alarms = publishLatencies[1]; + TestContext.Current.SendDiagnosticMessage( + $"L1 holds n={holds.Count} p50={P(holds, .5):F3} p99={P(holds, .99):F3} max={holds.Max():F3} ms; " + + $"WriteValue n={writes.Count} p99={P(writes, .99):F3} max={writes.Max():F3} ms; " + + $"WriteAlarmCondition n={alarms.Count} p99={P(alarms, .99):F3} max={alarms.Max():F3} ms"); + var line = $"L1 holds n={holds.Count} p50={P(holds, .5):F3} p99={P(holds, .99):F3} max={holds.Max():F3} ms; " + + $"WriteValue n={writes.Count} p50={P(writes, .5):F3} p99={P(writes, .99):F3} max={writes.Max():F3} ms; " + + $"WriteAlarmCondition n={alarms.Count} p50={P(alarms, .5):F3} p99={P(alarms, .99):F3} max={alarms.Max():F3} ms"; + if (Environment.GetEnvironmentVariable("OTOPCUA_L1_OUT") is { Length: > 0 } output) File.AppendAllText(output, line + Environment.NewLine); + holds.Count.ShouldBe(Samples); + P(holds, .99).ShouldBeLessThanOrEqualTo(10.0, "L1: snapshot Lock hold p99 ≤ 10 ms"); + writes.Max().ShouldBeLessThanOrEqualTo(50.0, "L1: no data publish delayed > 50 ms"); + await started.Host.DisposeAsync(); + } + + public void Dispose() + { + try { if (Directory.Exists(_pkiRoot)) Directory.Delete(_pkiRoot, recursive: true); } catch (IOException) { } + } +}