using Opc.Ua;
using Opc.Ua.Server;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using HistorianRead = ZB.MOM.WW.OtOpcUa.Core.Abstractions.HistoryReadResult;
using SdkHistoryReadResult = Opc.Ua.HistoryReadResult;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
///
/// H1: paged-vs-unpaged fuzz THROUGH THE HISTORY PORT (plan §9 H1). Random tie-heavy series (sub-resolution stamps,
/// bursts, gaps, tie clusters), random windows (on a tie, a step past one, between samples; forward, reverse and
/// end-only; with and without bounds), random NumValuesPerNode and an optional backend row ceiling, over three
/// backend shapes (SqlServer: ticks, native reverse; QuestDB: µs truncation, native reverse; Gateway: forward-only,
/// walked back). The concatenated pages must equal the one-shot read, which for a plain read must also equal the
/// series itself; paging must terminate; and on every tenth seed the SDK override path must return the SAME pages,
/// page for page, as the port — the override is an adapter over the port, so any divergence is an adapter defect.
///
/// Seeds are deterministic (0 … N−1), so a failure names a reproducible seed. Iterations:
/// OTOPCUA_PORT_FUZZ_ITERATIONS (default 10 000, the H1 gate minimum).
///
///
[Trait("Feature", "GrpcData")]
[Trait("Phase", "H1")]
public sealed class HistoryReadPortPagingFuzzTests(HistoryReadPortServerFixture fx) : IClassFixture
{
private static readonly DateTime T0 = new(2026, 10, 22, 12, 0, 0, DateTimeKind.Utc);
private enum Shape { SqlServer, QuestDb, Gateway }
private enum Direction { Forward, Reverse, EndOnly }
private static int Iterations =>
int.TryParse(Environment.GetEnvironmentVariable("OTOPCUA_PORT_FUZZ_ITERATIONS"), out var n) && n > 0 ? n : 10_000;
[Fact]
public async Task Paged_equals_unpaged_through_the_port_on_random_tie_series()
{
var iterations = Iterations;
iterations.ShouldBeGreaterThanOrEqualTo(1);
var counts = new Dictionary();
void Count(string key) => counts[key] = counts.GetValueOrDefault(key) + 1;
var (realm, id, nodeId) = fx.Nodes["dbl"];
await fx.Gate.WaitAsync(TestContext.Current.CancellationToken);
try
{
fx.Nm.MaxTieClusterOverfetch = 65536;
for (var seed = 0; seed < iterations; seed++)
{
var rng = new Random(seed);
var shape = (Shape)(seed % 3);
var resolution = shape == Shape.QuestDb ? 10L : 1L;
var series = RandomSeries(rng, resolution);
var n = rng.Next(6) switch { 0 => 1u, 1 => 2u, 2 => 3u, 3 => (uint)rng.Next(4, 12), 4 => 0u, _ => (uint)rng.Next(12, 60) };
var direction = rng.Next(5) switch { 0 => Direction.Reverse, 1 => Direction.EndOnly, _ => Direction.Forward };
if (direction == Direction.EndOnly && n == 0) direction = Direction.Forward; // Part 11: one bound only with a cap
var bounds = direction != Direction.EndOnly && rng.Next(4) == 0;
// A strict row ceiling only on the native shapes (the walk-back's own budget is the raw-cap fuzz's subject).
var ceiling = shape != Shape.Gateway && rng.Next(4) == 0 ? rng.Next(3, 12) : 0;
var a = PickBoundary(rng, series, resolution);
var b = PickBoundary(rng, series, resolution);
var (lo, hi) = a <= b ? (a, b) : (b, a);
var (start, end) = direction switch
{
Direction.Forward => (lo, hi),
Direction.Reverse => (hi, lo),
_ => (DateTime.MinValue, hi),
};
var tag = $"seed {seed} {shape} N {n} ceiling {ceiling} {direction} bounds {bounds} [{start:O} .. {end:O}]";
// The oracle: the port's one-shot answer with no cap and no ceiling (end-only: the explicit reverse to 1970).
fx.Nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore();
fx.Nm.HistorianDataSource = new FuzzSource(series, shape, ceiling: 0);
var oracleDetails = direction == Direction.EndOnly
? new HistoryReadRawVariant(hi, DateTime.UnixEpoch, 0, false)
: new HistoryReadRawVariant(start, end, 0, bounds);
var truth = PortRead(oracleDetails, realm, id, null);
truth.Status.ShouldBe(StatusCodes.Good.Code, $"oracle: {tag}");
truth.Cp.ShouldBeNull($"oracle is one page: {tag}");
if (!bounds) truth.Values.ShouldBe(SeriesOracle(series, start, end, direction, resolution), $"oracle vs series: {tag}");
// The read under test, through the port.
var source = new FuzzSource(series, shape, ceiling);
fx.Nm.HistorianDataSource = source;
var details = new HistoryReadRawVariant(start, end, n, bounds);
var portPages = Page(cp => PortRead(details, realm, id, cp), truth.Values.Count, tag, out var portStatus);
source.ReverseOnForwardOnly.ShouldBe(0, $"a reverse window reached a forward-only backend: {tag}");
if (portStatus == StatusCodes.BadTooManyOperations)
{
// Legitimate only when a tie cluster is too large for the page a ceiling leaves.
(ceiling > 0 && LargestTieCluster(series, resolution) >= ceiling - 1).ShouldBeTrue($"refused without an oversized tie cluster: {tag}");
Count("refused");
}
else
{
portStatus.ShouldBe(StatusCodes.Good.Code, tag);
string.Join(" | ", portPages.SelectMany(p => p)).ShouldBe(string.Join(" | ", truth.Values), $"paged ≠ unpaged: {tag}");
if (n > 0) portPages.ShouldAllBe(p => p.Count <= n, $"a page over N (bounds count toward it, #736): {tag}");
Count("exact");
}
// Every tenth seed: the SDK override path returns the same pages as the port.
if (seed % 10 == 0)
{
fx.Nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore();
fx.Nm.HistorianDataSource = new FuzzSource(series, shape, ceiling);
var sdkDetails = new ReadRawModifiedDetails
{
StartTime = start, EndTime = end, NumValuesPerNode = n, ReturnBounds = bounds, IsReadModified = false,
};
var overridePages = Page(cp => OverrideRead(sdkDetails, nodeId, cp), truth.Values.Count, tag, out var overrideStatus);
overrideStatus.ShouldBe(portStatus, $"override vs port status: {tag}");
overridePages.Select(p => string.Join(" | ", p)).ShouldBe(portPages.Select(p => string.Join(" | ", p)), $"override vs port pages: {tag}");
Count("override compared");
}
if (truth.Values.Count == 0) Count("empty");
if (portPages.Count > 1) Count("paged");
if (direction != Direction.Forward) Count(direction.ToString());
if (bounds) Count("bounds");
if (ceiling > 0) Count("ceiling");
if (n == 0) Count("N=0");
if (n == 1) Count("N=1");
Count(shape.ToString());
}
}
finally
{
fx.Nm.HistorianDataSource = NullHistorianDataSource.Instance;
fx.Nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore();
fx.Gate.Release();
}
var summary = string.Join(", ", counts.OrderBy(kv => kv.Key).Select(kv => $"{kv.Key}={kv.Value}"));
foreach (var required in new[] { "empty", "paged", "Reverse", "EndOnly", "bounds", "ceiling", "N=0", "N=1", "SqlServer", "QuestDb", "Gateway", "override compared" })
counts.GetValueOrDefault(required).ShouldBeGreaterThan(iterations / 200, $"{required} under-represented: {summary}");
counts.GetValueOrDefault("exact").ShouldBeGreaterThan(iterations * 9 / 10, summary);
TestContext.Current.TestOutputHelper?.WriteLine($"port paging fuzz: {iterations} iterations — {summary}");
}
private static List> Page(
Func Values, byte[]? Cp)> read, int truthCount, string tag, out uint status)
{
var pages = new List>();
byte[]? cp = null;
do
{
var (s, values, next) = read(cp);
status = s;
if ((s & 0x80000000u) != 0) return pages;
pages.Add(values);
cp = next;
pages.Count.ShouldBeLessThanOrEqualTo(2 * truthCount + 4, $"paging must terminate: {tag}");
}
while (cp is not null);
return pages;
}
private (uint Status, List Values, byte[]? Cp) PortRead(HistoryReadRawVariant details, AddressSpaceRealm realm, string id, byte[]? cp)
{
// The binding tag the SDK adapter would pass for THIS node: derived from the node read, not a fixed key.
var nodeId = fx.Nodes.Values.Single(n => n.Realm == realm && n.Id == id).NodeId;
var outcome = fx.Nm.ReadHistory(details, [new HistoryReadPortItem(realm, id, cp, BindingTag: fx.Nm.HistoryBindingTag(nodeId))],
fx.Nm.SessionHistoryContinuationScope(session: null), CancellationToken.None)[0];
// The operation slot, as the override's errors[i] (Status folds GoodNoData in; pinned by the parity tests).
return (outcome.Error?.StatusCode.Code ?? StatusCodes.BadHistoryOperationUnsupported.Code,
outcome.Values.Select(Render).ToList(), outcome.ContinuationPoint);
}
private (uint Status, List Values, byte[]? Cp) OverrideRead(ReadRawModifiedDetails details, NodeId nodeId, byte[]? cp)
{
var context = new OperationContext(new RequestHeader(), secureChannelContext: null, RequestType.HistoryRead,
requestLifetime: RequestLifetime.None, identity: null);
var nodesToRead = new List { new() { NodeId = nodeId, ContinuationPoint = ByteString.From(cp) } };
var results = new List { null! };
var errors = new List { null! };
fx.Nm.HistoryRead(context, details, TimestampsToReturn.Both, releaseContinuationPoints: false, nodesToRead, results, errors);
var values = results[0]?.HistoryData is { IsNull: false } body && ExtensionObject.ToEncodeable(body) is HistoryData data
? (data.DataValues.ToArray() ?? []).Select(Render).ToList()
: [];
return (errors[0].StatusCode.Code, values, results[0]?.ContinuationPoint.ToNullableArray());
}
private static string Render(DataValue v) =>
$"{v.SourceTimestamp.ToDateTime().Ticks}={SdkValueBoundary.ToClr(v.WrappedValue) ?? "null"}/{v.StatusCode.Code:X8}";
private static string Render(DataValueSnapshot s) =>
$"{Ts(s).Ticks}={s.Value ?? "null"}/{s.StatusCode:X8}";
private static DateTime Ts(DataValueSnapshot s) => s.SourceTimestampUtc ?? DateTime.MinValue;
private static DateTime Trunc(DateTime t, long resolution) => new(t.Ticks - t.Ticks % resolution, DateTimeKind.Utc);
private static List RandomSeries(Random rng, long resolution)
{
var list = new List();
var t = T0.Ticks - rng.Next(0, 3) * TimeSpan.TicksPerHour;
var count = rng.Next(0, 60);
var v = 0;
while (list.Count < count)
{
t += rng.Next(6) switch
{
0 => rng.Next(1, 10),
1 => rng.Next(1, 5) * TimeSpan.TicksPerMillisecond,
2 => rng.Next(1, 3) * TimeSpan.TicksPerSecond,
3 => rng.Next(1, 30) * TimeSpan.TicksPerMinute,
_ => rng.Next(1, 1000) * TimeSpan.TicksPerMillisecond,
};
var ties = rng.Next(5) == 0 ? rng.Next(2, 9) : 1;
for (var k = 0; k < ties; k++)
{
var ts = Trunc(new DateTime(t, DateTimeKind.Utc), resolution);
var bad = rng.Next(12) == 0;
list.Add(new DataValueSnapshot(bad ? null : (double)v, bad ? StatusCodes.Bad.Code : StatusCodes.Good.Code, ts, ts));
v++;
}
}
return list;
}
private static DateTime PickBoundary(Random rng, List series, long resolution)
{
if (series.Count == 0) return T0.AddSeconds(rng.Next(-100, 100));
var i = rng.Next(series.Count);
var t = Ts(series[i]);
switch (rng.Next(9))
{
case 0: return Ts(series[0]).AddSeconds(-rng.Next(1, 100));
case 1: return Ts(series[^1]).AddSeconds(rng.Next(1, 100));
case 2:
case 3: return t;
case 4: return t.AddTicks(resolution);
case 5: return t.AddTicks(-1);
case 6: return t.AddMilliseconds(1);
default:
var next = i + 1 < series.Count ? Ts(series[i + 1]) : t.AddSeconds(10);
return new DateTime(t.Ticks + (long)((next.Ticks - t.Ticks) * rng.NextDouble()), DateTimeKind.Utc);
}
}
private static List SeriesOracle(List series, DateTime start, DateTime end, Direction direction, long resolution)
{
var s = Trunc(start, resolution);
var e = Trunc(end, resolution);
IEnumerable window = direction switch
{
Direction.Forward or Direction.Reverse when s == e => series.Where(x => Ts(x) == s),
Direction.Forward => series.Where(x => Ts(x) >= s && Ts(x) < e),
Direction.Reverse => series.Where(x => Ts(x) > e && Ts(x) <= s).Reverse(),
_ => series.Where(x => Ts(x) <= e).Reverse(),
};
return window.Select(Render).ToList();
}
private static int LargestTieCluster(List series, long resolution) =>
series.GroupBy(x => Trunc(Ts(x), resolution).Ticks).Select(g => g.Count()).DefaultIfEmpty(0).Max();
/// A series-backed backend of one shape; a non-zero ceiling is a strict row ceiling (refused above it).
private sealed class FuzzSource(IReadOnlyList series, Shape shape, int ceiling) : IHistorianDataSource
{
public int ReverseOnForwardOnly;
public bool SupportsReverseRaw => shape != Shape.Gateway;
public long TimestampResolutionTicks => shape == Shape.QuestDb ? 10 : 1;
public int MaxRawValuesPerRead => ceiling;
public Task ReadRawAsync(
string fullReference, DateTime startUtc, DateTime endUtc, uint maxValuesPerNode, CancellationToken cancellationToken)
{
if (shape == Shape.Gateway && startUtc > endUtc)
{
Interlocked.Increment(ref ReverseOnForwardOnly);
throw new InvalidOperationException("start_time must be less than or equal to end_time.");
}
startUtc = Trunc(startUtc, TimestampResolutionTicks);
endUtc = Trunc(endUtc, TimestampResolutionTicks);
List window;
if (startUtc > endUtc) window = series.Where(x => Ts(x) > endUtc && Ts(x) <= startUtc).Reverse().ToList();
else if (startUtc == endUtc) window = series.Where(x => Ts(x) == startUtc).ToList();
else window = series.Where(x => Ts(x) >= startUtc && Ts(x) < endUtc).ToList();
var probe = ceiling > 0 && (maxValuesPerNode == 0 || maxValuesPerNode > (uint)ceiling);
if (probe && window.Count > ceiling)
throw new HistoryReadLimitExceededException(ceiling, $"more than {ceiling} rows");
var page = maxValuesPerNode == 0 ? window : window.Take((int)Math.Min(maxValuesPerNode, int.MaxValue)).ToList();
return Task.FromResult(new HistorianRead(page, null));
}
public Task ReadProcessedAsync(
string fullReference, DateTime startUtc, DateTime endUtc, TimeSpan interval,
HistoryAggregateType aggregate, CancellationToken cancellationToken) =>
Task.FromResult(new HistorianRead(Array.Empty(), null));
public Task ReadAtTimeAsync(
string fullReference, IReadOnlyList timestampsUtc, CancellationToken cancellationToken) =>
Task.FromResult(new HistorianRead(Array.Empty(), null));
public Task ReadEventsAsync(
string? sourceName, DateTime startUtc, DateTime endUtc, int maxEvents, CancellationToken cancellationToken) =>
Task.FromResult(new HistoricalEventsResult(Array.Empty(), null));
public HistorianHealthSnapshot GetHealthSnapshot() => NullHistorianDataSource.Instance.GetHealthSnapshot();
public void Dispose() { }
}
}