fix(virtualtags): #995 inputs held behind a slow run coalesce into one evaluation, array outputs dedup by value, and a failed source binding retries only the unbound tag with backoff

R-19: VirtualTagActor folds inputs that arrive during an in-flight evaluation
(latest value per input) and evaluates once when it completes, instead of
stashing one message per trigger and replaying one script run each (unbounded,
O(M^2) re-stash hops). One-dimensional array results compare element-wise in
the value dedup, so an unchanged array output is not republished, re-routed or
historized on every evaluation.

R-17: VirtualTagHostActor's source-binding retry re-attempts only the tags whose
binding failed (spawning the child / publishing the disabled status on
success), 250 ms doubling to 5 s, instead of re-delivering the whole
ApplyVirtualTags every 250 ms (quarantine reset, re-assert of every child,
BadOutOfService republish, cycle-graph recompute each time).
This commit is contained in:
Joseph Doherty
2026-12-03 10:56:30 -05:00
parent 677a680178
commit a1b8312ea4
5 changed files with 434 additions and 57 deletions
@@ -31,14 +31,22 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
/// <b>Evaluation never blocks the dispatcher (lmxopcua#779, #750 P0).</b> The evaluator is called through
/// <see cref="IVirtualTagEvaluator.EvaluateAsync"/>. A synchronously completed result (passthrough, the null
/// evaluator, test fakes) is applied inline in the same message turn, exactly as before. An incomplete one — a
/// Roslyn script run, up to its 2 s budget — switches the actor into an <i>evaluating</i> behaviour that
/// <b>stashes</b> every dependency / reassert message, and the result comes back as a private completion
/// message. Applying it unstashes everything in arrival order. So each trigger is still evaluated against
/// the dependency map as it stood at that trigger, results are applied and published in trigger order, and
/// the dedup / Bad-transition state sees exactly the sequence it saw when the call blocked — only the
/// dispatcher thread is no longer held while the script runs. The dependency map is not touched while a run
/// is in flight (the messages that would touch it are stashed), which is what makes handing it to the
/// script on another thread safe.
/// Roslyn script run, up to its 2 s budget — switches the actor into an <i>evaluating</i> behaviour, and the
/// result comes back as a private completion message. The dependency map is not touched while a run is in
/// flight, which is what makes handing it to the script on another thread safe.
/// </para>
/// <para>
/// <b>Inputs that arrive during a run are coalesced (#995, review R-19).</b> They are held one slot per input —
/// the newest value wins — and when the run completes they are applied together and evaluated <b>once</b>, stamped
/// with the newest arrival's timestamp (the rule a batched mux burst already follows). They used to be stashed one
/// message per trigger and replayed as one script run each, so a slow script (or the out-of-process runner under
/// load) built an unbounded backlog of evaluations against inputs that were already superseded, with O(M²)
/// re-stash hops. The backlog is now bounded by the tag's input count. Other messages (reassert, runner recovery,
/// source-binding retry, projected wakes) are still stashed and run after the coalesced evaluation starts.
/// </para>
/// <para>
/// The value dedup compares one-dimensional arrays element-wise (#995), so an array-typed tag whose output did not
/// change is not republished, re-routed to its dependents and historized on every evaluation.
/// </para>
/// </summary>
public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
@@ -135,6 +143,10 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
private readonly Dictionary<string, DataValueSnapshot> _dependencies = new(StringComparer.Ordinal);
private readonly Dictionary<string, Core.Abstractions.DataConnections.IProjectedSamplePublicationProof> _projectedDependencyProofs = new(StringComparer.Ordinal);
// #995 (R-19): inputs that arrived while a run was in flight, latest per input; applied when it completes.
private readonly Dictionary<string, DependencyValueChanged> _heldInputs = new(StringComparer.Ordinal);
private DateTime _heldTimestampUtc;
private bool _hasLastValue;
private object? _lastValue;
@@ -436,14 +448,75 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
if (msg.ActorIncarnation != _actorIncarnation) return;
UnbecomeStacked();
ApplyEvaluation(msg.Evaluation, msg.WorstInputStatus, msg.TimestampUtc);
// #995 (R-19): every input that arrived during the run lands now, at once, and is evaluated ONCE —
// before the stashed control messages, so a reassert queued behind the run re-emits the newest state.
ReleaseHeldInputs();
Stash.UnstashAll();
});
// A timer tick during a run is dropped, not stashed: the run in flight IS this interval's evaluation,
// and stashing would replay a backlog of ticks (one script run each) after a slow script (#783).
Receive<TimerTick>(_ => { });
// #995 (R-19): inputs are folded, latest value per input wins, instead of stashed one message per trigger.
Receive<DependencyValueChanged>(HoldInput);
Receive<DependencyValueBatch>(msg =>
{
var items = msg.Items;
for (var i = 0; i < items.Count; i++) HoldInput(items[i]);
});
ReceiveAny(_ => Stash.Stash());
}
/// <summary>
/// #995 (R-19): an input that arrived while a run is in flight. The dependency map cannot change under the
/// running script (it is handed to it on another thread), so the value is held here — one slot per input,
/// the newest wins — and applied when the run completes. This bounds the backlog by the tag's input count,
/// where stashing grew it by one message per trigger and replayed them as one script run each (O(M²)
/// re-stash hops under a slow script).
/// </summary>
/// <param name="item">The arrived input.</param>
private void HoldInput(DependencyValueChanged item)
{
_heldInputs[item.TagId] = item;
_heldTimestampUtc = item.TimestampUtc;
}
/// <summary>
/// Applies every held input (see <see cref="HoldInput"/>) to the dependency map and, for a change-triggered tag,
/// evaluates once against the result — stamped with the newest arrival's timestamp, the same rule
/// <see cref="OnDependencyBatch"/> applies to a mux burst. No-op when nothing arrived during the run.
/// </summary>
private void ReleaseHeldInputs()
{
if (_heldInputs.Count == 0) return;
foreach (var item in _heldInputs.Values)
{
SetDependencyProof(item);
_dependencies[item.TagId] = new DataValueSnapshot(item.Value, item.StatusCode, item.TimestampUtc, item.TimestampUtc);
}
_heldInputs.Clear();
if (_changeTriggered) Evaluate(_heldTimestampUtc);
}
/// <summary>
/// The value dedup's equality: <see cref="object.Equals(object?, object?)"/>, except that two one-dimensional
/// arrays compare element by element (#995, R-19). Each evaluation result is a fresh copy, so reference equality
/// made an array-typed tag publish — and re-trigger its dependents and historize — on every evaluation even when
/// its output never changed. Arrays of different element types never compare equal.
/// </summary>
/// <param name="a">The last published value.</param>
/// <param name="b">The new value.</param>
/// <returns>True when the two values are the same output.</returns>
internal static bool SameValue(object? a, object? b)
{
if (a is Array x && b is Array y)
{
if (ReferenceEquals(x, y)) return true;
if (x.Rank != 1 || y.Rank != 1 || x.GetType() != y.GetType()) return false;
return System.Collections.StructuralComparisons.StructuralEqualityComparer.Equals(x, y);
}
return Equals(a, b);
}
private static Task<VirtualTagEvalResult> FreezeEvaluation(Task<VirtualTagEvalResult> task)
{
if (!task.IsCompletedSuccessfully || !task.Result.Success || ReferenceEquals(task.Result, VirtualTagEvalResult.NoChange))
@@ -542,7 +615,7 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
// Dedup on (value, STATUS) — 02/S14 generalising 02/S13's recover-from-Bad bypass. Keying on
// value alone swallows every recovery whose value is unchanged, which is what a device coming
// back usually produces, and the node then stays Bad forever.
if (_hasPublished && _lastPublishedStatus == worst && _hasLastValue && Equals(_lastValue, result.Value))
if (_hasPublished && _lastPublishedStatus == worst && _hasLastValue && SameValue(_lastValue, result.Value))
{
OtOpcUaTelemetry.VirtualTagEval.Add(1, new KeyValuePair<string, object?>("outcome", "skip"));
return;
@@ -47,6 +47,23 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
/// <param name="Plans">The desired Equipment-namespace VirtualTag plans.</param>
public sealed record ApplyVirtualTags(IReadOnlyList<EquipmentVirtualTagPlan> Plans);
/// <summary>
/// #995 (review R-17): re-attempt the data-plane source binding of the tags the last apply could not bind —
/// and nothing else. The retry used to re-deliver the whole <see cref="ApplyVirtualTags"/> every 250 ms with no
/// backoff, so every attempt lifted the run guard's quarantines (re-running a runaway script), re-asserted every
/// surviving child, republished every disabled tag's <c>BadOutOfService</c> and recomputed the cycle graph.
/// </summary>
/// <param name="Attempt">Zero-based attempt number; the delay before the next attempt doubles with it.</param>
private sealed record RetrySourceBindings(int Attempt);
private const string SourceBindingRetryTimerKey = "source-binding-retry";
/// <summary>First source-binding retry delay (#995). Doubles per failed attempt up to <see cref="SourceBindingRetryCap"/>.</summary>
internal static readonly TimeSpan SourceBindingRetryInitial = TimeSpan.FromMilliseconds(250);
/// <summary>Longest source-binding retry delay (#995).</summary>
internal static readonly TimeSpan SourceBindingRetryCap = TimeSpan.FromSeconds(5);
private readonly IActorRef? _publishActor;
private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? _sourcePublisher;
private readonly HashSet<string> _publishedVirtualIds = new(StringComparer.Ordinal);
@@ -71,6 +88,11 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
private readonly HashSet<string> _deployedKeys = new(StringComparer.Ordinal);
// Keys on a VirtualTag dependency cycle (lmxopcua#791 runtime backstop): their outputs are never routed.
private readonly HashSet<string> _unroutedKeys = new(StringComparer.Ordinal);
// #995 (R-17): enabled tags of the current apply whose source binding failed, so no child was spawned yet.
private readonly HashSet<string> _unboundEnabled = new(StringComparer.Ordinal);
// #995 (R-17): disabled tags of the current apply whose source binding failed, so their BadOutOfService did not
// reach the data plane yet (the OPC UA node and the mux already have it).
private readonly HashSet<string> _unboundDisabled = new(StringComparer.Ordinal);
/// <summary>Factory method to create Props for a VirtualTagHostActor.</summary>
/// <param name="publishActor">The OPC UA publish actor that consumes
@@ -109,13 +131,16 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
_telemetryHub = telemetryHub;
Receive<ApplyVirtualTags>(OnApply);
Receive<RetrySourceBindings>(OnRetrySourceBindings);
Receive<VirtualTagActor.EvaluationResult>(OnResult);
Receive<Terminated>(OnChildTerminated);
}
private void OnApply(ApplyVirtualTags msg)
{
Timers.Cancel("source-binding-retry");
Timers.Cancel(SourceBindingRetryTimerKey);
_unboundEnabled.Clear();
_unboundDisabled.Clear();
// lmxopcua#978 (review R-5): drop a plan whose NodeId cannot be built BEFORE anything is stopped or
// spawned. Unguarded, one illegal name threw here, supervision restarted the host (stopping every
// child), and nothing re-sent ApplyVirtualTags — every VirtualTag on the node stopped evaluating, on
@@ -213,42 +238,8 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
foreach (var p in evaluated)
{
if (_children.ContainsKey(p.VirtualTagId)) continue;
// Auto-name the child: vtagIds can contain characters illegal in actor names, so let Akka
// assign a safe unique name. The child self-registers with the mux in PreStart.
long? sourceIncarnation = null;
if (_sourcePublisher is not null)
{
if (!_virtualSourceIncarnations.TryGetValue(p.VirtualTagId, out var currentToken))
currentToken = _sourcePublisher.RegisterVirtualIncarnation(p.VirtualTagId);
sourceIncarnation = currentToken;
}
if (sourceIncarnation is { } token)
{
_virtualSourceIncarnations[p.VirtualTagId] = token;
if (!_sourcePublisher!.EnsureVirtualBinding(p.VirtualTagId, token))
{
Timers.StartSingleTimer("source-binding-retry", msg, TimeSpan.FromMilliseconds(250));
continue;
}
}
var child = Context.ActorOf(VirtualTagActor.Props(
virtualTagId: p.VirtualTagId,
expression: p.Expression,
evaluator: _evaluator,
scriptId: p.VirtualTagId,
publisherFactory: null,
dependencyRefs: p.DependencyRefs,
mux: _mux,
telemetryHub: _telemetryHub,
changeTriggered: p.ChangeTriggered,
timerIntervalMs: p.TimerIntervalMs,
sourcePublisher: _sourcePublisher,
sourceIncarnation: sourceIncarnation));
Context.Watch(child);
_children[p.VirtualTagId] = child;
newlySpawned.Add(p.VirtualTagId);
_log.Debug("VirtualTagHost: spawned child for vtag {VirtualTagId}", p.VirtualTagId);
if (TrySpawnChild(p)) newlySpawned.Add(p.VirtualTagId);
else _unboundEnabled.Add(p.VirtualTagId);
}
// Refresh the plan map to exactly the desired set so the next apply can detect in-place
@@ -296,7 +287,7 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
}
if (_sourcePublisher is not null &&
!_sourcePublisher.EnsureVirtualBinding(p.VirtualTagId, _virtualSourceIncarnations[p.VirtualTagId]))
Timers.StartSingleTimer("source-binding-retry", msg, TimeSpan.FromMilliseconds(250));
_unboundDisabled.Add(p.VirtualTagId);
var nodeId = NodeIdFor(p);
var now = DateTime.UtcNow;
if (_sourcePublisher?.TryCaptureVirtual(p.VirtualTagId, out var ticket) == true)
@@ -306,10 +297,102 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
_mux?.Tell(new DependencyMuxActor.VirtualTagOutput(nodeId, null, now, OpcUaStatus.BadOutOfService));
}
if (_unboundEnabled.Count + _unboundDisabled.Count > 0)
{
// One degraded line per apply; the retries themselves log only at Debug, and once more on recovery.
_log.Warning("VirtualTagHost: {0} VirtualTag(s) could not bind their data-plane source ({1}); " +
"retrying only those, with backoff up to {2}",
_unboundEnabled.Count + _unboundDisabled.Count,
string.Join(", ", _unboundEnabled.Concat(_unboundDisabled).Take(10)), SourceBindingRetryCap);
Timers.StartSingleTimer(SourceBindingRetryTimerKey, new RetrySourceBindings(0), SourceBindingRetryInitial);
}
_log.Debug("VirtualTagHost: applied (desired={Desired}, children={Children}, disabled={Disabled})",
desired.Count, _children.Count, plans.Count - evaluated.Count);
}
/// <summary>
/// Spawns the child for <paramref name="p"/> once its data-plane source binding (when a source publisher is
/// wired) is established. Returns false — and spawns nothing — when the binding failed; the caller retries.
/// </summary>
/// <param name="p">An enabled plan with no live child.</param>
/// <returns>True when the child was spawned.</returns>
private bool TrySpawnChild(EquipmentVirtualTagPlan p)
{
long? sourceIncarnation = null;
if (_sourcePublisher is not null)
{
if (!_virtualSourceIncarnations.TryGetValue(p.VirtualTagId, out var token))
token = _sourcePublisher.RegisterVirtualIncarnation(p.VirtualTagId);
_virtualSourceIncarnations[p.VirtualTagId] = token;
sourceIncarnation = token;
if (!_sourcePublisher.EnsureVirtualBinding(p.VirtualTagId, token)) return false;
}
// Auto-name the child: vtagIds can contain characters illegal in actor names, so let Akka
// assign a safe unique name. The child self-registers with the mux in PreStart.
var child = Context.ActorOf(VirtualTagActor.Props(
virtualTagId: p.VirtualTagId,
expression: p.Expression,
evaluator: _evaluator,
scriptId: p.VirtualTagId,
publisherFactory: null,
dependencyRefs: p.DependencyRefs,
mux: _mux,
telemetryHub: _telemetryHub,
changeTriggered: p.ChangeTriggered,
timerIntervalMs: p.TimerIntervalMs,
sourcePublisher: _sourcePublisher,
sourceIncarnation: sourceIncarnation));
Context.Watch(child);
_children[p.VirtualTagId] = child;
_log.Debug("VirtualTagHost: spawned child for vtag {VirtualTagId}", p.VirtualTagId);
return true;
}
/// <summary>
/// #995 (R-17): re-attempts only the bindings the last apply could not make. An enabled tag that binds gets its
/// child (fresh, so nothing to re-assert); a disabled tag that binds gets its <c>BadOutOfService</c> on the data
/// plane. Nothing else of the apply is repeated. Still-unbound tags are retried after a doubling delay, capped at
/// <see cref="SourceBindingRetryCap"/>; a new apply cancels the retry and starts over from its own failures.
/// </summary>
/// <param name="msg">The attempt.</param>
private void OnRetrySourceBindings(RetrySourceBindings msg)
{
if (_sourcePublisher is null) { _unboundEnabled.Clear(); _unboundDisabled.Clear(); return; }
foreach (var id in _unboundEnabled.ToList())
{
// Gone from the plan set (a child terminated and was pruned) or already hosted: nothing left to bind.
if (!_planByVtag.TryGetValue(id, out var plan) || _children.ContainsKey(id)) { _unboundEnabled.Remove(id); continue; }
if (TrySpawnChild(plan)) _unboundEnabled.Remove(id);
}
foreach (var id in _unboundDisabled.ToList())
{
if (!_virtualSourceIncarnations.TryGetValue(id, out var token)) { _unboundDisabled.Remove(id); continue; }
if (!_sourcePublisher.EnsureVirtualBinding(id, token)) continue;
_unboundDisabled.Remove(id);
if (_sourcePublisher.TryCaptureVirtual(id, out var ticket))
_sourcePublisher.TryPublish(ticket, new DataValueSnapshot(null, OpcUaStatus.BadOutOfService, null, null));
}
var remaining = _unboundEnabled.Count + _unboundDisabled.Count;
if (remaining == 0)
{
_log.Info("VirtualTagHost: every VirtualTag source binding is established (after {0} retry attempt(s))",
msg.Attempt + 1);
return;
}
var next = msg.Attempt + 1;
var delay = TimeSpan.FromTicks(Math.Min(
SourceBindingRetryCap.Ticks, SourceBindingRetryInitial.Ticks << Math.Min(next, 16)));
_log.Debug("VirtualTagHost: {0} VirtualTag source binding(s) still unbound; retry {1} in {2}",
remaining, next, delay);
Timers.StartSingleTimer(SourceBindingRetryTimerKey, new RetrySourceBindings(next), delay);
}
/// <summary>
/// lmxopcua#791 bookkeeping for the mux leg: release the keys that left the deployed set, and recompute which
/// keys sit on a VirtualTag dependency cycle (an edge runs from a tag to every dependency that is itself a