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.
This commit is contained in:
@@ -285,7 +285,7 @@ When the Instance Actor is stopped (due to disable, delete, or redeployment), Ak
|
||||
- **WhileTrue**: On the `false → true` edge the script fires once, then re-fires on a periodic timer while the condition stays true; on the `true → false` edge the timer stops. The re-fire cadence is the script's **minimum time between runs**; with none configured the trigger degrades to the single edge fire and logs a warning.
|
||||
- **Minimum time between runs**: If configured, the Script Actor tracks the last execution time and skips trigger invocations that fire before the minimum interval has elapsed. For a WhileTrue trigger it doubles as the re-fire cadence.
|
||||
|
||||
> **Per-attribute change routing (P2).** Rather than broadcasting every attribute change to all child Script/Alarm Actors, the Instance Actor routes each change only to the children that monitor that attribute (built from their trigger configs at spawn time); **Expression-trigger children, which read an attribute snapshot, receive all changes**. Each child still keeps its own trigger gate as defense-in-depth — the routing is an optimization, not the authority.
|
||||
> **Per-attribute change routing (P2).** Rather than broadcasting every attribute change to all child Script/Alarm Actors, the Instance Actor routes each change only to the children that monitor that attribute (built from their trigger configs at spawn time); **Expression-trigger children are routed by the attribute keys their expression reads** (SRT-7, 2026-12-03): a compile-time syntax walk extracts the literal `Attributes["k"]` / `Children["c"].Attributes["k"]` reads, and the child hears only changes of those attributes. Any read the walk cannot pin down (a non-literal key, an alias or member access of the `Attributes`/`Children`/`Parent` globals, a parse error, or an expression that reads no attribute at all) falls back to **receiving all changes**, as before. Each child still keeps its own trigger gate as defense-in-depth — the routing is an optimization, not the authority.
|
||||
|
||||
### Concurrent Execution
|
||||
- Each invocation launches a **new run** on the script-execution scheduler.
|
||||
@@ -409,7 +409,7 @@ that owns the Instance Actor, and central reads the linkage from audit rows.
|
||||
- **Snapshot / SnapshotComplete (reconnect reconciliation)**: `Snapshot` updates buffer into a staging set; `SnapshotComplete` performs an **atomic swap** of the mirrored set with the staged set. Any condition that was previously mirrored but is **not present** in the new snapshot emits a return-to-normal `AlarmStateChanged` and drops out. This is how the mirror self-corrects after an outage.
|
||||
- **Live transitions** (`Raise` / `Ack` / `Clear` / `Retrigger` / `StateChange`): upsert the condition by `SourceReference`. Updates carrying a `TransitionTime` **older** than the currently held transition are ignored (out-of-order protection). Accepted transitions persist to SQLite and emit an enriched `AlarmStateChanged` upward to the Instance Actor.
|
||||
- **Retention**: a mirrored condition is dropped once it is both inactive **and** acknowledged (`!Active && Acknowledged`) — the alarm has fully run its course at the source and no longer needs mirroring. The drop emits a final state change and deletes the SQLite row.
|
||||
- **Per-source cap**: at most `MirroredAlarmCapPerSource` conditions are retained per source. When the cap is exceeded the **oldest** condition is dropped and the eviction is **logged** — there is no silent truncation. If the evicted condition is still **active**, a final return-to-normal `AlarmStateChanged` is emitted before it is dropped (mirroring the retention drop above), so a capped-out active condition is never left stuck-active downstream.
|
||||
- **Per-source cap**: at most `MirroredAlarmCapPerSource` conditions are retained per source. When the cap is exceeded the **oldest** condition is dropped (selected with a bounded heap, not a sort of the whole mirror — SRT-14) and the eviction is **logged** — there is no silent truncation; the Warning is rate-limited to one a minute during a sustained flood and carries the number of evictions since the previous one. If the evicted condition is still **active**, a final return-to-normal `AlarmStateChanged` is emitted before it is dropped (mirroring the retention drop above), so a capped-out active condition is never left stuck-active downstream.
|
||||
|
||||
### Persistence
|
||||
- Mirrored condition state is persisted to the site SQLite `native_alarm_state` table on every accepted transition and removed on drop-out.
|
||||
|
||||
@@ -185,7 +185,7 @@ public static class FlowShapePredictor
|
||||
_nodes.Add(new PredictedNode(id, kind, lane, title, inputDependent, mergedNote));
|
||||
if (_previous != null)
|
||||
{
|
||||
var fromLane = _nodes.First(n => n.Id == _previous).Lane;
|
||||
var fromLane = _nodes[IndexOf(_previous)].Lane;
|
||||
_edges.Add(new PredictedEdge(_previous, id, (fromLane == FlowLane.Central) != (lane == FlowLane.Central), async));
|
||||
}
|
||||
|
||||
@@ -194,12 +194,28 @@ public static class FlowShapePredictor
|
||||
return id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// CMN-11: O(1) node lookup. Ids are minted append-only as <c>"n" + (index + 1)</c>, so the
|
||||
/// index is read from the id; the linear scan is only a fallback for a foreign id.
|
||||
/// </summary>
|
||||
/// <param name="id">The node id.</param>
|
||||
/// <returns>The node's index, or -1 when absent.</returns>
|
||||
private int IndexOf(string id)
|
||||
{
|
||||
if (id.Length > 1 && id[0] == 'n'
|
||||
&& int.TryParse(id.AsSpan(1), NumberStyles.None, CultureInfo.InvariantCulture, out var ordinal)
|
||||
&& ordinal >= 1 && ordinal <= _nodes.Count
|
||||
&& _nodes[ordinal - 1].Id == id)
|
||||
return ordinal - 1;
|
||||
return _nodes.FindIndex(n => n.Id == id);
|
||||
}
|
||||
|
||||
/// <summary>Appends a note to an existing node.</summary>
|
||||
/// <param name="id">The id of the node to annotate.</param>
|
||||
/// <param name="note">The note to append.</param>
|
||||
internal void Annotate(string id, string note)
|
||||
{
|
||||
var i = _nodes.FindIndex(n => n.Id == id);
|
||||
var i = IndexOf(id);
|
||||
if (i < 0) return;
|
||||
var n = _nodes[i];
|
||||
_nodes[i] = n with { Note = n.Note == null ? note : $"{n.Note}; {note}" };
|
||||
|
||||
@@ -2180,6 +2180,19 @@ public class InstanceActor : ReceiveActor
|
||||
}
|
||||
list.Add(child);
|
||||
break;
|
||||
case TriggerRoutingKind.MonitoredAttributes:
|
||||
// SRT-7: an Expression trigger whose reads are all literal keys hears only
|
||||
// changes of those attributes (its snapshot is only ever read at those keys).
|
||||
foreach (var attribute in decision.MonitoredAttributeSet!)
|
||||
{
|
||||
if (!_childrenByMonitoredAttribute.TryGetValue(attribute, out var set))
|
||||
{
|
||||
set = new List<IActorRef>();
|
||||
_childrenByMonitoredAttribute[attribute] = set;
|
||||
}
|
||||
set.Add(child);
|
||||
}
|
||||
break;
|
||||
case TriggerRoutingKind.AllChanges:
|
||||
_allChangeChildren.Add(child);
|
||||
break;
|
||||
|
||||
@@ -443,10 +443,7 @@ public class NativeAlarmActor : ReceiveActor
|
||||
return;
|
||||
}
|
||||
|
||||
var overflow = _alarms.Values
|
||||
.OrderBy(a => a.TransitionTime)
|
||||
.Take(_alarms.Count - cap)
|
||||
.ToList();
|
||||
var overflow = SelectOldest(_alarms.Values, _alarms.Count - cap);
|
||||
|
||||
foreach (var evicted in overflow)
|
||||
{
|
||||
@@ -471,12 +468,68 @@ public class NativeAlarmActor : ReceiveActor
|
||||
// This condition is gone for good — evict the parent's
|
||||
// _latestAlarmEvents key so it does not retain a stale entry.
|
||||
NotifyParentDropped(sourceRef);
|
||||
_logger.LogWarning(
|
||||
"Native alarm cap {Cap} exceeded for {Source} on {Instance}; dropped oldest mirrored alarm {Ref}",
|
||||
cap, _source.CanonicalName, _instanceName, sourceRef);
|
||||
LogCapEviction(cap, sourceRef);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SRT-14: the <paramref name="count"/> oldest mirrored conditions (by transition time),
|
||||
/// oldest first, chosen with a bounded max-heap — O(n log k) with k almost always 1 — instead
|
||||
/// of sorting the whole mirror on every transition at the cap.
|
||||
/// </summary>
|
||||
/// <param name="alarms">The mirrored conditions.</param>
|
||||
/// <param name="count">How many to select.</param>
|
||||
/// <returns>The selected conditions, oldest first.</returns>
|
||||
internal static List<NativeAlarmTransition> SelectOldest(
|
||||
IEnumerable<NativeAlarmTransition> alarms, int count)
|
||||
{
|
||||
var result = new List<NativeAlarmTransition>(Math.Max(0, count));
|
||||
if (count <= 0) return result;
|
||||
|
||||
// Max-heap on transition time holding the k oldest seen so far.
|
||||
var heap = new PriorityQueue<NativeAlarmTransition, DateTimeOffset>(
|
||||
count + 1, Comparer<DateTimeOffset>.Create((a, b) => b.CompareTo(a)));
|
||||
foreach (var alarm in alarms)
|
||||
{
|
||||
if (heap.Count < count)
|
||||
{
|
||||
heap.Enqueue(alarm, alarm.TransitionTime);
|
||||
}
|
||||
else if (heap.TryPeek(out _, out var newestKept) && alarm.TransitionTime < newestKept)
|
||||
{
|
||||
heap.EnqueueDequeue(alarm, alarm.TransitionTime);
|
||||
}
|
||||
}
|
||||
|
||||
while (heap.TryDequeue(out var alarm, out _))
|
||||
result.Add(alarm);
|
||||
result.Reverse(); // the max-heap drains newest first
|
||||
return result;
|
||||
}
|
||||
|
||||
private DateTimeOffset _lastCapWarningAt = DateTimeOffset.MinValue;
|
||||
private int _capEvictionsSinceWarning;
|
||||
|
||||
/// <summary>
|
||||
/// SRT-14: the cap eviction Warning is rate-limited (once a minute, carrying the count of
|
||||
/// evictions since the last one) so a sustained flood at the cap does not log a Warning per
|
||||
/// transition. Evictions are never silent — the first one after a quiet minute logs at once.
|
||||
/// </summary>
|
||||
private void LogCapEviction(int cap, string sourceRef)
|
||||
{
|
||||
_capEvictionsSinceWarning++;
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
if (now - _lastCapWarningAt < CapWarningInterval) return;
|
||||
|
||||
_logger.LogWarning(
|
||||
"Native alarm cap {Cap} exceeded for {Source} on {Instance}; dropped oldest mirrored alarm {Ref} ({Evicted} eviction(s) since the last warning)",
|
||||
cap, _source.CanonicalName, _instanceName, sourceRef, _capEvictionsSinceWarning);
|
||||
_lastCapWarningAt = now;
|
||||
_capEvictionsSinceWarning = 0;
|
||||
}
|
||||
|
||||
private static readonly TimeSpan CapWarningInterval = TimeSpan.FromMinutes(1);
|
||||
|
||||
/// <summary>
|
||||
/// Signals the parent Instance Actor that a native condition has
|
||||
/// left the mirror for good so it can evict the matching <c>_latestAlarmEvents</c>
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts;
|
||||
|
||||
/// <summary>
|
||||
/// SRT-7: extracts the canonical attribute keys a trigger expression reads, so an
|
||||
/// Expression-triggered script/alarm can be routed only the changes it depends on instead
|
||||
/// of every attribute change on the instance.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// The walk is deliberately conservative. It recognises exactly the two literal read forms
|
||||
/// <see cref="TriggerExpressionGlobals"/> exposes — <c>Attributes["k"]</c> (key <c>k</c>) and
|
||||
/// <c>Children["c"].Attributes["k"]</c> (key <c>c.k</c>) — and gives up (returns
|
||||
/// <see langword="false"/>, which routes the child to every change exactly as before) on
|
||||
/// anything it cannot pin down: a non-literal index, any other use of the
|
||||
/// <c>Attributes</c>/<c>Children</c>/<c>Parent</c> globals (an alias, a member access, a
|
||||
/// method-group pass), a parse error, or an expression that reads no attribute at all (it may
|
||||
/// depend on something other than attribute values, e.g. the clock, and has always been
|
||||
/// re-evaluated on every change).
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Routing remains an optimisation: the child's own snapshot/evaluation is unchanged. A child
|
||||
/// routed by keys simply stops receiving changes for attributes its expression never reads.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal static class TriggerExpressionKeys
|
||||
{
|
||||
private static readonly CSharpParseOptions ScriptParse =
|
||||
CSharpParseOptions.Default.WithKind(SourceCodeKind.Script);
|
||||
|
||||
/// <summary>
|
||||
/// Tries to extract the literal attribute keys an expression reads.
|
||||
/// </summary>
|
||||
/// <param name="expression">The trigger expression source.</param>
|
||||
/// <param name="keys">The distinct canonical keys read, when the method returns <see langword="true"/>.</param>
|
||||
/// <returns><see langword="true"/> when every attribute read is a recognised literal form and at least one exists.</returns>
|
||||
public static bool TryExtract(string? expression, out IReadOnlyList<string> keys)
|
||||
{
|
||||
keys = Array.Empty<string>();
|
||||
if (string.IsNullOrWhiteSpace(expression)) return false;
|
||||
|
||||
SyntaxTree tree;
|
||||
try
|
||||
{
|
||||
tree = CSharpSyntaxTree.ParseText(expression, ScriptParse);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var root = tree.GetRoot();
|
||||
if (root.ContainsDiagnostics) return false;
|
||||
|
||||
var found = new List<string>();
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
|
||||
foreach (var id in root.DescendantNodes().OfType<IdentifierNameSyntax>())
|
||||
{
|
||||
switch (id.Identifier.ValueText)
|
||||
{
|
||||
case "Parent":
|
||||
return false;
|
||||
|
||||
case "Attributes":
|
||||
{
|
||||
// Children["c"].Attributes["k"]: the identifier is the Name of a member access
|
||||
// whose receiver is a literal Children index.
|
||||
if (id.Parent is MemberAccessExpressionSyntax member && member.Name == id)
|
||||
{
|
||||
if (!TryChildPrefix(member.Expression, out var childPrefix)) return false;
|
||||
if (!TryLiteralIndex(member, out var key)) return false;
|
||||
Add(childPrefix + "." + key);
|
||||
break;
|
||||
}
|
||||
|
||||
// Attributes["k"]
|
||||
if (!TryLiteralIndex(id, out var rootKey)) return false;
|
||||
Add(rootKey);
|
||||
break;
|
||||
}
|
||||
|
||||
case "Children":
|
||||
// Valid only as the receiver of Children["c"].Attributes[...]; that whole
|
||||
// form is validated from the Attributes identifier above.
|
||||
if (!IsChildrenReceiver(id)) return false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (found.Count == 0) return false;
|
||||
keys = found;
|
||||
return true;
|
||||
|
||||
void Add(string key)
|
||||
{
|
||||
if (seen.Add(key)) found.Add(key);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="node"/> is directly indexed by one string literal.</summary>
|
||||
private static bool TryLiteralIndex(ExpressionSyntax node, out string key)
|
||||
{
|
||||
key = "";
|
||||
if (node.Parent is not ElementAccessExpressionSyntax access || access.Expression != node)
|
||||
return false;
|
||||
return TrySingleStringLiteral(access.ArgumentList, out key);
|
||||
}
|
||||
|
||||
/// <summary>Matches <c>Children["c"]</c> and returns <c>c</c>.</summary>
|
||||
private static bool TryChildPrefix(ExpressionSyntax receiver, out string prefix)
|
||||
{
|
||||
prefix = "";
|
||||
return receiver is ElementAccessExpressionSyntax access
|
||||
&& access.Expression is IdentifierNameSyntax { Identifier.ValueText: "Children" }
|
||||
&& TrySingleStringLiteral(access.ArgumentList, out prefix);
|
||||
}
|
||||
|
||||
private static bool IsChildrenReceiver(IdentifierNameSyntax id) =>
|
||||
id.Parent is ElementAccessExpressionSyntax access
|
||||
&& access.Expression == id
|
||||
&& access.Parent is MemberAccessExpressionSyntax member
|
||||
&& member.Expression == access
|
||||
&& member.Name.Identifier.ValueText == "Attributes"
|
||||
&& TrySingleStringLiteral(access.ArgumentList, out _);
|
||||
|
||||
private static bool TrySingleStringLiteral(BracketedArgumentListSyntax args, out string value)
|
||||
{
|
||||
value = "";
|
||||
if (args.Arguments.Count != 1) return false;
|
||||
if (args.Arguments[0].Expression is not LiteralExpressionSyntax literal
|
||||
|| !literal.IsKind(SyntaxKind.StringLiteralExpression))
|
||||
return false;
|
||||
value = literal.Token.ValueText;
|
||||
return value.Length > 0;
|
||||
}
|
||||
}
|
||||
@@ -14,13 +14,18 @@ internal enum TriggerRoutingKind
|
||||
AllChanges,
|
||||
|
||||
/// <summary>Never reacts to attribute changes (interval / call-only scripts).</summary>
|
||||
None
|
||||
None,
|
||||
|
||||
/// <summary>SRT-7: reacts to changes of any of a set of named attributes — an Expression
|
||||
/// trigger whose attribute reads are all literal keys (see <see cref="TriggerExpressionKeys"/>).</summary>
|
||||
MonitoredAttributes
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Result of classifying a child's trigger for attribute-change routing.
|
||||
/// </summary>
|
||||
internal readonly record struct TriggerRoutingDecision(TriggerRoutingKind Kind, string? MonitoredAttribute)
|
||||
internal readonly record struct TriggerRoutingDecision(
|
||||
TriggerRoutingKind Kind, string? MonitoredAttribute, IReadOnlyList<string>? MonitoredAttributeSet = null)
|
||||
{
|
||||
public static readonly TriggerRoutingDecision AllChanges = new(TriggerRoutingKind.AllChanges, null);
|
||||
public static readonly TriggerRoutingDecision None = new(TriggerRoutingKind.None, null);
|
||||
@@ -29,6 +34,23 @@ internal readonly record struct TriggerRoutingDecision(TriggerRoutingKind Kind,
|
||||
/// <param name="attribute">The name of the attribute to monitor.</param>
|
||||
/// <returns>A <see cref="TriggerRoutingDecision"/> of kind <see cref="TriggerRoutingKind.MonitoredAttribute"/>.</returns>
|
||||
public static TriggerRoutingDecision Monitored(string attribute) => new(TriggerRoutingKind.MonitoredAttribute, attribute);
|
||||
|
||||
/// <summary>Creates a decision routing on changes to any of several named attributes (SRT-7).</summary>
|
||||
/// <param name="attributes">The attribute names to monitor.</param>
|
||||
/// <returns>A <see cref="TriggerRoutingDecision"/> of kind <see cref="TriggerRoutingKind.MonitoredAttributes"/>.</returns>
|
||||
public static TriggerRoutingDecision MonitoredSet(IReadOnlyList<string> attributes) =>
|
||||
new(TriggerRoutingKind.MonitoredAttributes, null, attributes);
|
||||
|
||||
/// <summary>
|
||||
/// SRT-7: routes an Expression trigger by the literal attribute keys it reads, falling back
|
||||
/// to all-changes whenever the keys cannot be pinned down.
|
||||
/// </summary>
|
||||
/// <param name="triggerConfigJson">The Expression trigger config JSON.</param>
|
||||
/// <returns>The routing decision.</returns>
|
||||
public static TriggerRoutingDecision ForExpression(string? triggerConfigJson) =>
|
||||
TriggerExpressionKeys.TryExtract(TriggerExpressionGlobals.ExtractExpression(triggerConfigJson), out var keys)
|
||||
? MonitoredSet(keys)
|
||||
: AllChanges;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -79,7 +101,8 @@ internal static class TriggerRouting
|
||||
|
||||
/// <summary>
|
||||
/// Classifies a script trigger. valuechange/conditional → the named attribute (fail open to
|
||||
/// all-changes if unparseable); expression → all-changes; interval/call → none; anything
|
||||
/// all-changes if unparseable); expression → its literal attribute keys (SRT-7; all-changes
|
||||
/// when they cannot be extracted); interval/call → none; anything
|
||||
/// unknown → all-changes (fail open — a misconfigured script still reacts, its own gate
|
||||
/// remains the correctness check).
|
||||
/// </summary>
|
||||
@@ -96,7 +119,7 @@ internal static class TriggerRouting
|
||||
? TriggerRoutingDecision.Monitored(attr)
|
||||
: TriggerRoutingDecision.AllChanges;
|
||||
case "expression":
|
||||
return TriggerRoutingDecision.AllChanges;
|
||||
return TriggerRoutingDecision.ForExpression(triggerConfigJson);
|
||||
case "interval":
|
||||
case "call":
|
||||
return TriggerRoutingDecision.None;
|
||||
@@ -106,7 +129,8 @@ internal static class TriggerRouting
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Classifies an alarm trigger. Expression → all-changes; HiLo/ValueMatch/RangeViolation/
|
||||
/// Classifies an alarm trigger. Expression → its literal attribute keys (SRT-7; all-changes
|
||||
/// when they cannot be extracted); HiLo/ValueMatch/RangeViolation/
|
||||
/// RateOfChange → the named attribute (fail open to all-changes if unparseable); an
|
||||
/// unknown/unparseable trigger type → all-changes (fail open).
|
||||
/// </summary>
|
||||
@@ -120,7 +144,7 @@ internal static class TriggerRouting
|
||||
switch (tt)
|
||||
{
|
||||
case AlarmTriggerType.Expression:
|
||||
return TriggerRoutingDecision.AllChanges;
|
||||
return TriggerRoutingDecision.ForExpression(triggerConfigJson);
|
||||
case AlarmTriggerType.HiLo:
|
||||
case AlarmTriggerType.ValueMatch:
|
||||
case AlarmTriggerType.RangeViolation:
|
||||
|
||||
+45
@@ -116,6 +116,51 @@ public class InstanceActorChildRoutingTests : TestKit, IDisposable
|
||||
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()
|
||||
|
||||
@@ -309,6 +309,31 @@ public class NativeAlarmActorTests : TestKit, IDisposable
|
||||
TimeSpan.FromSeconds(5));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SRT-14 (WP6 6.2): cap eviction picks the oldest conditions with a bounded heap; the
|
||||
/// selection (and its oldest-first order) matches the full sort it replaced.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(1)]
|
||||
[InlineData(3)]
|
||||
[InlineData(10)]
|
||||
public void SelectOldest_MatchesAFullSort(int count)
|
||||
{
|
||||
var rng = new Random(42);
|
||||
var t0 = DateTimeOffset.UtcNow;
|
||||
var alarms = Enumerable.Range(0, 1001)
|
||||
.Select(i => Transition($"ref-{i}", AlarmTransitionKind.Raise,
|
||||
new AlarmConditionState(true, false, null, AlarmShelveState.Unshelved, false, 800),
|
||||
t0.AddMilliseconds(rng.Next(0, 1_000_000))))
|
||||
.ToList();
|
||||
|
||||
var expected = alarms.OrderBy(a => a.TransitionTime).Take(count).Select(a => a.TransitionTime).ToList();
|
||||
var actual = NativeAlarmActor.SelectOldest(alarms, count).Select(a => a.TransitionTime).ToList();
|
||||
|
||||
Assert.Equal(expected, actual);
|
||||
Assert.Empty(NativeAlarmActor.SelectOldest(alarms, 0));
|
||||
}
|
||||
|
||||
/// <summary>A snapshot swap that drops several conditions deletes their rows via the batched flush, and a delete cancels a pending upsert (review 2026-10-21 01/SR-P2).</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests.Scripts;
|
||||
|
||||
/// <summary>
|
||||
/// SRT-7 (WP6 6.2): an Expression trigger is routed by the literal attribute keys it reads,
|
||||
/// and falls back to all-changes whenever those keys cannot be pinned down.
|
||||
/// </summary>
|
||||
public class TriggerExpressionKeysTests
|
||||
{
|
||||
/// <summary>Literal root and child reads are extracted as canonical keys.</summary>
|
||||
[Theory]
|
||||
[InlineData("(double)Attributes[\"Temp\"] > 50", new[] { "Temp" })]
|
||||
[InlineData("(double)Attributes[\"A\"] > (double)Attributes[\"B\"] && Attributes[\"A\"] != null", new[] { "A", "B" })]
|
||||
[InlineData("(double)Children[\"Pump1\"].Attributes[\"Speed\"] > 10", new[] { "Pump1.Speed" })]
|
||||
[InlineData("Attributes[\"Mode\"] as string == \"Auto\" || (bool)Children[\"V\"].Attributes[\"Open\"]", new[] { "Mode", "V.Open" })]
|
||||
public void LiteralReads_AreExtracted(string expression, string[] expected)
|
||||
{
|
||||
Assert.True(TriggerExpressionKeys.TryExtract(expression, out var keys));
|
||||
Assert.Equal(expected, keys);
|
||||
}
|
||||
|
||||
/// <summary>Anything that is not a recognised literal read falls back to all-changes.</summary>
|
||||
[Theory]
|
||||
[InlineData("true")] // no attribute read (may depend on the clock)
|
||||
[InlineData("DateTime.UtcNow.Second == 0")]
|
||||
[InlineData("Attributes[\"A\" + \"B\"] != null")] // non-literal key
|
||||
[InlineData("Attributes[name] != null")]
|
||||
[InlineData("Parent != null")]
|
||||
[InlineData("Children[\"P\"].Attributes[k] != null")] // non-literal child key
|
||||
[InlineData("Children[c].Attributes[\"S\"] != null")] // non-literal child name
|
||||
[InlineData("((Func<object>)(() => Attributes))() != null")] // alias of the global
|
||||
[InlineData("(double)Attributes[\"A\"] > 1 && this.Attributes[\"B\"] != null")]
|
||||
[InlineData("(double)Attributes[\"A\" > 1")] // parse error
|
||||
[InlineData("")]
|
||||
public void UnpinnableReads_FallBack(string expression)
|
||||
{
|
||||
Assert.False(TriggerExpressionKeys.TryExtract(expression, out _));
|
||||
}
|
||||
|
||||
/// <summary>Routing decisions for Expression scripts and alarms use the extracted keys.</summary>
|
||||
[Fact]
|
||||
public void ExpressionRouting_UsesKeysOrFallsBack()
|
||||
{
|
||||
var keyed = TriggerRouting.ForScript("Expression", "{\"expression\":\"(double)Attributes[\\\"A\\\"] > 1\"}");
|
||||
Assert.Equal(TriggerRoutingKind.MonitoredAttributes, keyed.Kind);
|
||||
Assert.Equal(new[] { "A" }, keyed.MonitoredAttributeSet);
|
||||
|
||||
var alarm = TriggerRouting.ForAlarm("Expression", "{\"expression\":\"Children[\\\"P\\\"].Attributes[\\\"X\\\"] != null\"}");
|
||||
Assert.Equal(TriggerRoutingKind.MonitoredAttributes, alarm.Kind);
|
||||
Assert.Equal(new[] { "P.X" }, alarm.MonitoredAttributeSet);
|
||||
|
||||
Assert.Equal(TriggerRoutingKind.AllChanges, TriggerRouting.ForScript("Expression", "{\"expression\":\"true\"}").Kind);
|
||||
Assert.Equal(TriggerRoutingKind.AllChanges, TriggerRouting.ForAlarm("Expression", "not json").Kind);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user