fix(calculation): #995 change-triggered evaluations coalesce latest-wins per calc tag, so a poll cycle evaluates once against all its new inputs and the queue is bounded by the tag count
At most one evaluation is pending per calc tag; a re-trigger only moves its timestamp forward and the dependency snapshot is taken when the pump dequeues it. Previously every dependency arrival enqueued a separate evaluation per dependent with a trigger-time snapshot: k inputs of one cycle ran k times (publishing intermediates computed from mixed old/new inputs) and the queue had no bound when triggers outpaced the pump. The out-of-process batch pump now dequeues every pending tag once per batch.
This commit is contained in:
+2
-2
@@ -175,8 +175,8 @@ processes:
|
||||
- **Batch submit (design §4.5).** `IScriptRunner.RunBatch` submits several evaluations at once: every item that is ready
|
||||
to run (its key loaded in a live worker, not a suspect) goes out in ONE `EvalBatch` frame per worker, and results are
|
||||
per item and streamed. The Calculation pump dequeues everything pending and submits it as one batch, publishing in
|
||||
dequeue order (a tag queued twice ends the batch, so every queued evaluation still runs against the snapshot that
|
||||
triggered it); the virtual-tag seam coalesces evaluations that become ready together (one actor per tag) into one
|
||||
dequeue order (the queue is latest-wins per calc tag since #995, so a batch never names a tag twice and each entry's
|
||||
snapshot is taken as it is dequeued); the virtual-tag seam coalesces evaluations that become ready together (one actor per tag) into one
|
||||
batch, with no timer; the scripted-alarm engine submits a pass's whole dirty set. In process the pump and the engine
|
||||
stay one-at-a-time, unchanged. **Per-item deadlines and blame stay exact:** an evaluation that arrives while every
|
||||
evaluation thread is busy is reported back as *deferred*, the host stops its clock, and restarts T and G when the worker
|
||||
|
||||
@@ -86,6 +86,15 @@ Two deploy-time gates run over the result:
|
||||
comes back after an outage usually comes back holding the reading it had before, so a value-only
|
||||
dedup would swallow the recovery and leave the node Bad forever.
|
||||
- **Timers are grouped by interval**, one timer per distinct interval, not one per tag.
|
||||
- **Change triggers are latest-wins per tag (#995, review S-9).** A dependency change queues the calc tags that read
|
||||
it, but at most **one** evaluation is ever pending per tag: a tag already queued keeps its place and only takes the
|
||||
newer trigger timestamp, and its dependency snapshot is taken when the single evaluation pump *dequeues* it. So
|
||||
the inputs of one poll cycle that arrive while the pump is busy evaluate **once**, against all the new values —
|
||||
not once per input, where the first k−1 runs mixed new and previous-cycle values and published those
|
||||
intermediates (an `A − B` spike when A had updated and B had not). The queue is bounded by the number of calc
|
||||
tags, so triggers that outpace the pump (slow scripts, an out-of-process runner under load) no longer build an
|
||||
unbounded backlog of stale evaluations. With an out-of-process runner the pump submits everything it dequeued as
|
||||
one batch, which therefore never names a tag twice. Pinned by `CalculationDriverCoalescingTests`.
|
||||
|
||||
## Input quality
|
||||
|
||||
|
||||
@@ -105,11 +105,13 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
|
||||
// run to its RunTimeout, exactly as before, since the pump drops its result once _running is false).
|
||||
private readonly CancellationTokenSource _evalCts = new();
|
||||
|
||||
// Change-triggered evaluations queued by OnDependencyValue and drained, in arrival order, by a single
|
||||
// pump task. Both fields are guarded by _lock; _pumpScheduled stays true until the pump observes an
|
||||
// empty queue under the lock, so an enqueue can never be lost against a pump that is exiting.
|
||||
private readonly LinkedList<PendingEvaluation> _pending = new();
|
||||
private readonly Dictionary<string, LinkedListNode<PendingEvaluation>> _pendingProjected = new(StringComparer.Ordinal);
|
||||
// Change-triggered evaluations queued by OnDependencyValue and drained, in first-trigger order, by a single
|
||||
// pump task. Latest-wins per calc tag (#995, review S-9): at most ONE entry per tag, carrying only the newest
|
||||
// trigger's timestamp — the dependency snapshot is taken when the pump dequeues it — so the queue is bounded
|
||||
// by the tag count. All three fields are guarded by _lock; _pumpScheduled stays true until the pump observes
|
||||
// an empty queue under the lock, so an enqueue can never be lost against a pump that is exiting.
|
||||
private readonly LinkedList<PendingTrigger> _pending = new();
|
||||
private readonly Dictionary<string, LinkedListNode<PendingTrigger>> _pendingByTag = new(StringComparer.Ordinal);
|
||||
private bool _pumpScheduled;
|
||||
private long _projectedQueueVisits;
|
||||
internal long ProjectedQueueVisitsForTest => Interlocked.Read(ref _projectedQueueVisits);
|
||||
@@ -419,12 +421,13 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
|
||||
// QUEUE each change-triggered dependent — never evaluate here. This
|
||||
// runs on the caller's thread, which for the live path is the Akka dispatcher thread of
|
||||
// Runtime's DependencyConsumerMuxAdapter, and a script run is bounded only by RunTimeout.
|
||||
// Everything under this lock is dictionary work; the script runs on the pump.
|
||||
// Everything under this lock is dictionary work; the script runs on the pump. A dependent that
|
||||
// already has a pending evaluation only has its trigger timestamp moved forward (#995).
|
||||
var queued = false;
|
||||
foreach (var calcRawPath in dependents)
|
||||
{
|
||||
if (PrepareEvaluation(calcRawPath, timestampUtc) is not { } prepared) continue;
|
||||
EnqueueEvaluation(prepared);
|
||||
if (!CanEvaluate(calcRawPath)) continue;
|
||||
EnqueueTrigger(calcRawPath, timestampUtc);
|
||||
queued = true;
|
||||
}
|
||||
if (queued) SchedulePump();
|
||||
@@ -487,11 +490,11 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
|
||||
|
||||
// ---- evaluation ----
|
||||
|
||||
/// <summary>One prepared evaluation: the calc tag's definition, the dependency snapshot taken when its
|
||||
/// trigger fired, and that trigger's timestamp. Built under <see cref="_lock"/> by
|
||||
/// <summary>One prepared evaluation: the calc tag's definition, the dependency snapshot taken when it was
|
||||
/// prepared (dequeue time for change-triggered work, #995), and the newest trigger's timestamp. Built under <see cref="_lock"/> by
|
||||
/// <see cref="PrepareEvaluation"/> and executed outside it, so the script itself needs no shared state.</summary>
|
||||
/// <param name="Definition">The calc tag being evaluated.</param>
|
||||
/// <param name="Dependencies">Its declared reads' snapshots — value, status and timestamps — as of the trigger.</param>
|
||||
/// <param name="Dependencies">Its declared reads' snapshots — value, status and timestamps — as of preparation.</param>
|
||||
/// <param name="TimestampUtc">The trigger's timestamp, stamped on whatever is published.</param>
|
||||
/// <param name="WorstInputStatus">The worst status among <paramref name="Dependencies"/>
|
||||
/// (<see cref="InputQuality.WorstOf"/>). Bad ⇒ the script is HELD and this status is published;
|
||||
@@ -525,19 +528,19 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
|
||||
/// Roslyn/compiled-cache invocation. Applying it here rather than on the pump is equivalent:
|
||||
/// <see cref="_arrivedDeps"/> only ever grows, and the arrival that completes the set queues its own
|
||||
/// evaluation.</para>
|
||||
/// <para>Snapshotting the dependency values HERE — at trigger time — is what keeps the queued path
|
||||
/// semantically identical to the old inline one: a burst of arrivals evaluates against the values
|
||||
/// that triggered it rather than collapsing onto whatever happened to be current when the pump
|
||||
/// caught up.</para>
|
||||
/// <para>For change-triggered work this is called when the pump DEQUEUES the tag (#995, review S-9), so a
|
||||
/// burst of arrivals that landed while the pump was busy evaluates once, against the newest value of every
|
||||
/// input. It used to be called at trigger time, which made each arrival its own evaluation against a mix of
|
||||
/// new and previous-cycle inputs — publishing those intermediate values — and let the queue grow without
|
||||
/// bound when triggers outpaced the pump.</para>
|
||||
/// </summary>
|
||||
/// <param name="rawPath">The calc tag to prepare.</param>
|
||||
/// <param name="timestampUtc">The trigger's timestamp.</param>
|
||||
/// <returns>The prepared evaluation, or null when the tag must not evaluate.</returns>
|
||||
private PendingEvaluation? PrepareEvaluation(string rawPath, DateTime timestampUtc)
|
||||
{
|
||||
if (!_tagsByRawPath.TryGetValue(rawPath, out var def)) return null;
|
||||
if (string.IsNullOrWhiteSpace(def.ScriptSource)) return null; // unresolved script — never computes
|
||||
if (!def.DependencyRefs.All(_arrivedDeps.Contains)) return null; // still warming up — do not evaluate
|
||||
if (!CanEvaluate(rawPath)) return null;
|
||||
var def = _tagsByRawPath[rawPath];
|
||||
|
||||
var deps = new Dictionary<string, DataValueSnapshot>(StringComparer.Ordinal);
|
||||
foreach (var dep in def.DependencyRefs)
|
||||
@@ -580,37 +583,63 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="rawPath"/> may evaluate now: a known tag with a resolved script whose every
|
||||
/// declared input has arrived (the warm-up gate — see <see cref="PrepareEvaluation"/>). MUST be called under
|
||||
/// <see cref="_lock"/>.</summary>
|
||||
/// <param name="rawPath">The calc tag.</param>
|
||||
/// <returns>True when the tag can evaluate.</returns>
|
||||
private bool CanEvaluate(string rawPath) =>
|
||||
_tagsByRawPath.TryGetValue(rawPath, out var def)
|
||||
&& !string.IsNullOrWhiteSpace(def.ScriptSource) // unresolved script — never computes
|
||||
&& def.DependencyRefs.All(_arrivedDeps.Contains); // still warming up — do not evaluate
|
||||
|
||||
/// <summary>One queued change-triggered evaluation (#995): the calc tag and its NEWEST trigger's timestamp. The
|
||||
/// dependency snapshot is not part of it — it is taken when the pump dequeues the entry.</summary>
|
||||
private sealed class PendingTrigger(string rawPath, DateTime timestampUtc)
|
||||
{
|
||||
public string RawPath { get; } = rawPath;
|
||||
|
||||
public DateTime TimestampUtc { get; set; } = timestampUtc;
|
||||
}
|
||||
|
||||
private void ClearPending()
|
||||
{
|
||||
while (_pending.Count != 0) DequeuePending().Dispose();
|
||||
_pending.Clear();
|
||||
_pendingByTag.Clear();
|
||||
}
|
||||
|
||||
private PendingEvaluation DequeuePending()
|
||||
/// <summary>
|
||||
/// Queue a change-triggered evaluation of <paramref name="rawPath"/>, latest-wins (#995, review S-9): a tag that
|
||||
/// is already queued keeps its place and takes the newer trigger timestamp, so the queue never holds more than
|
||||
/// one entry per calc tag. Keeping the place (rather than moving to the back) means a tag whose inputs change
|
||||
/// constantly is still served in its turn. MUST be called under <see cref="_lock"/>.
|
||||
/// </summary>
|
||||
/// <param name="rawPath">The calc tag.</param>
|
||||
/// <param name="timestampUtc">The trigger's timestamp, stamped on what the evaluation publishes.</param>
|
||||
private void EnqueueTrigger(string rawPath, DateTime timestampUtc)
|
||||
{
|
||||
var first = _pending.First!;
|
||||
_pending.RemoveFirst();
|
||||
if (first.Value.Proofs.Count > 0) _pendingProjected.Remove(first.Value.Definition.RawPath);
|
||||
return first.Value;
|
||||
}
|
||||
|
||||
private void EnqueueEvaluation(PendingEvaluation pending)
|
||||
{
|
||||
// Projected work is latest-wins per tag. Remove its indexed node and append the
|
||||
// replacement in arrival order, without traversing unrelated projected or local work.
|
||||
if (pending.Proofs.Count > 0)
|
||||
_projectedQueueVisits++;
|
||||
if (_pendingByTag.TryGetValue(rawPath, out var queued))
|
||||
{
|
||||
_projectedQueueVisits++;
|
||||
if (_pendingProjected.Remove(pending.Definition.RawPath, out var prior))
|
||||
{
|
||||
_projectedQueueVisits++;
|
||||
_pending.Remove(prior);
|
||||
prior.Value.Dispose();
|
||||
}
|
||||
var node = _pending.AddLast(pending);
|
||||
_pendingProjected.Add(pending.Definition.RawPath, node);
|
||||
_projectedQueueVisits++;
|
||||
queued.Value.TimestampUtc = timestampUtc;
|
||||
return;
|
||||
}
|
||||
else _pending.AddLast(pending);
|
||||
_pendingByTag.Add(rawPath, _pending.AddLast(new PendingTrigger(rawPath, timestampUtc)));
|
||||
}
|
||||
|
||||
/// <summary>Dequeue the next queued tag and prepare it against the CURRENT inputs; null when the queue holds
|
||||
/// nothing that can evaluate (an entry whose tag can no longer evaluate is dropped). MUST be called under
|
||||
/// <see cref="_lock"/>.</summary>
|
||||
/// <returns>The prepared evaluation, or null when the queue is drained.</returns>
|
||||
private PendingEvaluation? DequeuePrepared()
|
||||
{
|
||||
while (_pending.First is { } first)
|
||||
{
|
||||
_pending.RemoveFirst();
|
||||
_pendingByTag.Remove(first.Value.RawPath);
|
||||
if (PrepareEvaluation(first.Value.RawPath, first.Value.TimestampUtc) is { } prepared) return prepared;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Start the evaluation pump if it is not already running. MUST be called under
|
||||
@@ -644,12 +673,12 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
|
||||
lock (_lock)
|
||||
{
|
||||
if (!_running) ClearPending();
|
||||
if (_pending.Count == 0)
|
||||
if (DequeuePrepared() is not { } prepared)
|
||||
{
|
||||
_pumpScheduled = false;
|
||||
return;
|
||||
}
|
||||
next = DequeuePending();
|
||||
next = prepared;
|
||||
}
|
||||
|
||||
// _evalGate (never _lock) is held across the run, so the pump and the timer ticks still
|
||||
@@ -675,9 +704,9 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
|
||||
|
||||
/// <summary>
|
||||
/// The pump on the out-of-process path (lmxopcua#780, design §4.5): dequeue everything pending — each entry's
|
||||
/// dependency snapshot was captured at enqueue — submit it as ONE batch, and publish in dequeue order. A calc tag
|
||||
/// queued more than once (a burst of changes) ends the batch at its second entry, so every queued evaluation still
|
||||
/// runs, in order, against the snapshot that triggered it, exactly as the one-at-a-time pump would run them.
|
||||
/// dependency snapshot is taken as it is dequeued — submit it as ONE batch, and publish in dequeue order. The
|
||||
/// queue holds at most one entry per calc tag (#995), so a batch never names a tag twice; triggers that arrive
|
||||
/// while it runs coalesce into the next one.
|
||||
/// </summary>
|
||||
private async Task RunEvaluationBatchPumpAsync()
|
||||
{
|
||||
@@ -687,14 +716,13 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
|
||||
lock (_lock)
|
||||
{
|
||||
if (!_running) ClearPending();
|
||||
if (_pending.Count == 0)
|
||||
batch = [];
|
||||
while (DequeuePrepared() is { } prepared) batch.Add(prepared);
|
||||
if (batch.Count == 0)
|
||||
{
|
||||
_pumpScheduled = false;
|
||||
return;
|
||||
}
|
||||
batch = [];
|
||||
var inBatch = new HashSet<string>(StringComparer.Ordinal);
|
||||
while (_pending.Count > 0 && inBatch.Add(_pending.First!.Value.Definition.RawPath)) batch.Add(DequeuePending());
|
||||
}
|
||||
|
||||
if (!await TryEnterEvalGateAsync().ConfigureAwait(false)) { foreach (var item in batch) item.Dispose(); return; } // disposed
|
||||
@@ -913,8 +941,8 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
|
||||
{
|
||||
if (_stateByRawPath.TryGetValue(rawPath, out var st)) st.RecoveryArmed = false;
|
||||
if (!_running || _disposed) return;
|
||||
if (PrepareEvaluation(rawPath, DateTime.UtcNow) is not { } prepared) return;
|
||||
EnqueueEvaluation(prepared);
|
||||
if (!CanEvaluate(rawPath)) return;
|
||||
EnqueueTrigger(rawPath, DateTime.UtcNow);
|
||||
SchedulePump();
|
||||
}
|
||||
}
|
||||
|
||||
+8
-9
@@ -9,9 +9,9 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Calculation.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#780 batch submit (design §4.5) in the Calculation pump: with an out-of-process runner the pump hands
|
||||
/// everything it dequeued to ONE <see cref="IScriptRunner.RunBatch"/> and publishes in dequeue order. A tag queued
|
||||
/// twice ends the batch, so every queued evaluation still runs, in order, against the snapshot that triggered it —
|
||||
/// the published sequence is exactly the one-at-a-time pump's.
|
||||
/// everything it dequeued to ONE <see cref="IScriptRunner.RunBatch"/> and publishes in dequeue order. The queue holds
|
||||
/// at most one entry per calc tag (#995, review S-9), so triggers that arrive while a batch runs coalesce into ONE
|
||||
/// next batch evaluated against the newest inputs.
|
||||
/// </summary>
|
||||
public sealed class CalculationDriverBatchPumpTests
|
||||
{
|
||||
@@ -89,7 +89,7 @@ public sealed class CalculationDriverBatchPumpTests
|
||||
driver.OnDependencyValue("src/a", 1.0, StatusGood, DateTime.UtcNow);
|
||||
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10);
|
||||
while (DateTime.UtcNow < deadline && runner.Batches.IsEmpty) await Task.Delay(5, TestContext.Current.CancellationToken);
|
||||
// Two more triggers queue behind the held batch: six evaluations, each tag twice.
|
||||
// Two more triggers queue behind the held batch: they coalesce into one evaluation per tag (#995).
|
||||
driver.OnDependencyValue("src/a", 2.0, StatusGood, DateTime.UtcNow);
|
||||
driver.OnDependencyValue("src/a", 3.0, StatusGood, DateTime.UtcNow);
|
||||
runner.Release();
|
||||
@@ -97,14 +97,13 @@ public sealed class CalculationDriverBatchPumpTests
|
||||
|
||||
runner.SingleRuns.ShouldBe(0);
|
||||
runner.Batches.ToArray().ShouldBe(
|
||||
[["calc/t1", "calc/t2", "calc/t3"], ["calc/t1", "calc/t2", "calc/t3"], ["calc/t1", "calc/t2", "calc/t3"]],
|
||||
"a tag queued twice ends the batch; every queued evaluation still runs");
|
||||
sizes.ToArray().ShouldBe([3, 3, 3]);
|
||||
[["calc/t1", "calc/t2", "calc/t3"], ["calc/t1", "calc/t2", "calc/t3"]],
|
||||
"the two later triggers are one pending evaluation per tag, so one more batch");
|
||||
sizes.ToArray().ShouldBe([3, 3]);
|
||||
published.ToArray().ShouldBe(
|
||||
[
|
||||
("calc/t1", 1.0, StatusGood), ("calc/t2", 2.0, StatusGood), ("calc/t3", 3.0, StatusGood),
|
||||
("calc/t1", 2.0, StatusGood), ("calc/t2", 4.0, StatusGood), ("calc/t3", 6.0, StatusGood),
|
||||
("calc/t1", 3.0, StatusGood), ("calc/t2", 6.0, StatusGood), ("calc/t3", 9.0, StatusGood),
|
||||
], "dequeue order, each against the snapshot that triggered it");
|
||||
], "dequeue order; the coalesced batch sees the newest input, with no intermediate 2.0 cycle");
|
||||
}
|
||||
}
|
||||
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Serilog;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Calculation.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// #995 (review 2026-12-02 S-9) — change-triggered work is latest-wins per calc tag. Every dependency arrival used to
|
||||
/// enqueue a separate evaluation for each dependent, each with its own dependency snapshot taken at trigger time: a
|
||||
/// tag with k inputs fed by one poll cycle ran k times, the first k−1 against a mix of new and previous-cycle inputs
|
||||
/// (and published those intermediate values), and the queue had no bound, so a pump slower than the trigger rate
|
||||
/// fell further behind without limit. Now at most one evaluation is pending per tag and its snapshot is taken when
|
||||
/// the pump dequeues it.
|
||||
/// </summary>
|
||||
public sealed class CalculationDriverCoalescingTests
|
||||
{
|
||||
private const uint StatusGood = 0u;
|
||||
|
||||
private static RawTagEntry CalcTag(string rawPath, string source)
|
||||
{
|
||||
var json = $"{{\"scriptId\":\"s\",\"changeTriggered\":true,\"scriptSource\":{System.Text.Json.JsonSerializer.Serialize(source)}}}";
|
||||
return new RawTagEntry(rawPath, json, WriteIdempotent: false);
|
||||
}
|
||||
|
||||
private static async Task Settle(CalculationDriver driver)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(30);
|
||||
while (DateTime.UtcNow < deadline && !driver.IsEvaluationIdle) await Task.Delay(10);
|
||||
driver.IsEvaluationIdle.ShouldBeTrue();
|
||||
}
|
||||
|
||||
private static int PendingCount(CalculationDriver driver)
|
||||
{
|
||||
var field = typeof(CalculationDriver).GetField("_pending", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
|
||||
var pending = (System.Collections.ICollection)field!.GetValue(driver)!;
|
||||
return pending.Count;
|
||||
}
|
||||
|
||||
/// <summary>Blocks the pump inside the publish of the first Good value it sees after <see cref="Arm"/>.</summary>
|
||||
private sealed class PumpBlocker : IDisposable
|
||||
{
|
||||
private readonly ManualResetEventSlim _release = new();
|
||||
private readonly TaskCompletionSource _entered = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private int _armed;
|
||||
|
||||
public Task Entered => _entered.Task;
|
||||
|
||||
public void Arm() => Interlocked.Exchange(ref _armed, 1);
|
||||
|
||||
public void OnPublish()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _armed, 0) != 1) return;
|
||||
_entered.TrySetResult();
|
||||
_release.Wait(TimeSpan.FromSeconds(20));
|
||||
}
|
||||
|
||||
public void Release() => _release.Set();
|
||||
|
||||
public void Dispose() { _release.Set(); _release.Dispose(); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Five_inputs_arriving_while_the_pump_is_blocked_evaluate_once_with_all_five_values()
|
||||
{
|
||||
const string source = "return (double)ctx.GetTag(\"src/a\").Value + (double)ctx.GetTag(\"src/b\").Value + " +
|
||||
"(double)ctx.GetTag(\"src/c\").Value + (double)ctx.GetTag(\"src/d\").Value + (double)ctx.GetTag(\"src/e\").Value;";
|
||||
using var driver = new CalculationDriver(
|
||||
new CalculationDriverOptions { RawTags = [CalcTag("calc/sum", source)] },
|
||||
"calc-drv", new ScriptRootLogger(new LoggerConfiguration().CreateLogger()));
|
||||
using var blocker = new PumpBlocker();
|
||||
var published = new ConcurrentQueue<object?>();
|
||||
driver.OnDataChange += (_, e) =>
|
||||
{
|
||||
if (e.Snapshot.StatusCode != StatusGood || e.Snapshot.Value is null) return;
|
||||
published.Enqueue(e.Snapshot.Value);
|
||||
blocker.OnPublish();
|
||||
};
|
||||
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
foreach (var dep in new[] { "src/a", "src/b", "src/c", "src/d", "src/e" })
|
||||
driver.OnDependencyValue(dep, 0.0, StatusGood, DateTime.UtcNow);
|
||||
await Settle(driver);
|
||||
published.ToArray().ShouldBe(new object?[] { 0.0 });
|
||||
|
||||
// The next evaluation's publish parks the pump; the other four inputs of the same poll cycle land behind it.
|
||||
blocker.Arm();
|
||||
driver.OnDependencyValue("src/a", 1.0, StatusGood, DateTime.UtcNow);
|
||||
await blocker.Entered.WaitAsync(TimeSpan.FromSeconds(20), TestContext.Current.CancellationToken);
|
||||
driver.OnDependencyValue("src/b", 10.0, StatusGood, DateTime.UtcNow);
|
||||
driver.OnDependencyValue("src/c", 100.0, StatusGood, DateTime.UtcNow);
|
||||
driver.OnDependencyValue("src/d", 1000.0, StatusGood, DateTime.UtcNow);
|
||||
driver.OnDependencyValue("src/e", 10000.0, StatusGood, DateTime.UtcNow);
|
||||
PendingCount(driver).ShouldBe(1, "four triggers of one tag are one pending evaluation");
|
||||
|
||||
blocker.Release();
|
||||
await Settle(driver);
|
||||
|
||||
// One evaluation after the release, against all five new inputs — no intermediate 11 / 111 / 1111.
|
||||
published.ToArray().ShouldBe(new object?[] { 0.0, 1.0, 11111.0 });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Sustained_triggers_faster_than_the_pump_keep_the_queue_bounded_by_the_tag_count()
|
||||
{
|
||||
const int tagCount = 3;
|
||||
using var driver = new CalculationDriver(
|
||||
new CalculationDriverOptions
|
||||
{
|
||||
RawTags = Enumerable.Range(0, tagCount)
|
||||
.Select(i => CalcTag($"calc/t{i}", $"return (double)ctx.GetTag(\"src/a\").Value + {i};")).ToArray(),
|
||||
},
|
||||
"calc-drv", new ScriptRootLogger(new LoggerConfiguration().CreateLogger()));
|
||||
using var blocker = new PumpBlocker();
|
||||
var published = new ConcurrentQueue<(string Tag, object? Value)>();
|
||||
driver.OnDataChange += (_, e) =>
|
||||
{
|
||||
if (e.Snapshot.StatusCode != StatusGood || e.Snapshot.Value is null) return;
|
||||
published.Enqueue((e.FullReference, e.Snapshot.Value));
|
||||
blocker.OnPublish();
|
||||
};
|
||||
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
blocker.Arm();
|
||||
driver.OnDependencyValue("src/a", 0.0, StatusGood, DateTime.UtcNow);
|
||||
await blocker.Entered.WaitAsync(TimeSpan.FromSeconds(20), TestContext.Current.CancellationToken);
|
||||
|
||||
var maxPending = 0;
|
||||
for (var v = 1; v <= 1000; v++)
|
||||
{
|
||||
driver.OnDependencyValue("src/a", (double)v, StatusGood, DateTime.UtcNow);
|
||||
maxPending = Math.Max(maxPending, PendingCount(driver));
|
||||
}
|
||||
maxPending.ShouldBeLessThanOrEqualTo(tagCount, "the backlog is bounded by the number of calc tags, not the trigger count");
|
||||
|
||||
blocker.Release();
|
||||
await Settle(driver);
|
||||
|
||||
// Positive control: every tag ends on the newest input.
|
||||
for (var i = 0; i < tagCount; i++)
|
||||
published.Where(p => p.Tag == $"calc/t{i}").Last().Value.ShouldBe(1000.0 + i);
|
||||
published.Count.ShouldBeLessThanOrEqualTo(2 * tagCount, "one evaluation per tag before the block, one after it");
|
||||
}
|
||||
}
|
||||
@@ -199,10 +199,13 @@ public sealed class CalculationDriverTests
|
||||
CalcTag("calc/e/dbl", "return (double)ctx.GetTag(\"src/a\").Value * 2.0;"));
|
||||
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
// Each arrival is queued with the dependency snapshot that triggered it, so the three evaluations
|
||||
// see 5 / 5 / 7 in that order however far the pump lags behind them.
|
||||
// Settled between arrivals: triggers that land while an evaluation is pending coalesce into one (#995),
|
||||
// so each arrival here must be evaluated on its own for the dedup to be exercised.
|
||||
driver.OnDependencyValue("src/a", 5.0, StatusGood, DateTime.UtcNow); // → 10 (publish)
|
||||
await Settle(driver);
|
||||
driver.OnDependencyValue("src/a", 5.0, StatusGood, DateTime.UtcNow); // → 10 (dedup, no publish)
|
||||
await Settle(driver);
|
||||
published.Count.ShouldBe(1);
|
||||
driver.OnDependencyValue("src/a", 7.0, StatusGood, DateTime.UtcNow); // → 14 (publish)
|
||||
await Settle(driver);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user