diff --git a/docs/requirements/Component-SiteRuntime.md b/docs/requirements/Component-SiteRuntime.md
index 9689308a..82986622 100644
--- a/docs/requirements/Component-SiteRuntime.md
+++ b/docs/requirements/Component-SiteRuntime.md
@@ -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.
diff --git a/src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/FlowShapePredictor.cs b/src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/FlowShapePredictor.cs
index 8fb28308..e6f2986d 100644
--- a/src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/FlowShapePredictor.cs
+++ b/src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/FlowShapePredictor.cs
@@ -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;
}
+ ///
+ /// CMN-11: O(1) node lookup. Ids are minted append-only as "n" + (index + 1), so the
+ /// index is read from the id; the linear scan is only a fallback for a foreign id.
+ ///
+ /// The node id.
+ /// The node's index, or -1 when absent.
+ 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);
+ }
+
/// Appends a note to an existing node.
/// The id of the node to annotate.
/// The note to append.
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}" };
diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs
index 82138943..fae62ba4 100644
--- a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs
+++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs
@@ -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();
+ _childrenByMonitoredAttribute[attribute] = set;
+ }
+ set.Add(child);
+ }
+ break;
case TriggerRoutingKind.AllChanges:
_allChangeChildren.Add(child);
break;
diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/NativeAlarmActor.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/NativeAlarmActor.cs
index 26fae600..d1f97baa 100644
--- a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/NativeAlarmActor.cs
+++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/NativeAlarmActor.cs
@@ -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);
}
}
+ ///
+ /// SRT-14: the 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.
+ ///
+ /// The mirrored conditions.
+ /// How many to select.
+ /// The selected conditions, oldest first.
+ internal static List SelectOldest(
+ IEnumerable alarms, int count)
+ {
+ var result = new List(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(
+ count + 1, Comparer.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;
+
+ ///
+ /// 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.
+ ///
+ 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);
+
///
/// Signals the parent Instance Actor that a native condition has
/// left the mirror for good so it can evict the matching _latestAlarmEvents
diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/TriggerExpressionKeys.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/TriggerExpressionKeys.cs
new file mode 100644
index 00000000..9056cbf4
--- /dev/null
+++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/TriggerExpressionKeys.cs
@@ -0,0 +1,140 @@
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+
+namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts;
+
+///
+/// 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.
+///
+///
+///
+/// The walk is deliberately conservative. It recognises exactly the two literal read forms
+/// exposes — Attributes["k"] (key k) and
+/// Children["c"].Attributes["k"] (key c.k) — and gives up (returns
+/// , 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
+/// Attributes/Children/Parent 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).
+///
+///
+/// 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.
+///
+///
+internal static class TriggerExpressionKeys
+{
+ private static readonly CSharpParseOptions ScriptParse =
+ CSharpParseOptions.Default.WithKind(SourceCodeKind.Script);
+
+ ///
+ /// Tries to extract the literal attribute keys an expression reads.
+ ///
+ /// The trigger expression source.
+ /// The distinct canonical keys read, when the method returns .
+ /// when every attribute read is a recognised literal form and at least one exists.
+ public static bool TryExtract(string? expression, out IReadOnlyList keys)
+ {
+ keys = Array.Empty();
+ 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();
+ var seen = new HashSet(StringComparer.Ordinal);
+
+ foreach (var id in root.DescendantNodes().OfType())
+ {
+ 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);
+ }
+ }
+
+ /// True when is directly indexed by one string literal.
+ 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);
+ }
+
+ /// Matches Children["c"] and returns c.
+ 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;
+ }
+}
diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/TriggerRouting.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/TriggerRouting.cs
index f9bd6044..4b47a6b7 100644
--- a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/TriggerRouting.cs
+++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/TriggerRouting.cs
@@ -14,13 +14,18 @@ internal enum TriggerRoutingKind
AllChanges,
/// Never reacts to attribute changes (interval / call-only scripts).
- None
+ None,
+
+ /// SRT-7: reacts to changes of any of a set of named attributes — an Expression
+ /// trigger whose attribute reads are all literal keys (see ).
+ MonitoredAttributes
}
///
/// Result of classifying a child's trigger for attribute-change routing.
///
-internal readonly record struct TriggerRoutingDecision(TriggerRoutingKind Kind, string? MonitoredAttribute)
+internal readonly record struct TriggerRoutingDecision(
+ TriggerRoutingKind Kind, string? MonitoredAttribute, IReadOnlyList? 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,
/// The name of the attribute to monitor.
/// A of kind .
public static TriggerRoutingDecision Monitored(string attribute) => new(TriggerRoutingKind.MonitoredAttribute, attribute);
+
+ /// Creates a decision routing on changes to any of several named attributes (SRT-7).
+ /// The attribute names to monitor.
+ /// A of kind .
+ public static TriggerRoutingDecision MonitoredSet(IReadOnlyList attributes) =>
+ new(TriggerRoutingKind.MonitoredAttributes, null, attributes);
+
+ ///
+ /// 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.
+ ///
+ /// The Expression trigger config JSON.
+ /// The routing decision.
+ public static TriggerRoutingDecision ForExpression(string? triggerConfigJson) =>
+ TriggerExpressionKeys.TryExtract(TriggerExpressionGlobals.ExtractExpression(triggerConfigJson), out var keys)
+ ? MonitoredSet(keys)
+ : AllChanges;
}
///
@@ -79,7 +101,8 @@ internal static class TriggerRouting
///
/// 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).
///
@@ -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
}
///
- /// 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).
///
@@ -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:
diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorChildRoutingTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorChildRoutingTests.cs
index ced04a78..7b4b601c 100644
--- a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorChildRoutingTests.cs
+++ b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorChildRoutingTests.cs
@@ -116,6 +116,51 @@ public class InstanceActorChildRoutingTests : TestKit, IDisposable
Assert.Single(actor.AllChangeChildren);
}
+ ///
+ /// 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.
+ ///
+ [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"));
+ }
+
/// Verifies that a monitored-attribute alarm routes only to its attribute while an expression alarm routes to all changes.
[Fact]
public void MonitoredAttributeAlarm_RoutesToItsAttribute_ExpressionAlarm_RoutesToAllChanges()
diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/NativeAlarmActorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/NativeAlarmActorTests.cs
index 9497354c..4b286eb8 100644
--- a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/NativeAlarmActorTests.cs
+++ b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/NativeAlarmActorTests.cs
@@ -309,6 +309,31 @@ public class NativeAlarmActorTests : TestKit, IDisposable
TimeSpan.FromSeconds(5));
}
+ ///
+ /// 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.
+ ///
+ [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));
+ }
+
/// 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).
/// A task that represents the asynchronous operation.
[Fact]
diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Scripts/TriggerExpressionKeysTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Scripts/TriggerExpressionKeysTests.cs
new file mode 100644
index 00000000..f4de3490
--- /dev/null
+++ b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Scripts/TriggerExpressionKeysTests.cs
@@ -0,0 +1,56 @@
+using ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts;
+
+namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests.Scripts;
+
+///
+/// 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.
+///
+public class TriggerExpressionKeysTests
+{
+ /// Literal root and child reads are extracted as canonical keys.
+ [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);
+ }
+
+ /// Anything that is not a recognised literal read falls back to all-changes.
+ [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