Merge master into #937 (scenarios: keep A09 + F937)

This commit is contained in:
Joseph Doherty
2026-11-28 11:32:41 -05:00
82 changed files with 5349 additions and 210 deletions
@@ -69,7 +69,7 @@ public sealed class GrpcDataHistoryWireTests
byId["Plant/Modbus/dev1/Speed"].History.Historizing.ShouldBeFalse();
(byId["Plant/Modbus/dev1/Speed"].AllowedOperations & 32u).ShouldBe(0u);
// Header-less: the golden (no Metadata.history, no bit 32).
(await origin.DriveAsync("GetMetadata", new Metadata())).ShouldBe(GrpcDataV1RealOriginGoldens.Responses["GetMetadata"]);
(await origin.DriveAsync("GetMetadata", new Metadata())).ShouldBe(GrpcDataV1RealOriginCorrections.Expected("GetMetadata"));
// A caller whose ACL lacks HistoryRead sees historizing=false on Flow: the same as an unhistorized node.
await using var denied = new RealOrigin(permissions: NodePermissions.Operator & ~NodePermissions.HistoryRead);
var deniedMeta = W.MetadataResponse.Parser.ParseFrom(Convert.FromHexString(await denied.DriveAsync("GetMetadata", History)));
@@ -64,12 +64,30 @@ public sealed class GrpcDataV1CompatibilityTests
Hex(V1Requests.Bytes(rpc)).ShouldBe(GrpcDataV1Goldens.Requests[rpc], $"recorded {rpc} request");
}
/// <summary>#916: the only correction of the fake-origin goldens is field 10, and the recording really carried it.</summary>
[Fact]
public void V1_correction_916_clears_only_stable_source_id()
{
foreach (var rpc in RpcNames.Where(r => r != "Subscribe"))
{
var golden = GrpcDataV1Goldens.Responses[rpc];
if (GrpcDataV1Corrections.Corrected.Contains(rpc))
{
GrpcDataV1Corrections.Expected(rpc).ShouldNotBe(golden, $"{rpc}: the recorded fake metadata carried field 10");
IMessage parsed = rpc == "Browse" ? W.BrowseResponse.Parser.ParseFrom(Convert.FromHexString(golden))
: W.MetadataResponse.Parser.ParseFrom(Convert.FromHexString(golden));
Hex(parsed.ToByteArray()).ShouldBe(golden, $"{rpc}: re-serialising a golden is byte-identical");
}
else GrpcDataV1Corrections.Expected(rpc).ShouldBe(golden);
}
}
[Theory]
[MemberData(nameof(Rpcs))]
public async Task V1_client_without_feature_header_gets_the_recorded_v1_response_bytes(string rpc)
{
var actual = await V1CompatibilityHarness.DriveAsync(rpc, new Metadata());
actual.ShouldBe(GrpcDataV1Goldens.Responses[rpc], $"{rpc} response diverged from the recorded v1 bytes");
actual.ShouldBe(GrpcDataV1Corrections.Expected(rpc), $"{rpc} response diverged from the recorded v1 bytes");
}
[Theory]
@@ -79,9 +97,9 @@ public sealed class GrpcDataV1CompatibilityTests
// H2 supports history, but this origin advertises none (and conditions are A2): the effective set is empty.
var headers = new Metadata { { "x-otopcua-data-features", "history,conditions" } };
var actual = await V1CompatibilityHarness.DriveAsync(rpc, headers, history: false, conditions: false);
actual.ShouldBe(GrpcDataV1Goldens.Responses[rpc], $"{rpc} response must not change when nothing requested is servable");
actual.ShouldBe(GrpcDataV1Corrections.Expected(rpc), $"{rpc} response must not change when nothing requested is servable");
(await V1CompatibilityHarness.DriveAsync(rpc, new Metadata { { "x-otopcua-data-features", "conditions" } }, conditions: false))
.ShouldBe(GrpcDataV1Goldens.Responses[rpc], $"{rpc}: conditions on an origin that cannot serve them change nothing");
.ShouldBe(GrpcDataV1Corrections.Expected(rpc), $"{rpc}: conditions on an origin that cannot serve them change nothing");
}
[Fact]
@@ -254,6 +272,39 @@ public sealed class GrpcDataV1CompatibilityTests
internal static IMessage Normalise(IMessage message) => message;
}
/// <summary>
/// #916 (pre-deploy, never re-recorded): <c>DataProtoMapper</c> no longer encodes <c>Metadata.stable_source_id</c>
/// (field 10), so the fake origin's metadata loses it on the wire. The expected bytes are the recorded golden with field 10
/// cleared on every Metadata of Browse and GetMetadata. That is the only edit. The real-origin variant has its own corrections
/// (<see cref="GrpcDataV1RealOriginCorrections"/>).
/// </summary>
internal static class GrpcDataV1Corrections
{
internal static readonly string[] Corrected = ["Browse", "GetMetadata"];
internal static string Expected(string rpc)
{
var golden = GrpcDataV1Goldens.Responses[rpc];
if (!Corrected.Contains(rpc)) return golden;
var bytes = Convert.FromHexString(golden);
IMessage corrected;
if (rpc == "Browse")
{
var response = W.BrowseResponse.Parser.ParseFrom(bytes);
foreach (var item in response.Items) item.ClearStableSourceId();
corrected = response;
}
else
{
var response = W.MetadataResponse.Parser.ParseFrom(bytes);
foreach (var item in response.Items) item.Value?.ClearStableSourceId();
corrected = response;
}
return Convert.ToHexString(corrected.ToByteArray());
}
}
/// <summary>The recorded v1 client requests. Changing any value here invalidates the goldens.</summary>
internal static class V1Requests
{
@@ -66,13 +66,53 @@ public sealed class GrpcDataV1RealOriginCompatibilityTests
Hex(RealOriginRequests.Bytes(scenario)).ShouldBe(GrpcDataV1RealOriginGoldens.Requests[scenario], $"recorded {scenario} request");
}
/// <summary>
/// #916/#917: the corrections are exact and not vacuous — an unedited golden re-serialises byte-identically, the
/// uncorrected scenarios are the raw goldens, the recorded UNS browse really leaked the driver id + RawPath, and the
/// corrected bytes carry neither the leak nor a value-bearing HighTemp.
/// </summary>
[Fact]
public void V1_corrections_916_917_are_exact_and_the_recorded_leak_was_real()
{
foreach (var scenario in RealOriginRequests.Scenarios.Where(s => s != "Subscribe"))
{
var golden = GrpcDataV1RealOriginGoldens.Responses[scenario];
IMessage parsed = scenario.Split('/')[0] switch
{
"GetCapabilities" => W.CapabilitiesResponse.Parser.ParseFrom(Convert.FromHexString(golden)),
"Browse" => W.BrowseResponse.Parser.ParseFrom(Convert.FromHexString(golden)),
"GetMetadata" => W.MetadataResponse.Parser.ParseFrom(Convert.FromHexString(golden)),
"Read" => W.ReadResponse.Parser.ParseFrom(Convert.FromHexString(golden)),
_ => W.WriteResponse.Parser.ParseFrom(Convert.FromHexString(golden)),
};
Hex(parsed.ToByteArray()).ShouldBe(golden, $"{scenario}: re-serialising a golden is byte-identical");
if (GrpcDataV1RealOriginCorrections.Corrected.Contains(scenario))
GrpcDataV1RealOriginCorrections.Expected(scenario).ShouldNotBe(golden, $"{scenario} carries a corrected field");
else
GrpcDataV1RealOriginCorrections.Expected(scenario).ShouldBe(golden);
}
var leak = Hex(System.Text.Encoding.UTF8.GetBytes("driver-1Plant/Modbus/dev1/"));
GrpcDataV1RealOriginGoldens.Responses["Browse/uns"].ShouldContain(leak, Case.Sensitive, "the recorded v1 UNS browse leaked it (#916)");
foreach (var scenario in GrpcDataV1RealOriginCorrections.Corrected)
GrpcDataV1RealOriginCorrections.Expected(scenario).ShouldNotContain(leak, Case.Sensitive);
var metadata = W.MetadataResponse.Parser.ParseFrom(Convert.FromHexString(GrpcDataV1RealOriginCorrections.Expected("GetMetadata")));
metadata.Items.Count(x => x.Status == (int)DataItemStatus.Unsupported).ShouldBe(1);
metadata.Items.ShouldNotContain(x => x.Value != null && x.Value.View.Address.Identifier == RealOriginRequests.HighTemp.Address.Identifier);
// HighTemp was in the recorded device page and is the only item the correction drops (positive control).
var recorded = W.BrowseResponse.Parser.ParseFrom(Convert.FromHexString(GrpcDataV1RealOriginGoldens.Responses["Browse"]));
var corrected = W.BrowseResponse.Parser.ParseFrom(Convert.FromHexString(GrpcDataV1RealOriginCorrections.Expected("Browse")));
recorded.Items.Select(x => x.View.Address.Identifier).Except(corrected.Items.Select(x => x.View.Address.Identifier))
.ShouldBe([RealOriginRequests.HighTemp.Address.Identifier]);
corrected.Items.Count.ShouldBe(recorded.Items.Count - 1);
}
[Theory]
[MemberData(nameof(Scenarios))]
public async Task V1_client_without_feature_header_gets_the_recorded_v1_response_bytes(string scenario)
{
await using var origin = new RealOrigin();
var actual = await origin.DriveAsync(scenario, new Metadata());
actual.ShouldBe(GrpcDataV1RealOriginGoldens.Responses[scenario], $"{scenario} response diverged from the recorded v1 bytes");
actual.ShouldBe(GrpcDataV1RealOriginCorrections.Expected(scenario), $"{scenario} response diverged from the recorded v1 bytes");
}
[Theory]
@@ -83,10 +123,10 @@ public sealed class GrpcDataV1RealOriginCompatibilityTests
// effective set is empty and the bytes are v1.
await using var origin = new RealOrigin(historian: false, conditions: false);
var actual = await origin.DriveAsync(scenario, new Metadata { { "x-otopcua-data-features", "history,conditions" } });
actual.ShouldBe(GrpcDataV1RealOriginGoldens.Responses[scenario], $"{scenario} response must not change when nothing requested is servable");
actual.ShouldBe(GrpcDataV1RealOriginCorrections.Expected(scenario), $"{scenario} response must not change when nothing requested is servable");
await using var conditionsOnly = new RealOrigin(conditions: false);
(await conditionsOnly.DriveAsync(scenario, new Metadata { { "x-otopcua-data-features", "conditions" } }))
.ShouldBe(GrpcDataV1RealOriginGoldens.Responses[scenario], $"{scenario}: conditions on an origin that cannot serve them change nothing");
.ShouldBe(GrpcDataV1RealOriginCorrections.Expected(scenario), $"{scenario}: conditions on an origin that cannot serve them change nothing");
}
[Fact]
@@ -219,6 +259,56 @@ public sealed class GrpcDataV1RealOriginCompatibilityTests
internal static IMessage Normalise(IMessage message) => message;
}
/// <summary>
/// The deliberate pre-deploy v1 corrections (#916, #917; v1 was merged but never deployed, #915). The goldens in
/// <see cref="GrpcDataV1RealOriginGoldens"/> are NOT re-recorded: the expected bytes are the recorded golden with exactly
/// these edits applied to its parsed message, and every other byte must still match. Re-serialising an unedited golden is
/// byte-identical (asserted), so the edit is the only difference. Nothing here changes the wire SHAPE — both corrections
/// use fields and values a v1 client already handles (an absent optional field; one item fewer in a page; the existing
/// per-item Unsupported status).
/// <list type="bullet">
/// <item><b>#916</b> — <c>Metadata.stable_source_id</c> is never sent (it was <c>&lt;len&gt;:&lt;driverInstanceId&gt;&lt;RawPath&gt;</c>, even on
/// UNS exports). Cleared on every Metadata of every Browse/GetMetadata response.</item>
/// <item><b>#917</b> — the alarm-bearing raw tag (HighTemp) is an unsupported value node: a Browse page no longer lists it
/// (every consumer build applies a page all-or-nothing and cannot materialise one), and a GetMetadata item for it is
/// <c>status = Unsupported</c> with no value and no lease.</item>
/// </list>
/// </summary>
internal static class GrpcDataV1RealOriginCorrections
{
internal static readonly string[] Corrected = ["Browse", "Browse/uns", "GetMetadata"];
internal static string Expected(string scenario)
{
var golden = GrpcDataV1RealOriginGoldens.Responses[scenario];
if (!Corrected.Contains(scenario)) return golden;
var bytes = Convert.FromHexString(golden);
var alarm = RealOriginRequests.HighTemp.Address.Identifier;
IMessage corrected;
if (scenario == "GetMetadata")
{
var response = W.MetadataResponse.Parser.ParseFrom(bytes);
foreach (var item in response.Items)
{
if (item.Value is null) continue;
if (item.Value.View.Address.Identifier == alarm && item.Value.View.Realm == (int)DataRealm.Raw)
{ item.Status = (int)DataItemStatus.Unsupported; item.Value = null; item.Lease = null; continue; }
item.Value.ClearStableSourceId();
}
corrected = response;
}
else
{
var response = W.BrowseResponse.Parser.ParseFrom(bytes);
var hidden = response.Items.Where(item => item.View.Address.Identifier == alarm && item.View.Realm == (int)DataRealm.Raw).ToArray();
foreach (var item in hidden) response.Items.Remove(item);
foreach (var item in response.Items) item.ClearStableSourceId();
corrected = response;
}
return GrpcDataV1RealOriginCompatibilityTests.Hex(corrected.ToByteArray());
}
}
/// <summary>The recorded v1 client requests against <see cref="RealOrigin"/>'s catalog. Changing any value invalidates the goldens.</summary>
internal static class RealOriginRequests
{
@@ -6,6 +6,8 @@ namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections;
/// NEVER re-record these to make a later phase (H2, A2, A3, ...) pass: a difference is a v1 wire regression of the
/// real origin, not a stale golden. A later phase extends <see cref="RealOrigin"/>'s snapshot with its new-shape data
/// and must still produce these exact bytes for a headerless (and, while unsupported, a feature-requesting) v1 call.
/// The only sanctioned differences are the pre-deploy corrections #916/#917, applied to these bytes (not re-recorded) by
/// <see cref="GrpcDataV1RealOriginCorrections"/>.
/// </summary>
internal static class GrpcDataV1RealOriginGoldens
{
@@ -2,6 +2,7 @@ using System.Security.Cryptography;
using System.Text.Json;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
@@ -45,7 +46,7 @@ public sealed class GrpcDataConditionPlacementTests
Devices = [new() { DeviceId = "device", DriverInstanceId = "driver-id-7f3", Name = "Device", DeviceConfig = "{}" }],
TagGroups = [new() { TagGroupId = "group", DeviceId = "device", Name = "Group" }],
Tags = [new() { TagId = "tag", DeviceId = "device", Name = "Speed", DataType = "Int32", AccessLevel = TagAccessLevel.ReadWrite, TagConfig = "{}" },
new() { TagId = "alarm-tag", DeviceId = "device", TagGroupId = "group", Name = "OverTemp", DataType = "Boolean", AccessLevel = TagAccessLevel.Read,
new() { TagId = "alarm-tag", DeviceId = "device", TagGroupId = "group", Name = "OverTemp", DataType = "Boolean", AccessLevel = TagAccessLevel.ReadWrite,
TagConfig = withAlarms ? AlarmConfig : "{}" }],
UnsAreas = [new() { UnsAreaId = "area-id", ClusterId = "cluster", Name = "Area" }],
UnsLines = [new() { UnsLineId = "line-id", UnsAreaId = "area-id", Name = "Line" }],
@@ -306,6 +307,83 @@ public sealed class GrpcDataConditionPlacementTests
listedNative.ShouldBeGreaterThan(20); // the generator really exercised native UNS placements
}
/// <summary>
/// #916: no exported metadata carries <c>stable_source_id</c> — a driver source's internal key is
/// <c>&lt;len&gt;:&lt;driverInstanceId&gt;&lt;RawPath&gt;</c>, so sending it told a UNS-only peer the origin's driver ids and
/// RawPaths. The internal <see cref="BackingSourceKey"/> is unchanged (positive control: it still holds both, so the
/// search below would see a leak). Checked on the encoded wire bytes of every node, every realm, 60 seeds.
/// </summary>
[Fact]
public void No_exported_metadata_carries_the_internal_source_key_916()
{
var checkedSources = 0;
for (var seed = 1; seed <= 60; seed++)
{
var (snapshot, rawPaths, driverIds, _) = Generate(seed);
using var fixture = new LocalDataFixture();
var catalog = LocalExportCatalog.Compile(snapshot, fixture.Serving, fixture.Activation.CaptureAuthority());
foreach (var node in catalog.Nodes)
{
node.Metadata.StableSourceId.ShouldBeNull($"seed {seed} {node.EntityKind} {node.EntityId}");
var wire = DataProtoMapper.EncodeMetadata(node.Metadata);
wire.HasStableSourceId.ShouldBeFalse();
if (node.Metadata.View.Realm != DataRealm.Uns) continue;
var text = wire.ToString();
foreach (var rawPath in rawPaths) text.ShouldNotContain(rawPath, Case.Sensitive, $"seed {seed}");
foreach (var driverId in driverIds) text.ShouldNotContain(driverId, Case.Sensitive, $"seed {seed}");
// Positive control: the internal key of a driver-backed UNS reference still names its driver and RawPath.
if (node.Source is { SourceKind: "driver" } source)
{
driverIds.ShouldContain(d => source.StableSourceId.Contains(d, StringComparison.Ordinal));
rawPaths.ShouldContain(r => source.StableSourceId.EndsWith(r, StringComparison.Ordinal));
checkedSources++;
}
}
}
checkedSources.ShouldBeGreaterThan(20); // the generator really produced driver-backed UNS references
}
/// <summary>
/// #917: an alarm-bearing raw tag gets no value (DriverHostActor keeps it out of the value fan-out, and #896 gives it
/// no UNS variable), so v1 compiles it as an unsupported value node: kind <c>UnsupportedVariable</c>, never writable
/// (the fixture tag is ReadWrite), Unsupported on every value operation, and NOT listed by Browse — never a Variable
/// that waits forever. Its condition placements (A1) are untouched. An export rooted at it still compiles (the
/// deploy is not broken) but grants nothing: its values are unsupported and its condition is not under the root.
/// </summary>
[Fact]
public void An_alarm_bearing_raw_tag_is_an_UnsupportedVariable_and_keeps_its_condition_placements_917()
{
using var fixture = new LocalDataFixture();
var catalog = LocalExportCatalog.Compile(Fixed(), fixture.Serving, fixture.Activation.CaptureAuthority());
var alarm = catalog.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "alarm-tag");
alarm.Supported.ShouldBeFalse();
alarm.Metadata.NodeKind.ShouldBe("UnsupportedVariable");
alarm.Metadata.ValueKind.ShouldBe(DataValueKind.Null);
alarm.Metadata.Writable.ShouldBeFalse();
// (Every value gate keys on Supported; the operations a caller sees are masked to Browse by LocalDataServices —
// pinned on the wire by GrpcDataV1RealOriginCompatibilityTests.)
// Positive controls: a plain tag is still a Variable, and the same tag without its alarm config is one too.
var speed = catalog.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "tag");
speed.Supported.ShouldBeTrue();
speed.Metadata.NodeKind.ShouldBe("Variable");
var plain = LocalExportCatalog.Compile(Fixed(withAlarms: false), fixture.Serving, fixture.Activation.CaptureAuthority())
.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "alarm-tag");
plain.Supported.ShouldBeTrue();
plain.Metadata.NodeKind.ShouldBe("Variable");
plain.Metadata.ValueKind.ShouldBe(DataValueKind.Boolean);
plain.Metadata.Writable.ShouldBeTrue(); // the same ReadWrite tag without its alarm IS writable
// Condition forwarding is unaffected: the Raw placement at its RawPath and both UNS placements remain.
catalog.PlacementsOf(new(AddressSpaceRealm.Raw, "Plant/Driver/Device/Group/OverTemp")).Count.ShouldBe(3);
catalog.ListConditions("raw-peer", LocalExportCatalog.RealmRoot("cluster", DataRealm.Raw), DataOperations.Subscribe,
ConditionKeys.FromSecret(Secret)).ShouldHaveSingleItem();
// A deployable export rooted at the alarm-bearing tag still compiles (the node is kept, not removed).
var b = Fixed();
Should.NotThrow(() => LocalExportCatalog.Compile(With(b, exports: [.. b.DataExports,
Export("tag-root", DataRealm.Raw, "tag-peer", rootKind: "RawTag", rootId: "alarm-tag")]), fixture.Serving, fixture.Activation.CaptureAuthority()));
}
private static (DraftSnapshot Snapshot, string[] RawPaths, string[] DriverIds, int ExpectedUnsNative) Generate(int seed)
{
var random = new Random(seed);
@@ -0,0 +1,276 @@
using Opc.Ua;
using Opc.Ua.Client;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using DataBrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest;
using DataReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest;
using DataReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
/// <summary>
/// #922 security-review round 1: on-demand renewal admission must not starve the unary budget (cold reads, writes, subscription
/// renewals), a batch of N lapsed nodes renews all N, a slow origin cannot pin SDK threads, and every refusal that is not a
/// lapse (a revoked lease, a revoked grant, a removed node) stays a refusal.
/// </summary>
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
{
[Fact(Timeout = 90000), Trait("Issue", "922")]
public async Task A_read_batch_of_several_lapsed_nodes_renews_every_node_not_only_the_first()
{
var ct = TestContext.Current.CancellationToken;
using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1);
var connections = new GatedConnections(origin);
await WithComposedServer(origin, origin.Root, async (session, _, resolver, _, access, _, 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);
origin.Clock.Advance(TimeSpan.FromSeconds(16));
var ids = children.Select(c => c.IdentifierAsString).ToArray();
ids.Count(id => resolver.TryResolveProjected(DataRealm.Raw, id, out var _1)).ShouldBe(0);
var read = await client.ReadAsync(new RequestHeader(), LongMaxAge, TimestampsToReturn.Both,
children.Select(c => new ReadValueId { NodeId = c, AttributeId = Attributes.Value }).ToArray(), ct);
read.Results.ToArray()!.ShouldAllBe(r => r.StatusCode.Code == StatusCodes.BadWaitingForInitialData.Code);
access.LapseRenewalsStartedForTests.ShouldBe(3, "every lapsed node in the batch is admitted for renewal");
for (var i = 0; i < 400 && !ids.All(id => resolver.TryResolveProjected(DataRealm.Raw, id, out _)); i++) await Task.Delay(25, ct);
ids.Count(id => resolver.TryResolveProjected(DataRealm.Raw, id, out var _2)).ShouldBe(3, "all three renewed, with no re-browse");
connections.BrowseCalls.ShouldBe(1);
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
}
[Fact(Timeout = 90000), Trait("Issue", "922")]
public async Task A_history_batch_of_several_lapsed_nodes_renews_and_serves_every_node()
{
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);
origin.Clock.Advance(TimeSpan.FromSeconds(16));
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), string.Join(", ", results.Select(r => r.StatusCode.ToString())));
results.ShouldAllBe(r => Values(r).Count == 3);
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin));
}
[Fact(Timeout = 90000), Trait("Issue", "922")]
public async Task A_renewal_in_flight_does_not_crowd_out_a_cold_read_of_another_node()
{
var ct = TestContext.Current.CancellationToken;
using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1);
var connections = new GatedConnections(origin);
await WithComposedServer(origin, origin.Root, async (session, _, _, _, access, _, anchor) =>
{
var client = (SessionClient)session;
var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray();
var (a, b) = (children[0], children[1]);
origin.Clock.Advance(TimeSpan.FromSeconds(16));
connections.HoldMetadataFor = a.IdentifierAsString;
(await ReadValue(client, a, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadWaitingForInitialData.Code);
await connections.Held.Task.WaitAsync(TimeSpan.FromSeconds(10), ct); // A's renewal is now parked at the origin
// Re-browse renews B (and A) by page; B's cold read must still be dispatched while A's renewal is in flight.
await BrowseAll(client, anchor, 10);
var reads = connections.ReadCalls;
(await ReadValue(client, b, ct)).StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code);
for (var i = 0; i < 200 && connections.ReadCalls == reads; i++) await Task.Delay(25, ct);
connections.ReadCalls.ShouldBeGreaterThan(reads, "an on-demand renewal holds no unary capacity");
connections.Release();
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
}
[Fact(Timeout = 90000), Trait("Issue", "922")]
public async Task An_invalidated_lease_is_a_refusal_not_a_lapse_and_never_reaches_the_origin()
{
var ct = TestContext.Current.CancellationToken;
using var origin = new LocalDataFixture(servingGeneration: 1);
origin.Publish(42);
var connections = new GatedConnections(origin);
await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, access, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
(await ReadUntilGood(client, anchor, ct)).ShouldBe(42);
resolver.TryResolveProjected(DataRealm.Raw, anchor.IdentifierAsString, out var proof).ShouldBeTrue();
((BoundProjectionLease)proof!.Lease).Remote.Invalidate();
var metadata = connections.MetadataCalls;
(await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
access.LapseRenewalsStartedForTests.ShouldBe(0, "a revoked lease is never renewed");
connections.MetadataCalls.ShouldBe(metadata);
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
}
[Fact(Timeout = 90000), Trait("Issue", "922")]
public async Task A_grant_revoked_while_the_renewal_is_at_the_origin_is_not_committed_and_the_read_is_denied()
{
var ct = TestContext.Current.CancellationToken;
using var origin = new LocalDataFixture(servingGeneration: 1);
origin.Publish(42);
var connections = new GatedConnections(origin);
LocalCatalogCoordinator? coordinator = null;
await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, access, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
origin.Clock.Advance(TimeSpan.FromSeconds(16));
connections.HoldMetadataFor = anchor.IdentifierAsString;
(await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadWaitingForInitialData.Code);
await connections.Held.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
Prepare(coordinator!, localPermissions: BrowseOnlyGrant); // the caller's Read grant is gone from now on
connections.Release();
for (var i = 0; i < 40; i++)
{
var value = await ReadValue(client, anchor, ct);
StatusCode.IsGood(value.StatusCode).ShouldBeFalse("nothing is served after the grant was revoked");
if (value.StatusCode.Code == StatusCodes.BadUserAccessDenied.Code) break;
await Task.Delay(50, ct);
}
(await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
resolver.TryResolveProjected(DataRealm.Raw, anchor.IdentifierAsString, out _).ShouldBeFalse("the renewal never committed");
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale, onCoordinator: value => coordinator = value);
}
[Fact(Timeout = 90000), Trait("Issue", "922")]
public async Task A_node_whose_mapping_is_removed_while_it_renews_is_not_revived()
{
var ct = TestContext.Current.CancellationToken;
using var origin = new LocalDataFixture(servingGeneration: 1);
origin.Publish(42);
var connections = new GatedConnections(origin);
await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
origin.Clock.Advance(TimeSpan.FromSeconds(16));
connections.HoldMetadataFor = anchor.IdentifierAsString;
(await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadWaitingForInitialData.Code);
await connections.Held.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
resolver.ApplyMappings([]); // the mapping goes away mid-renewal
connections.Release();
await Task.Delay(300, ct);
resolver.TryResolveProjected(DataRealm.Raw, anchor.IdentifierAsString, out _).ShouldBeFalse();
resolver.TryResolveForRenewal(DataRealm.Raw, anchor.IdentifierAsString, out _).ShouldBeFalse();
var value = await ReadValue(client, anchor, ct);
StatusCode.IsGood(value.StatusCode).ShouldBeFalse();
value.StatusCode.Code.ShouldNotBe(StatusCodes.BadWaitingForInitialData.Code, "a removed node is not a lapse");
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
}
[Fact(Timeout = 90000), Trait("Issue", "922")]
public async Task Concurrent_history_reads_against_a_slow_origin_are_bounded_and_retryable_and_recover()
{
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
var connections = new GatedConnections(origin);
OtOpcUaNodeManager? manager = null;
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
origin.Clock.Advance(TimeSpan.FromSeconds(16));
connections.HoldMetadataFor = anchor.IdentifierAsString; // the origin never answers the renewal until released
var clock = System.Diagnostics.Stopwatch.StartNew();
async Task<(Opc.Ua.HistoryReadResult Result, TimeSpan Took)> Timed()
{
var each = System.Diagnostics.Stopwatch.StartNew();
var result = await RawHistory(client, anchor, 3, default);
return (result, each.Elapsed);
}
var reads = Enumerable.Range(0, 24).Select(_ => Timed()).ToArray();
var all = Task.WhenAll(reads);
// Every waiter is bounded (a non-local history slot, then at most the lapse wait) — none is pinned until the origin
// answers, which it never does while held.
(await Task.WhenAny(all, Task.Delay(TimeSpan.FromSeconds(30), TestContext.Current.CancellationToken))).ShouldBe(all,
"every concurrent HistoryRead returned while the origin was still silent");
clock.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(30));
var statuses = all.Result.Select(r => r.Result.StatusCode.Code).ToArray();
// Waiters are capped by the non-local history slots: the reads that found none answer at once instead of each pinning
// an SDK thread for the whole lapse wait (the pre-review code made all 24 wait it out).
var slots = OriginHistoryPort.RemoteSlots(manager!.MaxConcurrentHistoryReadBatches);
all.Result.Count(r => r.Took < TimeSpan.FromSeconds(2.5)).ShouldBeGreaterThanOrEqualTo(24 - slots,
string.Join(", ", all.Result.Select(r => r.Took.TotalMilliseconds.ToString("0"))));
statuses.ShouldAllBe(code => code == StatusCodes.BadResourceUnavailable.Code, "granted + lapsed + silent origin ⇒ retryable");
originServer.Source.Calls.ShouldBe(0);
connections.Release();
Opc.Ua.HistoryReadResult? served = null;
for (var i = 0; i < 40; i++)
{
served = await RawHistory(client, anchor, 3, default);
if (StatusCode.IsGood(served.StatusCode)) break;
origin.Clock.Advance(ProjectedDataAccess.LapseRenewalBackoff + TimeSpan.FromMilliseconds(1));
await Task.Delay(50, TestContext.Current.CancellationToken);
}
StatusCode.IsGood(served!.StatusCode).ShouldBeTrue(served.StatusCode.ToString());
}, localPermissions: 15, allowHistory: true, connectionSource: connections, onHistory: (_, nm) => manager = nm);
}
/// <summary>One persistent origin connection whose metadata call for one node can be parked; counts browse/metadata/read calls.</summary>
private sealed class GatedConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource
{
private IDataConnection? _inner;
private readonly object _gate = new();
private readonly object _route = new();
private int _browse, _metadata, _read;
private TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
public int BrowseCalls => Volatile.Read(ref _browse);
public int MetadataCalls => Volatile.Read(ref _metadata);
public int ReadCalls => Volatile.Read(ref _read);
/// <summary>The projected local identifier whose origin metadata call is parked until <see cref="Release"/>.</summary>
public volatile string? HoldMetadataFor;
public TaskCompletionSource Held { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public void Release() { HoldMetadataFor = null; _release.TrySetResult(); }
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken)
{
if (connectionId != "link") return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(null);
lock (_gate) _inner ??= peer.Connection();
return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(new Borrowed(new Gate(_inner, this), _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;
}
private sealed class Gate(IDataConnection inner, GatedConnections owner) : IDataConnection, IDataHistoryService
{
public DataTarget Target => inner.Target;
public TimeProvider Clock => inner.Clock;
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => inner.GetCapabilitiesAsync(budget, cancellationToken);
public Task<DataBrowseBranch> BrowseAsync(DataBrowseRequest request, CancellationToken cancellationToken)
{ Interlocked.Increment(ref owner._browse); return inner.BrowseAsync(request, cancellationToken); }
public async Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken)
{
Interlocked.Increment(ref owner._metadata);
if (owner.HoldMetadataFor is { } held && request.Views.Any(view =>
ProjectedDataIds.Identifier("map", view.Address) == held))
{
owner.Held.TrySetResult();
await owner._release.Task.WaitAsync(cancellationToken);
}
return await inner.GetMetadataAsync(request, cancellationToken);
}
public Task<IReadOnlyList<DataReadResult>> ReadAsync(DataReadRequest request, CancellationToken cancellationToken)
{ Interlocked.Increment(ref owner._read); return inner.ReadAsync(request, cancellationToken); }
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => inner.WriteAsync(request, cancellationToken);
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken) => inner.SubscribeAsync(cancellationToken);
public Task<IReadOnlyList<DataHistoryReadResult>> ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) =>
((IDataHistoryService)inner).ReadAsync(request, cancellationToken);
public Task ReleaseAsync(IReadOnlyList<byte[]> continuations, CancellationToken cancellationToken) =>
((IDataHistoryService)inner).ReleaseAsync(continuations, cancellationToken);
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}
}
@@ -0,0 +1,250 @@
using Opc.Ua;
using Opc.Ua.Client;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using DataBrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest;
using DataReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest;
using DataReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
/// <summary>
/// #922 — a projected node idle longer than its <c>MetadataLeaseMilliseconds</c> (15 s here) is a LAPSE, not an
/// authorization failure: a value Read answers a retryable status and renews the lease on demand (no re-browse), a
/// HistoryRead renews it within the request's deadline and is served, and a re-browse served from a still-cached page
/// renews a lease that is past half its life. A real ACL denial stays <c>BadUserAccessDenied</c> after a lapse too, and
/// never reaches the origin.
/// </summary>
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
{
private const int BrowseOnlyGrant = 1;
// The fixture origin observes its one sample at t0 and never again, so the sample's ORIGIN age grows with the manual clock:
// a stale timeout and a client maxAge longer than the test's idle gaps keep that age out of what is under test (the lease).
private const int LongStale = 120_000;
private const double LongMaxAge = 120_000;
[Fact(Timeout = 90000), Trait("Issue", "922")]
public async Task A_value_read_after_the_metadata_lease_lapses_is_retryable_and_renews_on_demand_without_a_browse()
{
var ct = TestContext.Current.CancellationToken;
using var origin = new LocalDataFixture(servingGeneration: 1);
origin.Publish(42);
var connections = new CountingConnections(origin);
await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
(await ReadUntilGood(client, anchor, ct)).ShouldBe(42);
var browses = connections.BrowseCalls;
var metadata = connections.MetadataCalls;
origin.Clock.Advance(TimeSpan.FromSeconds(16));
var id = ProjectedDataIds.Identifier("map", origin.Raw.Address);
resolver.TryResolveProjected(DataRealm.Raw, id, out _).ShouldBeFalse("precondition: the lease has lapsed");
// A non-Value attribute of the lapsed node is not access-denied either (retryable while the lease renews).
var name = (await client.ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Neither,
[new ReadValueId { NodeId = anchor, AttributeId = Attributes.DisplayName }], ct)).Results[0];
name.StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code);
var lapsed = await ReadValue(client, anchor, ct);
lapsed.StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code, "a lease lapse is not an authorization failure");
// The attribute read above already started the renewal, which may have finished (and fetched the value) by now.
(StatusCode.IsGood(lapsed.StatusCode) || lapsed.StatusCode.Code == StatusCodes.BadWaitingForInitialData.Code ||
lapsed.StatusCode.Code == StatusCodes.BadResourceUnavailable.Code).ShouldBeTrue(lapsed.StatusCode.ToString());
(await ReadUntilGood(client, anchor, ct)).ShouldBe(42);
resolver.TryResolveProjected(DataRealm.Raw, id, out _).ShouldBeTrue("the read renewed the node's authority");
connections.BrowseCalls.ShouldBe(browses, "the renewal is an exact metadata refresh, not a re-browse");
connections.MetadataCalls.ShouldBeGreaterThan(metadata, "renewed by an exact metadata call");
// And again: every idle gap longer than the lease renews the same way.
origin.Clock.Advance(TimeSpan.FromSeconds(16));
(await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadWaitingForInitialData.Code);
(await ReadUntilGood(client, anchor, ct)).ShouldBe(42);
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
}
[Fact(Timeout = 90000), Trait("Issue", "922")]
public async Task Without_the_local_read_grant_a_lapsed_value_read_is_still_BadUserAccessDenied_and_never_renews()
{
var ct = TestContext.Current.CancellationToken;
using var origin = new LocalDataFixture(servingGeneration: 1);
origin.Publish(42);
var connections = new CountingConnections(origin);
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, access, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
// Positive control: before the lapse the same caller is refused for the ACL, not the lease.
(await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
origin.Clock.Advance(TimeSpan.FromSeconds(16));
var metadata = connections.MetadataCalls;
for (var i = 0; i < 3; i++)
(await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
await Task.Delay(200, ct);
connections.MetadataCalls.ShouldBe(metadata, "an unauthorized caller never triggers a renewal at the origin");
connections.ReadCalls.ShouldBe(0);
// Counted synchronously when a renewal is admitted, so this absence is not a race with a background task.
access.LapseRenewalsStartedForTests.ShouldBe(0);
}, connectionSource: connections, localPermissions: BrowseOnlyGrant);
}
[Fact(Timeout = 90000), Trait("Issue", "922")]
public async Task A_history_read_after_the_metadata_lease_lapses_renews_within_the_request_and_is_served()
{
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);
StatusCode.IsGood((await RawHistory(client, anchor, 3, default)).StatusCode).ShouldBeTrue();
origin.Clock.Advance(TimeSpan.FromSeconds(16));
var lapsed = await RawHistory(client, anchor, 3, default);
lapsed.StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code, "a lease lapse is not an authorization failure");
StatusCode.IsGood(lapsed.StatusCode).ShouldBeTrue(lapsed.StatusCode.ToString());
Values(lapsed).Count.ShouldBe(3);
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin));
}
[Fact(Timeout = 90000), Trait("Issue", "922")]
public async Task A_lapsed_history_read_whose_renewal_cannot_reach_the_origin_is_retryable_not_denied_and_recovers()
{
await using var originServer = await HistoryOrigin.StartAsync(7);
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
var connections = new DownableConnections(new PersistentConnections(origin));
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
origin.Clock.Advance(TimeSpan.FromSeconds(16));
connections.Down = true;
var calls = originServer.Source.Calls;
var down = await RawHistory(client, anchor, 3, default);
down.StatusCode.Code.ShouldBe(StatusCodes.BadResourceUnavailable.Code, "granted, lapsed, origin unreachable: retryable");
originServer.Source.Calls.ShouldBe(calls, "nothing is read under a lapsed lease");
connections.Down = false;
origin.Clock.Advance(ProjectedDataAccess.LapseRenewalBackoff + TimeSpan.FromMilliseconds(1)); // past the failure back-off
var recovered = await RawHistory(client, anchor, 3, default);
StatusCode.IsGood(recovered.StatusCode).ShouldBeTrue(recovered.StatusCode.ToString());
}, localPermissions: 15, allowHistory: true, connectionSource: connections);
}
[Fact(Timeout = 90000), Trait("Issue", "922")]
public async Task Without_the_local_history_grant_a_lapsed_history_read_is_still_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);
origin.Clock.Advance(TimeSpan.FromSeconds(16));
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("Issue", "922")]
public async Task A_rebrowse_served_from_a_cached_page_past_half_its_lease_renews_the_lease()
{
var ct = TestContext.Current.CancellationToken;
using var origin = new LocalDataFixture(servingGeneration: 1);
origin.Publish(42);
var connections = new CountingConnections(origin);
await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, _, _, anchor) =>
{
var client = (SessionClient)session;
var id = ProjectedDataIds.Identifier("map", origin.Raw.Address);
await BrowseAll(client, anchor, 1);
var browses = connections.BrowseCalls;
// Inside the first half the cached page is served as is (no origin call).
origin.Clock.Advance(TimeSpan.FromSeconds(5));
await BrowseAll(client, anchor, 1);
await Task.Delay(200, ct);
connections.BrowseCalls.ShouldBe(browses, "a fresh cached page is served without an origin call");
// Past half its life the cached page is still served, and the re-browse refreshes it in the background.
origin.Clock.Advance(TimeSpan.FromSeconds(5));
await BrowseAll(client, anchor, 1);
for (var i = 0; i < 200 && connections.BrowseCalls == browses; i++) await Task.Delay(25, ct);
connections.BrowseCalls.ShouldBeGreaterThan(browses, "the re-browse refreshed the cached page");
// The original lease (t0 + 15 s) is gone; the renewed one still holds at t0 + 20 s.
ProjectedNodeProof? renewed = null;
for (var i = 0; i < 200; i++)
{
if (resolver.TryResolveProjected(DataRealm.Raw, id, out renewed) && renewed is not null &&
((BoundProjectionLease)renewed.Lease).Remaining > TimeSpan.FromSeconds(10)) break;
await Task.Delay(25, ct);
}
origin.Clock.Advance(TimeSpan.FromSeconds(10));
resolver.TryResolveProjected(DataRealm.Raw, id, out _).ShouldBeTrue("the re-browse renewed the node's lease");
(await ReadUntilGood(client, anchor, ct)).ShouldBe(42);
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
}
private static async Task<Opc.Ua.DataValue> ReadValue(SessionClient client, NodeId node, CancellationToken ct) =>
(await client.ReadAsync(new RequestHeader(), LongMaxAge, TimestampsToReturn.Both,
[new ReadValueId { NodeId = node, AttributeId = Attributes.Value }], ct)).Results[0];
private static async Task<object?> ReadUntilGood(SessionClient client, NodeId node, CancellationToken ct)
{
var deadline = DateTime.UtcNow.AddSeconds(10);
Opc.Ua.DataValue value;
do
{
value = await ReadValue(client, node, ct);
if (StatusCode.IsGood(value.StatusCode)) return value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy);
value.StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code);
await Task.Delay(25, ct);
} while (DateTime.UtcNow < deadline);
throw new ShouldAssertException($"the projected read never became Good (last {value.StatusCode})");
}
/// <summary>A connection source that can be switched to "no connection" (an unreachable origin / undeployed route).</summary>
private sealed class DownableConnections(IGrpcDataAdapterConnectionSource inner) : IGrpcDataAdapterConnectionSource
{
public volatile bool Down;
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken) =>
Down ? ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(null) : inner.AcquireAsync(connectionId, cancellationToken);
}
/// <summary>Like <c>FakeConnections</c>, counting browse, metadata and read calls separately.</summary>
private sealed class CountingConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource
{
private int _browse, _metadata, _read;
public int BrowseCalls => Volatile.Read(ref _browse);
public int MetadataCalls => Volatile.Read(ref _metadata);
public int ReadCalls => Volatile.Read(ref _read);
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken) =>
ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(connectionId == "link" ? new Lease(new Connection(peer.Connection(), this)) : null);
private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease
{
public IDataConnection Connection => connection;
public CancellationToken CancellationToken => CancellationToken.None;
public ValueTask DisposeAsync() => connection.DisposeAsync();
}
private sealed class Connection(IDataConnection inner, CountingConnections owner) : IDataConnection
{
public DataTarget Target => inner.Target;
public TimeProvider Clock => inner.Clock;
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => inner.GetCapabilitiesAsync(budget, cancellationToken);
public Task<DataBrowseBranch> BrowseAsync(DataBrowseRequest request, CancellationToken cancellationToken)
{ Interlocked.Increment(ref owner._browse); return inner.BrowseAsync(request, cancellationToken); }
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken)
{ Interlocked.Increment(ref owner._metadata); return inner.GetMetadataAsync(request, cancellationToken); }
public Task<IReadOnlyList<DataReadResult>> ReadAsync(DataReadRequest request, CancellationToken cancellationToken)
{ Interlocked.Increment(ref owner._read); return inner.ReadAsync(request, cancellationToken); }
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => inner.WriteAsync(request, cancellationToken);
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken) => inner.SubscribeAsync(cancellationToken);
public ValueTask DisposeAsync() => inner.DisposeAsync();
}
}
}
@@ -33,6 +33,43 @@ public sealed class GrpcDataLocalConnectionTests
expired.Items.ShouldBeEmpty();
}
/// <summary>
/// #917 review: Browse skips unsupported value nodes across page boundaries. With a page size of 2 and children
/// <c>[Speed, u, u, u, v, u, v]</c>, every supported child appears exactly once, no unsupported one appears, the walk
/// completes, and no page is empty: a skipped node does not count against the page's scan bound, so the skip
/// never produces an empty <c>Complete = false</c> page.
/// </summary>
[Fact]
public async Task Browse_skips_unsupported_value_nodes_across_page_boundaries_917()
{
using var fixture = new LocalDataFixture(siblingPattern: "uuuvuv");
await using var connection = fixture.Connection();
var budget = LocalDataFixture.Budget with { MaxItems = 2 };
var seen = new List<string>();
var pages = 0;
string? continuation = null;
while (true)
{
var page = await connection.BrowseAsync(new(fixture.Root, null, continuation, budget), TestContext.Current.CancellationToken);
page.Status.ShouldBe(DataItemStatus.Good);
page.Items.ShouldNotBeEmpty($"page {pages}");
page.Items.Count.ShouldBeLessThanOrEqualTo(2);
seen.AddRange(page.Items.Select(x => x.BrowseName));
pages++;
if (page.Complete) { page.Continuation.ShouldBeNull(); break; }
page.Continuation.ShouldNotBeNull();
continuation = page.Continuation;
pages.ShouldBeLessThan(10);
}
seen.ShouldBe(["Speed", "c3", "c5"]);
pages.ShouldBe(2);
// Positive control: the unsupported siblings are in the catalog and addressable (Unsupported, not NotFound).
fixture.Catalog.Nodes.Count(n => !n.Supported).ShouldBe(4);
var metadata = await connection.GetMetadataAsync(new([fixture.Root with { Address = fixture.Root.Address with { Identifier = "Plant/c0" },
Subject = "Plant/c0" }], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
metadata.ShouldHaveSingleItem().Status.ShouldBe(DataItemStatus.Unsupported);
}
[Fact]
public async Task Metadata_bootstrap_resolves_address_and_never_uses_the_claimed_subject_as_authority()
{
@@ -136,7 +173,8 @@ internal sealed class LocalDataFixture : IDisposable
bool advanceAuthority = false, string role = "Primary", long servingGeneration = 0, bool nestedCatalog = false, bool nestedUnsCatalog = false,
Func<DataAuthenticatedContext, IDataWriteService>? writes = null, bool denyReadExport = false,
ManualTimeProvider? clock = null, string servingNode = "node-a", string servingIncarnation = "serving-1",
IOriginHistoryPort? history = null, DataValueKind rawValueKind = DataValueKind.Int32, int maxBatchItems = 100)
IOriginHistoryPort? history = null, DataValueKind rawValueKind = DataValueKind.Int32, int maxBatchItems = 100,
string? siblingPattern = null)
{
if (clock is not null) Clock = clock;
Serving = Serving with { NodeId = servingNode, Incarnation = servingIncarnation, Role = role, ServingGeneration = servingGeneration };
@@ -191,6 +229,17 @@ internal sealed class LocalDataFixture : IDisposable
nodes.Add(new("RawTag", "extra-" + i, rawMetadata with { View = view, BrowseName = "Speed" + i },
new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Driver", "Device", "Speed" + i] }, Root, Ticket.Key));
}
// #917: "u" = an unsupported value node (as an alarm-bearing tag compiles), "v" = a supported one, named c0, c1, ...
// in order (they sort after "Speed"), all under Root.
for (var i = 0; i < (siblingPattern?.Length ?? 0); i++)
{
var name = "c" + i.ToString(System.Globalization.CultureInfo.InvariantCulture);
var view = Raw with { Address = Raw.Address with { Identifier = "Plant/" + name }, Subject = "Plant/" + name };
var supported = siblingPattern![i] == 'v';
nodes.Add(new("RawTag", "sibling-" + name, supported ? rawMetadata with { View = view, BrowseName = name }
: rawMetadata with { View = view, BrowseName = name, NodeKind = "UnsupportedVariable", ValueKind = DataValueKind.Null, Writable = false },
new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", name] }, Root, Ticket.Key, Supported: supported));
}
Catalog = new LocalExportCatalog("cluster", Serving, Activation.CaptureAuthority(), nodes,
[new() { DataExportId = "raw-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw, RootKind = "RawFolder", RootEntityId = "folder", PrincipalId = "peer", AllowedOperations = operations },
new() { DataExportId = "uns-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = nestedUnsCatalog ? "UnsArea" : "UnsTagReference", RootEntityId = nestedUnsCatalog ? "area" : "reference", PrincipalId = "peer", AllowedOperations = operations }]);
@@ -56,6 +56,21 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
var item = keys.Cast<object>().OfType<Opc.Ua.Server.MonitoredItem>().Single(x => x.ClientHandle == 1);
var candidates = (System.Collections.IEnumerable)item.GetType().GetField("_candidates", flags)!.GetValue(item)!;
candidates.Cast<object>().Count().ShouldBe(scenario is "ambiguous" or "missing_timestamp" ? 2 : 1);
// #920: SDK 2.0.1 delivers a node change to its items asynchronously (MonitoredNode2's channel), so the
// sample published above can reach this item AFTER the mode cycle below — and, at queue size 1, overwrite
// the injected notification with the genuinely proven sample. Wait until the SDK has queued it, so the
// mode cycle discards it and the injected notification is the one delivered. (With two publishes the
// second may still be in flight; it is ambiguous against both candidates and denied either way.)
var lastValue = typeof(Opc.Ua.Server.MonitoredItem).GetField("m_lastValue", flags).ShouldNotBeNull();
var delivered = System.Diagnostics.Stopwatch.StartNew();
// The baseline sample shares the fake clock's timestamp, so match the status too.
static bool IsPublishedSample(Opc.Ua.DataValue value, DateTime at) =>
value.SourceTimestamp == (DateTimeUtc)at && value.StatusCode == StatusCodes.BadNoCommunication;
while (!IsPublishedSample((Opc.Ua.DataValue)lastValue.GetValue(item)!, timestamp))
{
delivered.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(10), "the SDK never queued the published sample");
await Task.Delay(10, ct);
}
item.SetMonitoringMode(MonitoringMode.Disabled);
if (scenario == "different_status")
{
@@ -111,6 +111,75 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
});
}
/// <summary>
/// #920: a subscription demand disposed while its stream pump is publishing the snapshot it asked for (a failed
/// SDK item construction disposes it on the SDK thread) must not re-publish the already-published, still-fresh
/// acquisition as a new complete baseline. It did: the duplicate-baseline check read the dying demand's validity
/// as "the cache is not fresh", so the same acquisition reached every existing item on the node again and left an
/// orphan proof candidate (and its shared budget charge) on each — no SDK notification ever consumes it, because
/// the node's value did not change.
/// </summary>
[Fact(Timeout = 90000), Trait("Phase", "P11Wire")]
public async Task A_demand_disposed_mid_publish_does_not_republish_a_fresh_baseline()
{
var ct = TestContext.Current.CancellationToken;
LocalDataFixture? peer = null;
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions);
peer = origin; subscriptions.SampleClock = origin.Clock;
var published = Channel.CreateUnbounded<ProjectedValueUpdate>();
await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, access, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
IProjectedDemandLease? first = null;
var armed = 0;
var disposed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
access.AfterPublishDemandCheckForTests = demand =>
{
first ??= demand;
if (ReferenceEquals(demand, first) || Interlocked.Exchange(ref armed, 0) != 1) return;
demand.Dispose();
disposed.TrySetResult();
};
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
await AddComposedItem(client, sub, anchor, 1, 100, ct);
await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
(await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.SourceVersion == 1, ct)).Snapshot.Value.ShouldBe(7);
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!;
var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!;
var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!;
var existing = keys.Cast<object>().OfType<Opc.Ua.Server.MonitoredItem>().Single(x => x.ClientHandle == 1);
int Candidates() => ((System.Collections.IEnumerable)existing.GetType().GetField("_candidates", flags)!.GetValue(existing)!).Cast<object>().Count();
Candidates().ShouldBe(0, "the delivered baseline consumed its candidate");
// A second item on the same node: its stream snapshot repeats the same (still fresh) acquisition, and its
// demand is disposed on the pump right after the publish passed its demand check.
Volatile.Write(ref armed, 1);
await AddComposedItem(client, sub, anchor, 2, 100, ct);
var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
await disposed.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
// The pump handles the removal only after it finished that publish, so the publish is over once it is sent.
var removed = System.Diagnostics.Stopwatch.StartNew();
while (stream.RemoveCommands == 0)
{
removed.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(10), "the disposed demand's item was never removed");
await Task.Delay(10, ct);
}
// Positive control: a third item's snapshot carries a NEW acquisition (v2) through the same in-order publisher.
subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8;
await AddComposedItem(client, sub, anchor, 3, 100, ct);
var seen = new List<ProjectedValueUpdate>();
ProjectedValueUpdate next;
do { next = await NextPublished(published.Reader, _ => true, ct); seen.Add(next); } while (next.SourceVersion != 2);
seen.Count(x => x.SourceVersion == 1).ShouldBe(0, "the disposed demand re-published the fresh v1 baseline");
Candidates().ShouldBe(1, "only the v2 baseline holds a candidate on the existing item");
}, onPublished: update => published.Writer.TryWrite(update));
}
private sealed class ThrowingSourceProof(IProjectedSamplePublicationProof inner) : IProjectedSamplePublicationProof
{
public bool IsValid => inner.IsValid;
@@ -1,12 +1,14 @@
using System.Text.Json;
using Akka.Actor;
using Akka.Event;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Fleet;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Runtime.DeploymentCache;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
@@ -292,6 +294,69 @@ public sealed class DriverHostActorApplyingStashTests()
logs["appears WEDGED"].ShouldBe(0);
}
/// <summary>
/// The watchdog times the artifact read/fetch, NOT the synchronous Applying-row write that
/// precedes it — a slow ConfigDb row write must not be reported as a wedged fetch.
/// </summary>
/// <remarks>
/// <para>
/// The wedge timer used to be armed BEFORE <c>UpsertNodeDeploymentState(Applying)</c>, which
/// runs synchronously on the actor thread. Any write slower than the wedge delay therefore
/// enqueued the tick before the fetch had even started, so it was dequeued ahead of the
/// fetch's pipe-back and logged "the artifact read/fetch has neither answered nor failed" for
/// a fetch that answered immediately. This is what made
/// <see cref="ACompletedApply_NeverReportsAWedge"/> fail whenever it ran first in its process:
/// the cold EF Core model build on that first row write took ~350 ms against a 200 ms delay.
/// </para>
/// <para>
/// Every row write here is slowed to 4× the delay, deterministically. Writes that land
/// AFTER the fetch's pipe-back (the final Applied row) are harmless either way: a tick
/// enqueued during them is discarded by Akka's TimerScheduler once BecomeSteady cancels the
/// key. The presence control is the Applied ack — the apply really did run through the slow
/// writes.
/// </para>
/// </remarks>
[Fact]
public void ASlowApplyingRowWrite_IsNotReportedAsAWedgedFetch()
{
var wedgeTimeout = TimeSpan.FromMilliseconds(200);
var db = new SlowDbFactory(NewInMemoryDbFactory(), wedgeTimeout * 4);
var deploymentA = DeploymentId.NewId();
var coordinator = CreateTestProbe();
var actor = Sys.ActorOf(DriverHostActor.Props(
db, TestNode, coordinator.Ref,
localRoles: new HashSet<string> { "driver" },
deploymentArtifactCache: new NullArtifactCache(),
fetchAndCacheMode: true,
artifactFetcher: new GatedFetcher(ArtifactBytes(), gatedCalls: 0),
applyWedgeTimeout: wedgeTimeout));
var logs = SubscribeToLogs("appears WEDGED");
actor.Tell(new DispatchDeployment(deploymentA, RevA, CorrelationId.NewId()));
coordinator.ExpectMsg<ApplyAck>(TimeSpan.FromSeconds(20), cancellationToken: TestContext.Current.CancellationToken).Outcome.ShouldBe(ApplyAckOutcome.Applied);
db.Calls.ShouldBeGreaterThanOrEqualTo(1);
logs.Drain(SpinWindow);
logs["appears WEDGED"].ShouldBe(0);
}
/// <summary>Delays every <see cref="IDbContextFactory{TContext}.CreateDbContext"/> on the calling thread.</summary>
private sealed class SlowDbFactory(IDbContextFactory<OtOpcUaConfigDbContext> inner, TimeSpan delay)
: IDbContextFactory<OtOpcUaConfigDbContext>
{
private int _calls;
public int Calls => Volatile.Read(ref _calls);
public OtOpcUaConfigDbContext CreateDbContext()
{
Interlocked.Increment(ref _calls);
Thread.Sleep(delay);
return inner.CreateDbContext();
}
}
/// <summary>Subscribes a fresh counter to the EventStream's log events.</summary>
/// <remarks>
/// Every fragment of interest must be declared up front, because draining is destructive: a
@@ -115,6 +115,82 @@ public sealed class NativeAlarmInitialStateSignalTests : NativeAlarmSignalTestBa
AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(300));
}
/// <summary>
/// #926: a driver that signalled and then lost events WITHDRAWS: the host sends <c>Known: false</c> for exactly
/// those conditions (after the projections before it), puts them back in the F5 window (diagnosed if the driver
/// never re-signals), and a later real signal marks them known again.
/// </summary>
[Fact]
public void A_withdrawn_signal_takes_known_back_and_rearms_F5_until_the_next_signal()
{
var rig = StartRig(DriverTypeNames.OpcUaClient, ["hi", "lo"],
o => o.WithSignalTimeout(DriverTypeNames.OpcUaClient, TimeSpan.FromMilliseconds(400)));
rig.Driver.Signal([A, B]).ShouldBeTrue();
rig.Publish.FishForMessage<OpcUaPublishActor.MarkConditionsKnown>(m => m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct)
.ConditionIds.ShouldBe([A, B], ignoreOrder: true);
rig.Hub.Unsignalled.ContainsKey(DriverId).ShouldBeFalse();
rig.Driver.Raise(A).ShouldBeTrue();
rig.Driver.Signal([A], withdrawn: true).ShouldBeTrue();
var traffic = new List<object>();
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10);
while (DateTime.UtcNow < deadline)
{
var m = rig.Publish.ReceiveOne(deadline - DateTime.UtcNow, Ct);
if (m is null) break;
if (m is not (OpcUaPublishActor.AlarmStateUpdate or OpcUaPublishActor.MarkConditionsKnown)) continue;
traffic.Add(m);
if (m is OpcUaPublishActor.MarkConditionsKnown { Known: false }) break;
}
traffic[^1].ShouldBeOfType<OpcUaPublishActor.MarkConditionsKnown>().Known.ShouldBeFalse();
traffic.FindIndex(m => m is OpcUaPublishActor.AlarmStateUpdate u && u.AlarmNodeId == A)
.ShouldBeLessThan(traffic.Count - 1, "the withdrawal follows the projection raised before it");
var withdrawal = (OpcUaPublishActor.MarkConditionsKnown)traffic[^1];
withdrawal.ConditionIds.ShouldBe([A], "only the withdrawn conditions");
// Never re-signalled ⇒ F5 diagnoses it (and it is never marked known by a timer).
AwaitCondition(() => rig.Hub.Unsignalled.ContainsKey(DriverId), TimeSpan.FromSeconds(5), Ct);
rig.Hub.Unsignalled[DriverId].Conditions.ShouldBe(1);
AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(300));
// Positive control: the next real signal marks it known again and clears the diagnostic.
rig.Driver.Signal([A, B]).ShouldBeTrue();
rig.Publish.FishForMessage<OpcUaPublishActor.MarkConditionsKnown>(m => m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct);
AwaitCondition(() => !rig.Hub.Unsignalled.ContainsKey(DriverId), TimeSpan.FromSeconds(5), Ct);
}
/// <summary>#926: a withdrawal removes the conditions from the OpcUaClient backstop — the timer must never mark a
/// condition known whose source just said it lost events. Positive control: the sibling it did not withdraw IS
/// marked by the same backstop.</summary>
[Fact]
public void A_withdrawal_cancels_the_backstop_for_its_conditions()
{
var rig = StartRig(DriverTypeNames.OpcUaClient, ["hi", "lo"], o => o.WithOpcUaClientSettle(TimeSpan.FromMilliseconds(600)));
rig.Driver.Signal([A, B], unsignalable: true);
rig.Driver.Signal([A], withdrawn: true);
var mark = rig.Publish.FishForMessage<OpcUaPublishActor.MarkConditionsKnown>(m => m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct);
mark.ConditionIds.ShouldBe([B], "only the sibling the driver did not withdraw");
AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(800));
}
/// <summary>#926 review r2: a withdrawal after F5 already raised its diagnostic updates the diagnostic's count.</summary>
[Fact]
public void A_withdrawal_after_the_diagnostic_updates_its_count()
{
var rig = StartRig(DriverTypeNames.OpcUaClient, ["hi", "lo"],
o => o.WithSignalTimeout(DriverTypeNames.OpcUaClient, TimeSpan.FromMilliseconds(300)));
rig.Driver.Signal([A]).ShouldBeTrue(); // B stays pending
AwaitCondition(() => rig.Hub.Unsignalled.TryGetValue(DriverId, out var d) && d.Conditions == 1, TimeSpan.FromSeconds(5), Ct);
rig.Driver.Signal([A], withdrawn: true).ShouldBeTrue();
AwaitCondition(() => rig.Hub.Unsignalled.TryGetValue(DriverId, out var d) && d.Conditions == 2, TimeSpan.FromSeconds(5), Ct);
}
/// <summary>#926: the payload is either unsignalable or a withdrawal.</summary>
[Fact]
public void Unsignalable_and_withdrawn_are_exclusive() =>
Should.Throw<ArgumentException>(() => new AlarmInitialStateEventArgs([A], unsignalable: true, withdrawn: true));
// ---------------------------------------------------------------- review S2 / re-arm F5 / nits
/// <summary>
@@ -290,10 +290,10 @@ public sealed class FakeSignallingAlarmDriver(string driverInstanceId, string dr
/// <param name="conditionIds">The conditions it covers.</param>
/// <param name="unsignalable">Report InitialStateUnsignalable instead.</param>
/// <returns>Whether it was raised.</returns>
public bool Signal(IReadOnlyList<string> conditionIds, bool unsignalable = false)
public bool Signal(IReadOnlyList<string> conditionIds, bool unsignalable = false, bool withdrawn = false)
{
if (!_subscribed) return false;
InitialAlarmStateDelivered?.Invoke(this, new AlarmInitialStateEventArgs(conditionIds, unsignalable));
InitialAlarmStateDelivered?.Invoke(this, new AlarmInitialStateEventArgs(conditionIds, unsignalable, withdrawn));
return true;
}
@@ -13,8 +13,9 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.OpcUa;
/// <summary>
/// A1 (plan §5.1 F2/G3): <see cref="OpcUaPublishActor.MarkConditionsKnown"/> is an alarm message. Live it applies in
/// arrival order; while a plan is in flight it is deferred beside the alarm states and replayed AFTER them — and a
/// source that lost a deferred projection (overflow or out-of-scope skip) has its deferred marks discarded.
/// arrival order; while a plan is in flight it is deferred beside the alarm states and replayed with them in arrival
/// order (#926 review r2) — and a source that lost a deferred projection (overflow or out-of-scope skip) has its
/// deferred KNOWN marks discarded.
/// </summary>
[Trait("Feature", "GrpcData")]
[Trait("Phase", "A1")]
@@ -171,7 +172,8 @@ public sealed class OpcUaPublishActorConditionKnownTests : RuntimeActorTestBase
}
/// <summary>Review round 2 N1: a deferred withdrawal is never dropped by the deferral's capacity (a known mark may be —
/// unknown is the safe side).</summary>
/// unknown is the safe side). #926 review r2: deferred marks are held per condition, so repeated withdrawals of one
/// condition coalesce into one replayed withdrawal (bounded by the number of conditions).</summary>
[Fact]
public void A_withdrawal_beyond_the_deferral_capacity_is_never_dropped()
{
@@ -187,7 +189,45 @@ public sealed class OpcUaPublishActorConditionKnownTests : RuntimeActorTestBase
gate.Set();
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
AwaitAssert(() => sink.Log.Count(l => l == "unknown:al-1").ShouldBe(6), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
AwaitAssert(() => sink.Log.Count(l => l == "unknown:al-1").ShouldBe(4), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
sink.IsKnown("al-1").ShouldBeFalse();
}
/// <summary>
/// #926 review r2: a withdrawal followed by a live transition of the same condition, both deferred by a plan,
/// replays in ARRIVAL order — withdrawal, then the transition that re-establishes it — so the condition ends known,
/// as the live path leaves it (marks used to replay after every alarm, ending it unknown while the host no longer
/// counted it in F5). The mirror order (transition, then withdrawal) ends unknown.
/// </summary>
[Fact]
public void Deferred_alarms_and_marks_replay_in_arrival_order()
{
var sink = new OrderSink();
using var gate = new ManualResetEventSlim(false);
var actor = Spawn(sink, gate);
actor.Tell(Rebuild());
actor.Tell(new OpcUaPublishActor.MarkConditionsKnown("drv-1", ["al-1"], AddressSpaceRealm.Uns, Known: false));
actor.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-1", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, "drv-1"));
AwaitAssert(() => sink.Skipped.ShouldContain("alarm:al-1"), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
gate.Set();
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
sink.Log.ShouldBe(["unknown:al-1", "alarm:al-1:True"], "replayed in arrival order");
sink.IsKnown("al-1").ShouldBeTrue("the transition after the withdrawal re-established it");
// Mirror (positive control for the order): transition, then withdrawal ⇒ unknown.
var sink2 = new OrderSink();
using var gate2 = new ManualResetEventSlim(false);
var actor2 = Spawn(sink2, gate2);
actor2.Tell(Rebuild());
actor2.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-1", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, "drv-1"));
actor2.Tell(new OpcUaPublishActor.MarkConditionsKnown("drv-1", ["al-1"], AddressSpaceRealm.Uns, Known: false));
AwaitAssert(() => sink2.Skipped.ShouldContain("alarm:al-1"), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
gate2.Set();
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
sink2.Log.ShouldBe(["alarm:al-1:True", "unknown:al-1"]);
sink2.IsKnown("al-1").ShouldBeFalse();
}
/// <summary>Review round 2 N2: a G3 discard of a driver's deferred mark is reported back to the mark's sender, so its
@@ -338,11 +338,17 @@ public sealed class OpcUaPublishActorWarmTests : RuntimeActorTestBase
Encoding.UTF8.GetBytes("{\"Clusters\":[{\"ClusterId\":\"a\",\"RedundancyMode\":\"None\"},{\"ClusterId\":\"b\",\"RedundancyMode\":\"Hot\"}],"
+ "\"Nodes\":[{\"NodeId\":\"x:1\",\"ClusterId\":\"b\"}]}"), "x:1").ShouldBe("Hot");
// Read the counter BEFORE the listener exists. If OtOpcUaTelemetry's static initializer has not run
// yet (this test alone in its process), it runs at the actor's first use while the listener is live,
// Meter.CreateCounter publishes each instrument to the live listener from INSIDE that initializer, and
// the field still reads null there — the counter was never enabled and the count stayed 0
// (Runtime.Tests master failures). A captured local is assigned by the time anything is published.
var counter = ZB.MOM.WW.OtOpcUa.Commons.Observability.OtOpcUaTelemetry.RedundancyModeMismatch;
using var listener = new System.Diagnostics.Metrics.MeterListener();
long mismatches = 0;
listener.InstrumentPublished = (instrument, l) =>
{
if (ReferenceEquals(instrument, ZB.MOM.WW.OtOpcUa.Commons.Observability.OtOpcUaTelemetry.RedundancyModeMismatch))
if (ReferenceEquals(instrument, counter))
l.EnableMeasurementEvents(instrument);
};
listener.SetMeasurementEventCallback<long>((_, value, _, _) => Interlocked.Add(ref mismatches, value));