Files
lmxopcua/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation.Tests/CalculationDriverBatchPumpTests.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

110 lines
5.1 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>
/// 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. 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
{
private const uint StatusGood = 0u;
/// <summary>
/// Answers <c>src/a × n</c> for tag <c>calc/tn</c>. The first batch is held until <see cref="Release"/>, so the
/// test can queue more triggers behind it.
/// </summary>
private sealed class GatedRunner : IScriptRunner
{
private readonly TaskCompletionSource _gate = new(TaskCreationOptions.RunContinuationsAsynchronously);
private int _batches;
public ConcurrentQueue<string[]> Batches { get; } = new();
public int SingleRuns;
public void Release() => _gate.SetResult();
public Task<ScriptRunOutcome> RunAsync(ScriptInvocation invocation, CancellationToken ct = default)
{
Interlocked.Increment(ref SingleRuns);
return Task.FromResult(Answer(invocation));
}
public IReadOnlyList<Task<ScriptRunOutcome>> RunBatch(IReadOnlyList<ScriptInvocation> invocations, CancellationToken ct = default)
{
Batches.Enqueue(invocations.Select(i => i.Key).ToArray());
var held = Interlocked.Increment(ref _batches) == 1;
return invocations.Select(i => held ? Later(i) : Task.FromResult(Answer(i))).ToArray();
}
private async Task<ScriptRunOutcome> Later(ScriptInvocation invocation)
{
await _gate.Task.ConfigureAwait(false);
return Answer(invocation);
}
private static ScriptRunOutcome Answer(ScriptInvocation invocation)
=> ScriptRunOutcome.Ok((double)invocation.Inputs["src/a"].Value! * int.Parse(invocation.Key["calc/t".Length..]));
public void Reset(ScriptContextKind kind) { }
public IReadOnlyCollection<string> QuarantinedKeys(ScriptContextKind kind) => [];
}
private static RawTagEntry CalcTag(string rawPath, int factor)
{
var source = $"return (double)ctx.GetTag(\"src/a\").Value * {factor};";
var json = $"{{\"scriptId\":\"s{factor}\",\"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();
}
[Fact]
public async Task The_pump_submits_what_it_dequeued_as_one_batch_and_publishes_in_dequeue_order()
{
var runner = new GatedRunner();
var driver = new CalculationDriver(
new CalculationDriverOptions { RawTags = [CalcTag("calc/t1", 1), CalcTag("calc/t2", 2), CalcTag("calc/t3", 3)], ScriptRunner = runner },
"calc-drv", new ScriptRootLogger(new LoggerConfiguration().CreateLogger()));
var published = new ConcurrentQueue<(string Tag, object? Value, uint Status)>();
driver.OnDataChange += (_, e) => published.Enqueue((e.FullReference, e.Snapshot.Value, e.Snapshot.StatusCode));
var sizes = new ConcurrentQueue<int>();
driver.BatchSubmittedForTest = sizes.Enqueue;
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
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: 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();
await Settle(driver);
runner.SingleRuns.ShouldBe(0);
runner.Batches.ToArray().ShouldBe(
[["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", 3.0, StatusGood), ("calc/t2", 6.0, StatusGood), ("calc/t3", 9.0, StatusGood),
], "dequeue order; the coalesced batch sees the newest input, with no intermediate 2.0 cycle");
}
}