feat(grpc-data): X0 node-side tolerant readers drop unknown operation bits per row (counted) instead of rejecting the snapshot

Covers the deployment runtime (plan site) plus two node-side validator passes the plan missed:
DeploymentArtifact data-row parse and LocalExportCatalog.Compile now use DataConnectionValidator.ValidateDeployed.
Authoring (Validate) still rejects the reserved bits.
This commit is contained in:
Joseph Doherty
2026-11-23 17:21:35 -05:00
parent d96eafd138
commit a5ef7ea6d8
8 changed files with 341 additions and 13 deletions
@@ -212,7 +212,7 @@ public static class DataConnectionRegistration
var eligible = state.Generation > 0 && Enum.TryParse<RedundancyRole>(state.Role, out var actual)
&& DataConnectionRoleAdapter.MayAcquire(mode, state.WarmRole, actual);
return new DataConnectionConsumerRoleSnapshot(mode, eligible, state.Generation);
});
}, logger: sp.GetService<Microsoft.Extensions.Logging.ILoggerFactory>()?.CreateLogger<DataConnectionDeploymentRuntime>());
return runtime;
});
services.AddSingleton(sp =>
@@ -1,3 +1,7 @@
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;
@@ -39,7 +43,15 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
internal bool Ready;
internal int Leases;
}
/// <summary>Counter of connection rows whose unknown operation bits were dropped (X0 tolerant reader).</summary>
public const string UnknownOperationsCounterName = "otopcua.dataconnection.unknown_operations_dropped";
private static readonly Counter<long> UnknownOperationsCounter = OtOpcUaTelemetry.Meter.CreateCounter<long>(
UnknownOperationsCounterName, unit: "{row}",
description: "Data-connection rows carrying operation bits this node does not understand; the bits were dropped (no grant).");
private readonly object _sync = new();
private readonly ILogger _log;
private IReadOnlyDictionary<string, DataOperations> _droppedOperations = new Dictionary<string, DataOperations>();
private long _unknownOperationRows;
private readonly string _node, _owner;
private readonly IDataConnectionSecurityProvider _security;
private readonly IDataConnectionScopeActivator _activator;
@@ -64,8 +76,9 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
public DataConnectionDeploymentRuntime(string nodeId, string ownerCluster, IDataConnectionSecurityProvider security,
IDataConnectionScopeActivator scopeActivator, int maxConnections, TimeProvider? clock = null,
Func<bool>? consumerMayAcquire = null, bool useCompactBatches = true,
Func<RedundancyMode, DataConnectionConsumerRoleSnapshot?>? consumerRoleSnapshot = null)
Func<RedundancyMode, DataConnectionConsumerRoleSnapshot?>? consumerRoleSnapshot = null, ILogger? logger = null)
{
_log = logger ?? NullLogger.Instance;
ArgumentException.ThrowIfNullOrWhiteSpace(nodeId); ArgumentException.ThrowIfNullOrWhiteSpace(ownerCluster);
if (maxConnections <= 0) throw new ArgumentOutOfRangeException(nameof(maxConnections));
_node = nodeId; _owner = ownerCluster; _security = security ?? throw new ArgumentNullException(nameof(security));
@@ -81,6 +94,13 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
/// <summary>True only after the current scope version and allowlist are durably accepted.</summary>
public bool CurrentScopeReady { get { lock (_sync) return !_disposed && _scopeReady; } }
/// <summary>
/// X0 diagnostics: per enabled connection of the current artifact, the operation bits it was authored with that
/// this node does not understand and therefore dropped (an unknown grant is no grant). Empty when none.
/// </summary>
public IReadOnlyDictionary<string, DataOperations> DroppedUnknownOperations { get { lock (_sync) return _droppedOperations; } }
/// <summary>Cumulative count of connection rows that had unknown bits dropped, once per accepted artifact.</summary>
public long UnknownOperationRowsDropped => Interlocked.Read(ref _unknownOperationRows);
/// <summary>Configured redundancy mode from the current validated artifact.</summary>
public RedundancyMode CurrentConsumerMode { get { lock (_sync) return _desired?.ConsumerMode ?? RedundancyMode.None; } }
@@ -133,6 +153,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
if (snapshot.Connections.Count > _maximum) throw new ArgumentException("Connection capacity exceeded.", nameof(snapshot));
var specs = new Dictionary<string, Spec>(StringComparer.OrdinalIgnoreCase);
var allow = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var dropped = new Dictionary<string, DataOperations>(StringComparer.OrdinalIgnoreCase);
foreach (var item in snapshot.Connections)
{
ArgumentNullException.ThrowIfNull(item);
@@ -148,15 +169,18 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
item.MaxMessageBytes <= 0 || item.MaxStreams <= 0 || item.MaxMonitoredItems <= 0 || item.MaxPendingBytes <= 0 ||
item.Endpoints is null || item.Endpoints.Count == 0 || item.Endpoints.Count > 32 || item.EligibleTargetNodeIds is null)
throw new ArgumentException("Connection limits or endpoints are invalid.", nameof(snapshot));
const DataOperations known = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe;
if ((item.AllowedOperations & ~known) != 0) throw new ArgumentException("Unknown operation.", nameof(snapshot));
// X0 tolerant reader (plan §4.3): a bit a newer central authored that this build does not implement is
// 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;
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<string>(item.EligibleTargetNodeIds, StringComparer.OrdinalIgnoreCase);
if (target.Mode == DataTargetMode.Cluster && (eligible.Count == 0 || eligible.Any(string.IsNullOrWhiteSpace)))
throw new ArgumentException("Cluster target has no eligible nodes.", nameof(snapshot));
var spec = new Spec(item.DataConnectionId, item.Revision, target, endpoints, eligible, item.SecretReference,
item.AllowedOperations, TimeSpan.FromMilliseconds(item.TimeoutMilliseconds), item.MaxBatchItems,
operations, TimeSpan.FromMilliseconds(item.TimeoutMilliseconds), item.MaxBatchItems,
item.MaxPageItems, item.MaxMessageBytes, item.MaxStreams, item.MaxMonitoredItems, item.MaxPendingBytes);
if (!specs.TryAdd(spec.Id, spec) || !allow.TryAdd(spec.Id, spec.Secret))
throw new ArgumentException("Duplicate connection identity.", nameof(snapshot));
@@ -176,6 +200,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
{
if (snapshot.ScopeVersion != previous.ScopeVersion || snapshot.ConsumerMode != previous.ConsumerMode || !SameSpecs(previous.Specs, specs))
throw new InvalidOperationException("An artifact revision cannot identify different definitions.");
// Same revision re-applied: identical rows, so the dropped set is unchanged and is not recounted.
if (!_attemptPending) { if (!_scopeReady) DisarmRetryLocked(); WakeLocked(); return; }
}
}
@@ -183,7 +208,9 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
var generation = checked(++_generation);
_routeRevisions.Clear();
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);
_scopeReady = false;
old = _entries.Values.ToArray(); _entries.Clear();
ApplyManagerScopeLocked(_desired);
@@ -191,6 +218,19 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
WakeLocked();
}
}
private void RecordDroppedLocked(string revision, string? priorRevision, Dictionary<string, DataOperations> 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);
_log.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);
}
}
private static bool SameAllowlist(IReadOnlyDictionary<string, string> left, IReadOnlyDictionary<string, string> right) =>
left.Count == right.Count && left.All(x => right.TryGetValue(x.Key, out var value) && string.Equals(value, x.Value, StringComparison.Ordinal));
private static bool SameSpecs(IReadOnlyDictionary<string, Spec> left, IReadOnlyDictionary<string, Spec> right) =>
@@ -488,6 +528,8 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDisposable
RouteIdentity = routeIdentity;
}
internal Func<bool> RouteCurrent => _routeCurrent;
/// <summary>The configured row's operations, already masked to the understood set.</summary>
internal DataOperations AllowedOperations => _allowed;
public IDataConnection Connection => this;
public CancellationToken CancellationToken => _scope;
public DataTarget Target => _inner.Target;
@@ -25,7 +25,7 @@ public sealed partial class LocalExportCatalog
{
ArgumentNullException.ThrowIfNull(snapshot);
serving.Validate(requireEpochs: true);
if (DataConnectionValidator.Validate(snapshot).Count != 0)
if (DataConnectionValidator.ValidateDeployed(snapshot).Count != 0)
throw new InvalidDataException("Origin catalog configuration is invalid.");
var cluster = snapshot.ClusterId;
var ids = StringComparer.OrdinalIgnoreCase;
@@ -89,7 +89,8 @@ public sealed partial class LocalExportCatalog
|| export.MaxMonitoredItems <= 0 || export.MaxStreams <= 0)
throw new ArgumentException("Export has no valid origin root or policy.", nameof(exports));
rules.Add(new(export.DataExportId, export.PrincipalId, export.Realm, wholeRealm ? null : roots[0].Metadata.View, wholeRealm,
export.AllowedOperations, export.MaxBatchItems, export.MaxPageItems, export.MaxMonitoredItems, export.MaxStreams));
// 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));
}
_exports = rules.ToArray();
Nodes = new ReadOnlyCollection<LocalDataNode>(_nodes.Values.ToArray());
@@ -332,7 +332,7 @@ internal sealed partial class ParsedDeploymentArtifact
{
var requested = ids.ToHashSet(DataIds);
var error = DataConnectionValidator
.Validate(snapshot)
.ValidateDeployed(snapshot)
.FirstOrDefault(x => x.Context is not null && requested.Contains(x.Context));
if (error is not null)
throw InvalidRow(error.Context);