Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs
T
Joseph Doherty 5cccfd75ce fix(grpc-data): #994 projected cohorts batch, pace and scale past one item; busy origins no longer reset quiet streams
Wave 3 of the 2026-12-02 review (docs/reviews/2026-12-02/01-runtime.md R-2/3/7/8/9/10/12/13/21/22/23/24,
02-opcuaserver.md U-10/11/12/13).

Consumer (ProjectedDataAccess cohort):
- R-2: a cohort's OpenSubscription declared a snapshot budget of 1 item, which the origin uses to size the stream's
  handle table, so the 2nd item was refused LimitExceeded and the cohort re-opened in a loop (two projected items of
  one interval broke each other). Opens/adds/removes are now batched (IDataSubscriptionCommandLimits, <=256 items,
  bounded by estimated snapshot bytes) and paced (32 burst, 32/s, <=4 commands or snapshots outstanding).
- R-7: control events no longer share the bounded frame queue; a failed Remove can no longer Stop() the cohort.
- R-10: a local capacity refusal (TryPublishOrBackpressure -> CapacityExhausted) is retried for up to 2 s instead of
  invalidating healthy evidence and retiring the route.
- R-13: RemoteSubscription mutates its handle/version tables in place; the cohort caches the source per binding and
  drops the per-sample LINQ in EvidenceFor.
- R-8: only an unselectable endpoint arms the discovery backoff; a caller cancel is OperationCanceledException.
- R-24: the condition stream cancels and observes a pending frame read before disposing the enumerator.

Origin (DataSubscriptionSession / SamplePartition / SourceInterestLease):
- R-2 (found by the perf harness): the delivery index was sized MaxPendingFrames x 16 = 1024, so the 1025th item of a
  stream stopped the session after its ack; it now covers MaxMonitoredItems.
- R-3: interest reads count only own-ticket matches (scan budget separate), re-queue a lagging tick, and catch up from
  per-source last-change versions when the bounded history rolled off - no more "Source change history expired".
- R-9: a partition quiet bump resets a lease only when one of ITS sources was invalidated (per-source quiet version)
  or its binding retired; partition-wide invalidation still resets all.
- R-12: the per-item publish verdict is memoised per (catalog instance, authority generation) for <=1 s; Commit
  under the session lock re-checks identity only.
- R-21/R-22/R-23: registry prune is interval/capacity driven; a cleared history session refuses chunks; the snapshot
  barrier is decided and armed under the same gate its release is decided under.

Node manager: U-10 projected live items indexed by node; U-11 anchor removal / root-leaf swap tombstone the anchor's
own monitored node; U-12 per-parent child count; U-13 per-condition verdict index.

Also: Issue934_r1_N1 test clears its metadata failure before ending the stream (test-only sequencing race,
reproduced with a 200 ms delay; production behaviour correct).

Perf (Category=Perf, OTOPCUA_GRPCDATA_PERF=1): 10k-item cohort opens in 3.3 s / 80 commands / 1 stream (before: never
opens); 100 source versions at 1k/s -> 11,036 item values in 569 ms.
2026-12-03 11:59:26 -05:00

327 lines
20 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Security.Cryptography;
using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections;
/// <summary>
/// A3a (plan §5.2 N4, §5.4): an imported-condition id is classified BEFORE <c>RealmOf</c> on every authorizer entry point
/// (read, history, call, subscribe), whatever realm the caller computed; and the publish-time rewriter drops a marked
/// imported event whose re-check fails, and re-gates an unmarked one for the publishing session.
/// </summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "A3")]
public sealed class ImportedConditionClassifierTests : IAsyncDisposable
{
private readonly string _pki = Path.Combine(Path.GetTempPath(), $"otopcua-imported-classifier-{Guid.NewGuid():N}");
private OpcUaApplicationHost? _host;
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_condition_namespace_id_is_never_decided_by_the_realm_walk_on_any_authorizer_entry_point(bool aclEnabled)
{
var f = new Fixture(aclEnabled); // a Cluster-wide grant: the Raw/Uns walk would ALLOW everything
var conditionId = new NodeId("c1.anything", 9);
var calls = new List<(OpcUaOperation, NodeId)>();
f.Gate.ImportedConditionClassifier = (_, op, id) =>
{
if (id.NamespaceIndex != 9) return null;
calls.Add((op, id));
return false;
};
foreach (var realm in new[] { AddressSpaceRealm.Raw, AddressSpaceRealm.Uns })
{
foreach (var op in new[] { OpcUaOperation.Read, OpcUaOperation.Browse, OpcUaOperation.HistoryRead, OpcUaOperation.Call,
OpcUaOperation.CreateMonitoredItems, OpcUaOperation.AlarmAcknowledge })
{
f.Gate.Authorize(f.Identity, op, conditionId, realm).ShouldNotBeNull($"Authorize {op} {realm}");
f.Gate.AuthorizeIfRequired(f.Identity, op, conditionId, realm).ShouldNotBeNull($"AuthorizeIfRequired {op} {realm}");
f.Gate.IsAllowedCached(f.Identity, op, conditionId, realm).ShouldBeFalse($"IsAllowedCached {op} {realm}");
f.Gate.TryAuthorizeMapped(f.Identity, op, conditionId, realm, out var veto).ShouldBeTrue();
veto.ShouldNotBeNull();
}
}
calls.Count.ShouldBe(2 * 6 * 4, "every entry point asked the condition classifier, never the realm");
// Positive control: the same identity on an ordinary Raw id is decided by the grant walk (allowed).
f.Gate.Authorize(f.Identity, OpcUaOperation.Read, new NodeId("Plant/x", 2), AddressSpaceRealm.Raw).ShouldBeNull();
}
[Fact]
public async Task The_node_manager_classifier_allows_Read_and_Subscribe_through_the_condition_and_refuses_history_and_calls()
{
var nm = await BootAsync();
var f = new Fixture(aclEnabled: true);
nm.Authorizer = f.Gate;
var access = new Access();
nm.ProjectedConditionAccess = access;
var key = Convert.ToBase64String(SHA256.HashData("k"u8.ToArray())).TrimEnd('=').Replace('+', '-').Replace('/', '_');
var view = new DataView(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant/dev1/HR"), DataRealm.Raw, null, 0, "Plant/dev1/HR");
var placement = new ImportedConditionPlacement("map-a", DataRealm.Raw, view, "Plant/remote-a/dev1", "dev1/HR");
var state = new DataConditionState(key, 1, false, true, new DataConditionInfo("AlarmConditionType", "HR", DataConditionSourceKind.Native,
[view], 3), true, false, true, true, 0, 500, "m", 0, null, 0, DateTimeOffset.UtcNow, true, new DataActivationMarker("i", 1));
nm.ApplyConditions([new ImportedConditionUpdate("conn-a", state, state.Info, [placement], "Plant/remote-a/dev1/HR")]);
var alarm = nm.FindImportedCondition("conn-a", key).ShouldNotBeNull();
nm.IsImportedConditionId(alarm.NodeId).ShouldBeTrue();
var child = alarm.ActiveState!.Id!.NodeId;
nm.IsImportedConditionId(child).ShouldBeTrue("children live in the condition's namespace (#629)");
foreach (var realm in new[] { AddressSpaceRealm.Raw, AddressSpaceRealm.Uns })
{
access.Visible = true;
f.Gate.Authorize(f.Identity, OpcUaOperation.Read, child, realm).ShouldBeNull();
f.Gate.Authorize(f.Identity, OpcUaOperation.CreateMonitoredItems, alarm.NodeId, realm).ShouldBeNull();
f.Gate.Authorize(f.Identity, OpcUaOperation.HistoryRead, alarm.NodeId, realm).ShouldNotBeNull("no imported condition history");
f.Gate.Authorize(f.Identity, OpcUaOperation.Call, alarm.NodeId, realm).ShouldNotBeNull("remote methods are A3b");
f.Gate.Authorize(f.Identity, OpcUaOperation.AlarmAcknowledge, alarm.NodeId, realm).ShouldNotBeNull();
access.Visible = false;
access.Generation++;
f.Gate.Authorize(f.Identity, OpcUaOperation.Read, child, realm).ShouldNotBeNull("not visible ⇒ denied despite the Cluster grant");
}
}
[Fact]
public void The_rewriter_drops_a_failed_marked_event_and_regates_an_unmarked_imported_one()
{
var keep = new ProjectedEventFieldList(new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => true)) { ClientHandle = 1 };
var drop = new ProjectedEventFieldList(new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => false)) { ClientHandle = 2 };
var unmarkedDenied = new EventFieldList { ClientHandle = 3 };
var unmarkedOther = new EventFieldList { ClientHandle = 4 };
var throwing = new ProjectedEventFieldList(new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => throw new InvalidOperationException())) { ClientHandle = 5 };
var message = new NotificationMessage
{
SequenceNumber = 7,
NotificationData = [new ExtensionObject(new EventNotificationList { Events = [keep, drop, unmarkedDenied, unmarkedOther, throwing] })],
};
var projected = ProjectedNotificationRewriter.Project(message, republish: false, list => list.ClientHandle == 3 ? false : null);
var events = projected.NotificationData[0].TryGetValue<EventNotificationList>(out var list) ? list! : throw new InvalidOperationException();
projected.NotificationData.Count.ShouldBe(1);
events.Events.ToArray()!.Select(e => e.ClientHandle).ShouldBe([1u, 4u]);
// Every denied event emptied ⇒ the payload is left out entirely (events have no Bad-value form).
var allDenied = new NotificationMessage { SequenceNumber = 8,
NotificationData = [new ExtensionObject(new EventNotificationList { Events = [drop] })] };
ProjectedNotificationRewriter.Project(allDenied, republish: true, null).NotificationData.Count.ShouldBe(0);
// No imported gate and no marker: v1 messages pass through as the same instance.
var plain = new NotificationMessage { SequenceNumber = 9, NotificationData = [new ExtensionObject(new EventNotificationList { Events = [unmarkedOther] })] };
ReferenceEquals(ProjectedNotificationRewriter.Project(plain, republish: false, null), plain).ShouldBeTrue();
}
/// <summary>
/// A3 review round 2 (root cause of the intermittent OI ConditionRefresh failures): SDK 2.0.1 pools EventFieldList
/// process-wide, and <c>SentMessageQueue</c> calls <c>Reuse()</c> on every list of an acknowledged message. A marked
/// list that went back to the stock pool was rented by an unrelated server/session's <c>GetEventFields</c> (its
/// RefreshStart/RefreshEnd), carrying a revoked marker, and the rewriter dropped it. A released marked list must never
/// be rentable, and must not keep its marker (closure over condition + identity) alive.
/// </summary>
[Fact]
public void A_released_marked_event_list_never_returns_to_the_SDK_pool_so_no_other_session_rents_its_marker()
{
var marked = new ProjectedEventFieldList(new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => false)) { ClientHandle = 77 };
((IPooledEncodeable)marked).Reuse(); // exactly what SentMessageQueue.ReuseNotificationPayloads does on ACK / eviction
marked.Marker.ShouldBeNull("a released list holds no authority (and keeps no closure alive)");
// Drain more than the pool can hold: had the marked instance been returned, it would come out here.
var rented = new List<EventFieldList>();
try
{
for (var i = 0; i < PooledEncodeableType<EventFieldList>.DefaultMaximumRetained + 64; i++)
rented.Add((EventFieldList)EventFieldListActivator.Instance.CreateInstance());
rented.ShouldNotContain(l => l is ProjectedEventFieldList, "a stock list rented for any event is never a marked one");
}
finally
{
foreach (var l in rented) ((IPooledEncodeable)l).Reuse();
}
// A released marked list that somehow reached the rewriter fails closed (never judged by a stale marker).
var message = new NotificationMessage { SequenceNumber = 10,
NotificationData = [new ExtensionObject(new EventNotificationList { Events = [marked] })] };
ProjectedNotificationRewriter.Project(message, republish: false, null).NotificationData.Count.ShouldBe(0);
}
/// <summary>
/// Verification review r2: the rewriter never sees the queued instance — SDK 2.0.1 <c>SentMessageQueue</c> hands Publish
/// and Republish a <c>CoreUtils.Clone</c> of the stored message. The gate holds only because
/// <see cref="EventFieldList.Clone"/> is <c>MemberwiseClone</c>, which keeps the subclass, the marker and the handle. Pins
/// that dependency: an SDK that cloned through the activator (a stock list) would turn this red.
/// </summary>
[Fact]
public void Cloning_a_marked_event_list_the_way_the_SDK_does_keeps_the_subclass_and_the_marker()
{
var marker = new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => false);
var marked = new ProjectedEventFieldList(marker) { ClientHandle = 42 };
var direct = marked.Clone().ShouldBeOfType<ProjectedEventFieldList>();
direct.Marker.ShouldBeSameAs(marker);
direct.ClientHandle.ShouldBe(42u);
var message = new NotificationMessage { SequenceNumber = 11,
NotificationData = [new ExtensionObject(new EventNotificationList { Events = [marked] })] };
var delivered = CoreUtils.Clone(message)!; // exactly what SentMessageQueue returns for Publish / Republish
delivered.NotificationData[0].TryGetValue<EventNotificationList>(out var list).ShouldBeTrue();
var events = list!.Events;
var cloned = events[0].ShouldBeOfType<ProjectedEventFieldList>();
cloned.ShouldNotBeSameAs(marked, "the SDK delivers a copy, not the queued instance");
cloned.Marker.ShouldBeSameAs(marker);
ProjectedNotificationRewriter.Project(delivered, republish: false, null).NotificationData.Count
.ShouldBe(0, "the copy is still judged by its marker (and dropped when the re-check fails)");
}
[Fact]
public void S2_a_cached_positive_verdict_is_re_proved_past_the_credential_expiry_and_past_the_positive_TTL()
{
var registry = new ProjectedConditionRegistry();
var condition = new ImportedCondition(new AlarmConditionState(null) { NodeId = new NodeId("c", 9) }, "conn", "k");
registry.Add(condition); // #936 review r1 N4: verdicts are cached only for a live instance
var computes = 0;
bool Allow() { computes++; return true; }
var now = DateTimeOffset.UtcNow;
var expiringKey = new object();
registry.Verdict(expiringKey, condition, 1, now, now.AddSeconds(2), Allow).ShouldBeTrue();
registry.Verdict(expiringKey, condition, 1, now.AddSeconds(1), now.AddSeconds(2), Allow).ShouldBeTrue();
computes.ShouldBe(1, "served from cache inside both bounds");
registry.Verdict(expiringKey, condition, 1, now.AddSeconds(3), now.AddSeconds(2), () => { computes++; return false; })
.ShouldBeFalse("past the key's expiry the verdict is re-proved (and the policy now denies)");
var longLived = new object();
registry.Verdict(longLived, condition, 1, now, null, Allow).ShouldBeTrue();
registry.Verdict(longLived, condition, 1, now + ProjectedConditionRegistry.PositiveVerdictTtl + TimeSpan.FromSeconds(1), null, Allow);
computes.ShouldBe(4, "a positive verdict lives at most the TTL");
}
[Fact]
public void Issue936_r1_N4_a_verdict_computed_while_its_condition_was_removed_is_not_served_to_a_same_NodeId_re_creation()
{
var registry = new ProjectedConditionRegistry();
var id = new NodeId("c", 9);
var removed = new ImportedCondition(new AlarmConditionState(null) { NodeId = id }, "conn", "k");
registry.Add(removed);
var caller = new object();
// The compute runs off the verdict gate; the condition is removed while it runs (Remove purges this NodeId's verdicts).
registry.Verdict(caller, removed, 1, DateTimeOffset.UtcNow, null, () => { registry.Remove(removed); return true; }).ShouldBeTrue();
var recreated = new ImportedCondition(new AlarmConditionState(null) { NodeId = id }, "conn", "k");
registry.Add(recreated);
var computes = 0;
registry.Verdict(caller, recreated, 1, DateTimeOffset.UtcNow, null, () => { computes++; return false; })
.ShouldBeFalse("the new instance is decided (and admitted) afresh, not served the removed instance's verdict");
computes.ShouldBe(1);
// Positive control: a live instance's verdict IS cached.
registry.Verdict(caller, recreated, 1, DateTimeOffset.UtcNow, null, () => { computes++; return true; }).ShouldBeFalse();
computes.ShouldBe(1);
}
// #994 (U-13): removing a condition purges exactly ITS cached verdicts (via a per-condition identity index — it used to scan
// every cached verdict under the manager Lock, ~K × 65,536 comparisons for a K-condition removal).
[Fact, Trait("Issue", "994")]
public void U13_removing_conditions_purges_exactly_their_verdicts_and_keeps_the_rest()
{
var registry = new ProjectedConditionRegistry();
var conditions = Enumerable.Range(0, 1000).Select(i =>
new ImportedCondition(new AlarmConditionState(null) { NodeId = new NodeId("c" + i, 9) }, "conn", "k" + i)).ToArray();
foreach (var condition in conditions) registry.Add(condition);
var identities = Enumerable.Range(0, 60).Select(_ => new object()).ToArray();
var now = DateTimeOffset.UtcNow;
foreach (var condition in conditions)
foreach (var identity in identities) registry.Verdict(identity, condition, 1, now, null, () => false);
registry.VerdictCountForTests.ShouldBe(60_000);
var started = System.Diagnostics.Stopwatch.GetTimestamp();
foreach (var condition in conditions.Take(500)) registry.Remove(condition);
var elapsed = System.Diagnostics.Stopwatch.GetElapsedTime(started);
registry.VerdictCountForTests.ShouldBe(30_000);
// A survivor is still served from cache; a removed-and-re-added one is decided afresh.
var computes = 0;
registry.Verdict(identities[0], conditions[999], 1, now, null, () => { computes++; return true; }).ShouldBeFalse();
computes.ShouldBe(0);
registry.Add(conditions[0]);
registry.Verdict(identities[0], conditions[0], 1, now, null, () => { computes++; return true; }).ShouldBeTrue();
computes.ShouldBe(1);
elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(5), "500 removals against 60k verdicts are bounded per condition");
}
[Fact]
public void Issue936_r1_S3_S4_admission_is_recorded_lazily_per_credential_and_survives_a_new_identity_object()
{
var condition = new ImportedCondition(new AlarmConditionState(null) { NodeId = new NodeId("c", 9) }, "conn", "k");
condition.AdmittedAllocated.ShouldBeFalse("nothing is allocated for a condition nobody was admitted to");
RoleCarryingUserIdentity Identity(string principal, string? key) =>
new(new UserNameIdentityToken { UserName = "apikey" }, [], principal, key);
var first = Identity("reader", "key-a");
condition.WasAdmitted(first).ShouldBeFalse();
condition.Admit(first);
// The SDK builds a NEW identity object on every ActivateSession (re-activation, transfer): still admitted.
condition.WasAdmitted(Identity("reader", "key-a")).ShouldBeTrue();
condition.WasAdmitted(Identity("reader", "key-b")).ShouldBeFalse("another key is another credential");
condition.WasAdmitted(Identity("other", "key-a")).ShouldBeFalse();
condition.WasAdmitted(new object()).ShouldBeFalse();
// Bounded by credentials, not sessions: many sessions of one key are one entry.
for (var i = 0; i < 50; i++) condition.Admit(Identity("reader", "key-a"));
condition.AdmittedCount.ShouldBe(1);
for (var i = 0; i < ImportedCondition.MaxAdmittedCredentials + 10; i++) condition.Admit(Identity("p" + i, "k" + i));
condition.AdmittedCount.ShouldBe(ImportedCondition.MaxAdmittedCredentials, "capped per condition");
condition.ForgetAdmitted();
condition.AdmittedAllocated.ShouldBeFalse("dropped with the removal");
condition.WasAdmitted(first).ShouldBeFalse();
}
private async Task<OtOpcUaNodeManager> BootAsync()
{
var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions
{
ApplicationName = "ImportedClassifier", ApplicationUri = $"urn:ImportedClassifier:{Guid.NewGuid():N}",
OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = _pki,
}, NullLogger<OpcUaApplicationHost>.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken);
_host = started.Host;
return started.Server.NodeManager!;
}
public async ValueTask DisposeAsync()
{
if (_host is not null) await _host.DisposeAsync();
if (Directory.Exists(_pki))
try { Directory.Delete(_pki, recursive: true); } catch (IOException) { }
}
private sealed class Access : IProjectedConditionAccess
{
public bool Visible { get; set; }
public long Generation { get; set; } = 1;
public bool CanSee(RoleCarryingUserIdentity? caller, IReadOnlyList<ImportedConditionPlacement> placements) => caller is not null && Visible;
public long AuthorityGeneration => Generation;
public IDisposable? AcquireEventDemand(RoleCarryingUserIdentity? caller) => null;
public bool CanSubscribeFolder(RoleCarryingUserIdentity? caller, string mappingId, string folderLocalSubject) => caller is not null && Visible;
public bool IsConditionBearingMapping(string mappingId) => true;
}
private sealed class Fixture
{
private readonly DataPlaneAuthorityState _state = new();
private readonly ApiKey _key = new() { ApiKeyId = "key-a", Name = "key-a", Principal = "reader", SecretHash = "hash", Enabled = true,
ExpiresUtc = DateTime.UtcNow.AddHours(1) };
public DataPlaneAuthorizer Gate { get; }
public Fixture(bool aclEnabled)
{
_state.Apply("c1", "rev", [_key],
[new NodeAcl { NodeAclId = "acl", ClusterId = "c1", Principal = "reader", ScopeKind = NodeAclScopeKind.Cluster,
PermissionFlags = (NodePermissions)~0 }],
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
Gate = new DataPlaneAuthorizer(_state, new TriePermissionEvaluator(_state.Tries, TimeProvider.System), aclEnabled,
NullLogger.Instance, TimeProvider.System);
}
public RoleCarryingUserIdentity Identity => new(new UserNameIdentityToken { UserName = "apikey" }, [], "reader", _key.ApiKeyId,
DataCallerIdentity.CredentialVersionFor(_key), DateTimeOffset.UtcNow.AddMinutes(5));
}
}