fix(grpc-data): A3a review r1 — condition-bearing projected folders are event notifiers from materialisation (folder-only demand), null-safe revalidation log; NM tests: B3 revalidation + demand release, S1 rebuild, deviation 3/6/8, S2 verdict TTL, A3-SEC delivery gate isolated (DroppedOnPublish 0)

This commit is contained in:
Joseph Doherty
2026-11-24 18:46:11 -05:00
parent 69aeeb770b
commit 14343bf086
6 changed files with 242 additions and 4 deletions
@@ -73,6 +73,10 @@ public interface IProjectedConditionAccess
/// folder event item (and its demand) before any imported condition is wired there.</summary>
bool CanSubscribeFolder(RoleCarryingUserIdentity? caller, string mappingId, string folderLocalSubject);
/// <summary>Deviation 3 (review r1): whether a deployed mapping is condition-bearing — its projected folders are event
/// notifiers from materialisation (the SDK refuses an event item on a node without <c>SubscribeToEvents</c>).</summary>
bool IsConditionBearingMapping(string mappingId);
/// <summary>A generation that moves whenever anything the gate reads may have changed (verdict caches key on it).</summary>
long AuthorityGeneration { get; }
@@ -8707,7 +8707,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
if (eventsStoodDown > 0 || eventsRestored > 0)
{
_authorizer!.LogFiltered(
// An imported-notifier item is revalidated through the imported gate even where no authorizer is wired (A3 r1 B3).
_authorizer?.LogFiltered(
"RevalidateEventSubscriptions", principal: null, eventsStoodDown, _eventItems.Count);
}
}
@@ -73,6 +73,8 @@ internal sealed class ProjectedConditionRegistry
/// projected node per apply chunk); resolved against the live projected maps at use.</summary>
internal readonly Dictionary<(string Mapping, string Subject), NodeId> FolderIds = new();
internal readonly Dictionary<NodeId, (string Mapping, string Subject)> FolderKeys = new();
/// <summary>Deviation 3: projected folders of condition-bearing mappings, event notifiers from materialisation.</summary>
internal readonly HashSet<NodeId> PromotedFolders = new();
/// <summary>Review r1 S2: a positive verdict is re-proved at least this often (credential expiry is honoured exactly).</summary>
internal static readonly TimeSpan PositiveVerdictTtl = TimeSpan.FromSeconds(5);
private readonly object _verdictGate = new();
@@ -574,7 +576,8 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
{
_importedConditions.WiredByFolder.Remove(folder.NodeId);
RemoveRootNotifier(folder);
folder.EventNotifier = (byte)(folder.EventNotifier & ~EventNotifiers.SubscribeToEvents);
if (!_importedConditions.PromotedFolders.Contains(folder.NodeId))
folder.EventNotifier = (byte)(folder.EventNotifier & ~EventNotifiers.SubscribeToEvents);
folder.ClearChangeMasks(SystemContext, includeChildren: false);
}
}
@@ -585,6 +588,12 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
if (_importedConditions.FolderKeys.Remove(folder.NodeId, out var previous)) _importedConditions.FolderIds.Remove(previous);
_importedConditions.FolderIds[(mappingId, localSubject)] = folder.NodeId;
_importedConditions.FolderKeys[folder.NodeId] = (mappingId, localSubject);
if (ProjectedConditionAccess is { } access && access.IsConditionBearingMapping(mappingId))
{
// Deviation 3 (review r1): a folder-only client can subscribe (and so open condition demand) before anything is wired.
_importedConditions.PromotedFolders.Add(folder.NodeId);
folder.EventNotifier = (byte)(folder.EventNotifier | EventNotifiers.SubscribeToEvents);
}
if (_importedConditions.Count == 0 || !_importedConditions.ByFolderKey.TryGetValue((mappingId, localSubject), out var set)) return;
foreach (var id in set.ToList())
if (_importedConditions.Find(id) is { } c) WireImportedFolder(c, folder);
@@ -594,6 +603,7 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
private void OnProjectedFolderRemoving(NodeId folderId)
{
if (_importedConditions.FolderKeys.Remove(folderId, out var key)) _importedConditions.FolderIds.Remove(key);
_importedConditions.PromotedFolders.Remove(folderId);
if (!_importedConditions.WiredByFolder.TryGetValue(folderId, out var entry)) return;
foreach (var id in entry.Conditions.ToList())
if (_importedConditions.Find(id) is { } c) UnwireImportedFolder(c, entry.Folder);
@@ -606,6 +616,7 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
foreach (var folderId in _importedConditions.WiredByFolder.Keys.ToList()) OnProjectedFolderRemoving(folderId);
_importedConditions.FolderIds.Clear();
_importedConditions.FolderKeys.Clear();
_importedConditions.PromotedFolders.Clear();
}
/// <summary>
@@ -158,6 +158,11 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
return Gate(identity, _mappings.Current, mappingId, null, folderLocalSubject);
}
/// <inheritdoc />
public bool IsConditionBearingMapping(string mappingId) =>
_mappings.Current.Any(x => string.Equals(x.Mapping.RemoteNamespaceMappingId, mappingId, StringComparison.OrdinalIgnoreCase)
&& x.Authority.IsActive && IsConditionBearing(x.Mapping));
/// <summary>The mapping gate for one (mapping, folder) placement; <paramref name="realm"/> null = the mapping's own.</summary>
private bool Gate(DataCallerIdentity identity, IReadOnlyList<ProjectedMappingPlacement> current, string mappingId, DataRealm? realm,
string folderLocalSubject)
@@ -245,6 +245,136 @@ public sealed class ImportedConditionEventWireTests
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// Review round 1 (a3a-review-round1.md)
// ---------------------------------------------------------------------------------------------------------------------
private static bool IsRefreshRequired(ArrayOf<Variant> e) => e[EventTypeF].GetNodeId() == ObjectTypeIds.RefreshRequiredEventType;
[Fact]
public async Task B3_revalidation_keeps_an_admitted_folder_item_and_deleting_a_stood_down_item_releases_its_demand()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-r1-reval", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements()));
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new Events();
var subscription = await SubscribeAsync(session, events, ct);
var folder = AddItem(subscription, f.DeviceFolder);
await subscription.ApplyChangesAsync(ct);
f.Access.Outstanding.ShouldBe(1, "the admitted folder item opened demand");
rig.Nm.RevalidateMonitoredItems(); // the ACL timer tick / a deploy
f.Apply(Update(Key1, version: 4, active: true, acked: true, f.TwoPlacements(), message: "after-revalidation"));
await Events.WaitUntilAsync(() => events.Of(folder).Any(e => Message(e) == "after-revalidation"));
// A revocation stands the item down; the client's later delete must still release the lease.
f.Access.Allowed.Clear();
Interlocked.Increment(ref f.Access.Generation);
rig.Nm.RevalidateMonitoredItems();
subscription.RemoveItem(folder);
await subscription.ApplyChangesAsync(ct);
f.Access.Outstanding.ShouldBe(0, "a stood-down item's delete releases its condition demand");
}
[Fact]
public async Task S1_a_full_rebuild_unwires_and_the_re_created_folder_is_promoted_and_delivers_again()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-r1-rebuild", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements()));
rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeTrue();
rig.Nm.RebuildAddressSpace();
rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeFalse("the rebuild discarded the folder: its wiring goes with it");
f.Rematerialise(); // the same NodeIds, new FolderState instances
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new Events();
var subscription = await SubscribeAsync(session, events, ct);
var folder = AddItem(subscription, f.DeviceFolder);
await subscription.ApplyChangesAsync(ct);
(folder.Status.Error?.StatusCode ?? StatusCodes.Good).Code.ShouldBe(StatusCodes.Good.Code, "the new folder is an event notifier again");
f.Apply(Update(Key1, version: 4, active: true, acked: true, f.TwoPlacements(), message: "after-rebuild"));
await Events.WaitUntilAsync(() => events.Of(folder).Any(e => Message(e) == "after-rebuild"));
}
[Fact]
public async Task Deviation3_a_folder_only_client_opens_demand_on_a_projected_folder_with_no_condition_wired_yet()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-r1-folderdemand", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
rig.Nm.ImportedConditionCount.ShouldBe(0, "nothing materialised (after a restart or a linger)");
using var granted = await rig.ConnectAsync(anonymous: false, ct);
using var denied = await rig.ConnectAsync(anonymous: true, ct);
var events = new Events();
var grantedSub = await SubscribeAsync(granted, events, ct);
var deniedSub = await SubscribeAsync(denied, new Events(), ct);
var grantedItem = AddItem(grantedSub, f.AnchorB);
var deniedItem = AddItem(deniedSub, f.AnchorB);
await grantedSub.ApplyChangesAsync(ct);
await deniedSub.ApplyChangesAsync(ct);
(grantedItem.Status.Error?.StatusCode ?? StatusCodes.Good).Code.ShouldBe(StatusCodes.Good.Code);
deniedItem.Status.Error?.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code, "the mapping gate still decides");
f.Access.Outstanding.ShouldBe(1, "the folder-only client opened condition demand");
// The condition that demand brings in is delivered to that folder item.
f.Apply(Update(Key2, version: 3, active: true, acked: false, [f.BPlacement()], message: "arrived"));
await Events.WaitUntilAsync(() => events.Of(grantedItem).Any(e => Message(e) == "arrived"));
}
[Fact]
public async Task Deviation6_removing_an_imported_condition_sends_RefreshRequired_only_to_the_items_that_could_see_it()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-r1-remove", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements()));
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new Events();
var subscription = await SubscribeAsync(session, events, ct);
var server = AddItem(subscription, ObjectIds.Server);
var device = AddItem(subscription, f.DeviceFolder);
var other = AddItem(subscription, f.AnchorB); // map-b: Key1 is never wired here
await subscription.ApplyChangesAsync(ct);
var before = rig.Nm.ImportedRefreshRequiredQueued;
rig.Nm.RemoveConditions(Connection, [Key1]);
rig.Nm.ImportedConditionCount.ShouldBe(0);
await Events.WaitUntilAsync(() => events.Of(server).Any(IsRefreshRequired) && events.Of(device).Any(IsRefreshRequired));
(rig.Nm.ImportedRefreshRequiredQueued - before).ShouldBe(2, "one per item that held it");
// Must-arrive control on the map-b item, queued AFTER the removal.
f.Apply(Update(Key2, version: 3, active: true, acked: false, [f.BPlacement()], message: "control"));
await Events.WaitUntilAsync(() => events.Of(other).Any(e => Message(e) == "control"));
events.Of(other).Any(IsRefreshRequired).ShouldBeFalse("an item that never saw the removed condition is not told to refresh");
}
[Fact]
public async Task Deviation8_ConditionRefresh_replays_hundreds_of_imported_conditions_in_chunks_between_RefreshStart_and_RefreshEnd()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-r1-replay", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
const int count = 300; // > 2 × the 128-condition chunk
rig.Nm.ApplyConditions(Enumerable.Range(0, count)
.Select(i => Update(KeyOf("bulk-" + i), version: 3, active: true, acked: false, f.TwoPlacements(), message: "bulk")).ToList());
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new Events();
var subscription = await SubscribeAsync(session, events, ct);
var server = AddItem(subscription, ObjectIds.Server);
await subscription.ApplyChangesAsync(ct);
await subscription.ConditionRefreshAsync(ct);
await Events.WaitUntilAsync(() => events.Of(server).Any(e => e[EventTypeF].GetNodeId() == ObjectTypeIds.RefreshEndEventType));
var list = events.Of(server).ToList();
var startAt = list.FindIndex(e => e[EventTypeF].GetNodeId() == ObjectTypeIds.RefreshStartEventType);
var endAt = list.FindIndex(e => e[EventTypeF].GetNodeId() == ObjectTypeIds.RefreshEndEventType);
list.Skip(startAt + 1).Take(endAt - startAt - 1).Count(e => Message(e) == "bulk")
.ShouldBe(count, "every retained imported condition once, inside the refresh bracket");
}
private static string KeyOf(string seed) =>
Convert.ToBase64String(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(seed))).TrimEnd('=').Replace('+', '-').Replace('/', '_');
@@ -323,6 +453,7 @@ public sealed class ImportedConditionEventWireTests
public long AuthorityGeneration => Interlocked.Read(ref Generation);
public bool CanSubscribeFolder(RoleCarryingUserIdentity? caller, string mappingId, string folderLocalSubject) =>
caller is not null && Allowed.Contains(caller.Principal);
public bool IsConditionBearingMapping(string mappingId) => true;
/// <summary>Leases currently held (acquired minus released).</summary>
public int Outstanding;
public IDisposable? AcquireEventDemand(RoleCarryingUserIdentity? caller)
@@ -351,10 +482,10 @@ public sealed class ImportedConditionEventWireTests
public static Fixture Install(ServerEventRig rig, string grantedPrincipal)
{
var (anchor, anchorB, device, definition) = Materialise(rig.Nm);
var access = new FakeConditionAccess();
access.Allowed.Add(grantedPrincipal);
rig.Nm.ProjectedConditionAccess = access;
rig.Nm.ProjectedConditionAccess = access; // bound before projections materialise, as the host does
var (anchor, anchorB, device, definition) = Materialise(rig.Nm);
return new Fixture { Rig = rig, Access = access, Anchor = anchor, AnchorB = anchorB, DeviceFolder = device, DeviceDefinition = definition };
}
@@ -396,3 +527,67 @@ public sealed class ImportedConditionEventWireTests
public void Apply(ImportedConditionUpdate update) => Rig.Nm.ApplyConditions([update]);
}
}
/// <summary>
/// Review r1 (test adequacy): A3-SEC with the DELIVERY gate isolated — on the denied path nothing is queued at all, so the
/// publish-time marker re-check (the second layer) has nothing to drop: <c>ProjectedEventFieldList.DroppedOnPublish</c>
/// does not move. Non-parallel: the counter is process-wide.
/// </summary>
[Collection(ImportedDeliveryGateCollection.Name)]
[Trait("Feature", "GrpcData"), Trait("Phase", "A3")]
public sealed class ImportedConditionDeliveryGateTests
{
[Fact]
public async Task A3_SEC_the_delivery_gate_alone_withholds_a_denied_sessions_event_nothing_is_dropped_on_publish()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-r1-gate", encrypted: false, ct);
var nm = rig.Nm;
var access = new ImportedConditionEventWireTests.FakeConditionAccess();
access.Allowed.Add(ServerEventRig.KeyPrincipal);
nm.ProjectedConditionAccess = access;
using var allowed = await rig.ConnectAsync(anonymous: false, ct);
using var denied = await rig.ConnectAsync(anonymous: true, ct);
var received = new System.Collections.Concurrent.ConcurrentBag<(string Who, uint Handle, string? Message)>();
async Task<Subscription> Subscribe(ISession session, string who)
{
var subscription = new Subscription(session.DefaultSubscription) { PublishingInterval = 100 };
subscription.FastEventCallback = (_, n, _) =>
{
foreach (var e in n.Events)
received.Add((who, e.ClientHandle, e.EventFields[0].TryGetValue(out LocalizedText text) ? text.Text : null));
};
session.AddSubscription(subscription);
await subscription.CreateAsync(ct);
var filter = new EventFilter();
filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.Message));
subscription.AddItem(new SdkMonitoredItem(subscription.DefaultItem)
{ StartNodeId = ObjectIds.Server, AttributeId = Attributes.EventNotifier, Filter = filter, QueueSize = 1000, SamplingInterval = 0 });
await subscription.ApplyChangesAsync(ct);
return subscription;
}
await Subscribe(allowed, "allowed");
var deniedSub = await Subscribe(denied, "denied");
var dropped = ProjectedEventFieldList.DroppedOnPublish;
var key = Convert.ToBase64String(SHA256.HashData("gate"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 info = new DataConditionInfo("AlarmConditionType", "HR", DataConditionSourceKind.Native, [view], 3);
var state = new DataConditionState(key, 1, false, true, info, true, false, true, true, 0, 500, "gated", 0, null, 0,
DateTimeOffset.UtcNow, true, new DataActivationMarker("i", 1));
nm.ApplyConditions([new ImportedConditionUpdate("conn-a", state, info, [placement], "Plant/remote-a/dev1/HR")]);
await RecordedEvents.WaitUntilAsync(() => received.Any(r => r.Who == "allowed" && r.Message == "gated")); // positive control
await deniedSub.ConditionRefreshAsync(ct); // must-arrive on the denied session: its own RefreshStart/End
await RecordedEvents.WaitUntilAsync(() => received.Count(r => r.Who == "denied") >= 2);
received.ShouldNotContain(r => r.Who == "denied" && r.Message == "gated");
(ProjectedEventFieldList.DroppedOnPublish - dropped).ShouldBe(0, "the delivery gate withheld it; nothing reached the publish-time drop");
}
}
[CollectionDefinition(Name, DisableParallelization = true)]
public sealed class ImportedDeliveryGateCollection
{
public const string Name = "Imported delivery gate (process-wide counter)";
}
@@ -116,6 +116,27 @@ public sealed class ImportedConditionClassifierTests : IAsyncDisposable
ReferenceEquals(ProjectedNotificationRewriter.Project(plain, republish: false, null), plain).ShouldBeTrue();
}
[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");
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");
}
private async Task<OtOpcUaNodeManager> BootAsync()
{
var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions
@@ -142,6 +163,7 @@ public sealed class ImportedConditionClassifierTests : IAsyncDisposable
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