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:
Joseph Doherty
2026-12-03 09:45:50 -05:00
parent 8b64d1ec9c
commit d3c6295670
9 changed files with 389 additions and 17 deletions
@@ -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: