Files
lmxopcua/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation.Tests/CalculationDriverCoalescingTests.cs
T
Joseph Doherty 2827a4c3bf 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.
2026-12-03 11:05:32 -05:00

146 lines
6.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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");
}
}