using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
using Opc.Ua.Client;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using HistorianRead = ZB.MOM.WW.OtOpcUa.Core.Abstractions.HistoryReadResult;
using SdkDataValue = Opc.Ua.DataValue;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
///
/// H3 — a real consumer OPC UA session HistoryReads a projected node through the real projection stack
/// ( + ) and a real in-process origin
/// ( over a real history port and its
/// PeerHistoryContinuationStore ). Replaces the H2 pin that a projected node refused HistoryRead "until H3".
///
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
{
private static readonly DateTime HistoryT0 = new(2026, 11, 20, 10, 0, 0, DateTimeKind.Utc);
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
[Trait("Phase", "H2")] // replaces the H2 pin "a projected node refuses HistoryRead until H3"
public async Task Granted_projected_HistoryRead_is_served_verbatim_and_pages_to_completion_through_the_origin()
{
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
var connections = new PersistentConnections(origin);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var values = new List();
var cp = default(ByteString);
var pages = 0;
do
{
var result = await RawHistory(client, anchor, 3, cp);
StatusCode.IsGood(result.StatusCode).ShouldBeTrue(result.StatusCode.ToString());
values.AddRange(Values(result));
cp = result.ContinuationPoint;
pages++;
} while (!cp.IsEmpty && pages < 10);
values.Select(v => SdkValueBoundary.ToClr(v.WrappedValue)).ShouldBe(Enumerable.Range(0, 7).Cast());
values.Select(v => v.SourceTimestamp.ToDateTime()).ShouldBe(Enumerable.Range(0, 7).Select(i => HistoryT0.AddSeconds(i)));
pages.ShouldBe(3);
origin.Services.HistoryOpenContinuations.ShouldBe(0, "a page-through to completion leaves nothing open at the origin");
}, localPermissions: 15, allowHistory: true, connectionSource: connections);
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
[Trait("Phase", "H2")] // replaces the H2 pin "a projected node refuses HistoryRead until H3"
public async Task Without_the_local_HistoryRead_grant_on_the_mapping_scope_it_is_BadUserAccessDenied_and_unsent()
{
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var result = await RawHistory(client, anchor, 3, default);
result.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
result.ContinuationPoint.IsEmpty.ShouldBeTrue();
originServer.Source.Calls.ShouldBe(0);
}, localPermissions: 7, allowHistory: true, connectionSource: new PersistentConnections(origin));
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task Consumer_session_close_releases_the_origin_continuations()
{
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
ProjectedHistoryAccess? history = null;
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var page = await RawHistory(client, anchor, 2, default);
page.ContinuationPoint.IsEmpty.ShouldBeFalse();
origin.Services.HistoryOpenContinuations.ShouldBe(1);
await session.CloseAsync(TestContext.Current.CancellationToken);
await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0);
origin.Services.HistoryOpenContinuations.ShouldBe(0, "the SDK disposed the Remote point and the release reached the origin");
history!.ReleaseCallsForTests.ShouldBe(1);
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin),
onHistory: (h, _) => history = h);
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task ReleaseContinuationPoints_forwards_one_release_and_the_point_is_then_invalid()
{
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
ProjectedHistoryAccess? history = null;
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var page = await RawHistory(client, anchor, 2, default);
origin.Services.HistoryOpenContinuations.ShouldBe(1);
var released = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(2)), TimestampsToReturn.Both, true,
[new HistoryReadValueId { NodeId = anchor, ContinuationPoint = page.ContinuationPoint }], TestContext.Current.CancellationToken);
StatusCode.IsGood(released.Results[0].StatusCode).ShouldBeTrue();
await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0);
origin.Services.HistoryOpenContinuations.ShouldBe(0);
var resumed = await RawHistory(client, anchor, 2, page.ContinuationPoint);
resumed.StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin), onHistory: (h, _) => history = h);
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task A_resume_after_lease_expiry_or_an_origin_rebuild_epoch_bump_is_invalid_and_a_fresh_read_succeeds()
{
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
var connections = new PersistentConnections(origin);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
// Lease expiry / redeployment: the deployed connection (route) is replaced — its tokens never resume.
var page = await RawHistory(client, anchor, 2, default);
connections.Rotate();
(await RawHistory(client, anchor, 2, page.ContinuationPoint)).StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
var fresh = await RawHistory(client, anchor, 2, default);
StatusCode.IsGood(fresh.StatusCode).ShouldBeTrue();
// Origin rebuild: its history epoch moves (a removal), so the origin itself refuses the resumed token.
originServer.BumpEpoch();
(await RawHistory(client, anchor, 2, fresh.ContinuationPoint)).StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
StatusCode.IsGood((await RawHistory(client, anchor, 2, default)).StatusCode).ShouldBeTrue();
}, localPermissions: 15, allowHistory: true, connectionSource: connections);
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task Uncapped_raw_returns_the_origin_continuation_and_aggregates_are_refused_both_ways()
{
await using var originServer = await HistoryOrigin.StartAsync(25, maxRawPerRead: 10);
originServer.Source.Aggregates = new HashSet { HistoryAggregateType.Average };
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
// NumValuesPerNode = 0: the origin pages at its ceiling and the consumer hands back its continuation (Part 11).
var uncapped = await RawHistory(client, anchor, 0, default);
StatusCode.IsGood(uncapped.StatusCode).ShouldBeTrue();
uncapped.ContinuationPoint.IsEmpty.ShouldBeFalse();
Values(uncapped).Count.ShouldBeLessThan(25);
// The origin refuses an aggregate its backend does not serve.
var refused = await ProcessedHistory(client, anchor, ObjectIds.AggregateFunction_Count);
refused.StatusCode.Code.ShouldBe(StatusCodes.BadAggregateNotSupported.Code);
// The consumer refuses an aggregate it cannot name, unsent.
var calls = originServer.Source.Calls;
var unknown = await ProcessedHistory(client, anchor, new NodeId("no-such-aggregate", 1));
unknown.StatusCode.Code.ShouldBe(StatusCodes.BadAggregateNotSupported.Code);
originServer.Source.Calls.ShouldBe(calls);
// A served aggregate passes through.
var average = await ProcessedHistory(client, anchor, ObjectIds.AggregateFunction_Average);
StatusCode.IsGood(average.StatusCode).ShouldBeTrue(average.StatusCode.ToString());
// Found by the H3 live gate (H02): an aggregate's value has ITS OWN type (a Double Average of an Int32 node),
// never the node's — it must not be refused BadTypeMismatch against the catalog's value kind.
var interval = Values(average).ShouldHaveSingleItem();
StatusCode.IsGood(interval.StatusCode).ShouldBeTrue(interval.StatusCode.ToString());
SdkValueBoundary.ToClr(interval.WrappedValue).ShouldBeOfType().ShouldBe(3.0);
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin));
}
[Theory(Timeout = 90000)]
[Trait("Phase", "H3")]
[InlineData(1_000_000, 3)]
[InlineData(25_000, 2)] // ≈ 288 B a value × 40 per node: two nodes fit, the third is refused
[InlineData(15_000, 1)]
[InlineData(1_200, 0)]
public async Task The_per_request_assembly_budget_is_shared_across_the_batch(int budget, int expectedGood)
{
await using var originServer = await HistoryOrigin.StartAsync(7, extra: 2);
using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1, history: originServer.Port);
await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
var children = (await BrowseAll(client, anchor, 10))
.Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray();
children.Length.ShouldBe(3);
var details = new ReadAtTimeDetails { ReqTimes = Enumerable.Range(0, 40).Select(i => (DateTimeUtc)HistoryT0.AddSeconds(i)).ToArray() };
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(details), TimestampsToReturn.Both, false,
children.Select(c => new HistoryReadValueId { NodeId = c }).ToArray(), TestContext.Current.CancellationToken);
var results = response.Results.ToArray()!;
var statuses = results.Select(r => r.StatusCode.Code).ToArray();
statuses.Count(s => StatusCode.IsGood(s)).ShouldBe(expectedGood, string.Join(",", statuses.Select(x => x.ToString("X8"))));
foreach (var r in results.Where(r => !StatusCode.IsGood(r.StatusCode)))
{
r.StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code);
Values(r).ShouldBeEmpty("never a partial answer under an error status");
}
foreach (var r in results.Where(r => StatusCode.IsGood(r.StatusCode))) Values(r).Count.ShouldBe(40);
// The budget is consumed in request order: once a node does not fit, every later node is refused too.
statuses.TakeWhile(x => StatusCode.IsGood(x)).Count().ShouldBe(expectedGood);
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin),
configureMapping: m => m.MaxHistoryAssemblyBytesPerRequest = budget);
}
[Theory(Timeout = 90000)]
[Trait("Phase", "H3")]
[InlineData(false)]
[InlineData(true)]
public async Task Historizing_and_the_HistoryRead_bit_follow_the_mapping_grant_and_never_HistoryWrite(bool granted)
{
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var read = await client.ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Neither,
[new ReadValueId { NodeId = anchor, AttributeId = Attributes.Historizing },
new ReadValueId { NodeId = anchor, AttributeId = Attributes.AccessLevel }], TestContext.Current.CancellationToken);
read.Results[0].WrappedValue.TryGetValue(out bool historizing).ShouldBeTrue();
historizing.ShouldBe(granted);
read.Results[1].WrappedValue.TryGetValue(out byte level).ShouldBeTrue();
((level & AccessLevels.HistoryRead) != 0).ShouldBe(granted);
(level & AccessLevels.HistoryWrite).ShouldBe((byte)0);
if (granted) return;
var result = await RawHistory(client, anchor, 3, default);
result.StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code);
originServer.Source.Calls.ShouldBe(0);
}, localPermissions: 15, allowHistory: granted, connectionSource: new PersistentConnections(origin));
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task A_Float32_node_whose_backend_returns_Double_reads_Good_through_the_projection_as_it_does_locally()
{
// H3 review: SQL backends store every float as a Double. The origin port normalises Raw / AtTime to the node's type
// (Single) before the wire, so the projected rows are Good Singles — never a BadTypeMismatch per row while local works.
await using var originServer = await HistoryOrigin.StartAsync(5, dataType: "Float", value: i => i + 0.5);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port, rawValueKind: DataValueKind.Float);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var raw = await RawHistory(client, anchor, 0, default);
StatusCode.IsGood(raw.StatusCode).ShouldBeTrue(raw.StatusCode.ToString());
var values = Values(raw);
values.Count.ShouldBe(5);
values.ShouldAllBe(v => StatusCode.IsGood(v.StatusCode));
values.Select(v => SdkValueBoundary.ToClr(v.WrappedValue)).ShouldBe(Enumerable.Range(0, 5).Select(i => (object?)(float)(i + 0.5)));
var details = new ReadAtTimeDetails { ReqTimes = [(DateTimeUtc)HistoryT0.AddSeconds(2)] };
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(details), TimestampsToReturn.Both, false,
[new HistoryReadValueId { NodeId = anchor }], TestContext.Current.CancellationToken);
var atTime = Values(response.Results.ToArray()!.Single()).ShouldHaveSingleItem();
StatusCode.IsGood(atTime.StatusCode).ShouldBeTrue(atTime.StatusCode.ToString());
SdkValueBoundary.ToClr(atTime.WrappedValue).ShouldBeOfType().ShouldBe(2.5f);
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin));
}
[Theory(Timeout = 90000)]
[Trait("Phase", "H3")]
[InlineData(HistoryMode.Hang)]
[InlineData(HistoryMode.Throw)]
public async Task A_history_call_that_never_answers_or_faults_fails_only_the_projected_half_and_releases_its_cursor(HistoryMode mode)
{
// H3 review D1: a deadline during the connection's capability probe used to escape as an RpcException and fault the
// whole HistoryRead. Now the projected half fails per node (BadTimeout when the deadline fired), the local half of the
// same batch is served, and the claimed origin cursor is released (positive control: the origin store returns to 0).
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
var connections = new HistorySwitchConnections(origin);
ProjectedHistoryAccess? history = null;
OtOpcUaNodeManager? manager = null;
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
manager!.HistorianDataSource = new SeriesSource(Enumerable.Range(0, 3)
.Select(i => new DataValueSnapshot(i, 0, HistoryT0.AddSeconds(i), HistoryT0.AddSeconds(i))).ToArray());
manager.EnsureVariable("Plant/LocalH", "Plant", "LocalH", "Int32", false, AddressSpaceRealm.Raw, historianTagname: "local");
var local = manager.TryGetVariable("Plant/LocalH", AddressSpaceRealm.Raw)!.NodeId;
var page = await RawHistory(client, anchor, 2, default);
page.ContinuationPoint.IsEmpty.ShouldBeFalse();
origin.Services.HistoryOpenContinuations.ShouldBe(1);
connections.Mode = mode;
manager.HistoryReadDeadline = TimeSpan.FromSeconds(1);
var response = await client.HistoryReadAsync(new RequestHeader { TimeoutHint = 20_000 }, new ExtensionObject(RawDetails(2)),
TimestampsToReturn.Both, false,
[new HistoryReadValueId { NodeId = local }, new HistoryReadValueId { NodeId = anchor, ContinuationPoint = page.ContinuationPoint }],
TestContext.Current.CancellationToken);
var results = response.Results.ToArray()!;
StatusCode.IsGood(results[0].StatusCode).ShouldBeTrue("the local half of the batch is still served");
Values(results[0]).Count.ShouldBe(2);
results[1].StatusCode.Code.ShouldBe(mode == HistoryMode.Hang ? StatusCodes.BadTimeout.Code : StatusCodes.BadContinuationPointInvalid.Code);
await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0);
origin.Services.HistoryOpenContinuations.ShouldBe(0, "the claimed cursor's origin continuation was released");
}, localPermissions: 15, allowHistory: true, connectionSource: connections, onHistory: (h, m) => { history = h; manager = m; });
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task A_group_larger_than_the_origin_batch_is_split_into_sub_batches()
{
// H3 review D4: three projected nodes against an origin that admits two items per request.
await using var originServer = await HistoryOrigin.StartAsync(7, extra: 2);
using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1, history: originServer.Port, maxBatchItems: 2);
var connections = new HistorySwitchConnections(origin) { BatchItems = 2 };
await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray();
children.Length.ShouldBe(3);
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(3)), TimestampsToReturn.Both, false,
children.Select(c => new HistoryReadValueId { NodeId = c }).ToArray(), TestContext.Current.CancellationToken);
var results = response.Results.ToArray()!;
results.ShouldAllBe(r => StatusCode.IsGood(r.StatusCode));
results.ShouldAllBe(r => Values(r).Count == 3);
connections.HistoryCallSizes.ShouldBe([2, 1]);
foreach (var r in results) await RawHistory(client, children[Array.IndexOf(results, r)], 3, r.ContinuationPoint);
// H3 review round 2: the batch size is the deployed connection's own — no separate capability probe (a cancelled
// probe put the gRPC connection into discovery backoff).
var before = Volatile.Read(ref connections.CapabilityCalls);
await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(3)), TimestampsToReturn.Both, false,
children.Select(c => new HistoryReadValueId { NodeId = c }).ToArray(), TestContext.Current.CancellationToken);
Volatile.Read(ref connections.CapabilityCalls).ShouldBe(before, "a projected history read sends no capability probe");
}, localPermissions: 15, allowHistory: true, connectionSource: connections);
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task The_assembly_budget_is_charged_in_request_order_across_groups()
{
// H3 review D7: request [A fresh, B resumed, C fresh] runs as two groups ({A, C} then {B}); with room for two nodes the
// refused one must be C — the last in REQUEST order — not B.
await using var originServer = await HistoryOrigin.StartAsync(7, extra: 2);
using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1, history: originServer.Port);
await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray();
children.Length.ShouldBe(3);
var first = await RawHistory(client, children[1], 3, default);
first.ContinuationPoint.IsEmpty.ShouldBeFalse();
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(3)), TimestampsToReturn.Both, false,
[new HistoryReadValueId { NodeId = children[0] }, new HistoryReadValueId { NodeId = children[1], ContinuationPoint = first.ContinuationPoint },
new HistoryReadValueId { NodeId = children[2] }], TestContext.Current.CancellationToken);
var results = response.Results.ToArray()!;
StatusCode.IsGood(results[0].StatusCode).ShouldBeTrue(results[0].StatusCode.ToString());
StatusCode.IsGood(results[1].StatusCode).ShouldBeTrue("the resumed node is second in request order: it fits");
results[2].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code);
Values(results[2]).ShouldBeEmpty();
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin),
configureMapping: m => m.MaxHistoryAssemblyBytesPerRequest = 2 * 3 * 288 + 100); // ≈ 288 B a value: two 3-value nodes fit
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task Releases_queued_while_a_flush_is_finishing_are_never_lost()
{
// H3 review D6: the flush used to be re-armed from Task.IsCompleted, so a token queued after its last check but before it
// completed waited for the NEXT release — or forever. Many concurrent enqueues must all reach the connection.
await using var originServer = await HistoryOrigin.StartAsync(1);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
var connections = new HistorySwitchConnections(origin);
ProjectedHistoryAccess? history = null;
await WithComposedServer(origin, origin.Raw, async (_, _, _, _, _, _, _) =>
{
const int count = 2000;
await Task.WhenAll(Enumerable.Range(0, 8).Select(t => Task.Run(() =>
{
for (var i = t; i < count; i += 8) history!.EnqueueReleaseForTests("link", BitConverter.GetBytes(i));
})));
var deadline = DateTime.UtcNow.AddSeconds(20);
while (connections.ReleasedTokens < count && DateTime.UtcNow < deadline)
{
await history!.FlushReleasesForTestsAsync();
await Task.Delay(10, TestContext.Current.CancellationToken);
}
connections.ReleasedTokens.ShouldBe(count);
}, localPermissions: 15, allowHistory: true, connectionSource: connections, onHistory: (h, _) => history = h);
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task A_retired_lease_is_not_a_timeout_and_a_fault_mid_answer_releases_the_new_origin_token()
{
// H3 review round 2 (5): a cancel that is neither the caller's nor the deadline (a lease retired by a redeploy) is
// BadContinuationPointInvalid for a resume / BadNoCommunication for a fresh node — never BadTimeout.
// (4): an exception mid-answer leaves no new origin token behind (positive control: the origin store returns to 0).
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
var connections = new HistorySwitchConnections(origin);
ProjectedHistoryAccess? history = null;
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var page = await RawHistory(client, anchor, 2, default);
connections.Mode = HistoryMode.Retired;
(await RawHistory(client, anchor, 2, page.ContinuationPoint)).StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
(await RawHistory(client, anchor, 2, default)).StatusCode.Code.ShouldBe(StatusCodes.BadNoCommunication.Code);
await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0);
origin.Services.HistoryOpenContinuations.ShouldBe(0);
connections.Mode = HistoryMode.Poison;
(await RawHistory(client, anchor, 2, default)).StatusCode.Code.ShouldBe(StatusCodes.BadNoCommunication.Code);
await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0);
origin.Services.HistoryOpenContinuations.ShouldBe(0, "the new origin token of the faulted answer was released");
}, localPermissions: 15, allowHistory: true, connectionSource: connections, onHistory: (h, _) => history = h);
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task Once_the_connection_reports_the_assembly_budget_spent_no_further_origin_call_is_made()
{
// H3 review round 2 (3): [A fresh, B resumed] is two calls; when the first comes back budget-refused, B is refused unsent.
await using var originServer = await HistoryOrigin.StartAsync(7, extra: 1);
using var origin = new LocalDataFixture(additionalRawNodes: 1, servingGeneration: 1, history: originServer.Port);
var connections = new HistorySwitchConnections(origin);
await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray();
var first = await RawHistory(client, children[1], 3, default);
connections.Mode = HistoryMode.BudgetRefused;
var calls = connections.HistoryCallSizes.Count;
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(3)), TimestampsToReturn.Both, false,
[new HistoryReadValueId { NodeId = children[0] }, new HistoryReadValueId { NodeId = children[1], ContinuationPoint = first.ContinuationPoint }],
TestContext.Current.CancellationToken);
response.Results.ToArray()!.ShouldAllBe(r => r.StatusCode.Code == StatusCodes.BadTooManyOperations.Code);
(connections.HistoryCallSizes.Count - calls).ShouldBe(1, "the second run is refused unsent");
}, localPermissions: 15, allowHistory: true, connectionSource: connections);
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task A_bad_answer_to_a_resume_releases_the_prior_origin_cursor()
{
// H3 review round 3 nit (b): the connection answered the resume Bad without sending it — the origin still holds page 1's
// cursor; the consumer releases it (positive control: the store returns to 0).
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
var connections = new HistorySwitchConnections(origin);
ProjectedHistoryAccess? history = null;
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var page = await RawHistory(client, anchor, 2, default);
origin.Services.HistoryOpenContinuations.ShouldBe(1);
connections.Mode = HistoryMode.RefuseResumedUnsent;
(await RawHistory(client, anchor, 2, page.ContinuationPoint)).StatusCode.Code.ShouldBe(StatusCodes.BadNoCommunication.Code);
await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0);
origin.Services.HistoryOpenContinuations.ShouldBe(0, "the unconsumed prior cursor was released");
connections.Mode = HistoryMode.Pass;
}, localPermissions: 15, allowHistory: true, connectionSource: connections, onHistory: (h, _) => history = h);
}
[Fact(Timeout = 90000)]
[Trait("Phase", "H3")]
public async Task An_origins_budget_refusal_is_a_per_node_answer_and_never_stops_the_request()
{
// H3 review round 3 (S4): the stop keys on the consumer's typed marker, not on "budget" in the diagnostic — the origin's
// "remainder budget is full" refusal of A must not refuse B (sent in the next run) nor a Good answer after it.
await using var originServer = await HistoryOrigin.StartAsync(7, extra: 1);
using var origin = new LocalDataFixture(additionalRawNodes: 1, servingGeneration: 1, history: originServer.Port);
var connections = new HistorySwitchConnections(origin);
await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray();
var first = await RawHistory(client, children[1], 3, default);
connections.Mode = HistoryMode.OriginRefusedFresh;
var calls = connections.HistoryCallSizes.Count;
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(3)), TimestampsToReturn.Both, false,
[new HistoryReadValueId { NodeId = children[0] }, new HistoryReadValueId { NodeId = children[1], ContinuationPoint = first.ContinuationPoint }],
TestContext.Current.CancellationToken);
var results = response.Results.ToArray()!;
results[0].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code, "the origin refused A");
StatusCode.IsGood(results[1].StatusCode).ShouldBeTrue("B is still read: an origin refusal is not a spent consumer budget");
Values(results[1]).Count.ShouldBeGreaterThan(0);
(connections.HistoryCallSizes.Count - calls).ShouldBe(2, "both runs are sent");
connections.Mode = HistoryMode.Pass;
}, localPermissions: 15, allowHistory: true, connectionSource: connections);
}
// ------------------------------------------------------------------------------------------------------------------
private static ReadRawModifiedDetails RawDetails(uint count) => new()
{
StartTime = HistoryT0.AddSeconds(-1), EndTime = HistoryT0.AddHours(1), NumValuesPerNode = count, IsReadModified = false, ReturnBounds = false,
};
private static async Task RawHistory(SessionClient client, NodeId node, uint count, ByteString cp)
{
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(count)), TimestampsToReturn.Both, false,
[new HistoryReadValueId { NodeId = node, ContinuationPoint = cp }], TestContext.Current.CancellationToken);
return response.Results.ToArray()!.Single();
}
private static async Task ProcessedHistory(SessionClient client, NodeId node, NodeId aggregate)
{
var details = new ReadProcessedDetails
{
StartTime = HistoryT0, EndTime = HistoryT0.AddMinutes(1), ProcessingInterval = 10_000, AggregateType = [aggregate],
AggregateConfiguration = new AggregateConfiguration { UseServerCapabilitiesDefaults = true },
};
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(details), TimestampsToReturn.Both, false,
[new HistoryReadValueId { NodeId = node }], TestContext.Current.CancellationToken);
return response.Results.ToArray()!.Single();
}
private static IReadOnlyList Values(Opc.Ua.HistoryReadResult result) =>
result.HistoryData.IsNull || ExtensionObject.ToEncodeable(result.HistoryData) is not HistoryData data ? [] : data.DataValues.ToArray() ?? [];
private static async Task AwaitReleases(ProjectedHistoryAccess history, Func done)
{
for (var i = 0; i < 200 && !done(); i++)
{
await history.FlushReleasesForTestsAsync();
if (!done()) await Task.Delay(10, TestContext.Current.CancellationToken);
}
}
public enum HistoryMode { Pass, Hang, Throw, Retired, Poison, BudgetRefused, OriginRefusedFresh, RefuseResumedUnsent }
///
/// One long-lived origin connection whose HISTORY path can be switched to never answer (then fault as a cancelled gRPC call,
/// as a probe cancelled by its deadline did) or to fault at once; releases always pass through and are counted.
///
private sealed class HistorySwitchConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource
{
private IDataConnection? _inner;
private readonly object _gate = new();
private int _released;
private readonly List _sizes = [];
public HistoryMode Mode { get; set; }
/// The deployed connection's own batch size the lease reports.
public int? BatchItems { get; set; }
public int CapabilityCalls;
public int ReleasedTokens => Volatile.Read(ref _released);
public IReadOnlyList HistoryCallSizes { get { lock (_sizes) return _sizes.ToArray(); } }
public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken)
{
if (connectionId != "link") return ValueTask.FromResult(null);
lock (_gate) _inner ??= peer.Connection();
return ValueTask.FromResult(new Borrowed(new Switch(_inner, this), _gate));
}
private sealed class Borrowed(IDataConnection connection, object route) : IGrpcDataAdapterConnectionLease
{
public IDataConnection Connection => connection;
public CancellationToken CancellationToken => CancellationToken.None;
public object? RouteIdentity => route;
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
private sealed class Switch(IDataConnection inner, HistorySwitchConnections owner) : IDataConnection, IDataHistoryService, IHistoryBatchLimit
{
public int MaxHistoryBatchItems => owner.BatchItems ?? ProjectedHistoryAccess.DefaultBatchItems;
public DataTarget Target => inner.Target;
public TimeProvider Clock => inner.Clock;
public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken)
{
Interlocked.Increment(ref owner.CapabilityCalls);
return inner.GetCapabilitiesAsync(budget, cancellationToken);
}
public Task BrowseAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest request, CancellationToken cancellationToken) => inner.BrowseAsync(request, cancellationToken);
public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => inner.GetMetadataAsync(request, cancellationToken);
public Task> ReadAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest request, CancellationToken cancellationToken) => inner.ReadAsync(request, cancellationToken);
public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => inner.WriteAsync(request, cancellationToken);
public Task SubscribeAsync(CancellationToken cancellationToken) => inner.SubscribeAsync(cancellationToken);
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
public async Task> ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken)
{
lock (owner._sizes) owner._sizes.Add(request.Items.Count);
switch (owner.Mode)
{
case HistoryMode.Hang:
try { await Task.Delay(Timeout.Infinite, cancellationToken); }
catch (OperationCanceledException ex)
{ throw new Grpc.Core.RpcException(new Grpc.Core.Status(Grpc.Core.StatusCode.Cancelled, "probe cancelled", ex)); }
break;
case HistoryMode.Throw:
throw new Grpc.Core.RpcException(new Grpc.Core.Status(Grpc.Core.StatusCode.Internal, "boom"));
case HistoryMode.Retired:
// A deployment lease retired by a redeploy: its scope token cancels, not the caller's.
throw new OperationCanceledException("lease retired");
case HistoryMode.BudgetRefused:
return request.Items.Select(i => new DataHistoryReadResult(i.CorrelationId, 0x80100000u, [], null,
"History assembly budget exceeded.") { ConsumerBudgetRefused = true }).ToArray();
case HistoryMode.RefuseResumedUnsent when request.Items.Any(i => i.Continuation is not null):
// Answered Bad without the origin ever seeing the resume: its cursor is still open there.
return request.Items.Select(i => new DataHistoryReadResult(i.CorrelationId, 0x80310000u, [], null)).ToArray();
case HistoryMode.OriginRefusedFresh when request.Items.All(i => i.Continuation is null):
// The ORIGIN's own refusal, whose text also mentions a budget (LocalDataServices.History).
return request.Items.Select(i => new DataHistoryReadResult(i.CorrelationId, 0x80100000u, [], null,
"Origin history remainder budget is full; retry with a lower NumValuesPerNode.")).ToArray();
}
var answers = await ((IDataHistoryService)inner).ReadAsync(request, cancellationToken);
if (owner.Mode == HistoryMode.Poison)
foreach (var answer in answers) if (answer.Samples.Count > 0) answer.Samples[^1].Dispose(); // faults the reader mid-answer
return answers;
}
public async Task ReleaseAsync(IReadOnlyList continuations, CancellationToken cancellationToken)
{
Interlocked.Add(ref owner._released, continuations.Count);
await ((IDataHistoryService)inner).ReleaseAsync(continuations, cancellationToken);
}
}
}
/// One long-lived origin connection, as a deployed gRPC connection is; replaces it (a redeploy).
private sealed class PersistentConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource
{
private (IDataConnection Connection, object Route)? _current;
private readonly object _gate = new();
public void Rotate()
{
lock (_gate)
{
if (_current is { } old) _ = old.Connection.DisposeAsync();
_current = null;
}
}
public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken)
{
if (connectionId != "link") return ValueTask.FromResult(null);
lock (_gate)
{
_current ??= (peer.Connection(), new object());
return ValueTask.FromResult(new Borrowed(_current.Value.Connection, _current.Value.Route));
}
}
private sealed class Borrowed(IDataConnection connection, object route) : IGrpcDataAdapterConnectionLease
{
public IDataConnection Connection => connection;
public CancellationToken CancellationToken => CancellationToken.None;
public object? RouteIdentity => route;
public ValueTask DisposeAsync() => ValueTask.CompletedTask; // non-owning, like a deployment lease
}
}
/// A real origin node manager with a historized raw Plant/Driver/Device/Speed behind a real history port.
private sealed class HistoryOrigin : IAsyncDisposable
{
private readonly OpcUaApplicationHost _host;
private readonly string _pki;
private readonly OtOpcUaNodeManager _nm;
public SeriesSource Source { get; }
public OriginHistoryPort Port { get; }
private HistoryOrigin(OpcUaApplicationHost host, string pki, OtOpcUaNodeManager nm, SeriesSource source)
{ _host = host; _pki = pki; _nm = nm; Source = source; Port = new OriginHistoryPort(nm); }
public static async Task StartAsync(int samples, int maxRawPerRead = 0, int extra = 0, string dataType = "Int32",
Func? value = null)
{
var pki = Path.Combine(Path.GetTempPath(), $"h3-origin-{Guid.NewGuid():N}");
var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions
{
ApplicationName = "H3Origin", ApplicationUri = $"urn:h3-origin:{Guid.NewGuid():N}", OpcUaPort = port,
PublicHostname = "127.0.0.1", PkiStoreRoot = pki, EnabledSecurityProfiles = [OpcUaSecurityProfile.None],
}, NullLogger.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken);
var nm = started.Server.NodeManager!;
var source = new SeriesSource(Enumerable.Range(0, samples)
.Select(i => new DataValueSnapshot(value?.Invoke(i) ?? i, 0, HistoryT0.AddSeconds(i), HistoryT0.AddSeconds(i))).ToArray()) { MaxRawValuesPerRead = maxRawPerRead };
nm.HistorianDataSource = source;
nm.EnsureVariable("Plant/Driver/Device/Speed", null, "Speed", dataType, false, AddressSpaceRealm.Raw, historianTagname: "speed");
nm.EnsureVariable("Plant/Driver/Device/Other", null, "Other", "Int32", false, AddressSpaceRealm.Raw);
for (var i = 0; i < extra; i++)
nm.EnsureVariable("Plant/Driver/Device/Speed" + i, null, "Speed" + i, "Int32", false, AddressSpaceRealm.Raw, historianTagname: "speed" + i);
return new HistoryOrigin(started.Host, pki, nm, source);
}
public void BumpEpoch() => _nm.RemoveVariableNode("Plant/Driver/Device/Other", AddressSpaceRealm.Raw).ShouldBeTrue();
public async ValueTask DisposeAsync()
{
await _host.DisposeAsync();
if (Directory.Exists(_pki)) try { Directory.Delete(_pki, recursive: true); } catch (IOException) { }
}
}
private sealed class SeriesSource(IReadOnlyList series) : IHistorianDataSource
{
private int _calls;
public int Calls => Volatile.Read(ref _calls);
public int MaxRawValuesPerRead { get; init; }
public IReadOnlySet Aggregates { get; set; } = HistoryAggregateTypes.All;
public IReadOnlySet SupportedAggregates => Aggregates;
public bool SupportsReverseRaw => true;
public Task ReadRawAsync(string fullReference, DateTime startUtc, DateTime endUtc, uint maxValuesPerNode,
CancellationToken cancellationToken)
{
Interlocked.Increment(ref _calls);
IEnumerable window = startUtc <= endUtc
? series.Where(s => s.SourceTimestampUtc >= startUtc && s.SourceTimestampUtc < endUtc)
: series.Where(s => s.SourceTimestampUtc <= startUtc && s.SourceTimestampUtc > endUtc).Reverse();
return Task.FromResult(new HistorianRead((maxValuesPerNode == 0 ? window : window.Take((int)maxValuesPerNode)).ToList(), null));
}
public Task ReadProcessedAsync(string fullReference, DateTime startUtc, DateTime endUtc, TimeSpan interval,
HistoryAggregateType aggregate, CancellationToken cancellationToken)
{
Interlocked.Increment(ref _calls);
return Task.FromResult(new HistorianRead([new DataValueSnapshot(3.0, 0, startUtc, startUtc)], null));
}
public Task ReadAtTimeAsync(string fullReference, IReadOnlyList timestampsUtc, CancellationToken cancellationToken)
{
Interlocked.Increment(ref _calls);
return Task.FromResult(new HistorianRead(timestampsUtc.Select(t => series.LastOrDefault(s => s.SourceTimestampUtc <= t)
?? new DataValueSnapshot(null, 0x809B0000u, t, t)).Select(s => s with { SourceTimestampUtc = s.SourceTimestampUtc }).ToList(), 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() { }
}
}