perf(acl,grpc-data): #1053 alloc-free warm UNS ACL decisions; unresolvable configured refs back off; restart keeps the comms latch (decided)

U-8: a warm cached decision on a UNS node allocated 416-680 B/call ahead of the cache (live id-chain list, identifier
split, LINQ, segment array, string.Join key, DataCallerIdentity). Now 0 B: the live chain is cached per folder instance
(re-verified against the live ancestry every call), the generation hands out one segment array per path, the authorizer
keys its resolved cache keys on that array, reference variables key on their own identifier (scope = its split), and
the caller identity is built once per session identity.

R-25: ConfiguredProjectedInterestOwner re-ran discovery for an unresolvable configured reference every 1 s sweep forever;
a failed resolve now backs off 1 s doubling to 30 s (60 s unreachable: 61 discoveries -> 6). Publishing into the source hub
only for sources with interest is DECLINED: that cache answers a new subscription's first snapshot and projected Reads.

Restart comms latch (decided: keep): the nodes stay Bad across an operator Restart and the respawned incarnation must
re-publish them; the stopped child's PostStop announcement already re-latches and cancels the old audit. Pinned by test.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-12-03 15:30:07 -05:00
parent a24071405a
commit 6ea0f09614
11 changed files with 586 additions and 37 deletions
@@ -0,0 +1,228 @@
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.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
/// <summary>
/// lmxopcua#1053 (review 02 U-8): a WARM cached ACL decision on a UNS node used to allocate ahead of the decision
/// cache on every call — the live id-chain list, an identifier split, LINQ enumerators, the resolved segment array
/// and a <c>string.Join</c> cache key — about 8–12 short-lived objects per node per decision (≈10k per 1,000-node
/// UNS Read). The resolver still runs per call (it reads live topology); its products are now cached on the folder
/// instance / generation, so a warm hit allocates nothing.
/// </summary>
public sealed class NodeManagerUnsDecisionAllocationTests : IDisposable
{
private const string Cluster = "SITE-A";
private const string Principal = "scadabridge";
private const string KeyId = "k-1053";
private const string AreaId = "UA-0000000001";
private const string LineId = "UL-0000000001";
private const string Pump = "EQ-00000000a1b2";
private const string Fan = "EQ-00000000c3d4";
private const string VirtualTag = Pump + "/Temp";
private const string Reference = "Area1/Line1/Pump/Speed";
private const string RawTag = "Plant/Modbus/dev1/Speed";
private const string Alarm = "scripted-pump-hi";
private const int Calls = 2_000;
private static readonly DateTime Start = new(2026, 12, 3, 12, 0, 0, DateTimeKind.Utc);
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private readonly string _pkiRoot = Path.Combine(Path.GetTempPath(), $"otopcua-1053-{Guid.NewGuid():N}");
/// <summary>
/// Each UNS shape the resolver places — the equipment folder itself, a node it owns (a virtual tag), and a UNS
/// reference variable — answers a warm cached Read with zero bytes allocated on the calling thread. Positive
/// control: every verdict is an ALLOW from a narrow Equipment grant (so the placement did run), and the sibling
/// equipment the grant does not cover is a DENY.
/// </summary>
[Fact]
public async Task A_warm_cached_decision_on_a_uns_node_allocates_nothing()
{
var (host, server) = await BootAsync();
try
{
var nm = server.NodeManager!;
Topology(nm);
var authorizer = Wire(nm);
var ns = nm.NamespaceIndexForRealm(AddressSpaceRealm.Uns);
var identity = new RoleCarryingUserIdentity(
new UserNameIdentityToken { UserName = "apikey" }, [], Principal, KeyId);
nm.ResolveUnsAclSubject(Pump).Kind.ShouldBe(UnsAclSubjectKind.Folder);
nm.ResolveUnsAclSubject(VirtualTag).Kind.ShouldBe(UnsAclSubjectKind.Folder);
nm.ResolveUnsAclSubject(Reference).Kind.ShouldBe(UnsAclSubjectKind.ReferenceVariable);
nm.ResolveUnsAclSubject(Alarm).Kind.ShouldBe(UnsAclSubjectKind.ScriptedCondition);
authorizer.IsAllowedCached(identity, OpcUaOperation.Read, new NodeId(Fan, ns), AddressSpaceRealm.Uns)
.ShouldBeFalse("a sibling equipment the grant does not cover is denied (negative control)");
var measured = new List<(string Id, double PerCall)>();
foreach (var id in new[] { Pump, VirtualTag, Reference, Alarm })
{
var nodeId = new NodeId(id, ns);
authorizer.IsAllowedCached(identity, OpcUaOperation.Read, nodeId, AddressSpaceRealm.Uns)
.ShouldBeTrue($"{id} is covered by the Equipment grant");
var before = GC.GetAllocatedBytesForCurrentThread();
var allowed = 0;
for (var i = 0; i < Calls; i++)
if (authorizer.IsAllowedCached(identity, OpcUaOperation.Read, nodeId, AddressSpaceRealm.Uns)) allowed++;
var perCall = (GC.GetAllocatedBytesForCurrentThread() - before) / (double)Calls;
allowed.ShouldBe(Calls);
TestContext.Current.TestOutputHelper?.WriteLine($"{id}: {perCall:F3} bytes per warm decision");
measured.Add((id, perCall));
}
measured.ShouldAllBe(m => m.PerCall < 1d,
"a warm cached decision must not allocate: " + string.Join(", ", measured.Select(m => $"{m.Id}={m.PerCall:F3} B/call")));
}
finally { await host.DisposeAsync(); }
}
/// <summary>
/// The cached chain is never trusted blindly: moving the equipment to another line (a rebuild that re-mints the
/// folder under a new parent) is re-checked against the LIVE ancestry on the next decision, and is denied until
/// the generation agrees — exactly as before the cache.
/// </summary>
[Fact]
public async Task A_cached_chain_follows_a_live_reparent()
{
var (host, server) = await BootAsync();
try
{
var nm = server.NodeManager!;
Topology(nm);
var authorizer = Wire(nm);
var ns = nm.NamespaceIndexForRealm(AddressSpaceRealm.Uns);
var identity = new RoleCarryingUserIdentity(
new UserNameIdentityToken { UserName = "apikey" }, [], Principal, KeyId);
var pump = new NodeId(Pump, ns);
var vtag = new NodeId(VirtualTag, ns);
authorizer.IsAllowedCached(identity, OpcUaOperation.Read, pump, AddressSpaceRealm.Uns).ShouldBeTrue();
authorizer.IsAllowedCached(identity, OpcUaOperation.Read, vtag, AddressSpaceRealm.Uns).ShouldBeTrue();
// Re-parent Pump under a second line the generation does not know about: the live chain changes.
nm.RebuildAddressSpace();
nm.EnsureFolder(AreaId, parentNodeId: null, displayName: "Area1", realm: AddressSpaceRealm.Uns);
nm.EnsureFolder(LineId, parentNodeId: AreaId, displayName: "Line1", realm: AddressSpaceRealm.Uns);
nm.EnsureFolder("UL-0000000002", parentNodeId: AreaId, displayName: "Line2", realm: AddressSpaceRealm.Uns);
nm.EnsureFolder(Pump, parentNodeId: "UL-0000000002", displayName: "Pump", realm: AddressSpaceRealm.Uns);
nm.EnsureVariable(VirtualTag, Pump, "Temp", "Double", writable: false, AddressSpaceRealm.Uns);
nm.CompleteAddressSpaceApply();
((IReadOnlyList<string>)nm.ResolveUnsAclSubject(Pump).FolderChain!).ShouldBe([AreaId, "UL-0000000002", Pump]);
authorizer.IsAllowedCached(identity, OpcUaOperation.Read, pump, AddressSpaceRealm.Uns)
.ShouldBeFalse("the live chain no longer matches the generation's placement");
authorizer.IsAllowedCached(identity, OpcUaOperation.Read, vtag, AddressSpaceRealm.Uns).ShouldBeFalse();
}
finally { await host.DisposeAsync(); }
}
private static void Topology(OtOpcUaNodeManager nm)
{
nm.EnsureFolder(AreaId, parentNodeId: null, displayName: "Area1", realm: AddressSpaceRealm.Uns);
nm.EnsureFolder(LineId, parentNodeId: AreaId, displayName: "Line1", realm: AddressSpaceRealm.Uns);
nm.EnsureFolder(Pump, parentNodeId: LineId, displayName: "Pump", realm: AddressSpaceRealm.Uns);
nm.EnsureFolder(Fan, parentNodeId: LineId, displayName: "Fan", realm: AddressSpaceRealm.Uns);
nm.EnsureVariable(VirtualTag, Pump, "Temp", "Double", writable: false, AddressSpaceRealm.Uns);
nm.EnsureFolder("Plant/Modbus/dev1", parentNodeId: null, displayName: "dev1", realm: AddressSpaceRealm.Raw);
nm.EnsureVariable(RawTag, "Plant/Modbus/dev1", "Speed", "Double", writable: false, AddressSpaceRealm.Raw);
nm.EnsureVariable(Reference, Pump, "Speed", "Double", writable: false, AddressSpaceRealm.Uns);
nm.AddReference(Reference, AddressSpaceRealm.Uns, RawTag, AddressSpaceRealm.Raw, "Organizes");
nm.MaterialiseAlarmCondition(Alarm, Pump, "hi", "AlarmCondition", 500, AddressSpaceRealm.Uns);
}
private static AclScopePathResolver Resolver() => new(
new Dictionary<string, (string? ParentId, string Name)>(),
new Dictionary<string, (string? RawFolderId, string Name)>(),
new Dictionary<string, (string DriverInstanceId, string Name)>(),
new Dictionary<string, (string? ParentId, string DeviceId, string Name)>(),
new Dictionary<string, (string DeviceId, string? TagGroupId, string Name)>(),
new Dictionary<string, string> { [AreaId] = "Area1" },
new Dictionary<string, (string UnsAreaId, string Name)> { [LineId] = (AreaId, "Line1") },
new Dictionary<string, (string UnsLineId, string Name)> { [Pump] = (LineId, "Pump"), [Fan] = (LineId, "Fan") },
[]);
private static DataPlaneAuthorizer Wire(OtOpcUaNodeManager nm)
{
var resolver = Resolver();
NodeAclPath One(NodeAclScopeKind kind, string id) => resolver.ResolveOne(kind, id).ShouldHaveSingleItem();
var folders = new Dictionary<string, UnsFolderScope>
{
[AreaId] = new(One(NodeAclScopeKind.UnsArea, AreaId), [AreaId]),
[LineId] = new(One(NodeAclScopeKind.UnsLine, LineId), [AreaId, LineId]),
[Pump] = new(One(NodeAclScopeKind.Equipment, Pump), [AreaId, LineId, Pump]),
[Fan] = new(One(NodeAclScopeKind.Equipment, Fan), [AreaId, LineId, Fan]),
};
var owners = new Dictionary<string, NodeAclPath>
{
[Pump] = One(NodeAclScopeKind.Equipment, Pump),
[Fan] = One(NodeAclScopeKind.Equipment, Fan),
};
NodeAcl[] grants =
[
new()
{
NodeAclId = "acl-pump", ClusterId = Cluster, Principal = Principal,
ScopeKind = NodeAclScopeKind.Equipment, ScopeId = Pump, PermissionFlags = NodePermissions.ReadOnly,
},
];
ApiKey[] keys =
[
new()
{
ApiKeyId = KeyId, Name = KeyId, SecretHash = "hash", Principal = Principal, Enabled = true,
CreatedUtc = Start.AddDays(-1),
},
];
var state = new DataPlaneAuthorityState();
state.Apply(Cluster, "rev-1", keys, grants, resolver.Resolve(grants), owners,
new Dictionary<string, string> { [Alarm] = Pump }, folders);
var authorizer = new DataPlaneAuthorizer(
state, new TriePermissionEvaluator(state.Tries), enabled: true, NullLogger.Instance, new FixedClock(Start));
nm.DataPlaneAuthority = state;
nm.Authorizer = authorizer;
return authorizer;
}
private sealed class FixedClock(DateTime utcNow) : TimeProvider
{
public override DateTimeOffset GetUtcNow() => new(utcNow, TimeSpan.Zero);
}
private async Task<(OpcUaApplicationHost Host, OtOpcUaSdkServer Server)> BootAsync()
{
var started = await OpcUaHostStart.StartAsync(
port => new OpcUaApplicationHost(
new OpcUaApplicationHostOptions
{
ApplicationName = "OtOpcUa.UnsDecisionAllocationTest",
ApplicationUri = $"urn:OtOpcUa.UnsDecisionAllocationTest:{Guid.NewGuid():N}",
OpcUaPort = port,
PublicHostname = "localhost",
PkiStoreRoot = _pkiRoot,
},
NullLogger<OpcUaApplicationHost>.Instance),
() => new OtOpcUaSdkServer(), Ct);
return (started.Host, started.Server);
}
/// <inheritdoc />
public void Dispose()
{
if (Directory.Exists(_pkiRoot))
{
try { Directory.Delete(_pkiRoot, recursive: true); }
catch (IOException) { /* best effort */ }
}
}
}
@@ -0,0 +1,87 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
/// <summary>
/// lmxopcua#1053 (review 01 R-25): <c>ConfiguredProjectedInterestOwner.SweepAsync</c> re-queued every desired entry
/// every second, so a configured reference that cannot be resolved (origin down, mapping gone) re-ran discovery once a
/// second for as long as the interest lasted. A failed resolve now backs off exponentially (1 s doubling, 30 s cap).
/// </summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData")]
public sealed class GrpcDataConfiguredInterestBackoffTests
{
private static readonly string Reference = ProjectedDataIds.DependencyReference(DataRealm.Raw,
ProjectedDataIds.Identifier("mapping", new DataAddress("origin", "urn:raw", "string", "plant/unresolvable")));
/// <summary>
/// Sixty one-second sweeps against a reference that never resolves: one discovery per sweep before the fix (~61),
/// at most the backoff schedule's handful after it (t = 0, 1, 3, 7, 15, 31 s). Positive control: the retries do not
/// stop — once discovery succeeds, a later sweep within the 30 s cap acquires the lease.
/// </summary>
[Fact(Timeout = 60000)]
public async Task An_unresolvable_configured_reference_backs_off_instead_of_rediscovering_every_second()
{
var ct = TestContext.Current.CancellationToken;
var clock = new ManualTimeProvider();
var discovery = new FlakyDiscovery();
await using var owner = new ConfiguredProjectedInterestOwner(discovery, 4, clock: clock);
await clock.WaitForTimerDueAtAsync(clock.Start + TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5));
owner.SetInterest(Reference, true);
await WaitUntilAsync(() => Volatile.Read(ref discovery.Calls) >= 1, ct);
for (var second = 0; second < 60; second++)
{
clock.Advance(TimeSpan.FromSeconds(1));
await Task.Delay(30, ct); // let the sweep + a worker act on the tick (an upper bound is what is asserted)
}
var failedCalls = Volatile.Read(ref discovery.Calls);
failedCalls.ShouldBeLessThanOrEqualTo(8,
$"an unresolvable reference must back off; it was rediscovered {failedCalls} times in 60 s");
failedCalls.ShouldBeGreaterThanOrEqualTo(3, "it is still retried, just less often");
// Positive control: the origin comes back; a sweep within the 30 s cap resolves it.
discovery.Succeed = true;
for (var second = 0; second < 31 && discovery.Acquired == 0; second++)
{
clock.Advance(TimeSpan.FromSeconds(1));
await Task.Delay(30, ct);
}
await WaitUntilAsync(() => Volatile.Read(ref discovery.Acquired) == 1, ct);
}
private static async Task WaitUntilAsync(Func<bool> condition, CancellationToken ct)
{
var giveUp = DateTime.UtcNow + TimeSpan.FromSeconds(10);
while (!condition())
{
if (DateTime.UtcNow > giveUp) throw new TimeoutException("condition not reached");
await Task.Delay(5, ct);
}
}
private sealed class FlakyDiscovery : IConfiguredProjectionDiscovery
{
public int Calls, Acquired;
public volatile bool Succeed;
public Task<IConfiguredProjectionLease?> ResolveAsync(string reference, CancellationToken cancellationToken)
{
Interlocked.Increment(ref Calls);
if (!Succeed) return Task.FromResult<IConfiguredProjectionLease?>(null);
Interlocked.Increment(ref Acquired);
return Task.FromResult<IConfiguredProjectionLease?>(new Lease());
}
}
private sealed class Lease : IConfiguredProjectionLease
{
public bool IsValid => true;
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}
@@ -157,6 +157,53 @@ public sealed class DriverHostCommsLossRecoveryTests : RuntimeActorTestBase
meter.SumWithTag("driver_instance", "drv-removed").ShouldBe(0);
}
/// <summary>
/// #1053 (decided: KEEP). Unlike a removal (R-16, <see cref="Removing_a_comms_lost_driver_cancels_its_audit_and_leaves_no_false_warning_or_metric"/>),
/// an operator RESTART must not clear the comms latch: the nodes stay in the address space, still Bad, and the
/// respawned incarnation is what has to re-publish them — exactly what the audit checks. No host change is needed
/// for that: the stopped incarnation's <c>PostStop</c> comms-loss announcement re-latches the CURRENT ref set and
/// cancels the audit the old incarnation armed, and the new incarnation's <c>Connected</c> re-arms it. Pinned
/// here: no audit fires while the new incarnation is still connecting (well past the old window), and once it
/// connects and stays silent its OWN audit reports the kept ref.
/// </summary>
[Fact]
public void Restarting_a_comms_lost_driver_keeps_its_latch_and_audits_it_from_the_new_incarnations_reconnect()
{
var driver = new ScriptedSubscribeDriver { InstanceId = "drv-restart", InitialPush = null };
var db = NewInMemoryDbFactory();
var deploymentId = SeedV3Deployment(db, RevA,
rawTags: new[] { (Driver: "drv-restart", DriverName: "Modbus", Device: "dev1", Tag: "speed", DataType: "Double", Writable: false) },
unsRefs: new[] { (Area: "filling", Line: "line1", Equip: "station1", BackingTag: "speed", Effective: (string?)null) },
enabled: true);
var audit = TimeSpan.FromSeconds(6);
var (host, publish, _) = SpawnHostAndApply(
this, db, TestNode, deploymentId, RevA,
commsRecoveryAuditDelay: audit, driverFactory: new SingleDriverFactory(driver));
AwaitCondition(() => driver.SubscribeCount >= 1, PresenceBudget, TestContext.Current.CancellationToken);
using var meter = new MeterRecorder("otopcua.driver.comms_latched_refs");
host.Tell(new ReconnectDriver("c1", "drv-restart", "test-operator", Guid.NewGuid()));
publish.FishForMessage<OpcUaPublishActor.AttributeStatusBatchUpdate>(_ => true, ReconnectBudget, cancellationToken: TestContext.Current.CancellationToken);
// The reconnect (silent re-subscribe) arms the old incarnation's audit; restart inside its window, with the new
// incarnation's initialize held so it cannot connect (and re-arm the audit) before the old timer would fire.
AwaitCondition(() => driver.SubscribeCount >= 2, ReconnectBudget, TestContext.Current.CancellationToken);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
driver.InitializeGate = release.Task;
host.Tell(new RestartDriver("c1", "drv-restart", "test-operator", Guid.NewGuid()));
EventFilter.Warning(contains: "still BadNoCommunication")
.Expect(0, audit + TimeSpan.FromSeconds(3), () => { }, TestContext.Current.CancellationToken);
meter.SumWithTag("driver_instance", "drv-restart").ShouldBe(0);
// The new incarnation connects, re-subscribes silently, and its own audit reports the ref the restart kept.
EventFilter.Warning(contains: "still BadNoCommunication").ExpectOne(audit + ReconnectBudget, () =>
{
driver.InitializeGate = null;
release.SetResult();
}, TestContext.Current.CancellationToken);
AwaitCondition(() => meter.SumWithTag("driver_instance", "drv-restart") == 1, TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
}
private (IActorRef Host, Akka.TestKit.TestProbe Publish) Arrange(ScriptedSubscribeDriver driver, string driverId)
{
var db = NewInMemoryDbFactory();
@@ -214,7 +261,11 @@ public sealed class DriverHostCommsLossRecoveryTests : RuntimeActorTestBase
public string DriverType => "Modbus";
public Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken) => Task.CompletedTask;
/// <summary>When set, <see cref="InitializeAsync"/> waits on it (holds a respawned incarnation in Connecting).</summary>
public Task? InitializeGate { get; set; }
public Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken) =>
InitializeGate is { } gate ? gate.WaitAsync(cancellationToken) : Task.CompletedTask;
public Task ReinitializeAsync(string driverConfigJson, CancellationToken cancellationToken) => Task.CompletedTask;