From e3f21cb86c5bbcedbc64cb3fd01f76b77db23199 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 08:01:57 -0500 Subject: [PATCH 01/11] feat(grpc-data): H4 remote-history diagnostics and metrics MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Consumer and origin history evidence for data connections (plan §6): - DataConnectionHistoryDiagnostics: otopcua.dataconn.history.reads{variant,status_class,side} and otopcua.dataconn.history.continuations.active{side} on the exported OtOpcUa meter (the H2 origin counter sat on a private meter the host never exported); the plan's unknown-bits counter is the existing X0 otopcua.dataconnection.unknown_operations_dropped, reused - per-connection projected answers by status class and open consumer continuations (settled on resume claim or release); origin sessions, open continuations and answers by status class - negotiated features and advertised history variants/aggregates per connection - AdminUI data-connections page renders them plus the dropped unknown-operation bits (#919) - H4 unit-phase manifest key --- scripts/validation/grpc-data/unit-phases.json | 33 ++++ .../DataConnectionDiagnosticsSnapshot.cs | 22 ++- .../Interfaces/NodeDiagnosticsSnapshot.cs | 7 +- .../Clusters/ClusterDataConnections.razor | 30 +++- .../DataConnectionDiagnostics.cs | 37 +++++ .../DataConnectionRegistration.cs | 9 +- .../IProjectedHistoryAccess.cs | 10 +- .../DataConnectionDeploymentRuntime.cs | 17 +- .../DataConnectionHistoryDiagnostics.cs | 151 ++++++++++++++++++ .../GrpcDataConnection.Diagnostics.cs | 13 +- .../LocalDataRuntimeComposition.cs | 5 +- .../LocalDataServices.History.cs | 31 ++-- .../DataConnections/ProjectedHistoryAccess.cs | 51 +++++- .../Drivers/DriverHostActor.cs | 3 +- .../GrpcDataHistoryDiagnosticsDisplayTests.cs | 58 +++++++ .../GrpcDataDeploymentActivationTests.cs | 24 +++ .../GrpcDataHistoryDiagnosticsWireTests.cs | 85 ++++++++++ .../GrpcDataHistoryMetricsTests.cs | 127 +++++++++++++++ .../GrpcDataLocalConnectionTests.cs | 4 +- 19 files changed, 687 insertions(+), 30 deletions(-) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionHistoryDiagnostics.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/GrpcDataHistoryDiagnosticsDisplayTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryDiagnosticsWireTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryMetricsTests.cs diff --git a/scripts/validation/grpc-data/unit-phases.json b/scripts/validation/grpc-data/unit-phases.json index 9dc13d469..45f5d7b7b 100644 --- a/scripts/validation/grpc-data/unit-phases.json +++ b/scripts/validation/grpc-data/unit-phases.json @@ -919,5 +919,38 @@ "GrpcDataProjectedAccessTests" ] } + ], + "H4": [ + { + "project": "tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=H4)|FullyQualifiedName~.GrpcDataProjectedHistoryCursorTests.|FullyQualifiedName~.GrpcDataOriginHistorySessionTests.", + "new_classes": [ + "GrpcDataHistoryMetricsTests" + ], + "existing_classes": [ + "GrpcDataConfiguredDiscoveryWireTests", + "GrpcDataDeploymentActivationTests", + "GrpcDataProjectedHistoryCursorTests", + "GrpcDataOriginHistorySessionTests" + ] + }, + { + "project": "tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.csproj", + "filter": "FullyQualifiedName~.ProjectedHistoryReadTests.", + "new_classes": [], + "existing_classes": [ + "ProjectedHistoryReadTests" + ] + }, + { + "project": "tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ZB.MOM.WW.OtOpcUa.AdminUI.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=H4)|FullyQualifiedName~.GrpcDataDiagnosticsTests.", + "new_classes": [ + "GrpcDataHistoryDiagnosticsDisplayTests" + ], + "existing_classes": [ + "GrpcDataDiagnosticsTests" + ] + } ] } 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 819a0d770..7dcc5f6c5 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs @@ -38,4 +38,24 @@ public sealed record DataConnectionDiagnosticsSnapshot( // 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); + int? MappingsWithDroppedOperations = null, + // H4 consumer-side history evidence: the features the last capability handshake negotiated (None = v1 behaviour), the + // history variants and aggregate count the origin advertised to this caller, projected HistoryRead results by status + // class (per node, as answered to local OPC UA clients) and the remote continuations held in local sessions. + DataFeatures? NegotiatedFeatures = null, + IReadOnlyList? HistoryVariants = null, + int? HistoryAggregateCount = null, + long? HistoryReadsGood = null, + long? HistoryReadsUncertain = null, + long? HistoryReadsBad = null, + int? OpenRemoteContinuations = null); + +/// H4 origin-side remote-history evidence for one node (what it serves to peers over data connections). +/// The node has a historian backend and can serve remote history. +/// Live peer history sessions. +/// Origin continuations (page cursors and chunk remainders) held for peers. +/// Remote history items answered Good since process start. +/// Remote history items answered Uncertain since process start. +/// Remote history items answered Bad (including refusals) since process start. +public sealed record OriginHistoryDiagnostics(bool Available, int Sessions, int OpenContinuations, long ReadsGood, + long ReadsUncertain, long ReadsBad); 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 019d3404f..1517e0ea1 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/NodeDiagnosticsSnapshot.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/NodeDiagnosticsSnapshot.cs @@ -47,6 +47,10 @@ public sealed record DriverInstanceDiagnostics( /// 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. /// +/// +/// H4: remote history this node serves to data-connection peers. Null from a sender built before H4 or when the node +/// runs no data-connection services. +/// public sealed record NodeDiagnosticsSnapshot( NodeId NodeId, RevisionHash? CurrentRevision, @@ -54,4 +58,5 @@ public sealed record NodeDiagnosticsSnapshot( DateTime AsOfUtc, bool RunningFromCache = false, IReadOnlyList? DataConnections = null, - IReadOnlyDictionary? DroppedExportOperations = null); + IReadOnlyDictionary? DroppedExportOperations = null, + OriginHistoryDiagnostics? OriginHistory = null); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor index f6edf530f..e9cdb665f 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor @@ -35,7 +35,9 @@ else @if (live.Row.Serving is { } serving) { · serving @serving.NodeId · role @serving.Role · incarnation @serving.Incarnation }
Streams @live.Row.ActiveStreams · calls @live.Row.ActiveCalls · retained import views @Measure(live.Row.SourceCount) · registrations @Measure(live.Row.RegistrationCount) · resets @Measure(live.Row.ResetCount) · coalesced notices @Measure(live.Row.CoalescedCount) · overflows @Measure(live.Row.OverflowCount)
Writes succeeded @Measure(live.Row.WriteSucceededCount) · rejected @Measure(live.Row.WriteRejectedCount) · failed @Measure(live.Row.WriteFailedCount) · unconfirmed @Measure(live.Row.WriteUnconfirmedCount) · unknown @Measure(live.Row.WriteUnknownCount)
-
Last observed sample bound @Time(live.Row.LastSampleAtUtc) (age upper bound @DataConnectionDiagnostics.SampleAge(live.Row)) · metadata lease expires @Time(live.Row.MetadataLeaseExpiresAtUtc) · last handshake @Time(live.Row.LastVerifiedAtUtc) · observed @live.Row.AsOfUtc.ToString("u") · artifact @live.Row.ArtifactRevision · protocol @(live.Row.ProtocolMajor is { } major && live.Row.ProtocolMinor is { } minor ? $"{major}.{minor}" : "unavailable")
+
Last observed sample bound @Time(live.Row.LastSampleAtUtc) (age upper bound @DataConnectionDiagnostics.SampleAge(live.Row)) · metadata lease expires @Time(live.Row.MetadataLeaseExpiresAtUtc) · last handshake @Time(live.Row.LastVerifiedAtUtc) · observed @live.Row.AsOfUtc.ToString("u") · artifact @live.Row.ArtifactRevision · protocol @(live.Row.ProtocolMajor is { } major && live.Row.ProtocolMinor is { } minor ? $"{major}.{minor}" : "unavailable")
+
Negotiated features @DataConnectionDiagnostics.Features(live.Row.NegotiatedFeatures) · origin history @DataConnectionDiagnostics.HistoryServed(live.Row) · projected history reads @DataConnectionDiagnostics.HistoryCounts(live.Row.HistoryReadsGood, live.Row.HistoryReadsUncertain, live.Row.HistoryReadsBad) · open remote continuations (local sessions) @Measure(live.Row.OpenRemoteContinuations)
+
Dropped unknown operation bits: connection @DataConnectionDiagnostics.DroppedBits(live.Row.DroppedUnknownOperations) · mappings with dropped bits @Measure(live.Row.MappingsWithDroppedOperations)@if (DataConnectionDiagnostics.HasDrops(live.Row.DroppedUnknownOperations, live.Row.MappingsWithDroppedOperations)) { — this node's build is older than a feature authored here; the dropped bits grant nothing until the node is upgraded. }
} @foreach (var applied in _applied.Where(x => Same(x.ConnectionId, row.Id))) { @applied.NodeId: last applied revision @applied.Revision (@(applied.Enabled ? "enabled" : "disabled")) } @if (row.Draft is { } editable) { } @@ -43,6 +45,30 @@ else +
+

Origin evidence by node

+ @if (!_nodeSnapshots.Any()) {

No node has reported.

} + @foreach (var (nodeId, node) in _nodeSnapshots) + { +
@nodeId + @if (node.OriginHistory is { } origin) + { + · remote history @(origin.Available ? "served" : "no historian backend") · peer history sessions @origin.Sessions · open origin continuations @origin.OpenContinuations · history items answered @DataConnectionDiagnostics.HistoryCounts(origin.ReadsGood, origin.ReadsUncertain, origin.ReadsBad) + } + else { · remote history evidence unavailable } + @if (node.DroppedExportOperations is { } dropped) + { + @if (dropped.Count == 0) { · dropped unknown export bits: none } + else + { +
Exports with dropped unknown operation bits: @string.Join("; ", dropped.OrderBy(x => x.Key, StringComparer.OrdinalIgnoreCase).Select(x => $"{x.Key}: {DataConnectionDiagnostics.DroppedBits(x.Value)}")) — this node's build is older than a feature authored here; the dropped bits grant nothing until the node is upgraded.
+ } + } + else { · dropped unknown export bits unavailable } +
+ } +
+

Exports

@if (!Exports.Any()) {

No export grants have been authored.

} @@ -125,6 +151,7 @@ else private object? _deleteCandidate; private IReadOnlyList _applied = []; private List<(string NodeId, DataConnectionDiagnosticsSnapshot Row)> _live = []; + private List<(string NodeId, NodeDiagnosticsSnapshot Snapshot)> _nodeSnapshots = []; private IReadOnlyList ConnectionRows => DataConnectionDiagnostics.Rows(Connections, _applied.Select(x => x.ConnectionId), _live.Select(x => x.Row.ConnectionId)); private IEnumerable Connections => _snapshot!.DataConnections.Where(x => Same(x.ClusterId, ClusterId)); private IEnumerable Exports => _snapshot!.DataExports.Where(x => Same(x.ClusterId, ClusterId)); @@ -139,6 +166,7 @@ else try { return (node.NodeId, Snapshot: (NodeDiagnosticsSnapshot?)await Diagnostics.GetDiagnosticsAsync(NodeId.Parse($"{node.Host}:{node.AkkaPort}"), CancellationToken.None)); } catch (Exception) { return (node.NodeId, Snapshot: (NodeDiagnosticsSnapshot?)null); } })); + _nodeSnapshots = observations.Where(x => x.Snapshot is not null).Select(x => (x.NodeId, x.Snapshot!)).ToList(); _live = observations.Where(x => x.Snapshot?.DataConnections is not null) .SelectMany(x => x.Snapshot!.DataConnections!.Select(row => (x.NodeId, row))).ToList(); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataConnectionDiagnostics.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataConnectionDiagnostics.cs index 63d07dcb5..9badce08a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataConnectionDiagnostics.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataConnectionDiagnostics.cs @@ -1,4 +1,6 @@ +using ZB.MOM.WW.OtOpcUa.Commons.Interfaces; using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; namespace ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections; @@ -23,6 +25,41 @@ public static class DataConnectionDiagnostics "disabled" => "Disabled", "connecting" => "Connecting", "ready" => "Ready", "degraded" => "Degraded", "auth-failed" => "Authentication failed", "backoff" => "Backoff", _ => "Unavailable" }; + /// H4: the features the last handshake negotiated; "none (v1)" when the peer negotiated nothing optional. + public static string Features(DataFeatures? features) => features switch + { + null => "unavailable", + DataFeatures.None => "none (v1 behaviour)", + { } f => string.Join(", ", Enum.GetValues().Where(x => x != DataFeatures.None && f.HasFlag(x)).Select(x => x.ToString()) + .DefaultIfEmpty($"0x{(int)f:X}")), + }; + + /// H4: the history variants and aggregate count the origin advertised to this caller. + public static string HistoryServed(DataConnectionDiagnosticsSnapshot row) => + row.HistoryVariants is not { } variants ? "not advertised" + : variants.Count == 0 ? "advertised, no variant granted" + : string.Join(", ", variants) + (row.HistoryAggregateCount is { } n ? $" ({n} aggregates)" : ""); + + /// H4: history results by status class, "unavailable" from a node built before H4. + public static string HistoryCounts(long? good, long? uncertain, long? bad) => + good is null && uncertain is null && bad is null ? "unavailable" + : $"good {good ?? 0} · uncertain {uncertain ?? 0} · bad {bad ?? 0}"; + + /// + /// #919: operation bits a node dropped because its build does not implement them. Named when this AdminUI knows the + /// bit, hex otherwise; "unavailable" from a node built before X0. + /// + public static string DroppedBits(DataOperations? bits) => bits switch + { + null => "unavailable", + DataOperations.None => "none", + { } b => string.Join(", ", Enumerable.Range(0, 31).Select(i => (DataOperations)(1 << i)).Where(x => b.HasFlag(x)) + .Select(x => Enum.IsDefined(x) ? DataOperationAuthoring.Label(x) : $"0x{(int)x:X}")), + }; + + /// #919: true when the drop deserves the "node build is older than the authored feature" hint. + public static bool HasDrops(DataOperations? bits, int? mappings = null) => bits is { } b && b != DataOperations.None || mappings is > 0; + public static string Endpoint(string? value) => Uri.TryCreate(value, UriKind.Absolute, out var uri) && uri.Scheme == Uri.UriSchemeHttps ? (uri.HostNameType == UriHostNameType.IPv6 ? $"https://[{uri.Host}]{(uri.IsDefaultPort ? "" : $":{uri.Port}")}" : $"https://{uri.IdnHost}{(uri.IsDefaultPort ? "" : $":{uri.Port}")}") : "Unavailable"; } 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 ff33ad910..2f574c943 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs @@ -118,12 +118,15 @@ public static class DataConnectionRegistration (!settings.IsWarm || state.WarmRole == WarmRole.Active), state.Generation); }, renewalSink: sp.GetRequiredService())); services.AddSingleton(sp => sp.GetRequiredService()); + // H4: one dependency-free history diagnostics instance shared by the origin services, the consumer gateway and the + // diagnostics readers (it also backs the otopcua.dataconn.history.* metrics). + services.AddSingleton(); // H3: OPC UA HistoryRead on projected variables, forwarded over the mapping's deployed connection. services.AddSingleton(sp => new ProjectedHistoryAccess(sp.GetRequiredService(), sp.GetRequiredService(), mappingId => sp.GetRequiredService().TryGetHistoryAssemblyBudget(mappingId, out var bytes) ? bytes : null, - sp.GetRequiredService())); + sp.GetRequiredService(), sp.GetRequiredService())); services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(sp => new ConfiguredProjectionDiscovery( sp.GetRequiredService(), sp.GetRequiredService(), @@ -161,7 +164,8 @@ public static class DataConnectionRegistration options.MaxStreams, Math.Min(options.MaxStreams, options.MaxStreamsPerPrincipal), options.MaxTransportBytes, 128, 64, options.MaxPendingBytes, options.MaxSessionLifetime, TimeSpan.FromSeconds(5)), // H2: remote history over the node manager's history port, resolved once the SDK server is up. - new DeferredOriginHistoryPort(sp.GetRequiredService()), LoggerFor(sp)); + new DeferredOriginHistoryPort(sp.GetRequiredService()), LoggerFor(sp), + sp.GetRequiredService()); }); services.AddSingleton(sp => new DeferredFactory(() => sp.GetRequiredService().Services)); services.AddSingleton(); @@ -227,6 +231,7 @@ public static class DataConnectionRegistration }) { Logger = LoggerFor(sp), + HistoryDiagnostics = sp.GetRequiredService(), }; return runtime; }); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs index dc050e9ef..2ed760691 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs @@ -53,7 +53,15 @@ public abstract class ProjectedHistoryContinuation /// Marks the cursor as handed back for a resume: the resume read owns the origin token from here on. /// false when it was already released or resumed. - public bool TryClaimForResume() => Volatile.Read(ref _released) == 0 && Interlocked.Exchange(ref _claimed, 1) == 0; + public bool TryClaimForResume() + { + if (Volatile.Read(ref _released) != 0 || Interlocked.Exchange(ref _claimed, 1) != 0) return false; + OnClaimed(); + return true; + } + + /// Called once when the cursor is claimed for a resume (its origin token is about to be sent back). + protected virtual void OnClaimed() { } private void ReleaseOnce() { 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 96cce8cf0..307f0e3b0 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs @@ -46,6 +46,8 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable 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; + /// H4: consumer/origin remote-history evidence merged into the diagnostics; optional (init keeps the constructor shape). + public DataConnectionHistoryDiagnostics? HistoryDiagnostics { get; init; } private IReadOnlyDictionary _droppedOperations = new Dictionary(); private long _unknownOperationRows; private readonly string _node, _owner; @@ -118,7 +120,18 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable 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 => + var history = HistoryDiagnostics; + ZB.MOM.WW.OtOpcUa.Commons.Interfaces.DataConnectionDiagnosticsSnapshot WithHistory( + ZB.MOM.WW.OtOpcUa.Commons.Interfaces.DataConnectionDiagnosticsSnapshot row) + { + if (history is null) return row; + var counts = history.CaptureConsumer(row.ConnectionId); + return row with { HistoryReadsGood = counts.Good, HistoryReadsUncertain = counts.Uncertain, HistoryReadsBad = counts.Bad, + OpenRemoteContinuations = counts.OpenContinuations }; + } + return desired.Specs.Values.Select(spec => WithHistory(Capture(spec))).ToArray(); + + ZB.MOM.WW.OtOpcUa.Commons.Interfaces.DataConnectionDiagnosticsSnapshot Capture(Spec spec) { if (!_attemptPending && _scopeReady && _entries.TryGetValue(spec.Id, out var entry) && entry.Ready) return entry.Connection.CaptureDiagnostics(spec.Revision, desired.ScopeVersion, desired.ArtifactRevision) with @@ -128,7 +141,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable _attemptPending ? "connecting" : _retryNotBefore > _clock.GetTimestamp() ? "backoff" : "connecting", null, null, 0, 0, desired.ScopeVersion, desired.ArtifactRevision, _clock.GetUtcNow().UtcDateTime) { DroppedUnknownOperations = Dropped(spec.Id), MappingsWithDroppedOperations = MappingDrops(spec.Id) }; - }).ToArray(); + } } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionHistoryDiagnostics.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionHistoryDiagnostics.cs new file mode 100644 index 000000000..4fb7b961f --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionHistoryDiagnostics.cs @@ -0,0 +1,151 @@ +using System.Collections.Concurrent; +using System.Diagnostics.Metrics; +using System.Runtime.CompilerServices; +using ZB.MOM.WW.OtOpcUa.Commons.Interfaces; +using ZB.MOM.WW.OtOpcUa.Commons.Observability; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Consumer-side remote-history evidence for one deployed connection (H4 diagnostics). +public sealed record ConsumerHistoryCounts(long Good, long Uncertain, long Bad, int OpenContinuations); + +/// +/// H4 remote-history diagnostics and metrics for one process (plan §6 "Metrics"). It has no dependencies, so the origin +/// services (), the consumer gateway () and the +/// diagnostics readers (, the driver host) share one instance without a cycle. +/// +/// +/// Metrics, on , never carry an id in a label: +/// +/// — one per history item answered, tagged variant (raw | processed | attime), +/// status_class (good | uncertain | bad) and side (origin = served to a peer; consumer = a projected node's +/// answer to a local OPC UA client). A node can be both, so side keeps the two from being summed. +/// — open remote continuations, tagged side: origin cursors held for +/// peers, and consumer cursors held in local OPC UA sessions (created, neither resumed nor released). +/// +/// +/// The plan's …operations.unknown_bits_dropped is the X0 counter +/// (otopcua.dataconnection.unknown_operations_dropped, tag kind); it is reused, not duplicated. +/// +/// +public sealed class DataConnectionHistoryDiagnostics +{ + public const string ReadsCounterName = "otopcua.dataconn.history.reads"; + public const string ContinuationsGaugeName = "otopcua.dataconn.history.continuations.active"; + public const string OriginSide = "origin"; + public const string ConsumerSide = "consumer"; + + private static readonly Counter Reads = OtOpcUaTelemetry.Meter.CreateCounter(ReadsCounterName, unit: "{item}", + description: "Remote history items answered over data connections (tags: variant = raw|processed|attime; " + + "status_class = good|uncertain|bad; side = origin|consumer)."); + + // Weak: a process normally holds one instance, tests many; none needs disposing to leave the gauge. + private static readonly ConditionalWeakTable Live = new(); + + static DataConnectionHistoryDiagnostics() + { + OtOpcUaTelemetry.Meter.CreateObservableGauge(ContinuationsGaugeName, static () => Observe(), unit: "{continuation}", + description: "Open remote-history continuations (tag side = origin: cursors held for peers; consumer: cursors held " + + "in local OPC UA sessions)."); + } + + private static IEnumerable> Observe() + { + int origin = 0, consumer = 0; + foreach (var (instance, _) in Live) + { + origin += instance.CaptureOrigin()?.OpenContinuations ?? 0; + consumer += instance.OpenConsumerContinuations; + } + + return + [ + new Measurement(origin, new KeyValuePair("side", OriginSide)), + new Measurement(consumer, new KeyValuePair("side", ConsumerSide)), + ]; + } + + private sealed class Counts + { + public long Good, Uncertain, Bad; + public int Open; + } + + private readonly ConcurrentDictionary _consumer = new(StringComparer.OrdinalIgnoreCase); + private readonly Counts _origin = new(); + private Func<(bool Available, int Sessions, int Open)>? _originState; + + public DataConnectionHistoryDiagnostics() => Live.AddOrUpdate(this, new object()); + + /// The variant label of a request's details. + internal static string Variant(DataHistoryDetails details) => details switch + { + DataHistoryRawDetails => "raw", DataHistoryProcessedDetails => "processed", DataHistoryAtTimeDetails => "attime", _ => "unknown", + }; + + /// The status_class label of an OPC UA status code (its top two bits). + internal static string StatusClass(uint status) => (status >> 30) switch { 0 => "good", 1 => "uncertain", _ => "bad" }; + + private static void Add(Counts counts, uint status) + { + switch (status >> 30) + { + case 0: Interlocked.Increment(ref counts.Good); break; + case 1: Interlocked.Increment(ref counts.Uncertain); break; + default: Interlocked.Increment(ref counts.Bad); break; + } + } + + /// Counts one answer on the metric only (an origin or gateway built without a diagnostics instance). + internal static void Count(string side, string variant, uint status) => + Reads.Add(1, new KeyValuePair("variant", variant), + new KeyValuePair("status_class", StatusClass(status)), new KeyValuePair("side", side)); + + /// One origin answer to a peer's history item. + internal void RecordOriginRead(string variant, uint status) + { + Add(_origin, status); + Count(OriginSide, variant, status); + } + + /// One projected node's answer to a local OPC UA client; null when unresolved. + internal void RecordConsumerRead(string? connectionId, string variant, uint status) + { + if (connectionId is not null) Add(_consumer.GetOrAdd(connectionId, static _ => new Counts()), status); + Count(ConsumerSide, variant, status); + } + + /// A consumer continuation was handed to a local session. + internal void ConsumerContinuationOpened(string connectionId) => + Interlocked.Increment(ref _consumer.GetOrAdd(connectionId, static _ => new Counts()).Open); + + /// A consumer continuation was resumed (its token sent back) or released. + internal void ConsumerContinuationSettled(string connectionId) + { + if (_consumer.TryGetValue(connectionId, out var counts)) Interlocked.Decrement(ref counts.Open); + } + + /// Connects the origin services whose live state (backend, sessions, open cursors) this reports. + internal void AttachOrigin(Func<(bool Available, int Sessions, int Open)> state) => _originState = state; + + /// The consumer evidence for one connection; zeros when it has seen no history traffic. + public ConsumerHistoryCounts CaptureConsumer(string connectionId) => + _consumer.TryGetValue(connectionId, out var c) + ? new(Interlocked.Read(ref c.Good), Interlocked.Read(ref c.Uncertain), Interlocked.Read(ref c.Bad), Math.Max(0, Volatile.Read(ref c.Open))) + : new(0, 0, 0, 0); + + /// Consumer continuations open across every connection. + public int OpenConsumerContinuations => _consumer.Values.Sum(x => Math.Max(0, Volatile.Read(ref x.Open))); + + /// The origin evidence; null until origin services are attached (no data-connection origin on this node yet). + public OriginHistoryDiagnostics? CaptureOrigin() + { + if (_originState is not { } state) return null; + (bool Available, int Sessions, int Open) now; + try { now = state(); } + catch (Exception) { return null; } + return new(now.Available, now.Sessions, now.Open, Interlocked.Read(ref _origin.Good), Interlocked.Read(ref _origin.Uncertain), + Interlocked.Read(ref _origin.Bad)); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.Diagnostics.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.Diagnostics.cs index 794beae6c..93e533561 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.Diagnostics.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.Diagnostics.cs @@ -9,6 +9,9 @@ public sealed partial class GrpcDataConnection private string? _diagnosticEndpoint; private ServingIdentity? _diagnosticServing; private int? _diagnosticMajor, _diagnosticMinor; + private DataFeatures? _negotiatedFeatures; + private IReadOnlyList? _historyVariants; + private int? _historyAggregateCount; private string _diagnosticState = "connecting"; private DateTime? _lastSampleAtUtc, _metadataLeaseExpiresAtUtc, _lastVerifiedAtUtc; private TimeSpan? _sampleAgeUpper; @@ -32,7 +35,8 @@ public sealed partial class GrpcDataConnection SampleAgeUpperBound: ObservedUpperAge(), CoalescedCount: Interlocked.Read(ref _coalescedCount), CompactFrameCount: Interlocked.Read(ref _compactFrameCount), FallbackFrameCount: Interlocked.Read(ref _fallbackFrameCount), - SerializedValueFrameBytes: Interlocked.Read(ref _serializedValueFrameBytes), AccountingInstanceId: _accountingInstanceId); + SerializedValueFrameBytes: Interlocked.Read(ref _serializedValueFrameBytes), AccountingInstanceId: _accountingInstanceId, + NegotiatedFeatures: _negotiatedFeatures, HistoryVariants: _historyVariants, HistoryAggregateCount: _historyAggregateCount); } private TimeSpan? ObservedUpperAge() @@ -50,6 +54,13 @@ public sealed partial class GrpcDataConnection _diagnosticEndpoint = new UriBuilder(endpoint.Scheme, endpoint.Host, endpoint.Port).Uri.GetLeftPart(UriPartial.Authority); _diagnosticServing = capabilities.Serving; _lastVerifiedAtUtc = Clock.GetUtcNow().UtcDateTime; _diagnosticMajor = capabilities.ProtocolMajor; _diagnosticMinor = capabilities.ProtocolMinor; + // H4: what the data calls of this handshake negotiate, and the history the origin advertised to this caller. + _negotiatedFeatures = RequestedFeatures(capabilities); + _historyVariants = capabilities.History is { } history + ? new[] { history.Raw ? "raw" : null, history.Processed ? "processed" : null, history.AtTime ? "attime" : null } + .OfType().ToArray() + : null; + _historyAggregateCount = capabilities.History?.Aggregates.Count; _diagnosticState = capabilities.Readiness == DataReadiness.Ready ? "ready" : "degraded"; } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs index e3b37b9b1..3236f8848 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs @@ -18,7 +18,8 @@ public sealed class LocalDataRuntimeComposition : IDisposable public LocalDataRuntimeComposition(LocalCatalogCoordinator catalog, PartitionedSampleHub hub, DataOperationPolicy policy, DataCapabilitiesProvider capabilities, TimeProvider clock, DataWriteRuntime writes, IActorRef host, SubscriptionAcquisitionCapacity acquisitionCapacity, LocalDataRuntimeLimits limits, - ZB.MOM.WW.OtOpcUa.OpcUaServer.IOriginHistoryPort? history = null, Microsoft.Extensions.Logging.ILogger? logger = null) + ZB.MOM.WW.OtOpcUa.OpcUaServer.IOriginHistoryPort? history = null, Microsoft.Extensions.Logging.ILogger? logger = null, + DataConnectionHistoryDiagnostics? historyDiagnostics = null) { ArgumentNullException.ThrowIfNull(catalog); ArgumentNullException.ThrowIfNull(hub); ArgumentNullException.ThrowIfNull(policy); ArgumentNullException.ThrowIfNull(capabilities); @@ -38,7 +39,7 @@ public sealed class LocalDataRuntimeComposition : IDisposable writes: context => writes.ForCaller(context, () => host), targetSubscriptions: (context, target) => new LocalSubscriptionService(services!, context, target, _demand, sessionLimits, capacity), subscriptionFreshnessChallenges: true, history: history) - { Logger = logger ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance }; + { Logger = logger ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance, HistoryDiagnostics = historyDiagnostics }; Services = services; } public LocalDataServices Services { get; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.History.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.History.cs index b4c47d698..0400b110b 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.History.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.History.cs @@ -1,4 +1,3 @@ -using System.Diagnostics.Metrics; using System.Globalization; using System.Text; using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; @@ -24,8 +23,21 @@ public sealed partial class LocalDataServices internal const uint BadContinuationPointInvalid = 0x804A0000u; private const int ResponseMarginBytes = 64 * 1024; - private static readonly Meter HistoryMeter = new("ZB.MOM.WW.OtOpcUa.DataConnections.History"); - private static readonly Counter HistoryReads = HistoryMeter.CreateCounter("otopcua.dataconn.history.reads"); + private DataConnectionHistoryDiagnostics? _historyDiagnostics; + + /// + /// H4: where origin history answers are counted and this origin's live history state is reported (diagnostics and the + /// otopcua.dataconn.history.* metrics). Before H4 the counter sat on a private meter the host never exported. + /// + public DataConnectionHistoryDiagnostics? HistoryDiagnostics + { + get => _historyDiagnostics; + init + { + _historyDiagnostics = value; + value?.AttachOrigin(() => (HistoryServing is not null, HistorySessionCount, HistoryOpenContinuations)); + } + } private readonly IOriginHistoryPort? _history; private readonly OriginHistorySessions _historySessions; @@ -442,15 +454,14 @@ public sealed partial class LocalDataServices private static long SampleBytes(DataHistorySample sample, DataMetadata? catalog) => DataHistoryProtoMapper.EncodeSample(sample, catalog).CalculateSize() + 6L; - private static DataHistoryReadResult[] Record(DataHistoryReadRequest request, DataHistoryReadResult[] results) + private DataHistoryReadResult[] Record(DataHistoryReadRequest request, DataHistoryReadResult[] results) { - var variant = request.Details switch - { - DataHistoryRawDetails => "raw", DataHistoryProcessedDetails => "processed", DataHistoryAtTimeDetails => "attime", _ => "unknown", - }; + var variant = DataConnectionHistoryDiagnostics.Variant(request.Details); foreach (var result in results) - HistoryReads.Add(1, new KeyValuePair("variant", variant), - new KeyValuePair("status_class", (result.StatusCode >> 30) switch { 0 => "good", 1 => "uncertain", _ => "bad" })); + { + if (_historyDiagnostics is { } diagnostics) diagnostics.RecordOriginRead(variant, result.StatusCode); + else DataConnectionHistoryDiagnostics.Count(DataConnectionHistoryDiagnostics.OriginSide, variant, result.StatusCode); + } return results; } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs index e2ca73cb9..2f90f37c5 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs @@ -63,15 +63,20 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl /// The deployed connection registry. /// A mapping's MaxHistoryAssemblyBytesPerRequest; null = not deployed. /// The clock. + /// H4 per-connection counts and metrics; a private instance when not shared. public ProjectedHistoryAccess(ProjectedDataAccess access, IGrpcDataAdapterConnectionSource connections, - Func assemblyBudget, TimeProvider clock) + Func assemblyBudget, TimeProvider clock, DataConnectionHistoryDiagnostics? diagnostics = null) { + Diagnostics = diagnostics ?? new DataConnectionHistoryDiagnostics(); _access = access ?? throw new ArgumentNullException(nameof(access)); _connections = connections ?? throw new ArgumentNullException(nameof(connections)); _assemblyBudget = assemblyBudget ?? throw new ArgumentNullException(nameof(assemblyBudget)); _clock = clock ?? throw new ArgumentNullException(nameof(clock)); } + /// H4: projected answers by status class and the consumer continuations held in local sessions, per connection. + public DataConnectionHistoryDiagnostics Diagnostics { get; } + /// How long a release waits to coalesce with others for the same connection (a session close disposes one by one). internal TimeSpan ReleaseCoalesce { get; init; } = TimeSpan.FromMilliseconds(25); @@ -195,7 +200,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl left -= assembled[i]; } - return outcomes.Select(o => o ?? Fail(BadNoCommunication)).ToArray(); + return Recorded(outcomes.Select(o => o ?? Fail(BadNoCommunication)).ToArray()); } catch (Exception ex) when (ex is not OutOfMemoryException) { @@ -211,13 +216,21 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl outcomes[i] = Fail(timedOut ? BadTimeout : ex is OperationCanceledException && resumed ? BadContinuationPointInvalid : BadNoCommunication); } - return outcomes.Select(o => o!).ToArray(); + return Recorded(outcomes.Select(o => o!).ToArray()); } finally { foreach (var demand in demands) demand?.Dispose(); } + // H4: one count per node as answered to the local client, attributed to its connection when it resolved to one. + ProjectedHistoryOutcome[] Recorded(ProjectedHistoryOutcome[] answered) + { + var variant = DataConnectionHistoryDiagnostics.Variant(details); + for (var i = 0; i < answered.Length; i++) Diagnostics.RecordConsumerRead(targets[i]?.ConnectionId, variant, answered[i].StatusCode); + return answered; + } + TimeSpan Remaining() => deadline > TimeSpan.Zero ? deadline - _clock.GetElapsedTime(started) : TimeSpan.FromHours(1); // unbounded locally: the connection's HistoryTimeout still caps each call @@ -527,11 +540,34 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl private sealed record GroupKey(string ConnectionId, DataHistoryDetails Details, string Resume); /// The remote cursor in the consumer's SDK session store ( Remote). - private sealed class RemoteCursor(ProjectedHistoryAccess owner, DataRealm realm, string localIdentifier, byte[] token, string connectionId, - object? routeIdentity, ProjectedHistoryTarget target, string callerKey, DataHistoryDetails details, uint? aggregateId) - : ProjectedHistoryContinuation(realm, localIdentifier) + private sealed class RemoteCursor : ProjectedHistoryContinuation { - private int _originReleased; + private readonly ProjectedHistoryAccess owner; + private readonly byte[] token; + private readonly string connectionId; + private readonly object? routeIdentity; + private readonly ProjectedHistoryTarget target; + private readonly string callerKey; + private readonly DataHistoryDetails details; + private readonly uint? aggregateId; + private int _originReleased, _settled; + + internal RemoteCursor(ProjectedHistoryAccess owner, DataRealm realm, string localIdentifier, byte[] token, string connectionId, + object? routeIdentity, ProjectedHistoryTarget target, string callerKey, DataHistoryDetails details, uint? aggregateId) + : base(realm, localIdentifier) + { + this.owner = owner; this.token = token; this.connectionId = connectionId; this.routeIdentity = routeIdentity; + this.target = target; this.callerKey = callerKey; this.details = details; this.aggregateId = aggregateId; + owner.Diagnostics.ConsumerContinuationOpened(connectionId); + } + + /// H4: open until resumed (the origin consumes the token) or released, whichever comes first. + private void Settle() + { + if (Interlocked.Exchange(ref _settled, 1) == 0) owner.Diagnostics.ConsumerContinuationSettled(connectionId); + } + + protected override void OnClaimed() => Settle(); internal ProjectedHistoryAccess Owner => owner; internal byte[] Token => token; internal object? RouteIdentity => routeIdentity; @@ -546,6 +582,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl /// Releases the origin token (once), whether the cursor was claimed for a resume or not. internal void ReleaseOrigin() { + Settle(); if (Interlocked.Exchange(ref _originReleased, 1) == 0) owner.EnqueueRelease(connectionId, token); } 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 eeef8df2b..c301388c6 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -2983,7 +2983,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS RunningFromCache: _isRunningFromCache, DataConnections: _dataConnections?.CaptureDiagnostics(_projectedPublisher?.CaptureSourceCounts(), _catalogCoordinator?.ProjectedMappings?.CaptureDroppedByConnection()), - DroppedExportOperations: _catalogCoordinator?.Current?.DroppedUnknownOperations); + DroppedExportOperations: _catalogCoordinator?.Current?.DroppedUnknownOperations, + OriginHistory: _dataConnections?.HistoryDiagnostics?.CaptureOrigin()); Sender.Tell(snapshot); } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/GrpcDataHistoryDiagnosticsDisplayTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/GrpcDataHistoryDiagnosticsDisplayTests.cs new file mode 100644 index 000000000..61d92a9f7 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/GrpcDataHistoryDiagnosticsDisplayTests.cs @@ -0,0 +1,58 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections; +using ZB.MOM.WW.OtOpcUa.Commons.Interfaces; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.DataConnections; + +/// H4 diagnostics display (plan §6) and the X0 dropped-bit rendering (#919) on the data-connections page. +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H4")] +public sealed class GrpcDataHistoryDiagnosticsDisplayTests +{ + private static DataConnectionDiagnosticsSnapshot Row() => + new("link", 1, "ready", null, null, 0, 0, 1, "artifact", DateTime.UtcNow); + + [Fact] + public void Negotiated_features_distinguish_unavailable_v1_and_history() + { + DataConnectionDiagnostics.Features(null).ShouldBe("unavailable"); + DataConnectionDiagnostics.Features(DataFeatures.None).ShouldBe("none (v1 behaviour)"); + DataConnectionDiagnostics.Features(DataFeatures.History).ShouldBe("History"); + DataConnectionDiagnostics.Features(DataFeatures.History | DataFeatures.Conditions).ShouldBe("History, Conditions"); + } + + [Fact] + public void Origin_history_shows_the_advertised_variants_and_aggregate_count() + { + DataConnectionDiagnostics.HistoryServed(Row()).ShouldBe("not advertised"); + DataConnectionDiagnostics.HistoryServed(Row() with { HistoryVariants = [] }).ShouldBe("advertised, no variant granted"); + DataConnectionDiagnostics.HistoryServed(Row() with { HistoryVariants = ["raw", "processed", "attime"], HistoryAggregateCount = 12 }) + .ShouldBe("raw, processed, attime (12 aggregates)"); + } + + [Fact] + public void History_counts_by_status_class_are_unavailable_from_an_older_node_not_zero() + { + DataConnectionDiagnostics.HistoryCounts(null, null, null).ShouldBe("unavailable"); + DataConnectionDiagnostics.HistoryCounts(5, 0, 2).ShouldBe("good 5 · uncertain 0 · bad 2"); + } + + [Fact] + public void Dropped_bits_are_named_when_known_and_hex_when_not() + { + DataConnectionDiagnostics.DroppedBits(null).ShouldBe("unavailable"); + DataConnectionDiagnostics.DroppedBits(DataOperations.None).ShouldBe("none"); + DataConnectionDiagnostics.DroppedBits(DataOperations.HistoryRead | DataOperations.AlarmSubscribe).ShouldBe("HistoryRead, AlarmSubscribe"); + DataConnectionDiagnostics.DroppedBits((DataOperations)(1 << 20)).ShouldBe("0x100000"); + } + + [Fact] + public void The_older_build_hint_shows_only_when_something_was_dropped() + { + DataConnectionDiagnostics.HasDrops(null).ShouldBeFalse(); + DataConnectionDiagnostics.HasDrops(DataOperations.None, 0).ShouldBeFalse(); + DataConnectionDiagnostics.HasDrops(DataOperations.HistoryRead).ShouldBeTrue(); + DataConnectionDiagnostics.HasDrops(DataOperations.None, 2).ShouldBeTrue("a mapping's drop counts even when the connection dropped none"); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeploymentActivationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeploymentActivationTests.cs index be2c92882..f979a6bee 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeploymentActivationTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeploymentActivationTests.cs @@ -51,6 +51,30 @@ public sealed class GrpcDataDeploymentActivationTests runtime.CaptureDiagnostics().ShouldHaveSingleItem().State.ShouldBe("connecting"); } + [Fact, Trait("Phase", "H4")] + public async Task Diagnostics_carry_the_consumer_history_counts_and_open_continuations_per_connection() + { + var activator = new PausedActivator(); + var history = new DataConnectionHistoryDiagnostics(); + await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4) { HistoryDiagnostics = history }; + runtime.Apply(Snapshot(1, Definition("link", "secret-reference"), Definition("other", "secret-reference"))); + await activator.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + history.RecordConsumerRead("LINK", "raw", 0); + history.RecordConsumerRead("link", "processed", 0x40000000u); + history.RecordConsumerRead("link", "attime", 0x80720000u); + history.ConsumerContinuationOpened("link"); + var rows = runtime.CaptureDiagnostics(); + var link = rows.Single(x => x.ConnectionId == "link"); + (link.HistoryReadsGood, link.HistoryReadsUncertain, link.HistoryReadsBad, link.OpenRemoteContinuations).ShouldBe((1L, 1L, 1L, 1)); + var other = rows.Single(x => x.ConnectionId == "other"); + (other.HistoryReadsGood, other.HistoryReadsBad, other.OpenRemoteContinuations).ShouldBe((0L, 0L, 0), "zeros, not unavailable: no traffic yet"); + activator.Release.TrySetResult(); + await using var plain = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), new PausedActivator { PauseFirst = false }, 4); + plain.Apply(Snapshot(1, Definition("link", "secret-reference"))); + await EventuallyAsync(() => plain.CaptureDiagnostics().Count == 1); + plain.CaptureDiagnostics().ShouldHaveSingleItem().HistoryReadsGood.ShouldBeNull("no history diagnostics wired = unavailable"); + } + [Fact] public async Task Transient_security_resolution_exception_retries_without_a_change_event() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryDiagnosticsWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryDiagnosticsWireTests.cs new file mode 100644 index 000000000..1f856ca01 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryDiagnosticsWireTests.cs @@ -0,0 +1,85 @@ +using Opc.Ua; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// H4 — the remote-history diagnostics follow real traffic: a real consumer OPC UA session reads a projected node through +/// the real projection stack and a real in-process origin; both sides' counts by status class and open continuations +/// move with each page, resume and release. +/// +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Fact(Timeout = 90000)] + [Trait("Phase", "H4")] + public async Task History_diagnostics_count_answers_by_status_class_and_track_open_continuations_on_both_sides() + { + await using var originServer = await HistoryOrigin.StartAsync(7); + originServer.Source.Aggregates = new HashSet { HistoryAggregateType.Average }; + using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); + ProjectedHistoryAccess? history = null; + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var consumer = history!.Diagnostics; + + // Before any history traffic: nothing counted, nothing open; the origin reports its backend. + consumer.CaptureConsumer("link").ShouldBe(new ConsumerHistoryCounts(0, 0, 0, 0)); + var idle = origin.HistoryDiagnostics.CaptureOrigin().ShouldNotBeNull(); + idle.Available.ShouldBeTrue(); + (idle.ReadsGood, idle.ReadsBad, idle.OpenContinuations).ShouldBe((0L, 0L, 0)); + + // Page 1 of 7 at 2 per page: one Good answer on each side, one continuation open on each side. + var page = await RawHistory(client, anchor, 2, default); + page.ContinuationPoint.IsEmpty.ShouldBeFalse(); + consumer.CaptureConsumer("link").ShouldBe(new ConsumerHistoryCounts(1, 0, 0, 1)); + consumer.CaptureConsumer("LINK").Good.ShouldBe(1, "connection ids are case-insensitive"); + origin.HistoryDiagnostics.CaptureOrigin()!.OpenContinuations.ShouldBe(1); + origin.HistoryDiagnostics.CaptureOrigin()!.ReadsGood.ShouldBe(1); + + // Resume: the claimed cursor settles, its successor opens — still one open, two Good answers. + var next = await RawHistory(client, anchor, 2, page.ContinuationPoint); + next.ContinuationPoint.IsEmpty.ShouldBeFalse(); + consumer.CaptureConsumer("link").ShouldBe(new ConsumerHistoryCounts(2, 0, 0, 1)); + consumer.OpenConsumerContinuations.ShouldBe(1); + + // releaseContinuationPoints: the consumer cursor settles at once, the origin's after the coalesced release. + await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(2)), TimestampsToReturn.Both, true, + [new HistoryReadValueId { NodeId = anchor, ContinuationPoint = next.ContinuationPoint }], TestContext.Current.CancellationToken); + consumer.CaptureConsumer("link").OpenContinuations.ShouldBe(0); + await AwaitReleases(history, () => origin.Services.HistoryOpenContinuations == 0); + origin.HistoryDiagnostics.CaptureOrigin()!.OpenContinuations.ShouldBe(0); + + // An aggregate the origin refuses: one Bad answer on each side. + var refused = await ProcessedHistory(client, anchor, ObjectIds.AggregateFunction_Count); + refused.StatusCode.Code.ShouldBe(StatusCodes.BadAggregateNotSupported.Code); + consumer.CaptureConsumer("link").ShouldBe(new ConsumerHistoryCounts(2, 0, 1, 0)); + var after = origin.HistoryDiagnostics.CaptureOrigin()!; + (after.ReadsGood, after.ReadsUncertain, after.ReadsBad).ShouldBe((2L, 0L, 1L)); + }, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin), onHistory: (h, _) => history = h); + } + + [Fact(Timeout = 90000)] + [Trait("Phase", "H4")] + public async Task Consumer_session_close_settles_its_open_consumer_continuations() + { + await using var originServer = await HistoryOrigin.StartAsync(7); + using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); + ProjectedHistoryAccess? history = null; + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + (await RawHistory(client, anchor, 2, default)).ContinuationPoint.IsEmpty.ShouldBeFalse(); + history!.Diagnostics.OpenConsumerContinuations.ShouldBe(1); + await session.CloseAsync(TestContext.Current.CancellationToken); + await AwaitReleases(history, () => origin.Services.HistoryOpenContinuations == 0); + history.Diagnostics.OpenConsumerContinuations.ShouldBe(0, "the SDK disposed the Remote point on session close"); + origin.HistoryDiagnostics.CaptureOrigin()!.OpenContinuations.ShouldBe(0); + }, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin), onHistory: (h, _) => history = h); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryMetricsTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryMetricsTests.cs new file mode 100644 index 000000000..3ffc620ac --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryMetricsTests.cs @@ -0,0 +1,127 @@ +using System.Diagnostics.Metrics; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.Observability; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// H4 metrics (plan §6): otopcua.dataconn.history.reads{variant,status_class,side} and +/// otopcua.dataconn.history.continuations.active{side} on the exported OtOpcUa meter, no ids in labels; the plan's +/// unknown-bit counter is the existing X0 instrument (reused, not duplicated). +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H4")] +public sealed class GrpcDataHistoryMetricsTests +{ + private static readonly string[] AllowedLabels = ["variant", "status_class", "side"]; + + [Fact] + public void History_reads_are_counted_on_the_exported_meter_with_variant_status_class_and_side_only() + { + var seen = new List<(long Value, Dictionary Tags)>(); + using var listener = new MeterListener(); + listener.InstrumentPublished = (instrument, l) => + { + if (instrument.Meter.Name == OtOpcUaTelemetry.MeterName && instrument.Name == DataConnectionHistoryDiagnostics.ReadsCounterName) + l.EnableMeasurementEvents(instrument); + }; + listener.SetMeasurementEventCallback((_, value, tags, _) => + { + var map = new Dictionary(); + foreach (var tag in tags) map[tag.Key] = tag.Value; + lock (seen) seen.Add((value, map)); + }); + listener.Start(); + + var diagnostics = new DataConnectionHistoryDiagnostics(); + diagnostics.RecordConsumerRead("connection-with-an-id", "processed", 0x40000000u); + diagnostics.RecordOriginRead("attime", 0x80720000u); + listener.Dispose(); + + List<(long Value, Dictionary Tags)> snapshot; + lock (seen) snapshot = seen.ToList(); + // Other tests may count in parallel on the same static counter: assert presence of ours and the label set of all. + snapshot.ShouldContain(x => Equals(x.Tags["side"], "consumer") && Equals(x.Tags["variant"], "processed") + && Equals(x.Tags["status_class"], "uncertain")); + snapshot.ShouldContain(x => Equals(x.Tags["side"], "origin") && Equals(x.Tags["variant"], "attime") + && Equals(x.Tags["status_class"], "bad")); + foreach (var (value, tags) in snapshot) + { + value.ShouldBe(1); + tags.Keys.OrderBy(x => x).ShouldBe(AllowedLabels.OrderBy(x => x), "no connection, node or principal id in labels"); + tags.Values.ShouldNotContain("connection-with-an-id"); + } + } + + [Fact] + public void Open_continuations_gauge_reports_origin_and_consumer_sides() + { + var diagnostics = new DataConnectionHistoryDiagnostics(); + diagnostics.AttachOrigin(() => (true, 1, 3)); + diagnostics.ConsumerContinuationOpened("link"); + diagnostics.ConsumerContinuationOpened("link"); + + var observed = new Dictionary(); + using var listener = new MeterListener(); + listener.InstrumentPublished = (instrument, l) => + { + if (instrument.Meter.Name == OtOpcUaTelemetry.MeterName && instrument.Name == DataConnectionHistoryDiagnostics.ContinuationsGaugeName) + l.EnableMeasurementEvents(instrument); + }; + listener.SetMeasurementEventCallback((_, value, tags, _) => + { + foreach (var tag in tags) if (tag.Key == "side") observed[(string)tag.Value!] = value; + }); + listener.Start(); + listener.RecordObservableInstruments(); + + // Sums across live instances (other tests' instances may add), so at least ours. + observed.Keys.OrderBy(x => x).ShouldBe(["consumer", "origin"]); + observed["origin"].ShouldBeGreaterThanOrEqualTo(3); + observed["consumer"].ShouldBeGreaterThanOrEqualTo(2); + GC.KeepAlive(diagnostics); + } + + [Fact] + public void Consumer_counts_are_per_connection_case_insensitive_and_settle_never_goes_negative() + { + var diagnostics = new DataConnectionHistoryDiagnostics(); + diagnostics.RecordConsumerRead("Link", "raw", 0); + diagnostics.RecordConsumerRead(null, "raw", 0x80000000u); // unresolved node: metric only + diagnostics.ConsumerContinuationOpened("link"); + diagnostics.ConsumerContinuationSettled("LINK"); + diagnostics.ConsumerContinuationSettled("never-opened"); + diagnostics.CaptureConsumer("LINK").ShouldBe(new ConsumerHistoryCounts(1, 0, 0, 0)); + diagnostics.CaptureConsumer("never-opened").ShouldBe(new ConsumerHistoryCounts(0, 0, 0, 0)); + diagnostics.OpenConsumerContinuations.ShouldBe(0); + } + + [Fact] + public void Origin_evidence_is_unavailable_until_attached_and_when_the_state_probe_fails() + { + var diagnostics = new DataConnectionHistoryDiagnostics(); + diagnostics.CaptureOrigin().ShouldBeNull(); + diagnostics.RecordOriginRead("raw", 0); + diagnostics.AttachOrigin(() => (false, 0, 0)); + diagnostics.CaptureOrigin().ShouldBe(new ZB.MOM.WW.OtOpcUa.Commons.Interfaces.OriginHistoryDiagnostics(false, 0, 0, 1, 0, 0)); + diagnostics.AttachOrigin(() => throw new InvalidOperationException("history port not ready")); + diagnostics.CaptureOrigin().ShouldBeNull(); + } + + [Fact] + public void The_plan_unknown_bit_counter_is_the_existing_X0_instrument_not_a_second_one() + { + // Plan §6 names "…operations.unknown_bits_dropped"; X0 already counts exactly that (one per row per accepted change). + UnknownOperationDrops.CounterName.ShouldBe("otopcua.dataconnection.unknown_operations_dropped"); + var names = new List(); + using var listener = new MeterListener(); + listener.InstrumentPublished = (instrument, _) => + { + if (instrument.Meter.Name == OtOpcUaTelemetry.MeterName) lock (names) names.Add(instrument.Name); + }; + listener.Start(); + _ = new DataConnectionHistoryDiagnostics(); + lock (names) names.ShouldNotContain(x => x.Contains("unknown_bits", StringComparison.Ordinal)); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs index 5b89a1f11..d7338e99f 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs @@ -125,6 +125,8 @@ internal sealed class LocalDataFixture : IDisposable internal readonly DataView Raw = new(new("cluster", "https://zb.com/otopcua/raw", "string", "Plant/Driver/Device/Speed"), DataRealm.Raw, null, 0, "Plant/Driver/Device/Speed"); internal readonly DataView Uns = new(new("cluster", "https://zb.com/otopcua/uns", "string", "Area/Line/Equipment/Speed"), DataRealm.Uns, null, 0, "Area/Line/Equipment/Speed"); internal readonly LocalDataServices Services; + /// H4: the origin's history diagnostics (counts by status class, live sessions and continuations). + internal readonly DataConnectionHistoryDiagnostics HistoryDiagnostics = new(); internal readonly LocalExportCatalog Catalog; internal readonly DataAuthenticatedContext Context; @@ -196,7 +198,7 @@ internal sealed class LocalDataFixture : IDisposable var capabilities = new DataCapabilitiesProvider("cluster", () => Serving, () => Catalog.IsActive, limits); Services = new LocalDataServices(() => Catalog, Hub, new DataOperationPolicy(Authority, new TriePermissionEvaluator(Authority.Tries, Clock), Clock), capabilities, Clock, writes: writes, subscriptions: subscriptions, - targetSubscriptions: targetSubscriptions, history: history); + targetSubscriptions: targetSubscriptions, history: history) { HistoryDiagnostics = HistoryDiagnostics }; } internal IDataConnection Connection() => Services.Create(Context, new(DataTargetMode.Node, "cluster", Serving.NodeId)); From 1efe08483379f959ab69f6227c3ed130f54368b3 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 08:02:41 -0500 Subject: [PATCH 02/11] docs(grpc-data): H4 remote history supported (SqlServer/QuestDB verified, Gateway pending #923), diagnostics and metrics, CLI projected-history note --- docs/Client.CLI.md | 18 ++++++++++++++++++ docs/DataConnections.md | 42 ++++++++++++++++++++++++++++++++++++++++- docs/Historian.md | 29 ++++++++++++++++++++++++++++ 3 files changed, 88 insertions(+), 1 deletion(-) diff --git a/docs/Client.CLI.md b/docs/Client.CLI.md index 900b37d08..dcb617749 100644 --- a/docs/Client.CLI.md +++ b/docs/Client.CLI.md @@ -268,6 +268,24 @@ continuation points up to `--max`. `--events` cannot be combined with `--modifie | `--release-after-page` | With `--page-size`: send `releaseContinuationPoints` for page k's point and stop | | `--hold-seconds` | With `--abandon-after-page` / `--release-after-page`: keep the session open this long before disconnecting | +**Projected nodes (gRPC data connections).** A variable a data connection maps into this server lives in +`https://zb.com/otopcua/mapped/raw` or `…/mapped/uns` under an **opaque** `p1.` identifier. Never type or construct one: browse +from the mapping anchor (the local parent path plus the mapping's branch name) and pass the NodeId `browse` prints to `-n`. The +ids are stable across deploys, but a deploy retires a projected node the client has not browsed since — re-browse after a deploy +(and after the node has been idle past its metadata lease, #922), or the read answers `BadNodeIdUnknown` / `BadUserAccessDenied`. +History is served by the ORIGIN's historian, verbatim (values, statuses, timestamps, its paging); `--aggregate` is limited to what +the origin's backend serves (otherwise `BadAggregateNotSupported`), and `--modified` / `--events` are refused +`BadHistoryOperationUnsupported`. Verified with SqlServer and QuestDB origins; a Gateway (AVEVA) origin is unverified (#923). +The consumer's **Data connections** page shows the projected history counts and open continuations a read leaves behind +(`DataConnections.md` §"Remote history diagnostics and metrics"). + +```bash +# Resolve the projected NodeId by browsing from the anchor, then read it +otopcua-cli browse -u opc.tcp://localhost:4841/OtOpcUa -U apikey -P "$KEY" -n "" -r -d 3 +P='' +otopcua-cli historyread -u opc.tcp://localhost:4841/OtOpcUa -U apikey -P "$KEY" -n "$P" --max 100 +``` + The hand-paged modes exist for continuation-point lifecycle checks — most usefully on **projected** nodes of a gRPC data connection (`DataConnections.md` §"OPC UA HistoryRead on projected nodes"), where a resumed page is bound to the origin endpoint that issued it: pause after page 1, fail the origin over, create the resume file, and the resumed page prints diff --git a/docs/DataConnections.md b/docs/DataConnections.md index 18e1727f7..09c92c498 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -138,7 +138,10 @@ snapshot when a row carries a bit it does not know, taking down every connection `otopcua.dataconnection.unknown_operations_dropped` (tag `kind` = connection, export or mapping). - A drop is counted once per row per accepted artifact change. A → B → A counts again, and a restart resets the count. - - The dropped bits also show in the node's fleet diagnostics. + - The dropped bits also show in the node's fleet diagnostics and, since H4, on the cluster's + **Data connections** page (per connection, the count of mappings with drops, and per node the exports with + drops — named when the AdminUI knows the bit, hex otherwise, with a hint that the node's build is older + than the authored feature; #919). - Authoring rejects a bit until the release that implements it. H2 implements `HistoryRead`; the alarm bits stay rejected until A2. - The optional per-call header `x-otopcua-data-features` negotiates features. X0 parsed it and @@ -147,6 +150,11 @@ snapshot when a row carries a bit it does not know, taking down every connection ## Remote history (runtime consumers) +**Status: supported** (H4). Verified end to end (live gate H01–H06) with the origin on the **SqlServer** and **QuestDB** +historian backends. The **Gateway** backend (AVEVA Historian via HistorianGateway) is **unverified** pending its live leg, +#923 (blocked on the VPN to the historian) — the code path is the same origin history port, but no live read against it +has been run. + Since H2 a consumer can read the origin's history (HistoryRead Raw, Processed, AtTime) over a data connection. The origin serves it from its own historian backend (`ServerHistorian:Backend`) through the same pipeline its OPC UA clients use, so statuses (info bits included), timestamps and paging come back verbatim. H2 serves **runtime consumers** that hold the @@ -260,6 +268,38 @@ Modified-value reads (`IsReadModified`) and HistoryReadEvents on projected nodes `otopcua-cli historyread -n "" …`; `--page-size`, `--pause-after-page` and `--abandon-after-page` exercise the continuation lifecycle (`Client.CLI.md`). Live gate: `scripts/validation/grpc-data/history_gate.py` (H01–H06, README). +## Remote history diagnostics and metrics (H4) + +The cluster's **Data connections** page (`/clusters/{id}/data-connections`) shows, per consumer node and connection: + +- **Negotiated features** — what the last capability handshake negotiated for the data calls (`History`, or "none (v1 + behaviour)" against an origin without a historian backend or older than H2), and the **origin history** it advertised to this + caller: the variants (`raw`, `processed`, `attime`) and the aggregate count, or "not advertised". +- **Projected history reads** by status class (good / uncertain / bad) — one per projected node as answered to a local + OPC UA client, since process start (refusals before a node resolves to a connection are counted in the metric only). +- **Open remote continuations (local sessions)** — projected-history continuation points held in local OPC UA sessions: + issued, not yet resumed or released (a release, a session close or an eviction settles them). +- **Dropped unknown operation bits** — the X0 drops for that connection and how many of its mappings had bits dropped. + +And per node, under **Origin evidence by node**: whether the node serves remote history (has a historian backend), the live peer +history sessions, the **open origin continuations** (page cursors and chunk remainders held for peers), the history items it +answered by status class, and its exports with dropped unknown operation bits. + +All counts are since process start and reset on restart. "Unavailable" means the node did not report the measure (built +before H4, or no data-connection services) — never zero activity. + +Metrics, on the `ZB.MOM.WW.OtOpcUa` meter (exported on `/metrics` and OTLP like every OtOpcUa instrument), never carry a +connection, node or principal id in a label: + +| Instrument | Type | Labels | Meaning | +|---|---|---|---| +| `otopcua.dataconn.history.reads` | counter `{item}` | `variant` = raw \| processed \| attime, `status_class` = good \| uncertain \| bad, `side` = origin \| consumer | Origin: one per history item answered to a peer (refusals included). Consumer: one per projected node answered to a local OPC UA client. A node can be both, so `side` keeps them apart. | +| `otopcua.dataconn.history.continuations.active` | gauge `{continuation}` | `side` = origin \| consumer | Origin: cursors held for peers. Consumer: cursors held in local sessions. | +| `otopcua.dataconnection.unknown_operations_dropped` | counter `{row}` | `kind` = connection \| export \| mapping | The plan's `…operations.unknown_bits_dropped`: the X0 counter is reused rather than duplicated (see "Mixed versions"). | + +Before H4 the origin's `otopcua.dataconn.history.reads` sat on a private meter the host did not export; it is now on the +OtOpcUa meter and carries `side`. + ## Feature boundary Alarm/event forwarding and relay operations are future work; remote history is above. Authorized imported diff --git a/docs/Historian.md b/docs/Historian.md index 98896009e..c9a8f19fb 100644 --- a/docs/Historian.md +++ b/docs/Historian.md @@ -2625,6 +2625,35 @@ HistoryUpdate is gated in **both** ACL modes (rewriting recorded history was nev --- +## Remote history over data connections + +A node can serve its historian to other OtOpcUa clusters, and read theirs, over a gRPC **data connection** +(`docs/DataConnections.md`). Nothing in this section changes local HistoryRead; it describes the same historian seen +from a peer. + +- **Origin.** An export granting `HistoryRead` (bit 32) lets a peer principal HistoryRead (Raw, Processed, AtTime) the + exported historized nodes. The origin serves it through the same node-manager history port as local HistoryRead + (`IOriginHistoryPort`): the configured `ServerHistorian:Backend`, the same paging, bounds, aggregates and per-node + DataType rules, its own `MaxConcurrentHistoryReadBatches` limiter (remote reads hold at most N − max(1, N/4) slots), and + its own ACL `HistoryRead` check on every item. Denied, unhistorized and unknown nodes all answer + `BadHistoryOperationUnsupported`. The origin advertises only the aggregates its backend serves + (`IHistorianDataSource.SupportedAggregates`). HistoryUpdate, modified reads and event history are never served remotely. +- **Consumer.** A mapped (projected) variable is `Historizing` only when the mapping and the origin both grant it; an OPC UA + client of the consumer reads it like a local node, through opaque `p1.` NodeIds in `https://zb.com/otopcua/mapped/raw|uns` + that it resolves by browsing (`docs/Client.CLI.md`). The consumer has no historian of its own in this path: values, + statuses and continuation points come from the origin's backend verbatim. +- **Diagnostics and metrics (H4).** `otopcua.dataconn.history.reads{variant,status_class,side}` and + `otopcua.dataconn.history.continuations.active{side}`, plus per-connection and per-node evidence on the cluster's Data + connections page — `docs/DataConnections.md` §"Remote history diagnostics and metrics". + +**Verified backends.** Remote history is verified end to end (live gate H01–H06, `scripts/validation/grpc-data/history_gate.py`) +with the origin on **`SqlServer`** and **`QuestDb`**. The **`Gateway`** backend (AVEVA Historian via HistorianGateway) is +**unverified** remotely, pending its live leg (#923, blocked on the VPN to the historian). Nothing in the remote path is +backend-specific, but the Gateway's own differences (the four-plus-raw-evaluated aggregate set, the strict row ceiling, the +reverse-read walk-back) have not been observed through a data connection. + +--- + ## Authoring workflow 1. Open the equipment's **Tags** tab on `/uns/equipment/{id}`. From 25b4fc5c452f0575912f092ce10aa51726f3c08a Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 08:28:54 -0500 Subject: [PATCH 03/11] =?UTF-8?q?docs(grpc-data):=20H4=20evidence=20?= =?UTF-8?q?=E2=80=94=20diagnostics,=20metrics,=20live=20SqlServer=20gate,?= =?UTF-8?q?=20Gateway=20leg=20blocked=20(#923)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/plans/evidence/grpc-data-ext/H4.md | 115 ++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 docs/plans/evidence/grpc-data-ext/H4.md diff --git a/docs/plans/evidence/grpc-data-ext/H4.md b/docs/plans/evidence/grpc-data-ext/H4.md new file mode 100644 index 000000000..9d8f9f81b --- /dev/null +++ b/docs/plans/evidence/grpc-data-ext/H4.md @@ -0,0 +1,115 @@ +# H4 evidence — remote-history diagnostics, metrics, docs (capability "supported") + +Phase H4 of `docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md` (revision 7), 2026-11-24. History part only; +the alarm diagnostics are A4. + +## What changed + +- **`Runtime/DataConnections/DataConnectionHistoryDiagnostics.cs`** (new, DI singleton, no dependencies): shared by the origin + services (`LocalDataServices`), the consumer gateway (`ProjectedHistoryAccess`) and the diagnostics readers + (`DataConnectionDeploymentRuntime`, `DriverHostActor`), so none of them depends on another (the origin composition is resolved + lazily after the driver host exists; a direct dependency would be a cycle). +- **Metrics** on `OtOpcUaTelemetry.Meter` (`ZB.MOM.WW.OtOpcUa`, already in the host's exported-meter allowlist), no ids in labels: + - `otopcua.dataconn.history.reads{variant,status_class,side}` — origin: one per item answered to a peer; consumer: one per + projected node answered to a local OPC UA client. + - `otopcua.dataconn.history.continuations.active{side}` — observable gauge over the live diagnostics instances (weak table). + - `…operations.unknown_bits_dropped`: **reused, not added.** X0's `otopcua.dataconnection.unknown_operations_dropped{kind}` + counts exactly that (one per row per accepted artifact change); a second instrument would double-count. Pinned by + `The_plan_unknown_bit_counter_is_the_existing_X0_instrument_not_a_second_one`. +- **Defect found: the H2 origin counter was never exported.** `otopcua.dataconn.history.reads` sat on a private + `Meter("ZB.MOM.WW.OtOpcUa.DataConnections.History")` that is not in `ObservabilityExtensions.ObservedMeters` (a strict + allowlist), so it was absent from `/metrics` and OTLP. It now lives on the OtOpcUa meter (verified on the live rig's `/metrics`). +- **Consumer evidence per connection** (`ProjectedHistoryAccess`): answers by status class, attributed to the connection the + node resolved to; open consumer continuations — a `RemoteCursor` counts from creation until it is claimed for a resume (new + `ProjectedHistoryContinuation.OnClaimed` hook) or its origin token is released, whichever first, once. +- **Origin evidence per node** (`LocalDataServices.HistoryDiagnostics` init property): backend present, live peer history sessions, + open origin continuations, answers by status class. +- **Negotiated features** (`GrpcDataConnection.RecordSelected`): `RequestedFeatures(capabilities)` and the advertised history + variants + aggregate count. +- **Contracts** (Commons, additive optional members — older senders give null = "unavailable"): + `DataConnectionDiagnosticsSnapshot` + `NegotiatedFeatures, HistoryVariants, HistoryAggregateCount, HistoryReads{Good,Uncertain,Bad}, + OpenRemoteContinuations`; new `OriginHistoryDiagnostics`; `NodeDiagnosticsSnapshot.OriginHistory`. +- **AdminUI** (`ClusterDataConnections.razor`, already inside ``; helpers in `DataConnectionDiagnostics`): per + connection a history line (negotiated features, origin history advertised, projected reads by class, open remote continuations) + and a dropped-unknown-bits line; a new **Origin evidence by node** panel (remote history served, peer sessions, open origin + continuations, answers by class, exports with dropped bits). Dropped bits are named when the AdminUI knows the bit, hex otherwise, + and carry a "node build is older than the authored feature" hint when non-empty. +- **#919 closed by this work:** the X0 fields (`DroppedUnknownOperations`, `MappingsWithDroppedOperations`, + `DroppedExportOperations`) are now rendered on the data-connections page. +- **Docs:** `DataConnections.md` (remote history **supported**, SqlServer/QuestDB verified, Gateway unverified pending #923; + new §"Remote history diagnostics and metrics"; #919 note under Mixed versions), `Historian.md` (§"Remote history over data + connections"), `Client.CLI.md` (projected-history note: opaque `p1.` ids resolved by browse, re-browse after deploy/idle, paging + flags, what is refused). + +## Tests (H4 manifest key) + +| Suite | What | +|---|---| +| R `GrpcDataHistoryMetricsTests` (5, new) | counter on the exported meter with exactly `variant,status_class,side` (no id); gauge reports both sides; per-connection counts case-insensitive, settle never negative; origin evidence null until attached / when its probe throws; unknown-bit counter is X0's | +| R `GrpcDataConfiguredDiscoveryWireTests` H4 (2) | real consumer SDK session + real projection + real origin: page 1 ⇒ consumer `(1,0,0,open 1)` and origin open 1; resume ⇒ `(2,0,0,open 1)`; `releaseContinuationPoints` ⇒ consumer open 0, origin 0 after the coalesced release; an origin-refused aggregate ⇒ one Bad each side; session close ⇒ consumer open 0 | +| R `GrpcDataDeploymentActivationTests` H4 (1) | runtime diagnostics carry per-connection counts (zeros, not null, without traffic; null when no diagnostics wired) | +| AdminUI `GrpcDataHistoryDiagnosticsDisplayTests` (5, new) | features / history-served / counts / dropped-bit rendering (#919) and the older-build hint | +| plus existing | `GrpcDataProjectedHistoryCursorTests`, `GrpcDataOriginHistorySessionTests`, OpcUaServer `ProjectedHistoryReadTests` (base class gained `OnClaimed`), AdminUI `GrpcDataDiagnosticsTests` | + +Red/green: with `RemoteCursor.OnClaimed => Settle()` reverted, the wire test fails at the resume step (consumer open 2, not 1). + +## Gates + +| Gate | Result | +|---|---| +| `dotnet build ZB.MOM.WW.OtOpcUa.slnx` | 0 warnings, 0 errors | +| `run-unit-phase.py H4` (new key: Runtime 25, OpcUaServer 11, AdminUI 9) | passed | +| `run-unit-phase.py H3` / `H2` / `H1` / `X0` | all passed (H3 107 + 144; H2 44/36/7/40/96/25; H1 578 + 17; X0 25/14/5/72/11) | +| AdminUI.Tests (`Category!=E2E&Category!=LiveIntegration`) | 2698 passed | +| Runtime.Tests (same filter) | 1911 passed, 3 skipped | +| OpcUaServer.Tests (same filter) | 1419 passed, 1 skipped | + +## Live gate — H3 scenarios on SqlServer with the metrics and the page + +Fresh run `h4a-sqlserver` (OrbStack, macOS, normal build-hash checks, 2026-11-24 ~12:50–13:10 UTC): +`rig.py up --history --history-backend sqlserver --timeout 900`, `seed`, ~80 s, `deploy --timeout 300`, `history_gate.py`, `down`. + +- **H01–H06 all PASS** (47 / 34 / 35 / 71 / 58 / 238 assertions, every scenario restored). +- **`/metrics` before traffic:** both continuation gauges 0 on every node; no reads series. +- **`/metrics` after the gate:** consumer-1 `reads{side=consumer}` raw good 31, raw bad 2, processed good 1, processed bad 1, + attime good 2; source-2 (primary after H04's failover) `reads{side=origin}` raw good 7, raw bad 2. (The CLI's comparison reads on + the SOURCE primary are local OPC UA reads and are not counted, as designed; source-1 restarted in H04, so its counts restart.) +- **AdminUI page** (`http:///clusters/CONSUMER/data-connections`, login disabled on the rig, prerendered HTML via + `urllib`): consumer-1 `Ready · endpoint https://source-2:4057 · serving source-2 · role Primary`, "Negotiated features History · + origin history raw, processed, attime (19 aggregates) · projected history reads good 34 · uncertain 0 · bad 3 · open remote + continuations (local sessions) 0" — equal to the sum of consumer-1's metric series; "Dropped unknown operation bits: connection + none · mappings with dropped bits 0". The SOURCE page's origin panel: source-2 "remote history served · peer history sessions 0 · + open origin continuations 0 · history items answered good 7 · uncertain 0 · bad 2" — equal to source-2's metric. +- **Held continuation probe** (a scratch script driving the gate's own `HistoryGate.held` on the projected raw `counter`, page size 3, + pause after page 1): while held — consumer-1 gauge `consumer=1`, source-2 gauge `origin=1`, the CONSUMER page "open remote + continuations (local sessions) 1", the SOURCE page "peer history sessions 1"; after resume to completion — both gauges 0, page 0, + projected good 35 ⇒ 54 (19 pages). +- Mid-gate the page showed the connection `Connecting` with features "unavailable" — taken during a scenario's redeploy/failover; + after the gate it read `Ready` with features `History`. +- `down` ⇒ 0 run containers, 0 run volumes. + +## Gateway leg — BLOCKED (#923), substituted by doc scoping + +The plan's required Gateway leg (origin `ServerHistorian:Backend=Gateway` against a local read-only HistorianGateway reading the +real AVEVA Historian over VPN; H01–H04 with reverse/end-only and ceiling-bounded cases) was **not attempted**: the VPN to the +historian is down. Per the plan's fallback, **#923** (`type:deploy-gate`, `blocked`) tracks it, and the docs say remote history is +verified on the **SqlServer and QuestDB** origin backends only, with the **Gateway backend unverified pending #923** +(`DataConnections.md`, `Historian.md`, `Client.CLI.md`). + +## Not verified / notes + +- **Gateway backend** remotely (#923, above). +- **QuestDB** was not re-run for H4: the H4 change is backend-independent (counting around the same port), and the H3 rounds + passed H01–H06 on QuestDB at `713cbfb21`. The brief asked for one SqlServer leg. +- **Browser-rendered** page not driven (no Chrome session used); verified from the server-prerendered HTML, which runs the same + `OnInitializedAsync` + render as the interactive circuit. +- **Akka serialization of the new snapshot members** was exercised only live (the rig's control node read data-node snapshots + through the fleet-diagnostics path and rendered every new field), not by a unit round-trip test. +- **Deviation:** the reads counter carries a third label `side` (origin | consumer) beyond the plan's `{variant,status_class}` — + a node can be both, and without it the two populations would be summed into one series. The gauge carries `side` too. +- Consumer counts include every projected node answered (Bad included), but a node refused by the node manager BEFORE the gateway + (no local HistoryRead grant ⇒ `BadUserAccessDenied`, unhistorized ⇒ `BadHistoryOperationUnsupported` from the SDK) is not counted. + A consumer node shows "remote history evidence unavailable" in the origin panel until something resolves its origin services. +- Counts are since process start (no persistence), as the docs say. +- `GrpcDataConfiguredDiscoveryWireTests` (#920 flaky class): no failure in any run this phase (H4 manifest, H3 manifest, full Runtime suite). +- Umbrella history entry (plan exit gate): **not done here** — it is a commit on `scadaproj` `main` plus a push, and this worktree brief forbids pushing; left to the orchestrator (append to `../scadaproj/.claude/skills/sister-project-history/otopcua.md`). The Gitea close of #919 likewise belongs with the merge. From ce648523aba876bfdd2cf14e2d020bc9efeb781d Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 08:28:59 -0500 Subject: [PATCH 04/11] =?UTF-8?q?docs(grpc-data):=20H4=20evidence=20?= =?UTF-8?q?=E2=80=94=20correct=20the=20live=20run=20window?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/plans/evidence/grpc-data-ext/H4.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plans/evidence/grpc-data-ext/H4.md b/docs/plans/evidence/grpc-data-ext/H4.md index 9d8f9f81b..da798f502 100644 --- a/docs/plans/evidence/grpc-data-ext/H4.md +++ b/docs/plans/evidence/grpc-data-ext/H4.md @@ -66,7 +66,7 @@ Red/green: with `RemoteCursor.OnClaimed => Settle()` reverted, the wire test fai ## Live gate — H3 scenarios on SqlServer with the metrics and the page -Fresh run `h4a-sqlserver` (OrbStack, macOS, normal build-hash checks, 2026-11-24 ~12:50–13:10 UTC): +Fresh run `h4a-sqlserver` (OrbStack, macOS, normal build-hash checks, 2026-11-24, between ~13:01 and ~13:14 UTC): `rig.py up --history --history-backend sqlserver --timeout 900`, `seed`, ~80 s, `deploy --timeout 300`, `history_gate.py`, `down`. - **H01–H06 all PASS** (47 / 34 / 35 / 71 / 58 / 238 assertions, every scenario restored). From 2f11a9c609eee1a3c59b90a9468eb446b28fe4dc Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 08:35:55 -0500 Subject: [PATCH 05/11] =?UTF-8?q?fix(grpc-data):=20H4=20review=201=20?= =?UTF-8?q?=E2=80=94=20count=20every=20projected=20history=20answer=20wher?= =?UTF-8?q?e=20its=20status=20is=20set?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The consumer reads counter was fed from the gateway's outcomes, so limiter refusals, a spent deadline, a count mismatch and refusals before the gateway were never counted, and a serve-time fault after the gateway returned counted Good. The node manager now reports each projected node once with the status the client sees (IProjectedHistoryAccess.RecordAnswered); a fault that escapes to the SDK counts every projected node of the request Bad. Variant gains 'modified'. --- .../IProjectedHistoryAccess.cs | 9 +++ .../OtOpcUaNodeManager.cs | 2 +- .../ProjectedHistoryRead.cs | 75 ++++++++++++++--- .../DataConnections/ProjectedDataAccess.cs | 16 ++++ .../DataConnections/ProjectedHistoryAccess.cs | 24 +++--- .../ProjectedHistoryReadTests.cs | 81 ++++++++++++++++++- 6 files changed, 186 insertions(+), 21 deletions(-) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs index 2ed760691..3f3e17ecb 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs @@ -105,4 +105,13 @@ public interface IProjectedHistoryAccess /// One outcome per node. Task> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details, IReadOnlyList nodes, TimeSpan deadline, CancellationToken cancellationToken); + + /// + /// H4 diagnostics: the projected answers of one request exactly as the client sees them — every projected node once, with + /// its final status (refusals before or instead of a remote call included; a request that faults counts every projected + /// node Bad). Called by the node manager after the request, outside Lock. Default: nothing is counted. + /// + /// raw | processed | attime | modified. + /// Each projected node and the status the client got for it. + void RecordAnswered(string variant, IReadOnlyList<(NodeId NodeId, uint StatusCode)> answers) { } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index 749fe7248..fa936fd0e 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -9955,7 +9955,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage /// respected (the same benign wiring race as ). /// /// The shared batch limiter semaphore. - private SemaphoreSlim GetHistoryReadBatchLimiter() + internal SemaphoreSlim GetHistoryReadBatchLimiter() { var gate = _historyReadBatchLimiter; if (gate is not null) return gate; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs index 53ffdb3be..6d379355b 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs @@ -50,7 +50,11 @@ public sealed partial class OtOpcUaNodeManager ServeProjectedHistory(context, details, nodesToRead, projected, results, errors, started); } - /// The projected half of a variable-history request. + /// + /// The projected half of a variable-history request. H4: every projected answer is counted once, with the status the client + /// sees, at the point that status is set; a fault that escapes to the SDK (the service then fails) counts every projected + /// node of the request Bad instead. + /// private void ServeProjectedHistory( ServerSystemContext context, HistoryReadDetails details, @@ -59,15 +63,67 @@ public sealed partial class OtOpcUaNodeManager IList results, IList errors, long started) + { + var answered = new List<(NodeId NodeId, uint StatusCode)>(handles.Count); + var access = ProjectedHistoryAccess; + try + { + ServeProjectedHistoryCore(context, details, nodesToRead, handles, results, errors, started, access, answered); + } + catch + { + answered.Clear(); + foreach (var handle in handles) answered.Add((handle.NodeId, StatusCodes.BadInternalError.Code)); + throw; + } + finally + { + RecordProjectedAnswers(access, details, answered); + } + } + + /// The variant label of a HistoryRead's details. + internal static string HistoryVariant(HistoryReadDetails details) => details switch + { + ReadRawModifiedDetails { IsReadModified: true } => "modified", + ReadRawModifiedDetails => "raw", + ReadProcessedDetails => "processed", + ReadAtTimeDetails => "attime", + _ => "unknown", + }; + + private static void RecordProjectedAnswers(IProjectedHistoryAccess? access, HistoryReadDetails details, + List<(NodeId NodeId, uint StatusCode)> answered) + { + if (access is null || answered.Count == 0) return; + try { access.RecordAnswered(HistoryVariant(details), answered); } + catch (Exception ex) when (ex is not OutOfMemoryException) { } // diagnostics never fail a read + } + + private void ServeProjectedHistoryCore( + ServerSystemContext context, + HistoryReadDetails details, + ArrayOf nodesToRead, + List handles, + IList results, + IList errors, + long started, + IProjectedHistoryAccess? access, + List<(NodeId NodeId, uint StatusCode)> answered) { var session = context.OperationContext?.Session; var store = _historyContinuationStore; var epoch = Volatile.Read(ref _historyContinuationEpoch); - var access = ProjectedHistoryAccess; var identity = IdentityOf(context); var remote = ToRemoteDetails(details); var aggregates = details is ReadProcessedDetails processed ? processed.AggregateType : default; + void Refuse(NodeHandle handle, StatusCode status) + { + SetProjectedStatus(handle, results, errors, status); + answered.Add((handle.NodeId, status.Code)); + } + var pending = new List<(NodeHandle Handle, ProjectedHistoryNode Node)>(handles.Count); ProjectedHistoryContinuation? claimed = null; try @@ -87,7 +143,7 @@ public sealed partial class OtOpcUaNodeManager || !cursor.TryClaimForResume()) { state?.Remote?.Release(); - SetProjectedStatus(handle, results, errors, StatusCodes.BadContinuationPointInvalid); + Refuse(handle, StatusCodes.BadContinuationPointInvalid); continue; } @@ -99,7 +155,7 @@ public sealed partial class OtOpcUaNodeManager { // No projection gateway, no session identity, or a variant a remote read never serves (a modified read). resume?.ReleaseEvenIfClaimed(); - SetProjectedStatus(handle, results, errors, StatusCodes.BadHistoryOperationUnsupported); + Refuse(handle, StatusCodes.BadHistoryOperationUnsupported); continue; } @@ -110,7 +166,7 @@ public sealed partial class OtOpcUaNodeManager var aggregate = aggregates[handle.Index]; if (AggregateFunctionMap.Map(aggregate) is null || aggregate.NamespaceIndex != 0 || !aggregate.TryGetValue(out uint numeric)) { - SetProjectedStatus(handle, results, errors, StatusCodes.BadAggregateNotSupported); + Refuse(handle, StatusCodes.BadAggregateNotSupported); continue; } @@ -143,7 +199,7 @@ public sealed partial class OtOpcUaNodeManager if (!projectedSlots.Wait(0)) { ReleaseResumes(); - foreach (var p in pending) SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadTooManyOperations); + foreach (var p in pending) Refuse(p.Handle, StatusCodes.BadTooManyOperations); return; } @@ -181,7 +237,7 @@ public sealed partial class OtOpcUaNodeManager }, p => { p.Node.Resume?.ReleaseEvenIfClaimed(); - SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadTooManyOperations); + Refuse(p.Handle, StatusCodes.BadTooManyOperations); }); } finally @@ -194,7 +250,7 @@ public sealed partial class OtOpcUaNodeManager { foreach (var o in outcomes) o.Continuation?.Release(); ReleaseResumes(); - foreach (var p in pending) SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadInternalError); + foreach (var p in pending) Refuse(p.Handle, StatusCodes.BadInternalError); return; } @@ -224,7 +280,7 @@ public sealed partial class OtOpcUaNodeManager if (StatusCode.IsBad(status)) { outcome.Continuation?.Release(); - SetProjectedStatus(handle, results, errors, status); + Refuse(handle, status); return; } @@ -247,6 +303,7 @@ public sealed partial class OtOpcUaNodeManager HistoryData = new ExtensionObject(new HistoryData { DataValues = values }), ContinuationPoint = cp is null ? default : ByteString.From(cp), }; + answered.Add((handle.NodeId, status.Code)); } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs index aeae8532b..000d35ff8 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs @@ -151,6 +151,22 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable DataValueKind.Guid => items.Cast().ToArray(), _ => throw new ArgumentException("Unsupported array element kind.") }; } + /// + /// H4 diagnostics: the deployed connection a projected node's mapping uses, without authorizing or pinning anything; null + /// when the node no longer resolves. Never an access decision. + /// + internal string? ConnectionOf(NodeId nodeId) + { + try + { + return _nodes.TryResolve(nodeId, out var definition) && definition is not null + && _catalog.TryResolveProjected(definition.Realm, definition.LocalIdentifier, out var proof) && proof is not null + && proof.Metadata.View.MappingId is { } mapping && _connectionForMapping(mapping) is { Length: > 0 } connectionId + ? connectionId : null; + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return null; } + } + public bool TryAcquire(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out IProjectedDemandLease? demand) { demand = null; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs index 2f90f37c5..dcaadce18 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs @@ -97,6 +97,18 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl await flush.ConfigureAwait(false); } + /// + /// + /// H4 review: counted by the node manager at the point each status is set (limiter refusals, a spent deadline, a count + /// mismatch and a serve-time fault included), not here from the gateway's outcomes. Each node is attributed to the + /// connection its mapping is deployed on, best effort (none when the node no longer resolves: metric only). + /// + public void RecordAnswered(string variant, IReadOnlyList<(NodeId NodeId, uint StatusCode)> answers) + { + ArgumentNullException.ThrowIfNull(answers); + foreach (var (node, status) in answers) Diagnostics.RecordConsumerRead(_access.ConnectionOf(node), variant, status); + } + /// /// Whether a projected node is advertised as historizing: the mapping (masked by the export) grants HistoryRead AND the /// origin's negotiated metadata (HistoryInfo, bit 32) says historizing. @@ -200,7 +212,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl left -= assembled[i]; } - return Recorded(outcomes.Select(o => o ?? Fail(BadNoCommunication)).ToArray()); + return outcomes.Select(o => o ?? Fail(BadNoCommunication)).ToArray(); } catch (Exception ex) when (ex is not OutOfMemoryException) { @@ -216,21 +228,13 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl outcomes[i] = Fail(timedOut ? BadTimeout : ex is OperationCanceledException && resumed ? BadContinuationPointInvalid : BadNoCommunication); } - return Recorded(outcomes.Select(o => o!).ToArray()); + return outcomes.Select(o => o!).ToArray(); } finally { foreach (var demand in demands) demand?.Dispose(); } - // H4: one count per node as answered to the local client, attributed to its connection when it resolved to one. - ProjectedHistoryOutcome[] Recorded(ProjectedHistoryOutcome[] answered) - { - var variant = DataConnectionHistoryDiagnostics.Variant(details); - for (var i = 0; i < answered.Length; i++) Diagnostics.RecordConsumerRead(targets[i]?.ConnectionId, variant, answered[i].StatusCode); - return answered; - } - TimeSpan Remaining() => deadline > TimeSpan.Zero ? deadline - _clock.GetElapsedTime(started) : TimeSpan.FromHours(1); // unbounded locally: the connection's HistoryTimeout still caps each call diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ProjectedHistoryReadTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ProjectedHistoryReadTests.cs index ac9afe89f..52c8c20c8 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ProjectedHistoryReadTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ProjectedHistoryReadTests.cs @@ -214,6 +214,76 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable access.Issued[0].Released.ShouldBe(0, "the store owns the saved cursor"); } + [Fact] + [Trait("Phase", "H4")] + public async Task Every_projected_answer_is_recorded_once_with_the_status_the_client_sees() + { + // H4 review item 1: counted where the status is set — limiter refusals, a spent deadline, a count mismatch and a + // serve-time fault included — never from the gateway's outcomes alone. + var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead); + nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore(); + var a = Project(nm, f, "Speed", historizing: true); + var b = Project(nm, f, "Flow", historizing: true); + var access = new FakeAccess(); + nm.ProjectedHistoryAccess = access; + + (string Variant, uint[] Statuses) Delta(Action act) + { + var before = access.Answered.Count; + act(); + var added = access.Answered.Skip(before).ToArray(); + added.Select(x => x.Variant).Distinct().Count().ShouldBe(1); + return (added[0].Variant, added.Select(x => x.Status).ToArray()); + } + + // Served: Good, once per node. + var served = Delta(() => Raw(nm, f.Identity, [a, b])); + served.Variant.ShouldBe("raw"); + served.Statuses.ShouldBe([StatusCodes.Good.Code, StatusCodes.Good.Code]); + + // Refused unsent by the consumer: an unknown aggregate, a modified read. + var processed = new ReadProcessedDetails { StartTime = T0, EndTime = T0.AddHours(1), ProcessingInterval = 60_000, + AggregateType = [new NodeId("not-an-aggregate", 2)] }; + var unknown = Delta(() => Read(nm, f.Identity, processed, [a])); + unknown.Variant.ShouldBe("processed"); + unknown.Statuses.ShouldBe([StatusCodes.BadAggregateNotSupported.Code]); + var modified = new ReadRawModifiedDetails { StartTime = T0, EndTime = T0.AddHours(1), NumValuesPerNode = 5, IsReadModified = true }; + var refused = Delta(() => Read(nm, f.Identity, modified, [a])); + refused.Variant.ShouldBe("modified"); + refused.Statuses.ShouldBe([StatusCodes.BadHistoryOperationUnsupported.Code]); + + // The non-local (projected) slot limiter saturated. + var nonLocal = nm.GetNonLocalHistoryLimiter(); + var taken = 0; + while (nonLocal.Wait(0, TestContext.Current.CancellationToken)) taken++; + try { Delta(() => Raw(nm, f.Identity, [a, b])).Statuses.ShouldBe([StatusCodes.BadTooManyOperations.Code, StatusCodes.BadTooManyOperations.Code]); } + finally { nonLocal.Release(taken); } + + // The shared batch limiter saturated (its admission wait is capped by the request deadline). + var batch = nm.GetHistoryReadBatchLimiter(); + nm.HistoryReadDeadline = TimeSpan.FromMilliseconds(100); + taken = 0; + while (batch.Wait(0, TestContext.Current.CancellationToken)) taken++; + try { Delta(() => Raw(nm, f.Identity, [a])).Statuses.ShouldBe([StatusCodes.BadTooManyOperations.Code]); } + finally { batch.Release(taken); nm.HistoryReadDeadline = TimeSpan.FromSeconds(60); } + + // The request deadline spent before the remote call. + nm.HistoryReadDeadline = TimeSpan.FromTicks(1); + try { Delta(() => Raw(nm, f.Identity, [a])).Statuses.ShouldBe([StatusCodes.BadTimeout.Code]); } + finally { nm.HistoryReadDeadline = TimeSpan.FromSeconds(60); } + + // The gateway answered the wrong number of outcomes. + access.DropLast = true; + Delta(() => Raw(nm, f.Identity, [a, b])).Statuses.ShouldBe([StatusCodes.BadInternalError.Code, StatusCodes.BadInternalError.Code]); + access.DropLast = false; + + // A serve-time fault after the gateway returned: the service fails, so every projected node counts Bad — never Good. + var poisoned = new FakeAccess { FirstValue = new object() }; + nm.ProjectedHistoryAccess = poisoned; + Should.Throw(() => Raw(nm, f.Identity, [a, b])); + poisoned.Answered.Select(x => x.Status).ShouldBe([StatusCodes.BadInternalError.Code, StatusCodes.BadInternalError.Code]); + } + [Fact] public void Unset_bounds_travel_absent_and_AtTime_carries_its_times() { @@ -470,6 +540,15 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable /// When set, every call throws it (after claiming nothing — the cursors are the caller's to release). public Exception? Throw { get; set; } public int Entries; + /// When set, the answer omits the last node (an outcome count mismatch). + public bool DropLast { get; set; } + /// H4: what the node manager reported as answered, in order. + public readonly List<(string Variant, NodeId Node, uint Status)> Answered = []; + + public void RecordAnswered(string variant, IReadOnlyList<(NodeId NodeId, uint StatusCode)> answers) + { + lock (Answered) foreach (var (node, status) in answers) Answered.Add((variant, node, status)); + } public async Task> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details, IReadOnlyList nodes, TimeSpan deadline, CancellationToken cancellationToken) @@ -479,7 +558,7 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable if (Interlocked.Increment(ref Entries) > 0) Entered.TrySetResult(); if (Hold is { } hold) await hold.Task.ConfigureAwait(false); if (Throw is { } error) throw error; - return (nodes.Select(node => + return (nodes.Take(DropLast ? nodes.Count - 1 : nodes.Count).Select(node => { FakeCursor? next = null; if (Paged) From 005720bd02bd1863e919559325142eb6cac29476 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 08:37:38 -0500 Subject: [PATCH 06/11] =?UTF-8?q?fix(grpc-data):=20H4=20review=202=20?= =?UTF-8?q?=E2=80=94=20a=20fresh=20origin=20reports=20'no=20peer=20traffic?= =?UTF-8?q?=20yet',=20not=20'unavailable'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The origin services are composed on the first peer call (they need the driver host actor), so CaptureOrigin returned null until then and a fresh H4 origin read like a pre-H4 build. The DI singleton now probes the same deferred history port for backend availability and reports zeros with PeerServicesStarted=false; the page says 'no peer has called since start'. --- docs/DataConnections.md | 4 +++- .../DataConnectionDiagnosticsSnapshot.cs | 6 +++++- .../Clusters/ClusterDataConnections.razor | 2 +- .../DataConnectionRegistration.cs | 10 +++++++++- .../DataConnectionHistoryDiagnostics.cs | 20 +++++++++++++++++-- .../GrpcDataHistoryMetricsTests.cs | 17 ++++++++++++++++ 6 files changed, 53 insertions(+), 6 deletions(-) diff --git a/docs/DataConnections.md b/docs/DataConnections.md index 09c92c498..ccb9d0ca3 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -286,7 +286,9 @@ history sessions, the **open origin continuations** (page cursors and chunk rema answered by status class, and its exports with dropped unknown operation bits. All counts are since process start and reset on restart. "Unavailable" means the node did not report the measure (built -before H4, or no data-connection services) — never zero activity. +before H4, or no data-connection services) — never zero activity. The origin's data services are created on the first peer call, +so until a peer has called, a node's origin line shows its backend availability with zero sessions, continuations and answers and +"no peer has called since start". Metrics, on the `ZB.MOM.WW.OtOpcUa` meter (exported on `/metrics` and OTLP like every OtOpcUa instrument), never carry a connection, node or principal id in a label: 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 7dcc5f6c5..b19960bfb 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs @@ -57,5 +57,9 @@ public sealed record DataConnectionDiagnosticsSnapshot( /// Remote history items answered Good since process start. /// Remote history items answered Uncertain since process start. /// Remote history items answered Bad (including refusals) since process start. +/// +/// False while no peer has called this node since start: the origin data services are created on the first peer call, so +/// the zeros are "no peer traffic yet", not missing evidence. True once they run (and from a sender that predates the flag). +/// public sealed record OriginHistoryDiagnostics(bool Available, int Sessions, int OpenContinuations, long ReadsGood, - long ReadsUncertain, long ReadsBad); + long ReadsUncertain, long ReadsBad, bool PeerServicesStarted = true); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor index e9cdb665f..9bc071912 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor @@ -53,7 +53,7 @@ else
@nodeId @if (node.OriginHistory is { } origin) { - · remote history @(origin.Available ? "served" : "no historian backend") · peer history sessions @origin.Sessions · open origin continuations @origin.OpenContinuations · history items answered @DataConnectionDiagnostics.HistoryCounts(origin.ReadsGood, origin.ReadsUncertain, origin.ReadsBad) + · remote history @(origin.Available ? "served" : "no historian backend") · peer history sessions @origin.Sessions · open origin continuations @origin.OpenContinuations · history items answered @DataConnectionDiagnostics.HistoryCounts(origin.ReadsGood, origin.ReadsUncertain, origin.ReadsBad)@(origin.PeerServicesStarted ? "" : " · no peer has called since start") } else { · remote history evidence unavailable } @if (node.DroppedExportOperations is { } dropped) 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 2f574c943..1a6b07330 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs @@ -120,7 +120,15 @@ public static class DataConnectionRegistration services.AddSingleton(sp => sp.GetRequiredService()); // H4: one dependency-free history diagnostics instance shared by the origin services, the consumer gateway and the // diagnostics readers (it also backs the otopcua.dataconn.history.* metrics). - services.AddSingleton(); + services.AddSingleton(sp => + { + // Before the first peer call composes the origin services, report the backend's availability (and zeros) from a + // probe of the same deferred history port, so a fresh H4 origin never reads like a pre-H4 build (H4 review 2). + var diagnostics = new DataConnectionHistoryDiagnostics(); + var probe = new DeferredOriginHistoryPort(sp.GetRequiredService()); + diagnostics.AttachProvisionalOrigin(() => probe.Serving is not null); + return diagnostics; + }); // H3: OPC UA HistoryRead on projected variables, forwarded over the mapping's deployed connection. services.AddSingleton(sp => new ProjectedHistoryAccess(sp.GetRequiredService(), sp.GetRequiredService(), diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionHistoryDiagnostics.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionHistoryDiagnostics.cs index 4fb7b961f..b0f533bc4 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionHistoryDiagnostics.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionHistoryDiagnostics.cs @@ -75,6 +75,7 @@ public sealed class DataConnectionHistoryDiagnostics private readonly ConcurrentDictionary _consumer = new(StringComparer.OrdinalIgnoreCase); private readonly Counts _origin = new(); private Func<(bool Available, int Sessions, int Open)>? _originState; + private Func? _provisionalAvailability; public DataConnectionHistoryDiagnostics() => Live.AddOrUpdate(this, new object()); @@ -129,6 +130,13 @@ public sealed class DataConnectionHistoryDiagnostics /// Connects the origin services whose live state (backend, sessions, open cursors) this reports. internal void AttachOrigin(Func<(bool Available, int Sessions, int Open)> state) => _originState = state; + /// + /// H4 review: the origin's backend availability BEFORE its data services exist. They are composed on the first peer call + /// (the composition needs the driver host actor), so until then the evidence is "available/not, no peer traffic yet" — + /// zero sessions and continuations are facts, not unknowns — instead of null (which means a pre-H4 build). + /// + public void AttachProvisionalOrigin(Func available) => _provisionalAvailability = available; + /// The consumer evidence for one connection; zeros when it has seen no history traffic. public ConsumerHistoryCounts CaptureConsumer(string connectionId) => _consumer.TryGetValue(connectionId, out var c) @@ -138,10 +146,18 @@ public sealed class DataConnectionHistoryDiagnostics /// Consumer continuations open across every connection. public int OpenConsumerContinuations => _consumer.Values.Sum(x => Math.Max(0, Volatile.Read(ref x.Open))); - /// The origin evidence; null until origin services are attached (no data-connection origin on this node yet). + /// + /// The origin evidence: live once the origin services are attached; before that the provisional "no peer traffic yet" + /// state when one is attached; otherwise null (no data-connection origin on this node). + /// public OriginHistoryDiagnostics? CaptureOrigin() { - if (_originState is not { } state) return null; + if (_originState is not { } state) + { + if (_provisionalAvailability is not { } provisional) return null; + try { return new(provisional(), 0, 0, 0, 0, 0, PeerServicesStarted: false); } + catch (Exception) { return null; } + } (bool Available, int Sessions, int Open) now; try { now = state(); } catch (Exception) { return null; } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryMetricsTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryMetricsTests.cs index 3ffc620ac..3a2a122c8 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryMetricsTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryMetricsTests.cs @@ -109,6 +109,23 @@ public sealed class GrpcDataHistoryMetricsTests diagnostics.CaptureOrigin().ShouldBeNull(); } + [Fact] + public void Before_any_peer_call_a_provisional_origin_reports_no_peer_traffic_yet_not_unavailable() + { + // H4 review item 2: the origin services are composed on the first peer call; until then a fresh H4 origin must not + // read like a pre-H4 build (null). + var diagnostics = new DataConnectionHistoryDiagnostics(); + var backend = true; + diagnostics.AttachProvisionalOrigin(() => backend); + diagnostics.CaptureOrigin().ShouldBe(new ZB.MOM.WW.OtOpcUa.Commons.Interfaces.OriginHistoryDiagnostics(true, 0, 0, 0, 0, 0, + PeerServicesStarted: false)); + backend = false; + diagnostics.CaptureOrigin()!.Available.ShouldBeFalse("availability is probed live, not latched"); + diagnostics.AttachOrigin(() => (true, 2, 1)); + diagnostics.CaptureOrigin().ShouldBe(new ZB.MOM.WW.OtOpcUa.Commons.Interfaces.OriginHistoryDiagnostics(true, 2, 1, 0, 0, 0)); + diagnostics.CaptureOrigin()!.PeerServicesStarted.ShouldBeTrue(); + } + [Fact] public void The_plan_unknown_bit_counter_is_the_existing_X0_instrument_not_a_second_one() { From b5509dfc48fab29f17776ac3c9436a19abe76734 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 08:37:58 -0500 Subject: [PATCH 07/11] =?UTF-8?q?docs(grpc-data):=20H4=20review=203=20?= =?UTF-8?q?=E2=80=94=20origin=20history=20reads=20are=20counted=20per=20it?= =?UTF-8?q?em=20per=20wire=20call?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/DataConnections.md | 9 +++++---- .../DataConnections/DataConnectionHistoryDiagnostics.cs | 7 ++++--- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/docs/DataConnections.md b/docs/DataConnections.md index ccb9d0ca3..1dc5e0961 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -275,15 +275,16 @@ The cluster's **Data connections** page (`/clusters/{id}/data-connections`) show - **Negotiated features** — what the last capability handshake negotiated for the data calls (`History`, or "none (v1 behaviour)" against an origin without a historian backend or older than H2), and the **origin history** it advertised to this caller: the variants (`raw`, `processed`, `attime`) and the aggregate count, or "not advertised". -- **Projected history reads** by status class (good / uncertain / bad) — one per projected node as answered to a local - OPC UA client, since process start (refusals before a node resolves to a connection are counted in the metric only). +- **Projected history reads** by status class (good / uncertain / bad) — one per projected node per local OPC UA HistoryRead, + with the status the client got, since process start (a node that no longer resolves to a connection is counted in the + metric only). - **Open remote continuations (local sessions)** — projected-history continuation points held in local OPC UA sessions: issued, not yet resumed or released (a release, a session close or an eviction settles them). - **Dropped unknown operation bits** — the X0 drops for that connection and how many of its mappings had bits dropped. And per node, under **Origin evidence by node**: whether the node serves remote history (has a historian backend), the live peer history sessions, the **open origin continuations** (page cursors and chunk remainders held for peers), the history items it -answered by status class, and its exports with dropped unknown operation bits. +answered by status class (per wire call: a chunked page's follow-up calls count again), and its exports with dropped unknown operation bits. All counts are since process start and reset on restart. "Unavailable" means the node did not report the measure (built before H4, or no data-connection services) — never zero activity. The origin's data services are created on the first peer call, @@ -295,7 +296,7 @@ connection, node or principal id in a label: | Instrument | Type | Labels | Meaning | |---|---|---|---| -| `otopcua.dataconn.history.reads` | counter `{item}` | `variant` = raw \| processed \| attime, `status_class` = good \| uncertain \| bad, `side` = origin \| consumer | Origin: one per history item answered to a peer (refusals included). Consumer: one per projected node answered to a local OPC UA client. A node can be both, so `side` keeps them apart. | +| `otopcua.dataconn.history.reads` | counter `{item}` | `variant` = raw \| processed \| attime (\| modified, consumer only), `status_class` = good \| uncertain \| bad, `side` = origin \| consumer | Origin: one per item **per wire call** answered to a peer (refusals included) — a chunked answer's follow-up calls for the same page count again, so this measures served item-calls, not logical reads. Consumer: one per projected node per OPC UA HistoryRead, with the status the client got (refusals before any remote call included; a request that faults counts every projected node Bad). A node can be both, so `side` keeps them apart. | | `otopcua.dataconn.history.continuations.active` | gauge `{continuation}` | `side` = origin \| consumer | Origin: cursors held for peers. Consumer: cursors held in local sessions. | | `otopcua.dataconnection.unknown_operations_dropped` | counter `{row}` | `kind` = connection \| export \| mapping | The plan's `…operations.unknown_bits_dropped`: the X0 counter is reused rather than duplicated (see "Mixed versions"). | diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionHistoryDiagnostics.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionHistoryDiagnostics.cs index b0f533bc4..00754845f 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionHistoryDiagnostics.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionHistoryDiagnostics.cs @@ -18,9 +18,10 @@ public sealed record ConsumerHistoryCounts(long Good, long Uncertain, long Bad, /// /// Metrics, on , never carry an id in a label: /// -/// — one per history item answered, tagged variant (raw | processed | attime), -/// status_class (good | uncertain | bad) and side (origin = served to a peer; consumer = a projected node's -/// answer to a local OPC UA client). A node can be both, so side keeps the two from being summed. +/// — tagged variant (raw | processed | attime | modified), +/// status_class (good | uncertain | bad) and side: origin = one per item per WIRE CALL served to a peer (a +/// chunked page's follow-up calls count again); consumer = one per projected node per local OPC UA HistoryRead, with the +/// status the client got. A node can be both, so side keeps the two from being summed. /// — open remote continuations, tagged side: origin cursors held for /// peers, and consumer cursors held in local OPC UA sessions (created, neither resumed nor released). /// From 79cf50d50efa664dfd40a2738d2c165ba38a8ed3 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 08:39:02 -0500 Subject: [PATCH 08/11] =?UTF-8?q?fix(grpc-data):=20H4=20review=204=20?= =?UTF-8?q?=E2=80=94=20an=20origin=20chunk=20holding=20its=20page=20cursor?= =?UTF-8?q?=20is=20one=20open=20continuation,=20not=20two?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../OriginHistoryPort.cs | 3 +++ .../PeerHistoryContinuationStore.cs | 11 ++++++++ .../DataConnections/OriginHistorySessions.cs | 25 +++++++++++++++++-- .../GrpcDataOriginHistorySessionTests.cs | 18 +++++++++++++ 4 files changed, 55 insertions(+), 2 deletions(-) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginHistoryPort.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginHistoryPort.cs index e655f0fff..63a0787ba 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginHistoryPort.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginHistoryPort.cs @@ -58,6 +58,9 @@ public sealed class OriginHistoryCursors /// Releases a token (idempotent). public bool Release(byte[]? token) => Store.Release(token); + /// Whether a token names a live page cursor (diagnostics). + public bool Contains(byte[]? token) => Store.Contains(token); + /// Drops every record (the channel closed). public void Clear() => Store.Clear(); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/PeerHistoryContinuationStore.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/PeerHistoryContinuationStore.cs index 74d0aff4b..0aac055f5 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/PeerHistoryContinuationStore.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/PeerHistoryContinuationStore.cs @@ -185,6 +185,17 @@ internal sealed class PeerHistoryContinuationStore } } + /// Whether names a live (unexpired) record (diagnostics: de-duplicating open continuations). + public bool Contains(byte[]? token) + { + if (token is not { Length: TokenLength }) return false; + lock (_gate) + { + Sweep(_clock.GetTimestamp()); + return _entries.ContainsKey(new Guid(token)); + } + } + /// Drops a record without reading it (release_continuations). Idempotent. /// The token to release. /// Whether a live record was dropped. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/OriginHistorySessions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/OriginHistorySessions.cs index aed8567d5..d732203e5 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/OriginHistorySessions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/OriginHistorySessions.cs @@ -44,6 +44,27 @@ internal sealed class OriginHistorySession get { lock (_gate) { Sweep(_clock.GetTimestamp()); return _chunks.Count; } } } + /// + /// H4 review: open continuations of this session, each counted once — a chunk that still holds its page cursor (a + /// deferred node, or a remainder that ends with a continuation) is one open continuation, not two. + /// + public int OpenContinuations + { + get + { + byte[]?[] behindChunks; + int chunks; + lock (_gate) + { + Sweep(_clock.GetTimestamp()); + chunks = _chunks.Count; + behindChunks = _chunks.Values.Select(x => x.Continuation).ToArray(); + } + var shared = behindChunks.Count(token => token is not null && Cursors.Contains(token)); + return chunks + Cursors.Count - shared; + } + } + /// /// A stored part of one node's answer. = the node was not read yet because the response budget /// was spent: resuming reads it then, from (its original page token, or null = fresh). @@ -194,14 +215,14 @@ internal sealed class OriginHistorySessions(TimeProvider clock, int maxSessions /// Live sessions (diagnostics/tests). public int Count { get { lock (_gate) return _sessions.Count; } } - /// Open page cursors plus chunk remainders across every session (diagnostics/tests). + /// Open continuations across every session, each once (a chunk holding its page cursor counts once). public int OpenContinuations { get { OriginHistorySession[] sessions; lock (_gate) sessions = _sessions.Values.Select(x => x.Session).ToArray(); - return sessions.Sum(x => x.Cursors.Count + x.ChunkCount); + return sessions.Sum(x => x.OpenContinuations); } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataOriginHistorySessionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataOriginHistorySessionTests.cs index acaf1157d..a4c82a88e 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataOriginHistorySessionTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataOriginHistorySessionTests.cs @@ -73,6 +73,24 @@ public sealed class GrpcDataOriginHistorySessionTests sessions.RetainedBytes("a").ShouldBe(0); } + [Fact] + [Trait("Phase", "H4")] + public void Open_continuations_count_a_chunk_holding_its_page_cursor_once() + { + // H4 review item 4: Cursors.Count + ChunkCount counted a chunk AND the page cursor behind it. + var sessions = new OriginHistorySessions(TimeProvider.System); + var session = sessions.Get(Caller("a"), Channel("1"), 8); + var view = new DataView(new("c", "u", "string", "x"), DataRealm.Raw, null, 0, "x"); + byte[] Page() => session.Cursors.Store.Save(new ZB.MOM.WW.OtOpcUa.OpcUaServer.HistoryContinuationState("t", DateTime.UnixEpoch, + DateTime.UnixEpoch, 0, 1) { BoundIdentifier = "x" }, "a", "inc", "h"); + session.SaveChunk(new OriginHistorySession.Chunk(view, "k", "i", [], 0, Page(), null, 0, 10), 1000).ShouldNotBeNull(); + session.SaveChunk(new OriginHistorySession.Chunk(view, "k", "i", [], 0, null, null, 0, 10), 1000).ShouldNotBeNull(); + Page(); // a plain page cursor, no chunk + (session.Cursors.Count, session.ChunkCount).ShouldBe((2, 2)); + session.OpenContinuations.ShouldBe(3, "chunk+its cursor, a chunk without one, a plain cursor"); + sessions.OpenContinuations.ShouldBe(3); + } + [Fact] public void Remainder_bytes_are_budgeted_per_principal_across_sessions() { From 2fba03617618f14a51400eabbee7036c4c81e303 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 08:39:46 -0500 Subject: [PATCH 09/11] =?UTF-8?q?fix(grpc-data):=20H4=20review=205+6=20?= =?UTF-8?q?=E2=80=94=20AdminUI=20display:=20'unavailable'=20without=20hand?= =?UTF-8?q?shake=20evidence;=20every=20bit=20rendered?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit HistoryServed reads 'unavailable' when neither features nor variants were reported. Features() and DroppedBits() render every set bit across all 32 (bit 31 included), named when known and hex otherwise, so an unknown bit is never hidden beside a known one (#919). --- .../DataConnections/DataConnectionDiagnostics.cs | 15 ++++++++++----- .../GrpcDataHistoryDiagnosticsDisplayTests.cs | 10 ++++++++-- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataConnectionDiagnostics.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataConnectionDiagnostics.cs index 9badce08a..b56ff0092 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataConnectionDiagnostics.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataConnectionDiagnostics.cs @@ -26,17 +26,23 @@ public static class DataConnectionDiagnostics "auth-failed" => "Authentication failed", "backoff" => "Backoff", _ => "Unavailable" }; /// H4: the features the last handshake negotiated; "none (v1)" when the peer negotiated nothing optional. + /// Every set bit is shown — a name when this AdminUI knows it, hex otherwise (H4 review: never hidden by a known one). public static string Features(DataFeatures? features) => features switch { null => "unavailable", DataFeatures.None => "none (v1 behaviour)", - { } f => string.Join(", ", Enum.GetValues().Where(x => x != DataFeatures.None && f.HasFlag(x)).Select(x => x.ToString()) - .DefaultIfEmpty($"0x{(int)f:X}")), + { } f => Bits((uint)(int)f, bit => Enum.IsDefined((DataFeatures)(int)bit) ? ((DataFeatures)(int)bit).ToString() : null), }; + /// Each set bit of across all 32, low to high: its name, or hex when unnamed. + private static string Bits(uint value, Func name) => + string.Join(", ", Enumerable.Range(0, 32).Select(i => 1u << i).Where(bit => (value & bit) != 0) + .Select(bit => name(bit) ?? $"0x{bit:X}")); + /// H4: the history variants and aggregate count the origin advertised to this caller. public static string HistoryServed(DataConnectionDiagnosticsSnapshot row) => - row.HistoryVariants is not { } variants ? "not advertised" + row.NegotiatedFeatures is null && row.HistoryVariants is null ? "unavailable" + : row.HistoryVariants is not { } variants ? "not advertised" : variants.Count == 0 ? "advertised, no variant granted" : string.Join(", ", variants) + (row.HistoryAggregateCount is { } n ? $" ({n} aggregates)" : ""); @@ -53,8 +59,7 @@ public static class DataConnectionDiagnostics { null => "unavailable", DataOperations.None => "none", - { } b => string.Join(", ", Enumerable.Range(0, 31).Select(i => (DataOperations)(1 << i)).Where(x => b.HasFlag(x)) - .Select(x => Enum.IsDefined(x) ? DataOperationAuthoring.Label(x) : $"0x{(int)x:X}")), + { } b => Bits((uint)(int)b, bit => Enum.IsDefined((DataOperations)(int)bit) ? DataOperationAuthoring.Label((DataOperations)(int)bit) : null), }; /// #919: true when the drop deserves the "node build is older than the authored feature" hint. diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/GrpcDataHistoryDiagnosticsDisplayTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/GrpcDataHistoryDiagnosticsDisplayTests.cs index 61d92a9f7..51e032b48 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/GrpcDataHistoryDiagnosticsDisplayTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/GrpcDataHistoryDiagnosticsDisplayTests.cs @@ -20,13 +20,17 @@ public sealed class GrpcDataHistoryDiagnosticsDisplayTests DataConnectionDiagnostics.Features(DataFeatures.None).ShouldBe("none (v1 behaviour)"); DataConnectionDiagnostics.Features(DataFeatures.History).ShouldBe("History"); DataConnectionDiagnostics.Features(DataFeatures.History | DataFeatures.Conditions).ShouldBe("History, Conditions"); + // H4 review 6: an unknown bit is never hidden by a known one. + DataConnectionDiagnostics.Features(DataFeatures.History | (DataFeatures)8).ShouldBe("History, 0x8"); + DataConnectionDiagnostics.Features((DataFeatures)int.MinValue).ShouldBe("0x80000000"); } [Fact] public void Origin_history_shows_the_advertised_variants_and_aggregate_count() { - DataConnectionDiagnostics.HistoryServed(Row()).ShouldBe("not advertised"); - DataConnectionDiagnostics.HistoryServed(Row() with { HistoryVariants = [] }).ShouldBe("advertised, no variant granted"); + DataConnectionDiagnostics.HistoryServed(Row()).ShouldBe("unavailable", "no handshake evidence at all (H4 review 5)"); + DataConnectionDiagnostics.HistoryServed(Row() with { NegotiatedFeatures = DataFeatures.None }).ShouldBe("not advertised"); + DataConnectionDiagnostics.HistoryServed(Row() with { NegotiatedFeatures = DataFeatures.History, HistoryVariants = [] }).ShouldBe("advertised, no variant granted"); DataConnectionDiagnostics.HistoryServed(Row() with { HistoryVariants = ["raw", "processed", "attime"], HistoryAggregateCount = 12 }) .ShouldBe("raw, processed, attime (12 aggregates)"); } @@ -45,6 +49,8 @@ public sealed class GrpcDataHistoryDiagnosticsDisplayTests DataConnectionDiagnostics.DroppedBits(DataOperations.None).ShouldBe("none"); DataConnectionDiagnostics.DroppedBits(DataOperations.HistoryRead | DataOperations.AlarmSubscribe).ShouldBe("HistoryRead, AlarmSubscribe"); DataConnectionDiagnostics.DroppedBits((DataOperations)(1 << 20)).ShouldBe("0x100000"); + // H4 review 6: the full width, bit 31 included, beside a known bit. + DataConnectionDiagnostics.DroppedBits(DataOperations.HistoryRead | (DataOperations)int.MinValue).ShouldBe("HistoryRead, 0x80000000"); } [Fact] From 7498f1ce82b7660c16abe57ff59da7d1db7be01d Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 08:41:52 -0500 Subject: [PATCH 10/11] =?UTF-8?q?test(grpc-data):=20H4=20review=207=20?= =?UTF-8?q?=E2=80=94=20diagnostics=20snapshot=20round-trips=20on=20the=20c?= =?UTF-8?q?luster=20serializer;=20old-shape=20payloads=20decode?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Round-trips NodeDiagnosticsSnapshot (OriginHistory, HistoryVariants and the other H4 members) through the serializer Akka picks for the fleet-diagnostics reply, and decodes payloads stripped of the H4 members. The origin flag is renamed NoPeerTrafficYet (default false): Akka's JSON serializer fills a missing constructor argument with the CLR default, so a payload without it must never claim it. --- scripts/validation/grpc-data/unit-phases.json | 2 +- .../DataConnectionDiagnosticsSnapshot.cs | 9 +- .../Clusters/ClusterDataConnections.razor | 2 +- .../DataConnectionHistoryDiagnostics.cs | 2 +- .../GrpcDataDiagnosticsSerializationTests.cs | 92 +++++++++++++++++++ .../GrpcDataHistoryMetricsTests.cs | 4 +- 6 files changed, 102 insertions(+), 9 deletions(-) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDiagnosticsSerializationTests.cs diff --git a/scripts/validation/grpc-data/unit-phases.json b/scripts/validation/grpc-data/unit-phases.json index 45f5d7b7b..ce9141e4f 100644 --- a/scripts/validation/grpc-data/unit-phases.json +++ b/scripts/validation/grpc-data/unit-phases.json @@ -925,7 +925,7 @@ "project": "tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj", "filter": "(Feature=GrpcData&Phase=H4)|FullyQualifiedName~.GrpcDataProjectedHistoryCursorTests.|FullyQualifiedName~.GrpcDataOriginHistorySessionTests.", "new_classes": [ - "GrpcDataHistoryMetricsTests" + "GrpcDataHistoryMetricsTests", "GrpcDataDiagnosticsSerializationTests" ], "existing_classes": [ "GrpcDataConfiguredDiscoveryWireTests", 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 b19960bfb..21b6071f3 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Interfaces/DataConnectionDiagnosticsSnapshot.cs @@ -57,9 +57,10 @@ public sealed record DataConnectionDiagnosticsSnapshot( /// Remote history items answered Good since process start. /// Remote history items answered Uncertain since process start. /// Remote history items answered Bad (including refusals) since process start. -/// -/// False while no peer has called this node since start: the origin data services are created on the first peer call, so -/// the zeros are "no peer traffic yet", not missing evidence. True once they run (and from a sender that predates the flag). +/// +/// True while no peer has called this node since start: the origin data services are created on the first peer call, so +/// the zeros are "no peer traffic yet", not missing evidence. False once they run. Default false, so a payload without the +/// member (Akka's JSON serializer fills a missing constructor argument with the CLR default) never claims it. /// public sealed record OriginHistoryDiagnostics(bool Available, int Sessions, int OpenContinuations, long ReadsGood, - long ReadsUncertain, long ReadsBad, bool PeerServicesStarted = true); + long ReadsUncertain, long ReadsBad, bool NoPeerTrafficYet = false); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor index 9bc071912..90ecb8155 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor @@ -53,7 +53,7 @@ else
@nodeId @if (node.OriginHistory is { } origin) { - · remote history @(origin.Available ? "served" : "no historian backend") · peer history sessions @origin.Sessions · open origin continuations @origin.OpenContinuations · history items answered @DataConnectionDiagnostics.HistoryCounts(origin.ReadsGood, origin.ReadsUncertain, origin.ReadsBad)@(origin.PeerServicesStarted ? "" : " · no peer has called since start") + · remote history @(origin.Available ? "served" : "no historian backend") · peer history sessions @origin.Sessions · open origin continuations @origin.OpenContinuations · history items answered @DataConnectionDiagnostics.HistoryCounts(origin.ReadsGood, origin.ReadsUncertain, origin.ReadsBad)@(origin.NoPeerTrafficYet ? " · no peer has called since start" : "") } else { · remote history evidence unavailable } @if (node.DroppedExportOperations is { } dropped) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionHistoryDiagnostics.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionHistoryDiagnostics.cs index 00754845f..dbcf5697d 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionHistoryDiagnostics.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionHistoryDiagnostics.cs @@ -156,7 +156,7 @@ public sealed class DataConnectionHistoryDiagnostics if (_originState is not { } state) { if (_provisionalAvailability is not { } provisional) return null; - try { return new(provisional(), 0, 0, 0, 0, 0, PeerServicesStarted: false); } + try { return new(provisional(), 0, 0, 0, 0, 0, NoPeerTrafficYet: true); } catch (Exception) { return null; } } (bool Available, int Sessions, int Open) now; diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDiagnosticsSerializationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDiagnosticsSerializationTests.cs new file mode 100644 index 000000000..0cb3a34b2 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDiagnosticsSerializationTests.cs @@ -0,0 +1,92 @@ +using System.Text; +using Akka.TestKit.Xunit; +using Newtonsoft.Json.Linq; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.Interfaces; +using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// H4 review item 7: the fleet-diagnostics reply crosses Akka remoting (FleetDiagnosticsClient asks the node's +/// driver host) on the serializer Akka picks for it — round-trip the new members through THAT serializer, and decode an +/// old-shape payload (a pre-H4 sender) to show mixed-version tolerance. +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H4")] +public sealed class GrpcDataDiagnosticsSerializationTests : TestKit +{ + private static readonly string[] H4ConnectionMembers = + ["NegotiatedFeatures", "HistoryVariants", "HistoryAggregateCount", "HistoryReadsGood", "HistoryReadsUncertain", "HistoryReadsBad", + "OpenRemoteContinuations"]; + + private static NodeDiagnosticsSnapshot Snapshot() => new( + // Arrays, as production builds them (CaptureDiagnostics .ToArray()s; RecordSelected builds string[]): a C# collection + // expression typed IReadOnlyList is a compiler-synthesized type Newtonsoft cannot construct. + NodeId.Parse("consumer-1:4053"), null, Array.Empty(), new DateTime(2026, 11, 24, 13, 0, 0, DateTimeKind.Utc), + DataConnections: new[] + { + new DataConnectionDiagnosticsSnapshot("link", 3, "ready", "https://source-2:4057", null, 0, 0, 7, "artifact-7", + new DateTime(2026, 11, 24, 13, 0, 0, DateTimeKind.Utc), DroppedUnknownOperations: DataOperations.None, + MappingsWithDroppedOperations: 0, NegotiatedFeatures: DataFeatures.History, HistoryVariants: new[] { "raw", "processed", "attime" }, + HistoryAggregateCount: 19, HistoryReadsGood: 34, HistoryReadsUncertain: 1, HistoryReadsBad: 3, OpenRemoteContinuations: 2), + }, + DroppedExportOperations: new Dictionary { ["export-a"] = (DataOperations)(1 << 20) }, + OriginHistory: new OriginHistoryDiagnostics(true, 1, 2, 7, 0, 2, NoPeerTrafficYet: true)); + + private (Akka.Serialization.Serializer Serializer, string Manifest) SerializerFor(object message) + { + var serializer = Sys.Serialization.FindSerializerFor(message); + return (serializer, Akka.Serialization.Serialization.ManifestFor(serializer, message)); + } + + [Fact] + public void A_snapshot_with_the_H4_members_round_trips_on_the_cluster_serializer() + { + var message = Snapshot(); + var (serializer, manifest) = SerializerFor(message); + var round = (NodeDiagnosticsSnapshot)Sys.Serialization.Deserialize(serializer.ToBinary(message), serializer.Identifier, manifest); + + round.OriginHistory.ShouldBe(message.OriginHistory); + round.DroppedExportOperations!["export-a"].ShouldBe((DataOperations)(1 << 20)); + var row = round.DataConnections.ShouldNotBeNull().ShouldHaveSingleItem(); + row.NegotiatedFeatures.ShouldBe(DataFeatures.History); + row.HistoryVariants.ShouldBe(["raw", "processed", "attime"]); + (row.HistoryAggregateCount, row.HistoryReadsGood, row.HistoryReadsUncertain, row.HistoryReadsBad, row.OpenRemoteContinuations) + .ShouldBe((19, 34L, 1L, 3L, 2)); + } + + [Fact] + public void An_old_shape_payload_without_the_H4_members_decodes_with_them_unavailable() + { + var message = Snapshot(); + var (serializer, manifest) = SerializerFor(message); + var json = JObject.Parse(Encoding.UTF8.GetString(serializer.ToBinary(message))); + json.Remove("OriginHistory").ShouldBeTrue("the H4 node member is on the wire"); + var removed = 0; + foreach (var row in json.Descendants().OfType().Where(o => o.ContainsKey("ConnectionId")).ToArray()) + foreach (var member in H4ConnectionMembers) + if (row.Remove(member)) removed++; + removed.ShouldBe(H4ConnectionMembers.Length, "every H4 connection member was on the wire and is now stripped"); + + var legacy = (NodeDiagnosticsSnapshot)Sys.Serialization.Deserialize(Encoding.UTF8.GetBytes(json.ToString(Newtonsoft.Json.Formatting.None)), + serializer.Identifier, manifest); + legacy.OriginHistory.ShouldBeNull("a pre-H4 node reports no origin evidence (rendered 'unavailable')"); + + // An origin record without the later NoPeerTrafficYet member decodes as live evidence, never "no peer traffic yet". + var withOrigin = JObject.Parse(Encoding.UTF8.GetString(serializer.ToBinary(message))); + ((JObject)withOrigin["OriginHistory"]!).Remove("NoPeerTrafficYet").ShouldBeTrue(); + var partial = (NodeDiagnosticsSnapshot)Sys.Serialization.Deserialize( + Encoding.UTF8.GetBytes(withOrigin.ToString(Newtonsoft.Json.Formatting.None)), serializer.Identifier, manifest); + partial.OriginHistory.ShouldNotBeNull().NoPeerTrafficYet.ShouldBeFalse(); + partial.OriginHistory.ReadsGood.ShouldBe(7); + var row0 = legacy.DataConnections.ShouldNotBeNull().ShouldHaveSingleItem(); + row0.ConnectionId.ShouldBe("link"); + row0.NegotiatedFeatures.ShouldBeNull(); + row0.HistoryVariants.ShouldBeNull(); + row0.HistoryReadsGood.ShouldBeNull(); + row0.OpenRemoteContinuations.ShouldBeNull(); + row0.DroppedUnknownOperations.ShouldBe(DataOperations.None, "X0 members are untouched"); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryMetricsTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryMetricsTests.cs index 3a2a122c8..f0f7f9da2 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryMetricsTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryMetricsTests.cs @@ -118,12 +118,12 @@ public sealed class GrpcDataHistoryMetricsTests var backend = true; diagnostics.AttachProvisionalOrigin(() => backend); diagnostics.CaptureOrigin().ShouldBe(new ZB.MOM.WW.OtOpcUa.Commons.Interfaces.OriginHistoryDiagnostics(true, 0, 0, 0, 0, 0, - PeerServicesStarted: false)); + NoPeerTrafficYet: true)); backend = false; diagnostics.CaptureOrigin()!.Available.ShouldBeFalse("availability is probed live, not latched"); diagnostics.AttachOrigin(() => (true, 2, 1)); diagnostics.CaptureOrigin().ShouldBe(new ZB.MOM.WW.OtOpcUa.Commons.Interfaces.OriginHistoryDiagnostics(true, 2, 1, 0, 0, 0)); - diagnostics.CaptureOrigin()!.PeerServicesStarted.ShouldBeTrue(); + diagnostics.CaptureOrigin()!.NoPeerTrafficYet.ShouldBeFalse(); } [Fact] From 27d1501b690f6d6ea87c8726b7f64c59186867fb Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 09:08:52 -0500 Subject: [PATCH 11/11] =?UTF-8?q?docs(grpc-data):=20H4=20evidence=20?= =?UTF-8?q?=E2=80=94=20review=20table,=20gates=20and=20live=20re-run=20aft?= =?UTF-8?q?er=20the=20review=20fixes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/plans/evidence/grpc-data-ext/H4.md | 50 +++++++++++++++++++++---- 1 file changed, 43 insertions(+), 7 deletions(-) diff --git a/docs/plans/evidence/grpc-data-ext/H4.md b/docs/plans/evidence/grpc-data-ext/H4.md index da798f502..422212bc4 100644 --- a/docs/plans/evidence/grpc-data-ext/H4.md +++ b/docs/plans/evidence/grpc-data-ext/H4.md @@ -10,8 +10,8 @@ the alarm diagnostics are A4. (`DataConnectionDeploymentRuntime`, `DriverHostActor`), so none of them depends on another (the origin composition is resolved lazily after the driver host exists; a direct dependency would be a cycle). - **Metrics** on `OtOpcUaTelemetry.Meter` (`ZB.MOM.WW.OtOpcUa`, already in the host's exported-meter allowlist), no ids in labels: - - `otopcua.dataconn.history.reads{variant,status_class,side}` — origin: one per item answered to a peer; consumer: one per - projected node answered to a local OPC UA client. + - `otopcua.dataconn.history.reads{variant,status_class,side}` — origin: one per item per wire call served to a peer (review 3); + consumer: one per projected node per local HistoryRead, with the status the client got (review 1). - `otopcua.dataconn.history.continuations.active{side}` — observable gauge over the live diagnostics instances (weak table). - `…operations.unknown_bits_dropped`: **reused, not added.** X0's `otopcua.dataconnection.unknown_operations_dropped{kind}` counts exactly that (one per row per accepted artifact change); a second instrument would double-count. Pinned by @@ -96,6 +96,43 @@ historian is down. Per the plan's fallback, **#923** (`type:deploy-gate`, `block verified on the **SqlServer and QuestDB** origin backends only, with the **Gateway backend unverified pending #923** (`DataConnections.md`, `Historian.md`, `Client.CLI.md`). +## Review (Fable, approve-with-changes) — fixes + +One focused commit per item (5 and 6 share one AdminUI commit). Red/green by reverting the fix and re-running its test, unless noted. + +| # | Finding | Resolution | Red/green | +|---|---|---|---| +| 1 should-fix | Consumer reads were counted from the gateway's outcomes: the non-local and batch limiter `BadTooManyOperations`, the pre-call `BadTimeout` and the count-mismatch `BadInternalError` were never counted, and a serve-time throw after the gateway returned counted Good | The node manager counts where each projected status is set (`Refuse` + the served path) and hands the request's answers to `IProjectedHistoryAccess.RecordAnswered` (default no-op) in a `finally`; a fault escaping to the SDK (the service fails) counts every projected node of the request Bad. Attribution to a connection via `ProjectedDataAccess.ConnectionOf` (best effort, no authorization). Variant gains `modified`. `2f11a9c60` | O `Every_projected_answer_is_recorded_once_with_the_status_the_client_sees` (served, unknown aggregate, modified, non-local limiter saturated, batch limiter saturated, spent deadline, count mismatch, serve-time throw) — red with the non-local limiter refusal routed back to the uncounted path | +| 2 should-fix | `CaptureOrigin` null until the first peer call composes the origin services ⇒ a fresh H4 origin read like a pre-H4 build | Eager resolution is not clean: `LocalDataRuntimeComposition` needs the driver host actor registered and is composed by the first peer call through `DeferredFactory`. Instead the DI singleton gets a provisional probe of the same `DeferredOriginHistoryPort` (backend availability) and reports zeros with `NoPeerTrafficYet = true`; the page adds "no peer has called since start". Docs updated. `005720bd0` (+ rename in `7498f1ce8`) | R `Before_any_peer_call_a_provisional_origin_reports_no_peer_traffic_yet_not_unavailable`; live (below) | +| 3 nit | Origin reads count wire calls (chunk-token follow-ups count again) | Kept per call; docs, the class remarks and this file say "per item per wire call". `b5509dfc4` | — (doc) | +| 4 nit | `OpenContinuations = Cursors.Count + ChunkCount` double-counted a chunk holding its page cursor | `OriginHistorySession.OpenContinuations` counts chunks + cursors − cursors referenced by a live chunk (`OriginHistoryCursors.Contains`). `79cf50d50` | R `Open_continuations_count_a_chunk_holding_its_page_cursor_once` (3, was 4) — red on revert | +| 5 nit | `HistoryServed` said "not advertised" with no handshake evidence | "unavailable" when both `NegotiatedFeatures` and `HistoryVariants` are null. `2fba03617` | AdminUI display test (new assertion fails against the previous helper by inspection) | +| 6 nit | `Features()` hid unknown bits beside a known one; `DroppedBits` scanned bits 0–30 | Both render every set bit of all 32, named when known, hex otherwise. `2fba03617` | AdminUI display tests: `History, 0x8`, `0x80000000`, `HistoryRead, 0x80000000` (fail against the previous helpers by inspection) | +| 7 nit (tests) | No unit round-trip of the snapshot on the cluster serializer; no mixed-version payload | `GrpcDataDiagnosticsSerializationTests` round-trips a `NodeDiagnosticsSnapshot` with every H4 member through `Sys.Serialization.FindSerializerFor` (Akka's default JSON serializer — the fleet-diagnostics Ask has no custom binding), and decodes payloads stripped of the H4 members (null = "unavailable"). **Found by it:** Newtonsoft fills a missing constructor argument with the CLR default, not the C# default — the item-2 flag, first named `PeerServicesStarted = true`, would have decoded `false` from a sender without it; renamed `NoPeerTrafficYet` (default false) with a test. Also: a C# collection expression typed `IReadOnlyList` is a synthesized type Newtonsoft cannot construct — production builds arrays (checked), the test fixture uses arrays. `7498f1ce8` | new tests | + +Left as notes (no code change, per the review): + +- `OriginHistoryPort._serving` caches an unsynchronised nullable tuple — a pre-existing benign race (two callers may both compute + it); H4 adds the metrics scrape thread as a caller through `HistoryServing`. +- `DataConnectionHistoryDiagnostics._consumer` is never pruned; bounded by the deployed connection ids a process has seen. + +**Gates after the review fixes** (HEAD `7498f1ce8`), run one at a time: build 0 warnings / 0 errors; `run-unit-phase.py` H4 +(9 + 12 + 29), H3 (107 + 145), H2, H1, X0 all passed; AdminUI.Tests 2698; Runtime.Tests 1915 (+3 skips); OpcUaServer.Tests 1420 +(+1 skip) (`Category!=E2E&Category!=LiveIntegration`); no `GrpcDataConfiguredDiscoveryWireTests` (#920) failure. + +**Live re-run** (fresh `h4b-sqlserver`, 2026-11-24): items 1 and 2 changed runtime behaviour (the consumer count moved into the node +manager; a new DI-built provisional origin state), so the SqlServer leg was re-run. +- Right after deploy, before any history traffic, the CONSUMER page's origin panel showed consumer-1/2 "remote history no historian + backend · peer history sessions 0 · open origin continuations 0 · … · no peer has called since start", and source-2 (no peer + call yet) "remote history served · … · no peer has called since start" — where `h4a` had shown "remote history evidence + unavailable" (item 2). +- H01–H06 **all PASS** (47 / 34 / 35 / 71 / 58 / 238, all restored). +- After the gate: consumer-1 page "projected history reads good 36 · uncertain 0 · bad 3" = its `reads{side=consumer}` series + (raw good 33, processed good 1, attime good 2; raw bad 2, processed bad 1); source-2 page "good 7 · bad 2" = its origin series. +- Held probe: while held, consumer gauge 1, source-2 origin gauge 1, page "open remote continuations (local sessions) 1" and + source-2 "peer history sessions 1"; after resume to completion all 0, projected good 37 ⇒ 56. +- `down` ⇒ 0 run containers, 0 run volumes. + ## Not verified / notes - **Gateway backend** remotely (#923, above). @@ -103,13 +140,12 @@ verified on the **SqlServer and QuestDB** origin backends only, with the **Gatew passed H01–H06 on QuestDB at `713cbfb21`. The brief asked for one SqlServer leg. - **Browser-rendered** page not driven (no Chrome session used); verified from the server-prerendered HTML, which runs the same `OnInitializedAsync` + render as the interactive circuit. -- **Akka serialization of the new snapshot members** was exercised only live (the rig's control node read data-node snapshots - through the fleet-diagnostics path and rendered every new field), not by a unit round-trip test. +- **Akka serialization**: now unit-tested (review 7) as well as exercised live. - **Deviation:** the reads counter carries a third label `side` (origin | consumer) beyond the plan's `{variant,status_class}` — a node can be both, and without it the two populations would be summed into one series. The gauge carries `side` too. -- Consumer counts include every projected node answered (Bad included), but a node refused by the node manager BEFORE the gateway - (no local HistoryRead grant ⇒ `BadUserAccessDenied`, unhistorized ⇒ `BadHistoryOperationUnsupported` from the SDK) is not counted. - A consumer node shows "remote history evidence unavailable" in the origin panel until something resolves its origin services. +- Consumer counts cover every projected node that reaches the projected half (review 1). A node the SDK or the node manager's + authorization refuses before the split (no local HistoryRead grant ⇒ `BadUserAccessDenied`; not Historizing ⇒ + `BadHistoryOperationUnsupported` from the SDK's access-level check) is not counted: it never reaches the projected half. - Counts are since process start (no persistence), as the docs say. - `GrpcDataConfiguredDiscoveryWireTests` (#920 flaky class): no failure in any run this phase (H4 manifest, H3 manifest, full Runtime suite). - Umbrella history entry (plan exit gate): **not done here** — it is a commit on `scadaproj` `main` plus a push, and this worktree brief forbids pushing; left to the orchestrator (append to `../scadaproj/.claude/skills/sister-project-history/otopcua.md`). The Gitea close of #919 likewise belongs with the merge.