6004a5a565
1. A post-dispatch refusal now puts the node back to its captured pre-call state with one corrective event (skipped when the node changed since) — the SDK had already applied and reported the change. Blank scripted AddComment is refused in the handler before the SDK runs. 2. ScriptedAlarmCommandDispatch: ask the local engine first, broadcast to the peer only on Applied/OutcomeUnknown — a refusal now reached no engine anywhere. 3. ApplyAsync no longer checks 'loaded' before _evalGate: a command racing the first load queues behind it; never loaded => refusal (nothing applied). 4. One Call's requests are settled sequentially (no request runs against a node state the engine refused); <= 64 asks in flight node-wide, else BadTooManyOperations before anything applies; per-request bound starts at send. Measured 300 acks through one host + LocalDb: 59 ms sequential, max 24 ms/ask with 64 outstanding. 5. Mixed-batch wire test (scripted refused + native + imported + scripted applied + core-manager method): per-item status in order, one scripted ask at a time. L6: readiness from the engine's HasCompleteGeneration on a load fault. L7: the verdict slot is closed when its SDK call returns (timer-captured AsyncLocal can no longer park an ask). L10: remote budget never stretched. Co-Authored-By: Claude <noreply@anthropic.com>
121 lines
6.3 KiB
C#
121 lines
6.3 KiB
C#
using System.Diagnostics;
|
|
using Akka.Actor;
|
|
using Microsoft.Data.Sqlite;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using Serilog;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.LocalDb;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
|
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
|
using ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms;
|
|
using ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.ScriptedAlarms;
|
|
|
|
/// <summary>
|
|
/// #937 review r1 (item 4): what an "acknowledge all" costs through the ONE host mailbox with the production LocalDb
|
|
/// (SQLite) condition-state store — 300 active alarms, acknowledged one at a time (one Call's requests are settled
|
|
/// sequentially) and with the node manager's default in-flight cap of 64 asks outstanding at once. Asserts that no ask
|
|
/// waits anywhere near the 5 s verdict bound; the measured numbers are printed for the evidence file.
|
|
/// </summary>
|
|
public sealed class ScriptedAlarmCommandThroughputTests : RuntimeActorTestBase, IDisposable
|
|
{
|
|
private const int Alarms = 300;
|
|
private const int Cap = 64; // OtOpcUaNodeManager.DefaultMaxScriptedCommandsInFlight
|
|
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"otopcua-937-throughput-{Guid.NewGuid():N}.db");
|
|
private readonly ServiceProvider _provider;
|
|
private readonly ITestOutputHelper _output;
|
|
|
|
public ScriptedAlarmCommandThroughputTests(ITestOutputHelper output)
|
|
{
|
|
_output = output;
|
|
var configuration = new ConfigurationBuilder()
|
|
.AddInMemoryCollection(new Dictionary<string, string?> { ["LocalDb:Path"] = _dbPath }).Build();
|
|
_provider = new ServiceCollection()
|
|
.AddZbLocalDb(configuration, db =>
|
|
{
|
|
using (var connection = db.CreateConnection()) AlarmConditionStateSchema.Apply(connection);
|
|
db.RegisterReplicated(AlarmConditionStateSchema.StateTable);
|
|
db.RegisterReplicated(AlarmConditionStateSchema.CommentsTable);
|
|
})
|
|
.BuildServiceProvider();
|
|
}
|
|
|
|
void IDisposable.Dispose()
|
|
{
|
|
_provider.Dispose();
|
|
SqliteConnection.ClearAllPools();
|
|
foreach (var path in new[] { _dbPath, $"{_dbPath}-wal", $"{_dbPath}-shm" })
|
|
try { if (File.Exists(path)) File.Delete(path); } catch { /* best effort */ }
|
|
}
|
|
|
|
private static EquipmentScriptedAlarmPlan Plan(int i) =>
|
|
new(ScriptedAlarmId: $"alm-{i:D3}", EquipmentId: "Plant/Line1/M", Name: $"alm-{i:D3}", AlarmType: "AlarmCondition",
|
|
Severity: 800, MessageTemplate: "m", PredicateScriptId: "always", PredicateSource: "return true;",
|
|
DependencyRefs: [], HistorizeToAveva: false, Retain: true, Enabled: true);
|
|
|
|
[Fact]
|
|
public async Task Three_hundred_acks_through_one_host_stay_far_inside_the_verdict_bound()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
var store = new LocalDbAlarmConditionStateStore(_provider.GetRequiredService<ILocalDb>(), NullLogger<LocalDbAlarmConditionStateStore>.Instance);
|
|
var upstream = new DependencyMuxTagUpstreamSource();
|
|
var logger = new LoggerConfiguration().CreateLogger();
|
|
var engine = new ScriptedAlarmEngine(upstream, store, new ScriptLoggerFactory(logger), logger);
|
|
var readiness = new ScriptedAlarmCommandReadinessView();
|
|
var mux = CreateTestProbe();
|
|
var host = Sys.ActorOf(ScriptedAlarmHostActor.Props(CreateTestProbe().Ref, mux.Ref, () => (upstream, engine), readiness: readiness));
|
|
host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms(Enumerable.Range(0, Alarms).Select(Plan).ToList()));
|
|
mux.ExpectMsg<DependencyMuxActor.RegisterInterest>(TimeSpan.FromSeconds(60), cancellationToken: ct);
|
|
|
|
async Task<TimeSpan> Ack(int i, string op)
|
|
{
|
|
var started = Stopwatch.GetTimestamp();
|
|
var outcome = await host.Ask<AlarmCommandOutcome>(new ScriptedAlarmHostActor.ExecuteAlarmCommand(
|
|
new AlarmCommand($"alm-{i:D3}", op, "alice", op == "AddComment" ? "c" : null, null, Guid.NewGuid().ToString("N"))),
|
|
TimeSpan.FromSeconds(30), ct);
|
|
outcome.Verdict.ShouldBe(AlarmCommandVerdict.Applied);
|
|
return Stopwatch.GetElapsedTime(started);
|
|
}
|
|
|
|
// Sequential: one Call carrying 300 Acknowledge requests (each settled before the next).
|
|
var total = Stopwatch.StartNew();
|
|
var sequential = new List<TimeSpan>();
|
|
for (var i = 0; i < Alarms; i++) sequential.Add(await Ack(i, "Acknowledge"));
|
|
var sequentialTotal = total.Elapsed;
|
|
engine.GetState("alm-000")!.Active.ShouldBe(AlarmActiveState.Active, "precondition: every alarm is active");
|
|
engine.GetState("alm-299")!.Acked.ShouldBe(AlarmAckedState.Acknowledged, "each ack changed (and saved) its condition");
|
|
(await store.LoadAsync("alm-150", ct))!.Acked.ShouldBe(AlarmAckedState.Acknowledged);
|
|
|
|
// Concurrent: many sessions, at most the cap outstanding at once (AddComment always writes a row).
|
|
total.Restart();
|
|
var gate = new SemaphoreSlim(Cap);
|
|
var concurrent = await Task.WhenAll(Enumerable.Range(0, Alarms).Select(async i =>
|
|
{
|
|
await gate.WaitAsync(ct);
|
|
try { return await Ack(i, "AddComment"); }
|
|
finally { gate.Release(); }
|
|
}));
|
|
var concurrentTotal = total.Elapsed;
|
|
|
|
static string Stats(IEnumerable<TimeSpan> s)
|
|
{
|
|
var ms = s.Select(x => x.TotalMilliseconds).Order().ToArray();
|
|
return $"p50 {ms[ms.Length / 2]:0.0} ms, p99 {ms[(int)(ms.Length * 0.99)]:0.0} ms, max {ms[^1]:0.0} ms";
|
|
}
|
|
_output.WriteLine($"sequential 300 acks: total {sequentialTotal.TotalMilliseconds:0} ms; per ask {Stats(sequential)}");
|
|
_output.WriteLine($"cap-{Cap} concurrent 300 comments: total {concurrentTotal.TotalMilliseconds:0} ms; per ask {Stats(concurrent)}");
|
|
|
|
// Far inside the 5 s verdict bound even with a full cap queued behind the one mailbox.
|
|
concurrent.Max().ShouldBeLessThan(TimeSpan.FromSeconds(2.5));
|
|
sequential.Max().ShouldBeLessThan(TimeSpan.FromSeconds(2.5));
|
|
}
|
|
}
|