Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorChildRoutingTests.cs
T
Joseph Doherty d3c6295670 perf(site-runtime): route expression triggers by referenced keys; heap cap eviction; O(1) predictor lane (SRT-7, SRT-14, CMN-11, WP6 task 6.2)
SRT-7: TriggerExpressionKeys extracts the literal Attributes["k"] /
Children["c"].Attributes["k"] reads of an Expression trigger; the Instance
Actor routes the child only those attributes (new MonitoredAttributes routing
kind). Anything not pinnable (non-literal key, alias/member access of the
globals, Parent, parse error, zero reads) falls back to all-changes. Child
actors are unchanged (narrow: WP3 edits ScriptActor/AlarmActor).
  Evidence: instance with 250 attributes at 1 Hz and 10 expression children
  each reading 2 attributes — child mailbox deliveries (and per-eval snapshot
  copies + CTS allocations) go from 2,500/s to 20/s (routing-map test pins
  that a non-read attribute has no route).

SRT-14: EnforceCap selects the oldest conditions with a bounded max-heap and
rate-limits the eviction Warning (1/min with an eviction count).
  Stopwatch, n=1001 k=1 per transition at the cap: OrderBy 13.0-18.2 us -> heap 1.2 us.

CMN-11: FlowShapePredictor looks up a node by the index encoded in its
append-only id (O(1)) instead of a linear scan per AddNode/Annotate.
  Stopwatch PredictSiteScript, Release: 5,000 nodes 125.5 -> 54.9 ms,
  20,000 nodes 434.2 -> 83.3 ms.
2026-12-03 09:45:50 -05:00

200 lines
7.8 KiB
C#

using Akka.Actor;
using Akka.TestKit.Xunit2;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Flattening;
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Actors;
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Persistence;
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts;
using ZB.MOM.WW.ScadaBridge.TestSupport;
using System.Text.Json;
namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests.Actors;
/// <summary>
/// The Instance Actor routes each attribute change only to the
/// children interested in it. A value-change / conditional script (and a monitored-attribute
/// alarm) subscribes to a single named attribute; an Expression-triggered script/alarm hears
/// every change (it keeps a full attribute snapshot). These tests pin the routing-map
/// construction directly — the behavioral gate inside each child stays as defense in depth.
/// </summary>
public class InstanceActorChildRoutingTests : TestKit, IDisposable
{
private readonly SiteStorageService _storage;
private readonly ScriptCompilationService _compilationService;
private readonly SharedScriptLibrary _sharedScriptLibrary;
private readonly SiteRuntimeOptions _options;
private readonly TestLocalDb _localDb;
/// <summary>Creates the test class with a fresh storage service and actor system.</summary>
public InstanceActorChildRoutingTests()
{
_localDb = TestLocalDb.CreateTemp("instance-routing-test");
_storage = new SiteStorageService(
_localDb.Db,
NullLogger<SiteStorageService>.Instance);
_storage.InitializeAsync().GetAwaiter().GetResult();
_compilationService = new ScriptCompilationService(
NullLogger<ScriptCompilationService>.Instance);
_sharedScriptLibrary = new SharedScriptLibrary(
_compilationService, NullLogger<SharedScriptLibrary>.Instance);
_options = new SiteRuntimeOptions
{
MaxScriptCallDepth = 10,
ScriptExecutionTimeoutSeconds = 30
};
}
/// <inheritdoc />
void IDisposable.Dispose()
{
// TestKit teardown first, so no in-flight actor can reach a disposed ILocalDb;
// then dispose the database before deleting — the master connection anchors the WAL.
Shutdown();
var path = _localDb.Path;
_localDb.Dispose();
TestLocalDb.DeleteFiles(path);
}
private static FlattenedConfiguration ScriptsAB_and_Expression(string instanceName)
=> new()
{
InstanceUniqueName = instanceName,
Attributes =
[
new ResolvedAttribute { CanonicalName = "A", Value = "1", DataType = "Double" },
new ResolvedAttribute { CanonicalName = "B", Value = "2", DataType = "Double" }
],
Scripts =
[
new ResolvedScript
{
CanonicalName = "S_A", Code = "return 1;",
TriggerType = "ValueChange",
TriggerConfiguration = "{\"attributeName\":\"A\"}"
},
new ResolvedScript
{
CanonicalName = "S_B", Code = "return 2;",
TriggerType = "ValueChange",
TriggerConfiguration = "{\"attributeName\":\"B\"}"
},
new ResolvedScript
{
CanonicalName = "S_expr", Code = "return 3;",
TriggerType = "Expression",
TriggerConfiguration = "{\"expression\":\"true\"}"
}
]
};
private InstanceActor BuildInstance(FlattenedConfiguration config)
{
var testRef = ActorOfAsTestActorRef<InstanceActor>(
Props.Create(() => new InstanceActor(
config.InstanceUniqueName,
JsonSerializer.Serialize(config),
_storage,
_compilationService,
_sharedScriptLibrary,
null,
_options,
NullLogger<InstanceActor>.Instance)),
"instance-" + Guid.NewGuid().ToString("N"));
return testRef.UnderlyingActor;
}
/// <summary>Verifies that the routing maps are built from the trigger configurations.</summary>
[Fact]
public void RoutingMaps_AreBuiltFromTriggerConfigs()
{
var actor = BuildInstance(ScriptsAB_and_Expression("RoutePump"));
// Two value-change scripts route to their own attribute; the expression script
// routes to the all-changes bucket.
Assert.Single(actor.ChildrenByMonitoredAttribute["A"]);
Assert.Single(actor.ChildrenByMonitoredAttribute["B"]);
Assert.Single(actor.AllChangeChildren);
}
/// <summary>
/// SRT-7 (WP6 6.2): an Expression script/alarm whose reads are literal keys is routed only to
/// those attributes, so a change to any other attribute no longer reaches it.
/// </summary>
[Fact]
public void LiteralKeyExpression_RoutesOnlyToTheAttributesItReads()
{
var config = new FlattenedConfiguration
{
InstanceUniqueName = "ExprKeyPump",
Attributes =
[
new ResolvedAttribute { CanonicalName = "A", Value = "1", DataType = "Double" },
new ResolvedAttribute { CanonicalName = "B", Value = "2", DataType = "Double" },
new ResolvedAttribute { CanonicalName = "C", Value = "3", DataType = "Double" }
],
Scripts =
[
new ResolvedScript
{
CanonicalName = "S_expr", Code = "return 3;",
TriggerType = "Expression",
TriggerConfiguration = "{\"expression\":\"(double)Attributes[\\\"A\\\"] > (double)Attributes[\\\"B\\\"]\"}"
}
],
Alarms =
[
new ResolvedAlarm
{
CanonicalName = "ExprAlarm",
TriggerType = "Expression",
TriggerConfiguration = "{\"expression\":\"(double)Attributes[\\\"B\\\"] > 1\"}",
PriorityLevel = 1
}
]
};
var actor = BuildInstance(config);
Assert.Empty(actor.AllChangeChildren);
Assert.Single(actor.ChildrenByMonitoredAttribute["A"]); // the script
Assert.Equal(2, actor.ChildrenByMonitoredAttribute["B"].Count); // script + alarm
Assert.False(actor.ChildrenByMonitoredAttribute.ContainsKey("C"));
}
/// <summary>Verifies that a monitored-attribute alarm routes only to its attribute while an expression alarm routes to all changes.</summary>
[Fact]
public void MonitoredAttributeAlarm_RoutesToItsAttribute_ExpressionAlarm_RoutesToAllChanges()
{
var config = new FlattenedConfiguration
{
InstanceUniqueName = "AlarmRoutePump",
Attributes =
[
new ResolvedAttribute { CanonicalName = "Temp", Value = "10", DataType = "Double" }
],
Alarms =
[
new ResolvedAlarm
{
CanonicalName = "HiTemp",
TriggerType = "RangeViolation",
TriggerConfiguration = "{\"attributeName\":\"Temp\",\"min\":0,\"max\":100}",
PriorityLevel = 1
},
new ResolvedAlarm
{
CanonicalName = "ExprAlarm",
TriggerType = "Expression",
TriggerConfiguration = "{\"expression\":\"true\"}",
PriorityLevel = 1
}
]
};
var actor = BuildInstance(config);
Assert.Single(actor.ChildrenByMonitoredAttribute["Temp"]);
Assert.Single(actor.AllChangeChildren); // the expression alarm
}
}