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
+2 -1
View File
@@ -305,7 +305,8 @@ Virtual-tag nodes are materialised by `AddressSpaceApplier` and fed by `VirtualT
`ITagUpstreamSource` and `IHistoryWriter` are the two ports value consumers require from their host. Both live in `Core.VirtualTags`. In the v2 actor system:
- **Upstream-tag feed.** `DependencyMuxActor` (`src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyMuxActor.cs`) routes the items of each `DriverInstanceActor.AttributeValueBatchPublished` — and every VirtualTag output (`VirtualTagOutput`, lmxopcua#791, see below) — to the `VirtualTagActor` instances that declared interest in those tag refs. Each `VirtualTagActor` holds the in-memory per-tag dependency map; the `IVirtualTagEvaluator` (`RoslynVirtualTagEvaluator`) receives the dependency snapshot through `EvaluateAsync`. Reads of never-pushed dependency refs return `null` values in the dependency snapshot.
- **Evaluation is off the dispatcher thread (lmxopcua#779, #750 P0).** The actor used to call the blocking `Evaluate`, which parked an Akka dispatcher thread for the whole run — up to the 2 s budget per evaluation. It now calls `EvaluateAsync`: a passthrough, a compile failure or any synchronous evaluator completes in the same message turn as before, while a real script run (and a first-use compile, which is pushed to the pool) returns an incomplete task. Until it completes the actor **stashes** every further dependency / reassert message, then applies the result and unstashes in arrival order. So each trigger is still evaluated against the inputs as of that trigger, results are published in trigger order, and the dedup / Bad-transition state sees the same sequence — only the thread is freed. Pinned by `VirtualTagActorAsyncEvaluationTests` (a slow script on a one-thread dispatcher no longer starves a sibling actor; ordering, reassert and fault paths) and `RoslynVirtualTagEvaluatorAsyncTests`.
- **Evaluation is off the dispatcher thread (lmxopcua#779, #750 P0).** The actor used to call the blocking `Evaluate`, which parked an Akka dispatcher thread for the whole run — up to the 2 s budget per evaluation. It now calls `EvaluateAsync`: a passthrough, a compile failure or any synchronous evaluator completes in the same message turn as before, while a real script run (and a first-use compile, which is pushed to the pool) returns an incomplete task. Until it completes, inputs that arrive are **held, newest value per input** (#995, review R-19), and every other message (reassert, runner recovery, source-binding retry) is stashed. On completion the result is applied, the held inputs are applied together and evaluated **once** (stamped with the newest arrival, the rule a batched mux burst already follows), and the stash is replayed. The backlog is therefore bounded by the tag's input count: before #995 each held trigger was replayed as its own script run against superseded inputs, so a slow script or a loaded out-of-process runner built an unbounded queue of runs with O(M²) re-stash hops and published intermediate values. The value dedup compares one-dimensional arrays element-wise (same element type), so an array tag whose output did not change is no longer republished, re-routed to dependents and historized on every evaluation. Pinned by `VirtualTagActorAsyncEvaluationTests` (a slow script on a one-thread dispatcher no longer starves a sibling actor; ordering, reassert and fault paths) and `RoslynVirtualTagEvaluatorAsyncTests`.
- **Unbound data-plane sources retry alone (#995, review R-17).** When DataConnections is wired, `VirtualTagHostActor` spawns a tag's child only after `SourceSamplePublisher.EnsureVirtualBinding` succeeds. A failed binding is retried for **that tag only** (and, for a disabled tag, only its data-plane `BadOutOfService`), from 250 ms doubling to a 5 s cap, with one Warning per apply and one Info on recovery. The retry used to re-send the whole `ApplyVirtualTags` every 250 ms with no backoff, so a persistent cause (e.g. the hub's source cap) lifted every quarantine, re-asserted every child, republished every disabled tag and recomputed the cycle graph four times a second. A new apply cancels the retry and starts over from its own failures. Pinned by `VirtualTagHostSourceBindingRetryTests`.
- **VirtualTag → VirtualTag dependencies (lmxopcua#791).** A VirtualTag's key is its UNS NodeId identifier, `{EquipmentId}/{Name}` (VirtualTags have no FolderPath, and no raw-subtree node), and a script reads another VirtualTag with that literal: `ctx.GetTag("EQ-0123456789ab/LineRate")`. It cannot collide with a RawPath in the mux's key space: a key is two segments, a tag's RawPath at least three (Driver/Device/Tag). Until #791 this never worked — VirtualTag outputs were published to their OPC UA node only, the mux carried driver values only, so a dependent sat at `BadWaitingForInitialData` forever (proven by `VirtualTagToVirtualTagFlowTests` failing on the pre-fix code), and the AdminUI completion offered the bare leaf `Name`, which resolved to nothing. Now:
- **Routing.** `VirtualTagHostActor.OnResult` publishes each result to the node exactly as before (one publish path, one NodeId — VirtualTags exist only in the UNS realm, so there is no raw NodeId to keep consistent) and *additionally* sends it to the mux as `DependencyMuxActor.VirtualTagOutput` under the same string. A disabled tag's `BadOutOfService` is routed too. A re-assert is not routed (it repeats a state the mux already holds). So `ctx.GetTag(<key>)` returns the upstream's current value, status and timestamp, and the dependent inherits a Bad upstream status like any input (02/S14). Calculation tags and scripted alarms read the mux too, so they can read a VirtualTag by its key the same way.
- **Retention.** A VirtualTag output is **pinned** in the mux: retained whether or not anyone has registered for it yet (an upstream and its dependent spawn in one apply and register asynchronously, so the upstream may evaluate first), never put into the replay grace, and immune to a driver's `SourceRemoved`. A dependent that registers later — or respawns on a plan edit — is replayed the current value at once. Memory is bounded by the deployed VirtualTag count; the host sends `VirtualTagOutputsRemoved` for keys that leave the deployed set (a removed or renamed tag), which drops them.
@@ -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
@@ -71,8 +71,13 @@ one-thread-dispatcher {
}
}
/// <summary>
/// #995 (review R-19): triggers that arrive while a run is in flight are folded — newest value per input — and
/// evaluated ONCE after it, against the newest inputs, stamped with the newest arrival. (They used to be replayed
/// one run per trigger, each against the input as of its own trigger.)
/// </summary>
[Fact]
public void Triggers_during_a_run_are_evaluated_after_it_in_order_each_against_its_own_inputs()
public void Triggers_during_a_run_are_coalesced_into_one_evaluation_against_the_newest_inputs()
{
var parent = CreateTestProbe();
var evaluator = new ManualEvaluator();
@@ -93,16 +98,100 @@ one-thread-dispatcher {
evaluator.Complete(0, VirtualTagEvalResult.Ok(10));
var r1 = parent.ExpectMsg<VirtualTagActor.EvaluationResult>(cancellationToken: TestContext.Current.CancellationToken);
AwaitCondition(() => evaluator.Calls.Count == 2, PresenceBudget, TestContext.Current.CancellationToken);
evaluator.Complete(1, VirtualTagEvalResult.Ok(20));
evaluator.Complete(1, VirtualTagEvalResult.Ok(30));
var r2 = parent.ExpectMsg<VirtualTagActor.EvaluationResult>(cancellationToken: TestContext.Current.CancellationToken);
AwaitCondition(() => evaluator.Calls.Count == 3, PresenceBudget, TestContext.Current.CancellationToken);
evaluator.Complete(2, VirtualTagEvalResult.Ok(30));
var r3 = parent.ExpectMsg<VirtualTagActor.EvaluationResult>(cancellationToken: TestContext.Current.CancellationToken);
// Each evaluation saw the input as of ITS trigger — not the newest value — exactly as the blocking path did.
evaluator.Calls.ShouldBe(new object?[] { 1, 2, 3 });
new[] { r1.Value, r2.Value, r3.Value }.ShouldBe(new object?[] { 10, 20, 30 });
new[] { r1.TimestampUtc, r2.TimestampUtc, r3.TimestampUtc }.ShouldBe(new[] { t1, t2, t3 });
// Absence, with the positive control above (r2 arrived): no third run for the superseded trigger.
parent.ExpectNoMsg(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken);
evaluator.Calls.ShouldBe(new object?[] { 1, 3 }, "the held triggers ran once, against the newest input");
new[] { r1.Value, r2.Value }.ShouldBe(new object?[] { 10, 30 });
new[] { r1.TimestampUtc, r2.TimestampUtc }.ShouldBe(new[] { t1, t3 });
}
/// <summary>#995 (R-19): a backlog of 100 batches behind a slow run costs one more evaluation, not 100.</summary>
[Fact]
public async Task A_backlog_of_batches_behind_a_slow_run_is_evaluated_once_with_the_latest_inputs()
{
var parent = CreateTestProbe();
var evaluator = new ManualEvaluator();
var actor = parent.ChildActorOf(VirtualTagActor.Props("vt-1", "expr", evaluator: evaluator,
dependencyRefs: ["a", "b"]), TestContext.Current.CancellationToken);
var t0 = new DateTime(2026, 12, 3, 0, 0, 0, DateTimeKind.Utc);
actor.Tell(new VirtualTagActor.DependencyValueBatch(new[]
{
new VirtualTagActor.DependencyValueChanged("a", 0, t0), new VirtualTagActor.DependencyValueChanged("b", 0, t0),
}));
AwaitCondition(() => evaluator.Calls.Count == 1, PresenceBudget, TestContext.Current.CancellationToken);
for (var i = 1; i <= 100; i++)
{
var ts = t0.AddMilliseconds(i);
actor.Tell(new VirtualTagActor.DependencyValueBatch(new[]
{
new VirtualTagActor.DependencyValueChanged("a", i, ts), new VirtualTagActor.DependencyValueChanged("b", i * 10, ts),
}));
}
// Identify is handled in mailbox order: once it answers, all 100 batches have been received.
await actor.Ask<ActorIdentity>(new Identify(1), PresenceBudget, TestContext.Current.CancellationToken);
evaluator.Complete(0, VirtualTagEvalResult.Ok(0));
parent.ExpectMsg<VirtualTagActor.EvaluationResult>(cancellationToken: TestContext.Current.CancellationToken).Value.ShouldBe(0);
AwaitCondition(() => evaluator.Calls.Count == 2, PresenceBudget, TestContext.Current.CancellationToken);
evaluator.Complete(1, VirtualTagEvalResult.Ok(100));
var last = parent.ExpectMsg<VirtualTagActor.EvaluationResult>(cancellationToken: TestContext.Current.CancellationToken);
parent.ExpectNoMsg(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken);
evaluator.Calls.Count.ShouldBe(2, "100 batches held behind one run evaluate once, not 100 times");
evaluator.Calls[1].ShouldBe(100, "the coalesced evaluation saw the newest value of input a");
evaluator.InputsOfCall(1)["b"].ShouldBe(1000, "and of input b");
last.TimestampUtc.ShouldBe(t0.AddMilliseconds(100));
}
/// <summary>#995 (R-19): an array-typed result that did not change is published once; a changed one publishes.</summary>
[Fact]
public void An_unchanged_array_result_is_published_once_and_a_changed_one_publishes()
{
var parent = CreateTestProbe();
var evaluator = new ArrayEvaluator { Next = () => new[] { 1, 2, 3 } };
var actor = parent.ChildActorOf(VirtualTagActor.Props("vt-array", "expr", evaluator: evaluator), TestContext.Current.CancellationToken);
for (var i = 0; i < 5; i++) actor.Tell(new VirtualTagActor.DependencyValueChanged("a", i, DateTime.UtcNow));
parent.ExpectMsg<VirtualTagActor.EvaluationResult>(cancellationToken: TestContext.Current.CancellationToken)
.Value.ShouldBe(new[] { 1, 2, 3 });
parent.ExpectNoMsg(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken);
evaluator.Calls.ShouldBe(5, "every trigger evaluated; only the publish was deduplicated");
// Positive control: a changed element publishes.
evaluator.Next = () => new[] { 1, 2, 4 };
actor.Tell(new VirtualTagActor.DependencyValueChanged("a", 9, DateTime.UtcNow));
parent.ExpectMsg<VirtualTagActor.EvaluationResult>(cancellationToken: TestContext.Current.CancellationToken)
.Value.ShouldBe(new[] { 1, 2, 4 });
}
[Fact]
public void SameValue_compares_one_dimensional_arrays_by_element_and_type()
{
VirtualTagActor.SameValue(new[] { 1, 2 }, new[] { 1, 2 }).ShouldBeTrue();
VirtualTagActor.SameValue(new[] { 1, 2 }, new[] { 1, 3 }).ShouldBeFalse();
VirtualTagActor.SameValue(new[] { 1, 2 }, new long[] { 1, 2 }).ShouldBeFalse();
VirtualTagActor.SameValue(new[] { "x" }, new[] { "x" }).ShouldBeTrue();
VirtualTagActor.SameValue(new int[0], null).ShouldBeFalse();
VirtualTagActor.SameValue(5, 5).ShouldBeTrue();
VirtualTagActor.SameValue(new int[1, 1], new int[1, 1]).ShouldBeFalse("multi-dimensional arrays keep reference equality");
}
private sealed class ArrayEvaluator : IVirtualTagEvaluator
{
private int _calls;
public int Calls => Volatile.Read(ref _calls);
public volatile Func<int[]> Next = () => [];
public VirtualTagEvalResult Evaluate(string virtualTagId, string expression, IReadOnlyDictionary<string, object?> dependencies)
{
Interlocked.Increment(ref _calls);
return VirtualTagEvalResult.Ok(Next());
}
}
[Fact]
@@ -264,9 +353,13 @@ one-thread-dispatcher {
{
private readonly ConcurrentDictionary<int, TaskCompletionSource<VirtualTagEvalResult>> _pending = new();
private readonly ConcurrentQueue<object?> _calls = new();
private readonly ConcurrentDictionary<int, IReadOnlyDictionary<string, object?>> _inputs = new();
public IReadOnlyList<object?> Calls => _calls.ToArray();
/// <summary>Every input value the given call was handed, read at the start of its run.</summary>
public IReadOnlyDictionary<string, object?> InputsOfCall(int call) => _inputs[call];
public void Complete(int call, VirtualTagEvalResult result) => _pending[call].SetResult(result);
public void Fault(int call, Exception ex) => _pending[call].SetException(ex);
@@ -281,6 +374,7 @@ one-thread-dispatcher {
var a = dependencies.TryGetValue("a", out var snap) ? snap.Value : null;
var tcs = new TaskCompletionSource<VirtualTagEvalResult>(TaskCreationOptions.RunContinuationsAsynchronously);
_pending[_calls.Count] = tcs;
_inputs[_calls.Count] = dependencies.ToDictionary(kv => kv.Key, kv => kv.Value.Value, StringComparer.Ordinal);
_calls.Enqueue(a);
return tcs.Task;
}
@@ -0,0 +1,126 @@
using System.Collections.Concurrent;
using Akka.Actor;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Engines;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.VirtualTags;
/// <summary>
/// #995 (review 2026-12-02 R-17) — a VirtualTag whose data-plane source binding cannot be established used to make
/// the host re-deliver the WHOLE <see cref="VirtualTagHostActor.ApplyVirtualTags"/> to itself every 250 ms, with no
/// backoff or cap: every replay 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. The retry
/// now re-attempts only the still-unbound tags, with backoff, and leaves the rest of the apply alone.
/// </summary>
[Trait("Category", "Unit")]
public sealed class VirtualTagHostSourceBindingRetryTests : RuntimeActorTestBase
{
private static readonly ServingIdentity Serving = new("node-a", "instance-a", "Primary", 1, 1);
[Fact]
public void A_failing_source_binding_retries_only_the_unbound_tag_and_does_not_replay_the_apply()
{
var hub = new RejectingHub { Reject = id => id == "vt-broken" };
var publisher = new SourceSamplePublisher(hub, () => Serving, "cluster-a");
var evaluator = new CountingEvaluator();
var sink = CreateTestProbe();
var host = Sys.ActorOf(VirtualTagHostActor.Props(sink.Ref, null, evaluator, sourcePublisher: publisher));
var healthy = new EquipmentVirtualTagPlan("vt-ok", "eq-1", "", "ok", "Double", "1", Array.Empty<string>());
var broken = new EquipmentVirtualTagPlan("vt-broken", "eq-1", "", "broken", "Double", "2", Array.Empty<string>(),
TimerIntervalMs: 50);
var disabled = new EquipmentVirtualTagPlan("vt-off", "eq-1", "", "off", "Double", "3", Array.Empty<string>()) with { Enabled = false };
host.Tell(new VirtualTagHostActor.ApplyVirtualTags(new[] { healthy, broken, disabled }));
// Four 250 ms periods. The old retry replayed OnApply each time: four more quarantine resets and four more
// BadOutOfService publishes for the disabled tag.
var disabledNode = V3NodeIds.Uns("eq-1", "off");
var outOfServicePublishes = 0;
var deadline = DateTime.UtcNow + TimeSpan.FromMilliseconds(1100);
while (DateTime.UtcNow < deadline)
{
var msg = sink.ReceiveOne(TimeSpan.FromMilliseconds(50), TestContext.Current.CancellationToken);
if (msg is OpcUaPublishActor.AttributeValueUpdate u && u.NodeId == disabledNode) outOfServicePublishes++;
}
evaluator.ResetCount.ShouldBe(1, "only the apply itself lifts the quarantines — a binding retry is not a redeploy");
outOfServicePublishes.ShouldBe(1, "the disabled tag's BadOutOfService is published by the apply, not by every retry");
evaluator.CallsFor("vt-broken").ShouldBe(0, "no child is spawned for a tag whose source is unbound");
// Positive control: once the binding can be made, the retry spawns the tag's child, which evaluates on its timer.
hub.Reject = _ => false;
AwaitCondition(() => evaluator.CallsFor("vt-broken") > 0, PresenceBudget, TestContext.Current.CancellationToken);
publisher.TryCaptureVirtual("vt-broken", out _).ShouldBeTrue();
evaluator.ResetCount.ShouldBe(1, "the successful retry did not replay the apply either");
}
private sealed class CountingEvaluator : IVirtualTagEvaluator, IScriptQuarantineOwner
{
private readonly ConcurrentDictionary<string, int> _calls = new(StringComparer.Ordinal);
private int _resets;
public int ResetCount => Volatile.Read(ref _resets);
public int CallsFor(string id) => _calls.GetValueOrDefault(id);
public void ResetQuarantines() => Interlocked.Increment(ref _resets);
public IReadOnlyCollection<string> QuarantinedScripts => Array.Empty<string>();
public VirtualTagEvalResult Evaluate(string virtualTagId, string expression, IReadOnlyDictionary<string, object?> dependencies)
{
_calls.AddOrUpdate(virtualTagId, 1, (_, n) => n + 1);
return VirtualTagEvalResult.Ok(1d);
}
}
/// <summary>A minimal hub that refuses to bind the virtual sources <see cref="Reject"/> names.</summary>
private sealed class RejectingHub : ISourceSampleHub
{
private readonly ConcurrentDictionary<BackingSourceKey, SourceTicket> _current = new();
public volatile Func<string, bool> Reject = _ => false;
public bool TryBind(SourceTicket ticket)
{
if (Reject(ticket.Key.StableSourceId)) return false;
_current[ticket.Key] = ticket;
return true;
}
public bool TryBind(SourceTicket ticket, ProducerFence? fence) => TryBind(ticket);
public bool TryGetCurrentTicket(BackingSourceKey key, out SourceTicket ticket) => _current.TryGetValue(key, out ticket);
public bool IsTicketCurrentNonBlocking(SourceTicket ticket) => _current.TryGetValue(ticket.Key, out var c) && c == ticket;
public void InvalidatePartitionFor(BackingSourceKey key, string reason) { }
public bool TryReserveIngress(SourceTicket ticket, long estimatedRetainedBytes, out IIngressReservation? reservation)
{
reservation = new Reservation();
return true;
}
public void Invalidate(SourceTicket ticket, string reason) { }
public bool TryPublishStatus(SourceTicket ticket, long sequence, uint statusCode, DateTimeOffset? s, DateTimeOffset? v) => true;
public bool TryRemove(SourceTicket ticket, long sequence) => _current.TryRemove(ticket.Key, out _);
private sealed class Reservation : IIngressReservation
{
public bool TryCommit(DataSample sample, long sequence)
{
sample.Dispose();
return true;
}
public void Dispose() { }
}
}
}