diff --git a/scripts/validation/grpc-data/unit-phases.json b/scripts/validation/grpc-data/unit-phases.json
index 6be367df4..c4e16b89f 100644
--- a/scripts/validation/grpc-data/unit-phases.json
+++ b/scripts/validation/grpc-data/unit-phases.json
@@ -787,7 +787,8 @@
"new_classes": [
"HistoryReadPortParityTests",
"HistoryReadPortPagingFuzzTests",
- "PeerHistoryContinuationStoreTests"
+ "PeerHistoryContinuationStoreTests",
+ "HistoryReadPortLimiterAndSessionTests"
],
"existing_classes": [
"NodeManagerHistoryReadTests",
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/HistoryReadPortLimiterAndSessionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/HistoryReadPortLimiterAndSessionTests.cs
new file mode 100644
index 000000000..4e4c1effc
--- /dev/null
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/HistoryReadPortLimiterAndSessionTests.cs
@@ -0,0 +1,245 @@
+using System.Security.Cryptography;
+using System.Security.Cryptography.X509Certificates;
+using Microsoft.Extensions.Logging.Abstractions;
+using Opc.Ua;
+using Opc.Ua.Security.Certificates;
+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 (review 7): the port's process-wide batch limiter, its per-request deadline and request cancellation, and paging
+/// against the REAL SDK session-backed continuation store. Each case boots its own server, because the batch limiter is
+/// sized once per node manager at first use.
+///
+[Trait("Feature", "GrpcData")]
+[Trait("Phase", "H1")]
+public sealed class HistoryReadPortLimiterAndSessionTests : IAsyncDisposable
+{
+ private static readonly DateTime T0 = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
+ private readonly string _pki = Path.Combine(Path.GetTempPath(), $"otopcua-histport-limit-{Guid.NewGuid():N}");
+ private OpcUaApplicationHost? _host;
+
+ [Fact]
+ public async Task A_saturated_limiter_fails_every_node_of_the_waiting_batch_on_both_paths()
+ {
+ var (server, nm) = await BootAsync();
+ nm.MaxConcurrentHistoryReadBatches = 1;
+ nm.HistoryReadDeadline = TimeSpan.FromMilliseconds(500); // admission waits min(deadline, 5 s)
+ var source = new GatedSource();
+ nm.HistorianDataSource = source;
+ var nodeId = Add(nm, "lim/a", "P.a");
+ Add(nm, "lim/b", "P.b");
+ var details = new HistoryReadRawVariant(T0, T0.AddHours(1), 5, ReturnBounds: false);
+ var scope = nm.SessionHistoryContinuationScope(session: null);
+
+ // Batch A holds the only slot inside the backend.
+ var holder = Task.Run(() => nm.ReadHistory(details, [new HistoryReadPortItem(AddressSpaceRealm.Uns, "lim/a")], scope, CancellationToken.None));
+ await source.Entered.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
+
+ var waiting = nm.ReadHistory(details,
+ [new HistoryReadPortItem(AddressSpaceRealm.Uns, "lim/a"), new HistoryReadPortItem(AddressSpaceRealm.Uns, "lim/b")],
+ scope, CancellationToken.None);
+ waiting.ShouldAllBe(o => o.Error!.StatusCode == StatusCodes.BadTooManyOperations
+ && o.Result!.StatusCode == StatusCodes.BadTooManyOperations);
+ source.Calls.ShouldBe(1, "the rejected batch never reached the backend");
+
+ // The SDK override path shares the same limiter.
+ var context = new OperationContext(new RequestHeader(), secureChannelContext: null, RequestType.HistoryRead,
+ requestLifetime: RequestLifetime.None, identity: null);
+ var results = new List { null! };
+ var errors = new List { null! };
+ nm.HistoryRead(context, new ReadRawModifiedDetails { StartTime = T0, EndTime = T0.AddHours(1), NumValuesPerNode = 5, ReturnBounds = false, IsReadModified = false },
+ TimestampsToReturn.Both, false, new List { new() { NodeId = nodeId } }, results, errors);
+ errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code);
+ results[0].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code);
+
+ source.Release.SetResult();
+ var held = await holder.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
+ held.Single().Error!.StatusCode.Code.ShouldBe(StatusCodes.Good.Code, "the slot holder completes normally");
+ }
+
+ [Fact]
+ public async Task The_deadline_and_request_cancellation_time_out_each_in_flight_node()
+ {
+ var (_, nm) = await BootAsync();
+ nm.HistorianDataSource = new GatedSource { HonourCancellation = true };
+ Add(nm, "dl/a", "P.a");
+ var scope = nm.SessionHistoryContinuationScope(session: null);
+ HistoryReadVariant[] variants =
+ [
+ new HistoryReadRawVariant(T0, T0.AddHours(1), 5, ReturnBounds: false),
+ new HistoryReadAtTimeVariant([T0]),
+ new HistoryReadProcessedVariant(T0, T0.AddHours(1), TimeSpan.FromMinutes(10), null),
+ ];
+ var item = new HistoryReadPortItem(AddressSpaceRealm.Uns, "dl/a",
+ AggregateType: ObjectIds.AggregateFunction_Average);
+
+ // The application deadline.
+ nm.HistoryReadDeadline = TimeSpan.FromMilliseconds(200);
+ foreach (var variant in variants)
+ {
+ var o = nm.ReadHistory(variant, [item], scope, CancellationToken.None).Single();
+ o.Error!.StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code, variant.GetType().Name);
+ o.Result!.StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code);
+ }
+
+ // The caller's own cancellation (H2's per-node deadline rides it), with no application deadline.
+ nm.HistoryReadDeadline = TimeSpan.Zero;
+ foreach (var variant in variants)
+ {
+ using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200));
+ var o = nm.ReadHistory(variant, [item], scope, cts.Token).Single();
+ o.Error!.StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code, variant.GetType().Name);
+ }
+ }
+
+ [Fact]
+ public async Task The_port_pages_through_the_real_session_backed_store()
+ {
+ var (server, nm) = await BootAsync();
+ nm.HistoryContinuationStore = new SessionHistoryContinuationStore();
+ var source = new GatedSource { Opened = true };
+ source.Series.AddRange(Enumerable.Range(0, 7).Select(i => new DataValueSnapshot((double)i, 0, T0.AddSeconds(i), T0.AddSeconds(i))));
+ nm.HistorianDataSource = source;
+ Add(nm, "sess/a", "P.a");
+ var details = new HistoryReadRawVariant(T0, T0.AddHours(1), 2, ReturnBounds: false);
+ var item = new HistoryReadPortItem(AddressSpaceRealm.Uns, "sess/a");
+
+ using var certificateKey = RSA.Create(2048);
+ using var certificate = Certificate.From(new CertificateRequest("CN=H1.Port.Session", certificateKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1)
+ .CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)));
+ using var nonce = Nonce.CreateNonce(32);
+ using var session = NewSession(server, certificate, nonce);
+ using var other = NewSession(server, certificate, nonce);
+ var scope = nm.SessionHistoryContinuationScope(session);
+
+ var values = new List();
+ byte[]? cp = null;
+ byte[]? firstCp = null;
+ do
+ {
+ var o = nm.ReadHistory(details, [item with { ContinuationPoint = cp }], scope, CancellationToken.None).Single();
+ o.Error!.StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
+ values.AddRange(o.Values.Select(v => (double)SdkValueBoundary.ToClr(v.WrappedValue)!));
+ cp = o.ContinuationPoint;
+ firstCp ??= cp;
+ }
+ while (cp is not null);
+ values.ShouldBe([0, 1, 2, 3, 4, 5, 6]);
+
+ // Session-store semantics: single-use, and a point is never visible to another session.
+ nm.ReadHistory(details, [item with { ContinuationPoint = firstCp }], scope, CancellationToken.None).Single()
+ .Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
+ var fresh = nm.ReadHistory(details, [item], scope, CancellationToken.None).Single().ContinuationPoint!;
+ nm.ReadHistory(details, [item with { ContinuationPoint = fresh }], nm.SessionHistoryContinuationScope(other), CancellationToken.None).Single()
+ .Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
+ // With no session there is nowhere to keep a cursor: the read degrades to single-shot, as before.
+ nm.ReadHistory(details, [item], nm.SessionHistoryContinuationScope(session: null), CancellationToken.None).Single()
+ .ContinuationPoint.ShouldBeNull();
+ }
+
+ private static Session NewSession(OtOpcUaSdkServer server, Certificate certificate, Nonce nonce)
+ {
+ var endpoint = new EndpointDescription { EndpointUrl = "opc.tcp://localhost:4840", SecurityMode = MessageSecurityMode.None };
+ using var context = new OperationContext(new RequestHeader(),
+ new SecureChannelContext(Guid.NewGuid().ToString(), endpoint, RequestEncoding.Binary),
+ RequestType.CreateSession, RequestLifetime.None);
+ return new Session(context, server.CurrentInstance, certificate, new NodeId(Guid.NewGuid()), default,
+ nonce, "H1 port session", new ApplicationDescription(), endpoint.EndpointUrl, null!, null!, 60_000, 10, 10);
+ }
+
+ private static NodeId Add(OtOpcUaNodeManager nm, string id, string tag)
+ {
+ nm.EnsureVariable(id, parentFolderNodeId: null, displayName: id, dataType: "Double", writable: false,
+ realm: AddressSpaceRealm.Uns, historianTagname: tag);
+ return nm.TryGetVariable(id)!.NodeId;
+ }
+
+ private async Task<(OtOpcUaSdkServer Server, OtOpcUaNodeManager Nm)> BootAsync()
+ {
+ var started = await OpcUaHostStart.StartAsync(
+ port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions
+ {
+ ApplicationName = "OtOpcUa.HistoryPortLimit", ApplicationUri = $"urn:OtOpcUa.HistoryPortLimit:{Guid.NewGuid():N}",
+ OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = _pki,
+ }, NullLogger.Instance),
+ () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken);
+ _host = started.Host;
+ var nm = started.Server.NodeManager!;
+ nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore();
+ return (started.Server, nm);
+ }
+
+ public async ValueTask DisposeAsync()
+ {
+ if (_host is not null) await _host.DisposeAsync();
+ if (Directory.Exists(_pki))
+ {
+ try { Directory.Delete(_pki, recursive: true); }
+ catch { /* best-effort */ }
+ }
+ }
+
+ ///
+ /// A backend whose reads block until (ignoring cancellation, so a slot stays held) — or, with
+ /// , until the read's token fires; answers from
+ /// straight away.
+ ///
+ private sealed class GatedSource : IHistorianDataSource
+ {
+ private int _calls;
+ public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ public bool HonourCancellation { get; init; }
+ public bool Opened { get; init; }
+ public List Series { get; } = [];
+ public int Calls => Volatile.Read(ref _calls);
+
+ public bool SupportsReverseRaw => true;
+
+ private async Task Gate(Func> answer, CancellationToken ct)
+ {
+ Interlocked.Increment(ref _calls);
+ if (!Opened)
+ {
+ Entered.TrySetResult();
+ if (HonourCancellation) await Task.Delay(Timeout.Infinite, ct).ConfigureAwait(false);
+ else await Release.Task.ConfigureAwait(false);
+ }
+
+ await Task.Delay(1, CancellationToken.None).ConfigureAwait(false);
+ return new HistorianRead(answer(), null);
+ }
+
+ public Task ReadRawAsync(
+ string fullReference, DateTime startUtc, DateTime endUtc, uint maxValuesPerNode, CancellationToken cancellationToken) =>
+ Gate(() =>
+ {
+ var window = Series.Where(s => s.SourceTimestampUtc >= startUtc && s.SourceTimestampUtc < endUtc);
+ return (maxValuesPerNode == 0 ? window : window.Take((int)maxValuesPerNode)).ToList();
+ }, cancellationToken);
+
+ public Task ReadProcessedAsync(
+ string fullReference, DateTime startUtc, DateTime endUtc, TimeSpan interval,
+ HistoryAggregateType aggregate, CancellationToken cancellationToken) => Gate(() => [], cancellationToken);
+
+ public Task ReadAtTimeAsync(
+ string fullReference, IReadOnlyList timestampsUtc, CancellationToken cancellationToken) =>
+ Gate(() => [], cancellationToken);
+
+ 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() { }
+ }
+}
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/HistoryReadPortParityTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/HistoryReadPortParityTests.cs
index f7c930ec2..4d76be191 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/HistoryReadPortParityTests.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/HistoryReadPortParityTests.cs
@@ -495,6 +495,84 @@ public sealed class HistoryReadPortParityTests(HistoryReadPortServerFixture fx)
});
}
+ [Fact]
+ public async Task A_mixed_batch_maps_every_outcome_back_to_its_own_handle_index()
+ {
+ await RunAsync(async () =>
+ {
+ var source = new ParitySource { ProcessedResult = [S(1.0, 0)] };
+ source.Series["P.dbl"] = Enumerable.Range(0, 5).Select(i => S((double)i, i)).ToList();
+ source.Series["P.raw"] = Enumerable.Range(0, 5).Select(i => S(10.0 + i, i)).ToList();
+ fx.Nm.HistorianDataSource = source;
+
+ // "plain" has no HistoryRead access bit: the SDK drops it before the override, so every later handle's Index
+ // differs from its position in the port's item list.
+ var processed = Processed(ObjectIds.AggregateFunction_Average);
+ processed.AggregateType = new[]
+ {
+ ObjectIds.AggregateFunction_Minimum, ObjectIds.AggregateFunction_Maximum,
+ ObjectIds.AggregateFunction_Average, ObjectIds.AggregateFunction_Count,
+ };
+ var nodes = new[] { "plain", "dbl", "str", "raw" };
+ var viaOverride = Override(processed, nodes);
+ viaOverride.Select(o => o.Error).ShouldBe(new[]
+ {
+ StatusCodes.BadHistoryOperationUnsupported.Code, StatusCodes.Good.Code,
+ StatusCodes.BadAggregateNotSupported.Code, StatusCodes.Good.Code,
+ });
+ source.ProcessedAsked.OrderBy(kv => kv.Key).Select(kv => $"{kv.Key}:{kv.Value}")
+ .ShouldBe(new[] { "P.dbl:Maximum", "P.raw:Count" }, "each node reached the backend with ITS aggregate");
+ Port(processed, nodes).ShouldBe(viaOverride);
+
+ // Raw: per-node continuation points route to their own node.
+ var raw = Raw(T(0), T(100), 2, bounds: false);
+ var first = InvokeOverride(raw, [("plain", null), ("dbl", null), ("raw", null)]);
+ var cpDbl = first.Results[1]!.ContinuationPoint.ToNullableArray();
+ var cpRaw = first.Results[2]!.ContinuationPoint.ToNullableArray();
+ cpDbl.ShouldNotBeNull();
+ cpRaw.ShouldNotBeNull();
+ var second = InvokeOverride(raw, [("plain", null), ("raw", cpRaw), ("dbl", cpDbl)]);
+ ToOutcome(second.Errors[1], second.Results[1]).Values.ShouldStartWith("T0+2=12:Double");
+ ToOutcome(second.Errors[2], second.Results[2]).Values.ShouldStartWith("T0+2=2:Double");
+
+ var portFirst = PortRead(raw, [("plain", null), ("dbl", null), ("raw", null)]);
+ portFirst.Select(o => o.Outcome).ShouldBe(Enumerable.Range(0, 3).Select(i => ToOutcome(first.Errors[i], first.Results[i])));
+ var portSecond = PortRead(raw, [("plain", null), ("raw", portFirst[2].Cp), ("dbl", portFirst[1].Cp)]);
+ portSecond[1].Outcome.ShouldBe(ToOutcome(second.Errors[1], second.Results[1]));
+ portSecond[2].Outcome.ShouldBe(ToOutcome(second.Errors[2], second.Results[2]));
+ await Task.CompletedTask;
+ });
+ }
+
+ [Fact]
+ public async Task Modified_reads_page_and_resume_through_the_port_as_through_the_override()
+ {
+ await RunAsync(async () =>
+ {
+ var source = new ParitySource();
+ source.Trail["P.dbl"] = Enumerable.Range(0, 7)
+ .Select(i => new HistoryModifiedValue(S((double)i, i / 2), T(1000 + i), HistoryModificationType.Replace, "alice", i + 1, T(i / 2)))
+ .ToList();
+ fx.Nm.HistorianDataSource = source;
+ var details = Raw(T(0), T(100), 3, bounds: false);
+ details.IsReadModified = true;
+
+ var expected = "T0+0=0:Double/00000000 | T0+0=1:Double/00000000 | T0+1=2:Double/00000000 | T0+1=3:Double/00000000 | " +
+ "T0+2=4:Double/00000000 | T0+2=5:Double/00000000 | T0+3=6:Double/00000000";
+ DrainOverride(details, "dbl").ShouldBe(expected);
+ DrainPort(details, "dbl").ShouldBe(expected);
+
+ // A modified cursor is bound to the modified kind: a plain raw resume is refused (and the reverse).
+ var modifiedCp = ReadPortRaw(details, "dbl", null).Cp!;
+ ReadPortRaw(Raw(T(0), T(100), 3, bounds: false), "dbl", modifiedCp).Outcome.Error
+ .ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
+ source.Series["P.dbl"] = Enumerable.Range(0, 7).Select(i => S((double)i, i)).ToList();
+ var rawCp = ReadPortRaw(Raw(T(0), T(100), 3, bounds: false), "dbl", null).Cp!;
+ ReadPortRaw(details, "dbl", rawCp).Outcome.Error.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
+ await Task.CompletedTask;
+ });
+ }
+
[Fact]
public async Task The_outcome_status_carries_GoodNoData_and_Bad_operation_statuses_verbatim()
{
@@ -653,6 +731,8 @@ public sealed class HistoryReadPortParityTests(HistoryReadPortServerFixture fx)
internal sealed class ParitySource : IHistorianDataSource
{
public Dictionary> Series { get; } = new();
+ public Dictionary> Trail { get; } = new();
+ public System.Collections.Concurrent.ConcurrentDictionary ProcessedAsked { get; } = new();
public IReadOnlyList ProcessedResult { get; init; } = [];
public IReadOnlyList AtTimeResult { get; set; } = [];
public bool NativeReverse { get; init; } = true;
@@ -709,9 +789,24 @@ public sealed class HistoryReadPortParityTests(HistoryReadPortServerFixture fx)
HistoryAggregateType aggregate, CancellationToken cancellationToken)
{
Interlocked.Increment(ref ProcessedCalls);
+ ProcessedAsked[fullReference] = aggregate;
return Task.FromResult(new HistorianRead(ProcessedResult, null));
}
+ public Task ReadModifiedAsync(
+ string fullReference, DateTime startUtc, DateTime endUtc, uint maxValues, HistoryModifiedCursor? resumeAfter,
+ CancellationToken cancellationToken)
+ {
+ if (!Trail.TryGetValue(fullReference, out var trail)) throw new NotSupportedException("no trail");
+ var window = trail.Where(m => m.SourceTimeUtc >= startUtc && m.SourceTimeUtc < endUtc)
+ .OrderBy(m => m.SourceTimeUtc).ThenBy(m => m.ModifiedId)
+ .Where(m => resumeAfter is null || m.SourceTimeUtc > resumeAfter.SourceTimeUtc
+ || (m.SourceTimeUtc == resumeAfter.SourceTimeUtc && m.ModifiedId > resumeAfter.ModifiedId))
+ .ToList();
+ var page = maxValues == 0 ? window : window.Take((int)maxValues).ToList();
+ return Task.FromResult(new HistoryModifiedReadResult(page, page.Count < window.Count));
+ }
+
public Task ReadAtTimeAsync(
string fullReference, IReadOnlyList timestampsUtc, CancellationToken cancellationToken) =>
Task.FromResult(new HistorianRead(AtTimeResult, null));