From 4d29d539d828a92e85f65be141733aaa0051ceee Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Mon, 23 Nov 2026 18:28:48 -0500 Subject: [PATCH] feat(grpc-data): X0 review - tolerate any unknown bit at the artifact/catalog seam; drop diagnostics for exports and mappings - ValidateDeployed ignores every bit outside Understood (understood subset still validated); P02's two 1<<30 rows become 'tolerated, grants nothing'. - UnknownOperationDrops: Warning + counter tagged kind=connection|export|mapping, counted once per row per accepted artifact change; collected under each lock, logged after release. Mappings masked at Stage. - Surfaced via DataConnectionDiagnosticsSnapshot (DroppedUnknownOperations, MappingsWithDroppedOperations) and NodeDiagnosticsSnapshot.DroppedExportOperations. - End-to-end test: 1<<30 through parse -> catalog compile -> mapping stage -> runtime apply. - DataConnectionProtoContract.Validate() now runs at AddOtOpcUaDataConnections. --- scripts/validation/grpc-data/unit-phases.json | 5 +- .../DataConnectionDiagnosticsSnapshot.cs | 6 +- .../Interfaces/NodeDiagnosticsSnapshot.cs | 7 +- .../Validation/DataConnectionValidator.cs | 13 +-- .../DataConnectionRegistration.cs | 13 ++- .../DataConnectionDeploymentRuntime.cs | 55 ++++++------ .../LocalCatalogCoordinator.cs | 12 ++- .../DataConnections/LocalExportCatalog.cs | 7 ++ .../ProjectedMappingDeploymentRuntime.cs | 39 +++++++++ .../DataConnections/UnknownOperationDrops.cs | 51 +++++++++++ .../Drivers/DriverHostActor.cs | 4 +- ...GrpcDataReservedOperationAuthoringTests.cs | 21 +++-- .../GrpcDataArtifactReadTests.cs | 25 +++++- .../GrpcDataCatalogStagingTests.cs | 86 +++++++++++++++++++ .../GrpcDataUnknownOperationToleranceTests.cs | 14 ++- 15 files changed, 304 insertions(+), 54 deletions(-) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/UnknownOperationDrops.cs diff --git a/scripts/validation/grpc-data/unit-phases.json b/scripts/validation/grpc-data/unit-phases.json index bcab887f9..b92871cfc 100644 --- a/scripts/validation/grpc-data/unit-phases.json +++ b/scripts/validation/grpc-data/unit-phases.json @@ -756,7 +756,10 @@ "GrpcDataUnknownOperationToleranceTests", "GrpcDataFeatureHeaderClientTests" ], - "existing_classes": [] + "existing_classes": [ + "GrpcDataArtifactReadTests", + "GrpcDataCatalogStagingTests" + ] }, { "project": "tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/ZB.MOM.WW.OtOpcUa.Host.Tests.csproj", diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs index eab2c01a8..819a0d770 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs @@ -34,4 +34,8 @@ public sealed record DataConnectionDiagnosticsSnapshot( long? CompactFrameCount = null, long? FallbackFrameCount = null, long? SerializedValueFrameBytes = null, - string? AccountingInstanceId = null); + string? AccountingInstanceId = null, + // X0 tolerant reader: operation bits this connection row was authored with that this node does not implement and + // dropped (None = nothing dropped; null = from an older sender), and how many of its mappings had bits dropped. + DataOperations? DroppedUnknownOperations = null, + int? MappingsWithDroppedOperations = null); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/NodeDiagnosticsSnapshot.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/NodeDiagnosticsSnapshot.cs index f8686d205..019d3404f 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/NodeDiagnosticsSnapshot.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/NodeDiagnosticsSnapshot.cs @@ -43,10 +43,15 @@ public sealed record DriverInstanceDiagnostics( /// needs to be explicitly visible rather than inferred. Defaults to false, which is also what /// every node that booted normally reports. /// +/// +/// X0 tolerant reader: origin exports on this node whose operation bits this build does not implement, with the +/// bits dropped (no grant). Empty when none; null from a sender built before X0 or when no catalog is staged. +/// public sealed record NodeDiagnosticsSnapshot( NodeId NodeId, RevisionHash? CurrentRevision, IReadOnlyList Drivers, DateTime AsOfUtc, bool RunningFromCache = false, - IReadOnlyList? DataConnections = null); + IReadOnlyList? DataConnections = null, + IReadOnlyDictionary? DroppedExportOperations = null); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs index 00990a538..9ba11d5ac 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs @@ -21,10 +21,11 @@ public static class DataConnectionValidator /// /// Node-side re-validation of an already-deployed artifact (artifact parse, origin catalog compile). Identical to - /// except that the X0-RESERVED operation bits () - /// are IGNORED rather than rejected: a newer central may author them, and rejecting would take down every data - /// connection/export on the node. Each consumer of the rows keeps only the bits it understands (fail closed). A bit - /// outside both sets is still a malformed row (nothing can author it). + /// except that operation bits outside + /// are IGNORED rather than rejected (X0 tolerant reader): a newer central may author them, and rejecting would take + /// down every data connection/export on the node. The understood subset is still validated (a row must be non-empty; + /// a mapping may not grant an understood operation its connection lacks), and every consumer of the rows masks the + /// rest away, so an unknown bit grants nothing (fail closed). /// public static IReadOnlyList ValidateDeployed(DraftSnapshot draft) => Validate(draft, deployed: true); @@ -34,8 +35,8 @@ public static class DataConnectionValidator var errors = new List(); void Add(string code, string id, string message) => errors.Add(new(code, message, id)); bool Same(string? a, string? b) => Ids.Equals(a, b); - var accepted = deployed ? KnownOperations | DataOperationSets.Reserved : KnownOperations; - bool ValidOps(DataOperations operations) => operations != DataOperations.None && (operations & ~accepted) == 0; + bool ValidOps(DataOperations operations) => operations != DataOperations.None && + (deployed || (operations & ~KnownOperations) == 0); DataOperations Understood(DataOperations operations) => deployed ? operations & DataOperationSets.Understood : operations; bool NodesValid(IEnumerable ids, string owner) { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs index d4fbb71fb..a99b7f078 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs @@ -33,6 +33,8 @@ public static class DataConnectionRegistration services.AddSingleton>(new DataConnectionOptionsValidator(environment)); if (!options.Enabled) return options; if (!hasDriver) throw new InvalidOperationException("DataConnections requires this node's driver role."); + // Fail host start on a wire-contract drift (frozen field numbers and the X0 reservations); a descriptor walk, cheap. + ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnectionProtoContract.Validate(); services.TryAddSingleton(TimeProvider.System); services.TryAddSingleton(); @@ -56,7 +58,7 @@ public static class DataConnectionRegistration var state = CaptureReadRole(role, warm); var servingRole = settings.IsWarm && state.WarmRole != WarmRole.Active ? "Standby" : state.Role; return new(identity.NodeId, identity.Incarnation, servingRole, 0, 0, state.Generation); - }); + }) { Logger = LoggerFor(sp) }; }); services.AddSingleton(sp => new PartitionedSampleHub(options.Hub, sp.GetRequiredService())); services.AddSingleton(sp => new SourceSamplePublisher(sp.GetRequiredService(), @@ -72,7 +74,8 @@ public static class DataConnectionRegistration sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), 256, options.MaxConcurrentCalls)); services.AddSingleton(sp => sp.GetRequiredService()); - services.AddSingleton(); + services.AddSingleton(sp => new ProjectedMappingDeploymentRuntime(sp.GetRequiredService(), + sp.GetRequiredService()) { Logger = LoggerFor(sp) }); services.TryAddSingleton(); services.AddSingleton(); services.AddSingleton(sp => sp.GetRequiredService()); @@ -214,8 +217,7 @@ public static class DataConnectionRegistration return new DataConnectionConsumerRoleSnapshot(mode, eligible, state.Generation); }) { - Logger = (Microsoft.Extensions.Logging.ILogger?)sp.GetService()?.CreateLogger() - ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance, + Logger = LoggerFor(sp), }; return runtime; }); @@ -237,6 +239,9 @@ public static class DataConnectionRegistration return options; } + private static Microsoft.Extensions.Logging.ILogger LoggerFor(IServiceProvider sp) => + (Microsoft.Extensions.Logging.ILogger?)sp.GetService()?.CreateLogger() + ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance; private static (string Role, long Generation, WarmRole? WarmRole, long ReadEpoch) CaptureReadRole( RedundancyRoleView role, DataConnectionWarmRoleView warm) { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs index 513345b26..7f712b127 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs @@ -1,7 +1,5 @@ -using System.Diagnostics.Metrics; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using ZB.MOM.WW.OtOpcUa.Commons.Observability; using ZB.MOM.WW.OtOpcUa.Configuration.Entities; using ZB.MOM.WW.OtOpcUa.Configuration.Enums; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; @@ -43,11 +41,8 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable internal bool Ready; internal int Leases; } - /// Counter of connection rows whose unknown operation bits were dropped (X0 tolerant reader). - public const string UnknownOperationsCounterName = "otopcua.dataconnection.unknown_operations_dropped"; - private static readonly Counter UnknownOperationsCounter = OtOpcUaTelemetry.Meter.CreateCounter( - UnknownOperationsCounterName, unit: "{row}", - description: "Data-connection rows carrying operation bits this node does not understand; the bits were dropped (no grant)."); + /// Counter of rows whose unknown operation bits were dropped (X0 tolerant reader); see . + public const string UnknownOperationsCounterName = UnknownOperationDrops.CounterName; private readonly object _sync = new(); /// Diagnostics sink for the X0 dropped-operation warning; optional (an init property keeps the constructor shape). public ILogger Logger { private get; init; } = NullLogger.Instance; @@ -99,25 +94,40 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable /// this node does not understand and therefore dropped (an unknown grant is no grant). Empty when none. /// public IReadOnlyDictionary DroppedUnknownOperations { get { lock (_sync) return _droppedOperations; } } - /// Cumulative count of connection rows that had unknown bits dropped, once per accepted artifact. + /// + /// Cumulative count of connection rows that had unknown bits dropped: once per row per accepted artifact change + /// (same revision re-applied does not recount; A → B → A does; a restart resets). + /// public long UnknownOperationRowsDropped => Interlocked.Read(ref _unknownOperationRows); /// Configured redundancy mode from the current validated artifact. public RedundancyMode CurrentConsumerMode { get { lock (_sync) return _desired?.ConsumerMode ?? RedundancyMode.None; } } /// Captures only this node's applied scope and current transport evidence. - public IReadOnlyList CaptureDiagnostics(IReadOnlyDictionary? retainedSourceCounts = null) + /// Per connection id, the projected sources retained (host-supplied). + /// + /// Per connection id, how many of its mappings had unknown operation bits dropped (from + /// ); null = not available. + /// + public IReadOnlyList CaptureDiagnostics(IReadOnlyDictionary? retainedSourceCounts = null, + IReadOnlyDictionary? mappingsWithDroppedOperations = null) { lock (_sync) { if (_disposed || _desired is not { } desired) return []; + var dropped = _droppedOperations; + DataOperations? Dropped(string id) => dropped.TryGetValue(id, out var bits) ? bits : DataOperations.None; + int? MappingDrops(string id) => mappingsWithDroppedOperations is null ? null + : mappingsWithDroppedOperations.TryGetValue(id, out var count) ? count : 0; return desired.Specs.Values.Select(spec => { if (!_attemptPending && _scopeReady && _entries.TryGetValue(spec.Id, out var entry) && entry.Ready) return entry.Connection.CaptureDiagnostics(spec.Revision, desired.ScopeVersion, desired.ArtifactRevision) with - { SourceCount = retainedSourceCounts is null ? null : retainedSourceCounts.TryGetValue(spec.Id, out var count) ? count : 0 }; + { SourceCount = retainedSourceCounts is null ? null : retainedSourceCounts.TryGetValue(spec.Id, out var count) ? count : 0, + DroppedUnknownOperations = Dropped(spec.Id), MappingsWithDroppedOperations = MappingDrops(spec.Id) }; return new ZB.MOM.WW.OtOpcUa.Commons.Interfaces.DataConnectionDiagnosticsSnapshot(spec.Id, spec.Revision, _attemptPending ? "connecting" : _retryNotBefore > _clock.GetTimestamp() ? "backoff" : "connecting", - null, null, 0, 0, desired.ScopeVersion, desired.ArtifactRevision, _clock.GetUtcNow().UtcDateTime); + null, null, 0, 0, desired.ScopeVersion, desired.ArtifactRevision, _clock.GetUtcNow().UtcDateTime) + { DroppedUnknownOperations = Dropped(spec.Id), MappingsWithDroppedOperations = MappingDrops(spec.Id) }; }).ToArray(); } } @@ -173,7 +183,8 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable // dropped from THIS row only, fail closed, and counted. It used to reject the whole snapshot. A row left // with no understood operation stays configured and grants nothing. var operations = item.AllowedOperations & DataOperationSets.Understood; - if (operations != item.AllowedOperations) dropped[item.DataConnectionId] = item.AllowedOperations & ~DataOperationSets.Understood; + if (UnknownOperationDrops.Unknown(item.AllowedOperations) is var unknown && unknown != DataOperations.None) + dropped[item.DataConnectionId] = unknown; var endpoints = item.Endpoints.Select(value => Uri.TryCreate(value, UriKind.Absolute, out var uri) && uri.Scheme == Uri.UriSchemeHttps ? uri : throw new ArgumentException("Only HTTPS endpoints are accepted.", nameof(snapshot))).Distinct().ToArray(); var eligible = new HashSet(item.EligibleTargetNodeIds, StringComparer.OrdinalIgnoreCase); @@ -186,6 +197,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable throw new ArgumentException("Duplicate connection identity.", nameof(snapshot)); } Entry[] old; + var report = false; lock (_sync) { ObjectDisposedException.ThrowIf(_disposed, this); @@ -210,26 +222,17 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable foreach (var id in specs.Keys) _routeRevisions.Add(id, generation); var priorRevision = _desired?.ArtifactRevision; _desired = new(snapshot.ScopeVersion, snapshot.ArtifactRevision, generation, snapshot.ConsumerMode, specs, allow); - RecordDroppedLocked(snapshot.ArtifactRevision, priorRevision, dropped); + _droppedOperations = dropped; + report = dropped.Count != 0 && !string.Equals(snapshot.ArtifactRevision, priorRevision, StringComparison.Ordinal); + if (report) Interlocked.Add(ref _unknownOperationRows, dropped.Count); _scopeReady = false; old = _entries.Values.ToArray(); _entries.Clear(); ApplyManagerScopeLocked(_desired); foreach (var entry in old) Retire(entry); WakeLocked(); } - } - private void RecordDroppedLocked(string revision, string? priorRevision, Dictionary dropped) - { - _droppedOperations = dropped; - if (dropped.Count == 0 || string.Equals(revision, priorRevision, StringComparison.Ordinal)) return; - Interlocked.Add(ref _unknownOperationRows, dropped.Count); - foreach (var (id, bits) in dropped) - { - UnknownOperationsCounter.Add(1); - Logger.LogWarning("Data connection {DataConnectionId} in artifact {ArtifactRevision} grants operation bits {UnknownOperations} " + - "this node does not implement; they were dropped (no grant). Upgrade this node before relying on them.", - id, revision, (int)bits); - } + // Collected under _sync, reported after release (logging may block). + if (report) UnknownOperationDrops.Report(Logger, UnknownOperationDrops.ConnectionKind, snapshot.ArtifactRevision, dropped); } private static bool SameAllowlist(IReadOnlyDictionary left, IReadOnlyDictionary right) => left.Count == right.Count && left.All(x => right.TryGetValue(x.Key, out var value) && string.Equals(value, x.Value, StringComparison.Ordinal)); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalCatalogCoordinator.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalCatalogCoordinator.cs index 33e61d771..388416776 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalCatalogCoordinator.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalCatalogCoordinator.cs @@ -46,6 +46,10 @@ public sealed class LocalCatalogCoordinator // A test can hold the host's existing subscription boundary to observe ordering. internal Action? BeforeSubscriptionApplyForTests { get; set; } + private string? _droppedExportRevision; + /// Diagnostics sink for the X0 dropped export-operation warning. + public Microsoft.Extensions.Logging.ILogger Logger { private get; init; } = Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance; + public LocalCatalogCoordinator(CatalogActivation activation, DataPlaneAuthorityState authority, Func serving) { _activation = activation ?? throw new ArgumentNullException(nameof(activation)); @@ -132,6 +136,7 @@ public sealed class LocalCatalogCoordinator { ArgumentNullException.ThrowIfNull(attempt); ArgumentNullException.ThrowIfNull(snapshot); + IReadOnlyDictionary? dropped = null; lock (_gate) { var state = _activation.Current; @@ -145,8 +150,13 @@ public sealed class LocalCatalogCoordinator && node.Enabled && !node.MaintenanceMode)) return false; var token = _activation.CaptureStagedAuthority(attempt.Epoch, state.AuthorityEpoch); _staged = LocalExportCatalog.Compile(snapshot, serving, token); - return true; + if (_staged.DroppedUnknownOperations.Count != 0 && !string.Equals(_droppedExportRevision, attempt.Revision, StringComparison.Ordinal)) + dropped = _staged.DroppedUnknownOperations; + _droppedExportRevision = attempt.Revision; } + // Collected under _gate, reported after release. + if (dropped is not null) UnknownOperationDrops.Report(Logger, UnknownOperationDrops.ExportKind, attempt.Revision, dropped); + return true; } public bool Complete(CatalogAttempt attempt, bool topologySucceeded) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs index c7b5d9b36..4eac8c855 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs @@ -78,6 +78,7 @@ public sealed partial class LocalExportCatalog .ToDictionary(x => x.Key, x => x.OrderBy(n => n.Metadata.BrowseName, StringComparer.Ordinal) .ThenBy(n => n.Metadata.View.Address.Identifier, StringComparer.Ordinal).ToArray()); var rules = new List(); + var dropped = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var export in exports.Where(x => x.Enabled && string.Equals(x.ClusterId, clusterId, StringComparison.OrdinalIgnoreCase))) { var wholeRealm = export.RootKind == "Cluster" && string.Equals(export.RootEntityId, clusterId, StringComparison.OrdinalIgnoreCase); @@ -91,12 +92,17 @@ public sealed partial class LocalExportCatalog rules.Add(new(export.DataExportId, export.PrincipalId, export.Realm, wholeRealm ? null : roots[0].Metadata.View, wholeRealm, // X0: an export bit this build does not implement grants nothing (a None-after-mask rule is kept and inert). export.AllowedOperations & DataOperationSets.Understood, export.MaxBatchItems, export.MaxPageItems, export.MaxMonitoredItems, export.MaxStreams)); + if (UnknownOperationDrops.Unknown(export.AllowedOperations) is var unknown && unknown != DataOperations.None) + dropped[export.DataExportId] = unknown; } _exports = rules.ToArray(); + DroppedUnknownOperations = dropped; Nodes = new ReadOnlyCollection(_nodes.Values.ToArray()); } public string ClusterId { get; } + /// X0 diagnostics: exports whose operation bits this build does not implement were dropped, by export id. + public IReadOnlyDictionary DroppedUnknownOperations { get; } public ServingIdentity Serving { get; } internal IDataMappedCatalogAuthority MappingAuthority => _activation; public long AuthorityEpoch => _activation.AuthorityEpoch; @@ -112,6 +118,7 @@ public sealed partial class LocalExportCatalog throw new ArgumentException("A new process or catalog generation requires a newly compiled catalog.", nameof(serving)); ClusterId = current.ClusterId; Serving = serving; _activation = current._activation; _nodes = current._nodes; _children = current._children; _exports = current._exports; Nodes = current.Nodes; + DroppedUnknownOperations = current.DroppedUnknownOperations; } /// A role-only transition changes serving provenance without freshening source acquisitions. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedMappingDeploymentRuntime.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedMappingDeploymentRuntime.cs index 57867d25c..e6386667b 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedMappingDeploymentRuntime.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedMappingDeploymentRuntime.cs @@ -29,6 +29,12 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable private object _configuredStamp = new(); private bool _disposed; + private IReadOnlyDictionary _droppedOperations = + new Dictionary(); + private string? _droppedRevision; + /// Diagnostics sink for the X0 dropped-operation warning (init so the DI constructor shape is unchanged). + public Microsoft.Extensions.Logging.ILogger Logger { private get; init; } = Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance; + public ProjectedMappingDeploymentRuntime(LocalCatalogCoordinator coordinator, RemoteNamespaceResolver resolver) { _coordinator = coordinator ?? throw new ArgumentNullException(nameof(coordinator)); @@ -123,13 +129,45 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable ArgumentNullException.ThrowIfNull(connections); var frozenMappings = mappings.Select(Copy).ToArray(); var frozenConnections = connections.Select(Copy).ToArray(); + // X0 tolerant reader: a mapping bit this build does not implement grants nothing. Mask the frozen copies (the + // caller's rows are untouched) so every downstream check sees only understood operations. + var dropped = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var mapping in frozenMappings) + { + var unknown = UnknownOperationDrops.Unknown(mapping.AllowedOperations); + if (unknown == DataOperations.None) continue; + mapping.AllowedOperations &= DataOperationSets.Understood; + dropped[mapping.RemoteNamespaceMappingId] = (mapping.DataConnectionId, unknown); + } + var report = false; lock (_gate) { ObjectDisposedException.ThrowIf(_disposed, this); if (!ReferenceEquals(attempt, _attempt)) return; _staged = frozenMappings; _connections = frozenConnections; + _droppedOperations = dropped; + report = dropped.Count != 0 && !string.Equals(_droppedRevision, attempt.Revision, StringComparison.Ordinal); + _droppedRevision = attempt.Revision; } + // Collected under _gate, reported after release. + if (report) + UnknownOperationDrops.Report(Logger, UnknownOperationDrops.MappingKind, attempt.Revision, + dropped.ToDictionary(x => x.Key, x => x.Value.Bits, StringComparer.OrdinalIgnoreCase)); + } + + /// X0 diagnostics: the staged mappings whose unknown operation bits were dropped, by mapping id. + public IReadOnlyDictionary DroppedUnknownOperations + { + get { lock (_gate) return _droppedOperations.ToDictionary(x => x.Key, x => x.Value.Bits, StringComparer.OrdinalIgnoreCase); } + } + + /// Per data connection id, how many of the staged mappings had unknown operation bits dropped. + public IReadOnlyDictionary CaptureDroppedByConnection() + { + lock (_gate) + return _droppedOperations.Values.GroupBy(x => x.ConnectionId, StringComparer.OrdinalIgnoreCase) + .ToDictionary(x => x.Key, x => x.Count(), StringComparer.OrdinalIgnoreCase); } internal void AttemptBegan(CatalogAttempt attempt) @@ -144,6 +182,7 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable Volatile.Write(ref _configuredStamp, new object()); _configuredCapabilities.Clear(); _staged = []; _connections = []; + _droppedOperations = new Dictionary(); changed = _active.Count != 0; Volatile.Write(ref _active, Array.Empty()); _byMapping.Clear(); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/UnknownOperationDrops.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/UnknownOperationDrops.cs new file mode 100644 index 000000000..f702397af --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/UnknownOperationDrops.cs @@ -0,0 +1,51 @@ +using System.Diagnostics.Metrics; +using Microsoft.Extensions.Logging; +using ZB.MOM.WW.OtOpcUa.Commons.Observability; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// +/// X0 tolerant-reader diagnostics. A deployed row (connection, export or mapping) may carry operation bits a newer +/// central authored and this build does not implement. They are dropped (no grant). Each drop is logged and counted. +/// +/// +/// +/// Semantics: counted once per row per ACCEPTED ARTIFACT CHANGE for that kind. Re-applying the same revision does not +/// recount, but A → B → A does (each is a change), and a process restart resets the per-kind memory. +/// +/// +/// The counter is , tagged kind = connection | export | mapping. +/// +/// +/// Callers collect under their own lock and call after releasing it. +/// +/// +public static class UnknownOperationDrops +{ + public const string CounterName = "otopcua.dataconnection.unknown_operations_dropped"; + public const string ConnectionKind = "connection"; + public const string ExportKind = "export"; + public const string MappingKind = "mapping"; + + private static readonly Counter Counter = OtOpcUaTelemetry.Meter.CreateCounter(CounterName, unit: "{row}", + description: "Deployed data-connection, export or mapping rows carrying operation bits this node does not implement; " + + "the bits were dropped (no grant). Counted once per row per accepted artifact change."); + + /// The bits of this build drops (zero when it understands all of them). + public static DataOperations Unknown(DataOperations authored) => authored & ~DataOperationSets.Understood; + + /// Logs a Warning and counts one per row. Never call while holding a component lock. + public static void Report(ILogger logger, string kind, string revision, IReadOnlyDictionary dropped) + { + ArgumentNullException.ThrowIfNull(logger); + ArgumentNullException.ThrowIfNull(dropped); + foreach (var (id, bits) in dropped) + { + Counter.Add(1, new KeyValuePair("kind", kind)); + logger.LogWarning("Data {Kind} {Id} in artifact {ArtifactRevision} grants operation bits 0x{UnknownOperations:X} this node " + + "does not implement; they were dropped (no grant). Upgrade this node before relying on them.", + kind, id, revision, (int)bits); + } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs index d60a19b5f..eeef8df2b 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -2981,7 +2981,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS Drivers: drivers, AsOfUtc: DateTime.UtcNow, RunningFromCache: _isRunningFromCache, - DataConnections: _dataConnections?.CaptureDiagnostics(_projectedPublisher?.CaptureSourceCounts())); + DataConnections: _dataConnections?.CaptureDiagnostics(_projectedPublisher?.CaptureSourceCounts(), + _catalogCoordinator?.ProjectedMappings?.CaptureDroppedByConnection()), + DroppedExportOperations: _catalogCoordinator?.Current?.DroppedUnknownOperations); Sender.Tell(snapshot); } diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataReservedOperationAuthoringTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataReservedOperationAuthoringTests.cs index bca7eaff3..ebb94867d 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataReservedOperationAuthoringTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataReservedOperationAuthoringTests.cs @@ -50,16 +50,19 @@ public sealed class GrpcDataReservedOperationAuthoringTests [Theory] [InlineData(1 << 10)] [InlineData(1 << 30)] - public void A_bit_outside_v1_and_the_reservation_is_malformed_in_both_modes(int bit) + public void Any_bit_outside_v1_is_rejected_at_authoring_and_tolerated_on_a_deployed_artifact(int bit) { - // Nothing can author it (no release reserves it), so node-side it stays a malformed row, as before X0 - // (GrpcDataArtifactReadTests pins 1 << 30 failing closed). - foreach (var errors in new[] { DataConnectionValidator.Validate(Snapshot(DataOperations.Read | (DataOperations)bit)), - DataConnectionValidator.ValidateDeployed(Snapshot(DataOperations.Read | (DataOperations)bit)) }) - { - errors.ShouldContain(x => x.Code == "DataConnectionOperationsInvalid"); - errors.ShouldContain(x => x.Code == "DataExportOperationsInvalid"); - } + // Authoring rejects anything outside V1. A deployed artifact may come from a newer central that defines bits this + // build has never heard of (not only the X0 reservation), so node-side re-validation ignores them; consumers mask + // them away (GrpcDataArtifactReadTests / GrpcDataUnknownOperationToleranceTests pin "parses, grants nothing"). + var authored = DataConnectionValidator.Validate(Snapshot(DataOperations.Read | (DataOperations)bit)); + authored.ShouldContain(x => x.Code == "DataConnectionOperationsInvalid"); + authored.ShouldContain(x => x.Code == "DataExportOperationsInvalid"); + DataConnectionValidator.ValidateDeployed(Snapshot(DataOperations.Read | (DataOperations)bit)) + .ShouldNotContain(x => x.Code.EndsWith("OperationsInvalid", StringComparison.Ordinal)); + // An all-unknown row is non-empty, so it is not an error; it simply grants nothing downstream. + DataConnectionValidator.ValidateDeployed(Snapshot((DataOperations)bit)) + .ShouldNotContain(x => x.Code == "DataConnectionOperationsInvalid" || x.Code == "DataExportOperationsInvalid"); } private static DraftSnapshot Snapshot(DataOperations operations) => new() diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataArtifactReadTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataArtifactReadTests.cs index eb7837c7e..f73118526 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataArtifactReadTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataArtifactReadTests.cs @@ -188,7 +188,6 @@ public sealed class GrpcDataArtifactReadTests [InlineData("Endpoints", "null")] [InlineData("Endpoints", "[\"http://node-b:7443\"]")] [InlineData("AllowedOperations", "0")] - [InlineData("AllowedOperations", "1073741824")] [InlineData("MaxBatchItems", "0")] [InlineData("Revision", "0")] public void Malformed_enabled_connection_fails_closed_with_row_diagnostics( @@ -235,7 +234,6 @@ public sealed class GrpcDataArtifactReadTests [InlineData("Realm", "0")] [InlineData("RootEntityId", "\"missing-origin\"")] [InlineData("RootKind", "\"RemoteNamespaceMapping\"")] - [InlineData("AllowedOperations", "1073741824")] [InlineData("Revision", "0")] public void Malformed_enabled_export_cannot_become_a_broad_or_reexport_grant( string field, @@ -251,6 +249,29 @@ public sealed class GrpcDataArtifactReadTests error.Message.ShouldContain("export-a"); } + [Trait("Phase", "X0")] + // X0 (plan section 4.3): an operation bit this build does not understand, e.g. one a newer central authored, is + // TOLERATED at the parse seam and grants nothing downstream. Before X0 it failed the whole row closed (and with it + // the snapshot). Only the understood subset is validated; an all-unknown row parses and is inert. + [Theory] + [InlineData(1073741824, 0)] + [InlineData(5 | 1073741824, 5)] + [InlineData(5 | 32, 5)] + public void Unknown_operation_bit_on_a_connection_or_export_parses_and_grants_nothing(int authored, int understood) + { + var root = Fixture(); + root["DataConnections"]![0]!["AllowedOperations"] = authored; + root["DataExports"]![0]!["AllowedOperations"] = authored; + using var parsed = DeploymentArtifact.Open(Blob(root)); + + var connection = parsed.ParseDataConnections(NodeA).ShouldHaveSingleItem(); + var export = parsed.ParseDataExports(NodeA).ShouldHaveSingleItem(); + connection.AllowedOperations.ShouldBe((DataOperations)authored, "rows are returned as authored"); + (connection.AllowedOperations & DataOperationSets.Understood).ShouldBe((DataOperations)understood); + (export.AllowedOperations & DataOperationSets.Understood).ShouldBe((DataOperations)understood); + (DataOperationSets.Understood & (DataOperations)1073741824).ShouldBe(DataOperations.None, "the bit is never granted"); + } + [Fact] public void Missing_connection_array_does_not_leave_an_enabled_orphan_mount() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCatalogStagingTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCatalogStagingTests.cs index 344942182..f368ab2f0 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCatalogStagingTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCatalogStagingTests.cs @@ -152,6 +152,92 @@ public sealed class GrpcDataCatalogStagingTests : RuntimeActorTestBase runtime.Active.ShouldBeEmpty(); } + /// + /// X0 end to end (plan §4.3): an operation bit no build defines (1 << 30) on one connection, one export and one mapping + /// flows through the REAL artifact parse, origin catalog compile, mapping stage and consumer runtime. Every other + /// connection/export stays up, the bit is never granted anywhere, and each drop is visible in diagnostics. + /// + [Fact(Timeout = 30000), Trait("Phase", "X0")] + public async Task X0_unknown_operation_bit_flows_through_parse_catalog_mapping_and_runtime_and_is_never_granted() + { + const DataOperations Unknown = (DataOperations)(1 << 30); + const DataOperations Bmr = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read; + var root = JsonNode.Parse(Artifact())!.AsObject(); + root["DataConnectionScopeVersion"] = 1; + DataConnection Connection(string id, DataOperations operations) => new() + { + DataConnectionId = id, ClusterId = "cluster", Revision = 1, Enabled = true, ConsumerNodeIds = ["node-a"], + TargetMode = DataTargetMode.Node, Consistency = DataConsistency.Primary, ExpectedClusterId = "remote-cluster", + ExpectedNodeId = "remote", Endpoints = ["https://remote.example:8443"], SecretReference = "secret:data/" + id, + SecretScopeClusterId = "cluster", AllowedOperations = operations, MaxMessageBytes = 65536, MaxBatchItems = 16, + MaxPageItems = 16, MaxStreams = 2, MaxMonitoredItems = 16, MaxPendingBytes = 65536, TimeoutMilliseconds = 5000, + }; + root["DataConnections"] = JsonSerializer.SerializeToNode(new[] { Connection("link", Bmr | Unknown), Connection("plain", Bmr) }); + root["DataExports"]![0]!["AllowedOperations"] = (int)(Bmr | Unknown); + root["DataExports"]!.AsArray().Add(JsonNode.Parse(""" + {"DataExportId":"uns","ClusterId":"cluster","Enabled":true,"Realm":2,"RootKind":"Cluster","RootEntityId":"cluster","PrincipalId":"other","AllowedOperations":7} + """)); + var mapping = TestMapping(); mapping.ConsumerNodeIds = ["node-a"]; mapping.RemoteNamespaceUri = V3NodeIds.RawNamespaceUri; + mapping.AllowedOperations = DataOperations.Browse | Unknown; + root["RemoteNamespaceMappings"] = JsonSerializer.SerializeToNode(new[] { mapping }); + var bytes = Encoding.UTF8.GetBytes(root.ToJsonString()); + + // Origin side: the catalog compiles (pre-X0 it threw "Origin catalog configuration is invalid"). + var authority = new DataPlaneAuthorityState(); + var coordinator = NewCoordinator(authority, new CatalogActivation()); + var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System); + using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy), + new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2); + using var mappings = new ProjectedMappingDeploymentRuntime(coordinator, resolver); + var attempt = Prepare(coordinator, bytes); + using var parsed = DeploymentArtifact.Open(bytes); + var connections = parsed.ParseDataConnections(Node.Value); + mappings.Stage(attempt, parsed.ParseRemoteNamespaceMappings(Node.Value), connections); + coordinator.Complete(attempt, true).ShouldBeTrue(); + var catalog = coordinator.Current.ShouldNotBeNull(); + catalog.ExportOperations("peer").ShouldBe(Bmr, "the unknown export bit is never granted"); + catalog.ExportOperations("other").ShouldBe(Bmr, "the unaffected export is up"); + catalog.DroppedUnknownOperations.ShouldBe(new Dictionary { ["raw"] = Unknown }); + + // Mapping stage: masked, placed, counted per connection. + mappings.Active.ShouldHaveSingleItem().Mapping.AllowedOperations.ShouldBe(DataOperations.Browse); + mappings.DroppedUnknownOperations.ShouldBe(new Dictionary { ["map"] = Unknown }); + var mappingDrops = mappings.CaptureDroppedByConnection(); + mappingDrops.ShouldBe(new Dictionary { ["link"] = 1 }); + + // Consumer runtime: both connections are up; the bit is never granted; diagnostics carry the drops. + await using var runtime = new DataConnectionDeploymentRuntime(Node.Value, "cluster", new X0Security(), new X0Activator(), 4); + runtime.Apply(new(1, attempt.Revision, connections)); + foreach (var id in new[] { "link", "plain" }) + { + DataConnectionDeploymentLease? lease = null; + for (var i = 0; i < 250 && !runtime.TryAcquire(id, out lease); i++) await Task.Delay(20, TestContext.Current.CancellationToken); + lease.ShouldNotBeNull(id); + using (lease) lease.AllowedOperations.ShouldBe(Bmr, id); + } + var diagnostics = runtime.CaptureDiagnostics(null, mappingDrops).ToDictionary(x => x.ConnectionId); + diagnostics["link"].DroppedUnknownOperations.ShouldBe(Unknown); + diagnostics["link"].MappingsWithDroppedOperations.ShouldBe(1); + diagnostics["plain"].DroppedUnknownOperations.ShouldBe(DataOperations.None); + diagnostics["plain"].MappingsWithDroppedOperations.ShouldBe(0); + } + + private sealed class X0Security : IDataConnectionSecurityProvider + { + public event Action? Changed { add { } remove { } } + public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => + ValueTask.FromResult(new("1", "trust", "key", () => new X0NoNetwork())); + } + private sealed class X0NoNetwork : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => + throw new InvalidOperationException("This test must not use the network."); + } + private sealed class X0Activator : IDataConnectionScopeActivator + { + public Task SetScopeAsync(long version, IReadOnlyDictionary allowlist, CancellationToken cancellationToken) => Task.CompletedTask; + } + private static RemoteNamespaceMapping TestMapping() => new() { RemoteNamespaceMappingId = "map", ClusterId = "cluster", DataConnectionId = "link", Revision = 1, Enabled = true, Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw, LocalParentKind = "RawFolder", LocalParentId = "folder", BranchName = "Remote", RemoteRootEntityId = "remote-root", diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataUnknownOperationToleranceTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataUnknownOperationToleranceTests.cs index 5758d673a..e7076e1ae 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataUnknownOperationToleranceTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataUnknownOperationToleranceTests.cs @@ -36,7 +36,7 @@ public sealed class GrpcDataUnknownOperationToleranceTests await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4); var history = Definition("history", DataOperations.Read | DataOperations.Browse | DataOperations.HistoryRead | DataOperations.AlarmShelve); var plain = Definition("plain", DataOperations.Read | DataOperations.Subscribe); - var future = Definition("future", (DataOperations)(1 << 20) | DataOperations.AlarmSubscribe); + var future = Definition("future", (DataOperations)(1 << 30) | DataOperations.AlarmSubscribe); // The pre-X0 runtime threw ArgumentException("Unknown operation.") here for the whole snapshot. Should.NotThrow(() => runtime.Apply(new(1, "artifact-1", [history, plain, future]))); @@ -50,9 +50,15 @@ public sealed class GrpcDataUnknownOperationToleranceTests runtime.DroppedUnknownOperations.ShouldBe(new Dictionary(StringComparer.OrdinalIgnoreCase) { ["history"] = DataOperations.HistoryRead | DataOperations.AlarmShelve, - ["future"] = (DataOperations)(1 << 20) | DataOperations.AlarmSubscribe, + ["future"] = (DataOperations)(1 << 30) | DataOperations.AlarmSubscribe, }); runtime.UnknownOperationRowsDropped.ShouldBe(2); + // The production reader: the node diagnostics snapshot carries each row's dropped bits. + var diagnostics = runtime.CaptureDiagnostics().ToDictionary(x => x.ConnectionId); + diagnostics["history"].DroppedUnknownOperations.ShouldBe(DataOperations.HistoryRead | DataOperations.AlarmShelve); + diagnostics["plain"].DroppedUnknownOperations.ShouldBe(DataOperations.None); + diagnostics["future"].DroppedUnknownOperations.ShouldBe((DataOperations)(1 << 30) | DataOperations.AlarmSubscribe); + diagnostics["plain"].MappingsWithDroppedOperations.ShouldBeNull("no mapping evidence was supplied"); // The input rows are not mutated: the drop is the node's reading, not a rewrite of the artifact. history.AllowedOperations.ShouldBe(DataOperations.Read | DataOperations.Browse | DataOperations.HistoryRead | DataOperations.AlarmShelve); activator.Allowlists.Last().Keys.Order(StringComparer.OrdinalIgnoreCase).ShouldBe(["future", "history", "plain"]); @@ -71,6 +77,10 @@ public sealed class GrpcDataUnknownOperationToleranceTests runtime.Apply(new(2, "artifact-2", [Definition("history", DataOperations.Read)])); runtime.DroppedUnknownOperations.ShouldBeEmpty(); runtime.UnknownOperationRowsDropped.ShouldBe(1); + + // A -> B -> A is an accepted artifact CHANGE each time, so it recounts (documented semantics). + runtime.Apply(new(3, "artifact-1", [Definition("history", DataOperations.Read | DataOperations.HistoryRead)])); + runtime.UnknownOperationRowsDropped.ShouldBe(2); } [Fact]