test(grpc-data): H1 override paging over a real Session, override-path cross-kind refusal, deterministic limiter holder (verification 4-6, 7a)

This commit is contained in:
Joseph Doherty
2026-11-23 20:10:18 -05:00
parent 100dd5ca44
commit efea401915
3 changed files with 92 additions and 11 deletions
@@ -31,7 +31,9 @@ public sealed class HistoryReadPortLimiterAndSessionTests : IAsyncDisposable
{
var (server, nm) = await BootAsync();
nm.MaxConcurrentHistoryReadBatches = 1;
nm.HistoryReadDeadline = TimeSpan.FromMilliseconds(500); // admission waits min(deadline, 5 s)
// The holder runs with NO deadline (it is captured when its batch starts), so it holds the slot until released,
// whatever the machine's speed; the waiting batches then get a short deadline, so their admission wait is short.
nm.HistoryReadDeadline = TimeSpan.Zero;
var source = new GatedSource();
nm.HistorianDataSource = source;
var nodeId = Add(nm, "lim/a", "P.a");
@@ -42,6 +44,7 @@ public sealed class HistoryReadPortLimiterAndSessionTests : IAsyncDisposable
// 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);
nm.HistoryReadDeadline = TimeSpan.FromMilliseconds(300); // admission waits min(deadline, 5 s)
var waiting = nm.ReadHistory(details,
[new HistoryReadPortItem(AddressSpaceRealm.Uns, "lim/a"), new HistoryReadPortItem(AddressSpaceRealm.Uns, "lim/b")],
@@ -97,6 +100,7 @@ public sealed class HistoryReadPortLimiterAndSessionTests : IAsyncDisposable
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);
o.Result!.StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code, variant.GetType().Name);
}
}
@@ -145,6 +149,66 @@ public sealed class HistoryReadPortLimiterAndSessionTests : IAsyncDisposable
.ContinuationPoint.ShouldBeNull();
}
[Fact]
public async Task The_override_pages_and_resumes_through_the_real_session_store_with_a_real_session()
{
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;
var nodeId = Add(nm, "sess/o", "P.o");
using var certificateKey = RSA.Create(2048);
using var certificate = Certificate.From(new CertificateRequest("CN=H1.Override.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);
(uint Error, List<double> Values, byte[]? Cp) Read(ISession s, byte[]? cp)
{
var context = new OperationContext(new RequestHeader(), null!, RequestType.HistoryRead, RequestLifetime.None, s);
var results = new List<SdkHistoryReadResult> { null! };
var errors = new List<ServiceResult> { null! };
nm.HistoryRead(context,
new ReadRawModifiedDetails { StartTime = T0, EndTime = T0.AddHours(1), NumValuesPerNode = 2, ReturnBounds = false, IsReadModified = false },
TimestampsToReturn.Both, false, new List<HistoryReadValueId> { new() { NodeId = nodeId, ContinuationPoint = ByteString.From(cp) } },
results, errors);
var values = results[0]?.HistoryData is { IsNull: false } body && ExtensionObject.ToEncodeable(body) is HistoryData data
? (data.DataValues.ToArray() ?? []).Select(v => (double)SdkValueBoundary.ToClr(v.WrappedValue)!).ToList()
: [];
return (errors[0].StatusCode.Code, values, results[0]?.ContinuationPoint.ToNullableArray());
}
var collected = new List<double>();
byte[]? cp = null;
var pages = 0;
do
{
var (error, values, next) = Read(session, cp);
error.ShouldBe(StatusCodes.Good.Code);
collected.AddRange(values);
cp = next;
pages++;
}
while (cp is not null && pages < 20);
collected.ShouldBe([0, 1, 2, 3, 4, 5, 6]);
pages.ShouldBe(4, "N = 2 over 7 values: four pages, the session store holding each cursor in between");
// An override-issued cursor lives in the SDK session: another session cannot resume it, a reuse is a miss, and the
// port resumes it through the same session with the adapter's binding tag.
var first = Read(session, null).Cp!;
Read(other, first).Error.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
var second = Read(session, null).Cp!;
var viaPort = nm.ReadHistory(new HistoryReadRawVariant(T0, T0.AddHours(1), 2, ReturnBounds: false),
[new HistoryReadPortItem(AddressSpaceRealm.Uns, "sess/o", second, BindingTag: nm.HistoryBindingTag(nodeId))],
nm.SessionHistoryContinuationScope(session), CancellationToken.None).Single();
viaPort.Error!.StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
viaPort.Values.Select(v => (double)SdkValueBoundary.ToClr(v.WrappedValue)!).ShouldBe([2, 3]);
Read(session, second).Error.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code, "single use");
}
private static Session NewSession(OtOpcUaSdkServer server, Certificate certificate, Nonce nonce)
{
var endpoint = new EndpointDescription { EndpointUrl = "opc.tcp://localhost:4840", SecurityMode = MessageSecurityMode.None };
@@ -164,7 +164,9 @@ public sealed class HistoryReadPortPagingFuzzTests(HistoryReadPortServerFixture
private (uint Status, List<string> Values, byte[]? Cp) PortRead(HistoryReadRawVariant details, AddressSpaceRealm realm, string id, byte[]? cp)
{
var outcome = fx.Nm.ReadHistory(details, [new HistoryReadPortItem(realm, id, cp, BindingTag: fx.Nm.HistoryBindingTag(fx.Nodes["dbl"].NodeId))],
// 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,
@@ -96,9 +96,14 @@ public sealed class CapturingLogger : Microsoft.Extensions.Logging.ILogger<OtOpc
/// H1 (gRPC data history plan §3.1): the override-level history port is the ONE pipeline the SDK overrides and a remote
/// peer's HistoryRead (H2) are served through. Every case runs the same request two ways against the same fake backend —
/// the SDK override path (<c>HistoryRead</c> on the node manager, the path every local OPC UA client takes) and the port
/// directly with <c>(realm, identifier)</c> items — and requires identical per-node outcomes. Each case also pins the
/// override outcome to explicit expected values recorded against the pre-port node manager, so "identical" can never
/// mean "identically wrong after the refactor".
/// directly with <c>(realm, identifier)</c> items — and requires identical per-node outcomes.
/// <para>
/// What this class proves is port ≡ adapter. Since H1 the override IS an adapter over the port, so that equality
/// alone cannot detect a behaviour change the port introduced. The tie to PRE-H1 behaviour is (a) the pinned literal
/// outcomes in these cases, which were recorded and run green against the pre-port node manager (the port calls then
/// stubbed onto the override), and (b) the legacy history suites (<c>NodeManagerHistoryRead*Tests</c>,
/// <c>HistoryUpdateTests</c>, the raw-cap fuzz …), unchanged and re-run by the H1 gate.
/// </para>
/// </summary>
[Trait("Feature", "GrpcData")]
[Trait("Phase", "H1")]
@@ -568,13 +573,23 @@ public sealed class HistoryReadPortParityTests(HistoryReadPortServerFixture fx)
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);
// A modified cursor is bound to the modified kind: a plain raw resume is refused (and the reverse) — on the
// override path and on the port alike.
var plain = Raw(T(0), T(100), 3, bounds: false);
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);
foreach (var (name, read) in new (string, Func<HistoryReadDetails, byte[]?, (Outcome Outcome, byte[]? Cp)>)[]
{
("override", (d, cp) => ReadOverrideRaw(d, "dbl", cp)),
("port", (d, cp) => ReadPortRaw(d, "dbl", cp)),
})
{
var modifiedCp = read(details, null).Cp!;
var crossed = read(plain, modifiedCp).Outcome;
crossed.Error.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code, name);
crossed.ResultStatus.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code, name);
var rawCp = read(plain, null).Cp!;
read(details, rawCp).Outcome.Error.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code, name);
}
await Task.CompletedTask;
});
}