From dc6cc7779de54b4a2e00bdc6a4d89c4ce07f8f3b Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 00:27:51 -0500 Subject: [PATCH 01/25] feat(grpc-data): H3 SDK side of projected history Projected variables advertise Historizing + the HistoryRead access bit (never HistoryWrite) only when the definition says so. The Raw/Processed/AtTime overrides split authorized handles: local ones go to the H1 port unchanged, projected ones to IProjectedHistoryAccess, each written back to its own slot; nothing waits under Lock. HistoryCursorKind.Remote stores the projection's cursor in the SDK session store; disposing the point (session close, eviction, releaseContinuationPoints, faulted request) releases it at the origin. Mapped HistoryRead is opened deliberately in DataPlaneAuthorizer; other mapped operations outside the allowlist stay closed. --- .../HistoryContinuationStore.cs | 40 +- .../HistoryPaging.cs | 9 +- .../IProjectedHistoryAccess.cs | 86 ++++ .../OtOpcUaNodeManager.cs | 23 +- .../ProjectedHistoryRead.cs | 264 +++++++++++++ .../Security/DataPlaneAuthorizer.cs | 6 + .../ProjectedHistoryReadTests.cs | 372 ++++++++++++++++++ ...s => GrpcDataProjectedHistoryWireTests.cs} | 0 8 files changed, 788 insertions(+), 12 deletions(-) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ProjectedHistoryReadTests.cs rename tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/{GrpcDataProjectedHistoryRefusalTests.cs => GrpcDataProjectedHistoryWireTests.cs} (100%) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryContinuationStore.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryContinuationStore.cs index b91a33e6b..cb0f6494e 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryContinuationStore.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryContinuationStore.cs @@ -87,7 +87,10 @@ internal sealed class SessionHistoryContinuationStore : IHistoryContinuationStor // RestoreHistoryContinuationPoint REMOVES the slot (single-use) and returns null for an unknown / // malformed (non-16-byte) point — exactly the "miss ⇒ BadContinuationPointInvalid" contract. using var point = session.ContinuationPoints.RestoreHistory(ByteString.From(continuationPoint)); - return (point as SessionHistoryPoint)?.State; + if (point is not SessionHistoryPoint taken) return null; + // A take hands the state (and an H3 remote cursor) back to the caller: disposing the slot must not release it. + taken.Taken = true; + return taken.State; } /// @@ -98,8 +101,15 @@ internal sealed class SessionHistoryContinuationStore : IHistoryContinuationStor { public Guid Id { get; } = id; public HistoryContinuationState State { get; } = state; - // The immutable resume state contains managed value data only. No handles or owned resources. - public void Dispose() { } + public bool Taken { get; set; } + + // Local resume state is managed values only. An H3 remote cursor holds an origin continuation: the SDK disposes the + // point on session close, oldest-eviction, releaseContinuationPoints and a faulted request — each of those (never a + // take) releases it at the origin, best effort (the origin's idle expiry is the backstop). + public void Dispose() + { + if (!Taken) State.Remote?.Release(); + } } } @@ -132,7 +142,7 @@ internal sealed class InMemoryHistoryContinuationStore(int capacity = 100) : IHi while (_states.Count >= _capacity && _order.Count > 0) { var oldest = _order.Dequeue(); - _states.Remove(oldest); + if (_states.Remove(oldest, out var evicted)) evicted.Remote?.Release(); } _states[id] = state; @@ -160,9 +170,29 @@ internal sealed class InMemoryHistoryContinuationStore(int capacity = 100) : IHi { if (continuationPoint is null || continuationPoint.Length != 16) return; var id = new Guid(continuationPoint); + HistoryContinuationState? released; lock (_gate) { - _states.Remove(id); + _states.Remove(id, out released); } + + released?.Remote?.Release(); + } + + /// Live entries (tests). + public int Count { get { lock (_gate) return _states.Count; } } + + /// Drops every entry as an SDK session close does — releasing remote cursors (tests). + public void Clear() + { + HistoryContinuationState[] all; + lock (_gate) + { + all = _states.Values.ToArray(); + _states.Clear(); + _order.Clear(); + } + + foreach (var state in all) state.Remote?.Release(); } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryPaging.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryPaging.cs index c36c552b3..18a682592 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryPaging.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryPaging.cs @@ -98,7 +98,8 @@ internal sealed record HistoryContinuationState( AddressSpaceRealm BoundRealm = default, string? BoundIdentifier = null, string? BoundTag = null, - long AddressSpaceEpoch = -1) + long AddressSpaceEpoch = -1, + ProjectedHistoryContinuation? Remote = null) { /// The walk-back hint this cursor carries. public ReverseWalkHint WalkHint => new(SegmentWidthTicks, EmptyFromTicks, EmptyToTicks); @@ -115,6 +116,12 @@ internal enum HistoryCursorKind /// HistoryReadRaw with IsReadModified = true — the Part 11 modification trail. Modified, + + /// + /// H3: a projected node's remote cursor () — an origin token plus what the + /// projection bound it to. Disposing the stored point (session close, eviction, release) releases it at the origin. + /// + Remote, } /// diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs new file mode 100644 index 000000000..35cc08751 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs @@ -0,0 +1,86 @@ +using Opc.Ua; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; + +/// +/// H3 — the remote cursor behind a continuation point in the consumer's SDK session +/// store (gRPC data history plan §3.2). Opaque to the node manager: the projection side (Runtime) owns what it binds — +/// the origin token, mapping id/revision, serving incarnation, projection generation, caller key and the ORIGINAL request +/// details — and re-checks all of it on resume. The node manager only binds it to the projected node it was issued for. +/// +public abstract class ProjectedHistoryContinuation +{ + private int _released; + + /// Creates a cursor bound to one projected node. + /// The projected node's realm. + /// The projected node's opaque local identifier. + protected ProjectedHistoryContinuation(DataRealm realm, string localIdentifier) + { + ArgumentException.ThrowIfNullOrWhiteSpace(localIdentifier); + Realm = realm; + LocalIdentifier = localIdentifier; + } + + /// The projected node's realm. + public DataRealm Realm { get; } + + /// The projected node's local identifier. + public string LocalIdentifier { get; } + + /// True once the cursor was released or handed back for a resume (it is single-use either way). + public bool IsSpent => Volatile.Read(ref _released) != 0; + + /// + /// Best-effort, idempotent, non-blocking release of the origin continuation (releaseContinuationPoints, session + /// close, eviction, a store refusal). The origin's idle expiry is the backstop. + /// + public void Release() + { + if (Interlocked.Exchange(ref _released, 1) == 0) OnRelease(); + } + + /// 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() => Interlocked.Exchange(ref _released, 1) == 0; + + /// Forwards the release to the origin (called at most once). + protected abstract void OnRelease(); +} + +/// One projected node of a consumer HistoryRead (H3). +/// The projected node. +/// Processed only: the requested aggregate's ns=0 numeric id. +/// The claimed remote cursor of a resumed read; null = a fresh read. +public sealed record ProjectedHistoryNode(NodeId NodeId, uint? AggregateId = null, ProjectedHistoryContinuation? Resume = null); + +/// One projected node's outcome: the origin's Part 11 status verbatim, its values, and the next cursor. +/// The full OPC UA status. +/// The values (CLR values, verbatim status and timestamps). +/// The next remote cursor; null when the read is complete. +public sealed record ProjectedHistoryOutcome(uint StatusCode, IReadOnlyList Samples, ProjectedHistoryContinuation? Continuation = null); + +/// +/// H3 — HistoryRead on projected variables (plan §2.1, §3.2): resolves each projected node to its mapping, deployed +/// connection lease and origin view, authorizes it (the mapping's HistoryRead bit and a local +/// NodePermissions.HistoryRead grant on the mapping scope, ACLs on or off), and forwards through +/// . A fresh read may move endpoint within its deadline; a resumed read never moves. +/// +public interface IProjectedHistoryAccess +{ + /// + /// Reads one batch of projected nodes for . Never called under the node-manager Lock. + /// Results are in order. Every cursor is owned by + /// the call (resumed or released), whatever the outcome. + /// + /// The session identity. + /// The request details (fresh nodes; a resumed node resends its ORIGINAL details). + /// The projected nodes. + /// The consumer request's remaining HistoryReadDeadline; non-positive = unbounded. + /// The SDK request lifetime. + /// One outcome per node. + Task> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details, + IReadOnlyList nodes, TimeSpan deadline, CancellationToken cancellationToken); +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index 4616d6e2a..6e2247825 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -39,6 +39,12 @@ public sealed record ProjectedVariableDefinition(DataRealm Realm, string LocalId { /// Stable across same-node metadata renewal, replaced on node retirement. public ProjectedNodeLifetime Lifetime { get; init; } = new(); + + /// + /// H3: the node is Historizing with the HistoryRead access bit — only when the mapping grants HistoryRead AND the + /// origin's negotiated metadata says the node is historizing (plan §2.1). Never the HistoryWrite bit. + /// + public bool Historizing { get; init; } } /// Locally authorized placement for a configured mapping anchor. @@ -4677,6 +4683,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage !commit() || !renewed.AuthorityIsCurrent() || !old.Lifetime.IsActive) return false; _projectedVariables[nodeId] = (existing.Parent, renewed.ProjectionGeneration, renewed.Metadata, existing.Node, renewed.AuthorityIsCurrent); _projectedDefinitions[nodeId] = renewed; + ApplyProjectedHistorizing(existing.Node, renewed.Historizing); _projectedNodeBytes += delta; _projectedNodeCharges[nodeId] = charge; CommitProjectedDefinition(nodeId, renewed); return true; @@ -4740,6 +4747,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage _projectedVariables[renewal.Id] = (previous.Parent, renewal.Definition.ProjectionGeneration, renewal.Definition.Metadata, previous.Node, renewal.Definition.AuthorityIsCurrent); _projectedDefinitions[renewal.Id] = renewal.Definition; + ApplyProjectedHistorizing(previous.Node, renewal.Definition.Historizing); _projectedNodeBytes += renewal.Charge - _projectedNodeCharges[renewal.Id]; _projectedNodeCharges[renewal.Id] = renewal.Charge; } @@ -4796,6 +4804,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage !installed.AuthorityIsCurrent() || !commit() || !installed.AuthorityIsCurrent()) return false; _projectedVariables[anchorId] = (existing.Parent, existing.Generation, installed.Metadata, existingNode, installed.AuthorityIsCurrent); _projectedDefinitions[anchorId] = installed; + ApplyProjectedHistorizing(existingNode, installed.Historizing); _projectedNodeCharges[anchorId] = renewedCharge; _projectedNodeBytes += delta; CommitProjectedDefinition(anchorId, installed); @@ -4833,6 +4842,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage var charged = false; try { + ApplyProjectedHistorizing(variable, installed.Historizing); parent.RemoveChild(folder); PredefinedNodes?.Remove(anchorId); parent.AddChild(variable); AddPredefinedNode(SystemContext, variable); _projectedAnchors[anchorId] = (anchor.Definition, variable); @@ -4925,6 +4935,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage AccessLevel = AccessLevels.CurrentRead, UserAccessLevel = AccessLevels.CurrentRead, Value = Variant.Null, StatusCode = StatusCodes.BadWaitingForInitialData, Timestamp = DateTime.MinValue }; if (!definition.AuthorityIsCurrent()) return false; + ApplyProjectedHistorizing(node, definition.Historizing); parent.AddChild(node); AddPredefinedNode(SystemContext, node); _projectedVariables.Add(candidate, (definition.Parent, definition.ProjectionGeneration, definition.Metadata, node, definition.AuthorityIsCurrent)); _projectedDefinitions.Add(candidate, definition); @@ -8798,7 +8809,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage } /// - /// A thin adapter over the history port (): authorize, then serve. + /// A thin adapter over the history port (): authorize, then serve (H3: projected handles go remote). protected override void HistoryReadRawModified( ServerSystemContext context, ReadRawModifiedDetails details, @@ -8810,11 +8821,11 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage IDictionary cache) { nodesToProcess = AuthorizeHistoryRead(context, nodesToProcess, results, errors); - ServeHistoryReadAdapter(context, details, nodesToRead, nodesToProcess, results, errors); + ServeHistoryReadSplit(context, details, nodesToRead, nodesToProcess, results, errors); } /// - /// A thin adapter over the history port (): authorize, then serve. + /// A thin adapter over the history port (): authorize, then serve (H3: projected handles go remote). protected override void HistoryReadProcessed( ServerSystemContext context, ReadProcessedDetails details, @@ -8826,11 +8837,11 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage IDictionary cache) { nodesToProcess = AuthorizeHistoryRead(context, nodesToProcess, results, errors); - ServeHistoryReadAdapter(context, details, nodesToRead, nodesToProcess, results, errors); + ServeHistoryReadSplit(context, details, nodesToRead, nodesToProcess, results, errors); } /// - /// A thin adapter over the history port (): authorize, then serve. + /// A thin adapter over the history port (): authorize, then serve (H3: projected handles go remote). protected override void HistoryReadAtTime( ServerSystemContext context, ReadAtTimeDetails details, @@ -8842,7 +8853,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage IDictionary cache) { nodesToProcess = AuthorizeHistoryRead(context, nodesToProcess, results, errors); - ServeHistoryReadAdapter(context, details, nodesToRead, nodesToProcess, results, errors); + ServeHistoryReadSplit(context, details, nodesToRead, nodesToProcess, results, errors); } /// diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs new file mode 100644 index 000000000..bc5c78f45 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs @@ -0,0 +1,264 @@ +using System.Diagnostics; +using Opc.Ua; +using Opc.Ua.Server; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using SdkHistoryReadResult = Opc.Ua.HistoryReadResult; +using DataValue = Opc.Ua.DataValue; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; + +/// +/// H3 — consumer OPC UA projection of remote history (gRPC data history plan §3.2). The Raw / Processed / AtTime overrides +/// split one request's authorized handles: local handles go to the H1 port exactly as before, projected handles (the +/// mapped/raw and mapped/uns namespaces) to . Every result is written back to its own +/// handle's slot, so a mixed batch keeps request order. Nothing here runs under, or takes, Lock: the SDK releases it +/// before it dispatches the overrides, and the remote read is block-bridged once per batch, like the port. +/// +public sealed partial class OtOpcUaNodeManager +{ + private IProjectedHistoryAccess? _projectedHistoryAccess; + + /// The remote history gateway for projected variables (H3); null = projected nodes answer unsupported. + public IProjectedHistoryAccess? ProjectedHistoryAccess + { + get => Volatile.Read(ref _projectedHistoryAccess); + set => Volatile.Write(ref _projectedHistoryAccess, value); + } + + /// Serves local handles through the port (unchanged) and projected handles remotely, each into its own slot. + private void ServeHistoryReadSplit( + ServerSystemContext context, + HistoryReadDetails details, + ArrayOf nodesToRead, + List nodesToProcess, + IList results, + IList errors) + { + List? projected = null; + foreach (var handle in nodesToProcess) + if (IsProjectedDescendant(handle.NodeId)) (projected ??= []).Add(handle); + if (projected is null) + { + ServeHistoryReadAdapter(context, details, nodesToRead, nodesToProcess, results, errors); + return; + } + + var started = Stopwatch.GetTimestamp(); + var local = nodesToProcess.Where(h => !IsProjectedDescendant(h.NodeId)).ToList(); + if (local.Count > 0) ServeHistoryReadAdapter(context, details, nodesToRead, local, results, errors); + ServeProjectedHistory(context, details, nodesToRead, projected, results, errors, started); + } + + /// The projected half of a variable-history request. + private void ServeProjectedHistory( + ServerSystemContext context, + HistoryReadDetails details, + ArrayOf nodesToRead, + List handles, + IList results, + IList errors, + long started) + { + 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; + + var pending = new List<(NodeHandle Handle, ProjectedHistoryNode Node)>(handles.Count); + foreach (var handle in handles) + { + var key = MapKey(handle.NodeId); + var tag = HistoryBindingTag(handle.NodeId); + var cp = nodesToRead[handle.Index].ContinuationPoint; + ProjectedHistoryContinuation? resume = null; + if (cp.Length > 0) + { + // Single-use: the take removes the SDK slot. A cursor of another node / kind / epoch is refused AND released. + var state = store.TryTake(session, cp.ToArray()); + if (state is not { Kind: HistoryCursorKind.Remote, Remote: { } cursor } + || !HistoryContinuationMatches(state, key.Realm, key.Id, tag, epoch) + || !cursor.TryClaimForResume()) + { + state?.Remote?.Release(); + SetProjectedStatus(handle, results, errors, StatusCodes.BadContinuationPointInvalid); + continue; + } + + resume = cursor; + } + + if (access is null || identity is null || remote is null) + { + // No projection gateway, no session identity, or a variant a remote read never serves (a modified read). + resume?.Release(); + SetProjectedStatus(handle, results, errors, StatusCodes.BadHistoryOperationUnsupported); + continue; + } + + uint? aggregateId = null; + if (remote is DataHistoryProcessedDetails && resume is null) + { + // Consumer-side unknown aggregate: refused up front, unsent (the origin refuses what IT cannot serve). + 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); + continue; + } + + aggregateId = numeric; + } + + pending.Add((handle, new ProjectedHistoryNode(handle.NodeId, aggregateId, resume))); + } + + if (pending.Count == 0) return; + var nodes = pending.Select(p => p.Node).ToArray(); + IReadOnlyList? outcomes = null; + // The same process-wide batch limiter as local reads: a remote read also holds an SDK request thread. + WithHistoryBatchLimiter(pending, () => + { + TimeSpan remaining; + if (HistoryReadDeadline > TimeSpan.Zero) + { + remaining = HistoryReadDeadline - Stopwatch.GetElapsedTime(started); + if (remaining <= TimeSpan.Zero) + { + outcomes = nodes.Select(_ => new ProjectedHistoryOutcome(StatusCodes.BadTimeout.Code, [])).ToArray(); + foreach (var node in nodes) node.Resume?.Release(); + return; + } + } + else remaining = TimeSpan.Zero; + + try + { + outcomes = access!.ReadAsync(identity!, remote!, nodes, remaining, + context.OperationContext?.CancellationToken ?? CancellationToken.None).GetAwaiter().GetResult(); + } + catch (OperationCanceledException) + { + // The SDK request ended: a timeout for this caller, never an origin fault (the access owns the resumes). + outcomes = nodes.Select(_ => new ProjectedHistoryOutcome(StatusCodes.BadTimeout.Code, [])).ToArray(); + } + catch (Exception ex) when (ex is InvalidOperationException or ArgumentException or ObjectDisposedException) + { + outcomes = nodes.Select(_ => new ProjectedHistoryOutcome(StatusCodes.BadNoCommunication.Code, [])).ToArray(); + } + }, p => + { + p.Node.Resume?.Release(); + SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadTooManyOperations); + }); + + if (outcomes is null) return; // the limiter rejected the batch + if (outcomes.Count != pending.Count) + { + foreach (var o in outcomes) o.Continuation?.Release(); + foreach (var p in pending) SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadInternalError); + return; + } + + for (var i = 0; i < pending.Count; i++) + { + var handle = pending[i].Handle; + var outcome = outcomes[i]; + var status = new StatusCode(outcome.StatusCode); + if (StatusCode.IsBad(status)) + { + outcome.Continuation?.Release(); + SetProjectedStatus(handle, results, errors, status); + continue; + } + + byte[]? cp = null; + if (outcome.Continuation is { } next) + { + var key = MapKey(handle.NodeId); + cp = SaveRemoteContinuation(session, store, key.Realm, key.Id, HistoryBindingTag(handle.NodeId), epoch, next); + } + + var values = new List(outcome.Samples.Count); + foreach (var sample in outcome.Samples) + values.Add(new DataValue(SdkValueBoundary.FromClr(sample.Value), new StatusCode(sample.StatusCode), + sample.SourceTimestampUtc ?? DateTime.MinValue, sample.ServerTimestampUtc ?? DateTime.MinValue)); + errors[handle.Index] = ServiceResult.Good; + results[handle.Index] = new SdkHistoryReadResult + { + StatusCode = status, + HistoryData = new ExtensionObject(new HistoryData { DataValues = values }), + ContinuationPoint = cp is null ? default : ByteString.From(cp), + }; + } + } + + /// + /// Stores a remote cursor in the session store, bound to its node and the current epoch. When it cannot be stored (no + /// session, the epoch moved, the session refused it) the page is returned without a continuation point — as a local + /// read degrades — and the origin cursor is released. + /// + private byte[]? SaveRemoteContinuation(ISession? session, IHistoryContinuationStore store, AddressSpaceRealm realm, string identifier, + string tag, long epoch, ProjectedHistoryContinuation cursor) + { + if (epoch != Volatile.Read(ref _historyContinuationEpoch)) { cursor.Release(); return null; } + byte[]? cp; + try + { + cp = store.Save(session, new HistoryContinuationState(string.Empty, default, default, 0, 0, HistoryCursorKind.Remote, + BoundRealm: realm, BoundIdentifier: identifier, BoundTag: tag, AddressSpaceEpoch: epoch, Remote: cursor)); + } + catch (ServiceResultException) { cp = null; } // the SDK disposed (released) it + if (cp is null) cursor.Release(); + return cp; + } + + /// + /// H3: the projected node's history advertisement — the HistoryRead access bit (CurrentRead | HistoryRead) and + /// Historizing when the definition says so, plain CurrentRead otherwise. Never HistoryWrite. Under Lock. + /// + private void ApplyProjectedHistorizing(BaseInstanceState node, bool historizing) + { + if (node is not BaseDataVariableState variable) return; + var access = historizing ? (byte)(AccessLevels.CurrentRead | AccessLevels.HistoryRead) : AccessLevels.CurrentRead; + if (variable.AccessLevel == access && variable.UserAccessLevel == access && variable.Historizing == historizing) return; + variable.AccessLevel = access; + variable.UserAccessLevel = access; + variable.Historizing = historizing; + variable.ClearChangeMasks(SystemContext, includeChildren: false); + } + + private static void SetProjectedStatus(NodeHandle handle, IList results, IList errors, StatusCode status) + { + errors[handle.Index] = new ServiceResult(status); + results[handle.Index] = new SdkHistoryReadResult { StatusCode = status }; + } + + /// + /// The SDK details as the SDK-free remote shape. An unset Part 11 bound travels ABSENT, never MinValue (plan §3.3). A + /// modified read is never served remotely (null). + /// + internal static DataHistoryDetails? ToRemoteDetails(HistoryReadDetails details) => details switch + { + ReadRawModifiedDetails { IsReadModified: true } => null, + ReadRawModifiedDetails raw => new DataHistoryRawDetails(Bound(raw.StartTime), Bound(raw.EndTime), raw.NumValuesPerNode, raw.ReturnBounds), + ReadProcessedDetails processed => new DataHistoryProcessedDetails(Bound(processed.StartTime), Bound(processed.EndTime), + TimeSpan.FromMilliseconds(processed.ProcessingInterval), processed.AggregateConfiguration is { } c + ? new DataAggregateConfiguration(c.UseServerCapabilitiesDefaults, c.TreatUncertainAsBad, c.PercentDataBad, c.PercentDataGood, + c.UseSlopedExtrapolation) + : null), + ReadAtTimeDetails atTime => new DataHistoryAtTimeDetails( + (atTime.ReqTimes.ToArray() ?? []).Select(t => new DateTimeOffset(DateTime.SpecifyKind(t.ToDateTime(), DateTimeKind.Utc))).ToArray(), + atTime.UseSimpleBounds), + _ => null, + }; + + private static DateTimeOffset? Bound(DateTimeUtc value) + { + var clr = SdkValueBoundary.ToClrTimestamp(value); + return clr == DateTime.MinValue ? null : new DateTimeOffset(DateTime.SpecifyKind(clr, DateTimeKind.Utc)); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs index 5c0d5ec6d..f3bfdce2a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs @@ -185,6 +185,12 @@ public sealed class DataPlaneAuthorizer // lease expires, so a periodic detach is not a final-send gate. Until P08 installs a verified publish-time // gate, do not admit mapped data or event subscriptions at all. if (operation == OpcUaOperation.CreateMonitoredItems) { veto = DeniedResult; return true; } + // H3: HistoryRead on a mapped node is opened DELIBERATELY — it needs the mapping's own HistoryRead bit (masked by the + // export's) AND a local NodePermissions.HistoryRead grant on the mapping scope, with ACLs on or off (plan §6). Every + // other mapped operation outside this allowlist (HistoryUpdate, alarm methods…) stays closed. + if (operation is not (OpcUaOperation.Browse or OpcUaOperation.Read or OpcUaOperation.WriteOperate or OpcUaOperation.WriteTune + or OpcUaOperation.WriteConfigure or OpcUaOperation.TransferSubscriptions or OpcUaOperation.HistoryRead)) + { veto = DeniedResult; return true; } var caller = new DataCallerIdentity(identity.Principal, identity.ApiKeyId, identity.CredentialVersion, identity.CredentialExpiresUtc); try 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 new file mode 100644 index 000000000..7bceeb877 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ProjectedHistoryReadTests.cs @@ -0,0 +1,372 @@ +using Microsoft.Extensions.Logging.Abstractions; +using Opc.Ua; +using Opc.Ua.Server; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; +using SdkHistoryReadResult = Opc.Ua.HistoryReadResult; +using DataValue = Opc.Ua.DataValue; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections; + +/// +/// H3 — the SDK side of projected history: the projected access level, the mapped HistoryRead gate with ACLs on and off, +/// the local/projected split keeping per-index slots, the Remote cursor in the session store (resume, release, session +/// close, wrong node), consumer-side aggregate refusal and the never-remote modified read. +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H3")] +public sealed class ProjectedHistoryReadTests : IAsyncDisposable +{ + private static readonly DateTimeOffset Now = new(2026, 11, 15, 12, 0, 0, TimeSpan.Zero); + private static readonly DateTime T0 = new(2026, 11, 15, 11, 0, 0, DateTimeKind.Utc); + private readonly string _pki = Path.Combine(Path.GetTempPath(), $"otopcua-projected-history-{Guid.NewGuid():N}"); + private OpcUaApplicationHost? _host; + + [Fact] + public async Task Only_a_historizing_definition_gets_the_HistoryRead_bit_and_never_HistoryWrite() + { + var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead); + var plain = Project(nm, f, "Plain", historizing: false); + var historized = Project(nm, f, "Hist", historizing: true); + var plainNode = Variable(nm, plain); + plainNode.AccessLevel.ShouldBe(AccessLevels.CurrentRead); + plainNode.Historizing.ShouldBeFalse(); + var histNode = Variable(nm, historized); + histNode.AccessLevel.ShouldBe((byte)(AccessLevels.CurrentRead | AccessLevels.HistoryRead)); + histNode.UserAccessLevel.ShouldBe((byte)(AccessLevels.CurrentRead | AccessLevels.HistoryRead)); + (histNode.AccessLevel & AccessLevels.HistoryWrite).ShouldBe((byte)0); + histNode.Historizing.ShouldBeTrue(); + + var access = new FakeAccess(); + nm.ProjectedHistoryAccess = access; + var (results, errors) = Raw(nm, f.Identity, [plain, historized]); + errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code, "no bit ⇒ the SDK refuses before any history code"); + errors[1].StatusCode.Code.ShouldBe(StatusCodes.Good.Code); + access.Calls.ShouldBe(1); + access.LastNodes.Single().NodeId.ShouldBe(historized); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Mapped_HistoryRead_needs_the_local_grant_and_the_mapping_bit_with_acls_on_and_off(bool aclEnabled) + { + // Granted: served through the projection, ACLs on or off. + var (nm, f) = await BootAsync(aclEnabled, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead); + var node = Project(nm, f, "Speed", historizing: true); + var access = new FakeAccess(); + nm.ProjectedHistoryAccess = access; + var (results, errors) = Raw(nm, f.Identity, [node]); + errors[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code); + Values(results[0]).Select(v => SdkValueBoundary.ToClr(v.WrappedValue)).ShouldBe([1.0, 2.0]); + access.Calls.ShouldBe(1); + + // No local HistoryRead grant on the mapping scope ⇒ BadUserAccessDenied, never sent — even with ACLs off. + f.Grant(NodePermissions.Browse | NodePermissions.Read); + (_, errors) = Raw(nm, f.Identity, [node]); + errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code); + access.Calls.ShouldBe(1); + + // Local grant but the mapping (subject) lacks HistoryRead ⇒ denied too. + f.Grant(NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead); + f.SubjectOperations = DataOperations.Browse | DataOperations.Read; + (_, errors) = Raw(nm, f.Identity, [node]); + errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code); + access.Calls.ShouldBe(1); + + // No identity at all ⇒ denied. + (_, errors) = Raw(nm, null, [node]); + errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code); + access.Calls.ShouldBe(1); + } + + [Fact] + public async Task A_mixed_local_and_projected_batch_keeps_every_slot() + { + var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead); + nm.EnsureVariable("Plant/LocalA", "Plant", "LocalA", "Double", false, AddressSpaceRealm.Raw, historianTagname: "L.a"); + nm.EnsureVariable("Plant/LocalB", "Plant", "LocalB", "Double", false, AddressSpaceRealm.Raw, historianTagname: "L.b"); + var localA = nm.TryGetVariable("Plant/LocalA", AddressSpaceRealm.Raw)!.NodeId; + var localB = nm.TryGetVariable("Plant/LocalB", AddressSpaceRealm.Raw)!.NodeId; + var p1 = Project(nm, f, "One", historizing: true); + var p2 = Project(nm, f, "Two", historizing: true); + var access = new FakeAccess { Answer = node => node.NodeId == p1 ? [10.0] : [20.0, 21.0] }; + nm.ProjectedHistoryAccess = access; + + var (results, errors) = Raw(nm, f.Identity, [p1, localA, p2, localB]); + Values(results[0]).Select(v => SdkValueBoundary.ToClr(v.WrappedValue)).ShouldBe([10.0]); + Values(results[2]).Select(v => SdkValueBoundary.ToClr(v.WrappedValue)).ShouldBe([20.0, 21.0]); + // The local slots are the H1 port's answer (no historian ⇒ GoodNoData), untouched by the projected half. + results[1].StatusCode.Code.ShouldBe(StatusCodes.GoodNoData.Code); + results[3].StatusCode.Code.ShouldBe(StatusCodes.GoodNoData.Code); + errors.ShouldAllBe(e => StatusCode.IsGood(e.StatusCode)); + access.Calls.ShouldBe(1, "one remote call for the batch's projected half"); + access.LastNodes.Select(n => n.NodeId).ShouldBe([p1, p2]); + } + + [Fact] + public async Task A_remote_cursor_resumes_once_and_is_released_by_releaseContinuationPoints_and_session_close() + { + var (nm, f) = await BootAsync(aclEnabled: true, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead); + var store = new InMemoryHistoryContinuationStore(); + nm.HistoryContinuationStore = store; + var node = Project(nm, f, "Paged", historizing: true); + var other = Project(nm, f, "Other", historizing: true); + var access = new FakeAccess { Paged = true }; + nm.ProjectedHistoryAccess = access; + + var (results, _) = Raw(nm, f.Identity, [node]); + var cp = results[0].ContinuationPoint; + cp.IsEmpty.ShouldBeFalse(); + var first = access.Issued.Single(); + store.Count.ShouldBe(1); + + // Resume: the SAME cursor comes back to the projection, claimed for the resume (not released). + (results, _) = Raw(nm, f.Identity, [node], cp); + access.LastNodes.Single().Resume.ShouldBeSameAs(first); + first.Released.ShouldBe(0); + var second = access.Issued[1]; + var cp2 = results[0].ContinuationPoint; + + // The same point again ⇒ invalid (single-use), unsent. + var calls = access.Calls; + (results, var errors) = Raw(nm, f.Identity, [node], cp); + errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); + access.Calls.ShouldBe(calls); + + // A cursor resumed on ANOTHER node ⇒ invalid and released. + (_, errors) = Raw(nm, f.Identity, [other], cp2); + errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); + second.Released.ShouldBe(1); + + // releaseContinuationPoints forwards one release. + (results, _) = Raw(nm, f.Identity, [node]); + var third = access.Issued[2]; + Release(nm, f.Identity, node, results[0].ContinuationPoint); + third.Released.ShouldBe(1); + store.Count.ShouldBe(0); + + // Session close (the SDK disposes every point) releases what is still open. + Raw(nm, f.Identity, [node]); + Raw(nm, f.Identity, [other]); + store.Count.ShouldBe(2); + store.Clear(); + access.Issued.Skip(3).ShouldAllBe(c => c.Released == 1); + } + + [Fact] + public async Task A_bad_remote_answer_carries_no_cursor_and_unknown_aggregates_and_modified_reads_are_refused_unsent() + { + var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead); + nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore(); + var node = Project(nm, f, "Speed", historizing: true); + var access = new FakeAccess { Status = StatusCodes.BadAggregateNotSupported.Code, Paged = true }; + nm.ProjectedHistoryAccess = access; + + // The origin refuses the aggregate: verbatim, no cursor kept (and the one it returned is released). + var processed = new ReadProcessedDetails + { + StartTime = T0, EndTime = T0.AddHours(1), ProcessingInterval = 60_000, + AggregateType = [ObjectIds.AggregateFunction_Average], + }; + var (results, errors) = Read(nm, f.Identity, processed, [node]); + errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadAggregateNotSupported.Code); + results[0].ContinuationPoint.IsEmpty.ShouldBeTrue(); + access.Issued.ShouldAllBe(c => c.Released == 1); + access.LastNodes.Single().AggregateId.ShouldBe(Objects.AggregateFunction_Average); + + // An aggregate the consumer cannot name ⇒ BadAggregateNotSupported without a call. + var calls = access.Calls; + processed.AggregateType = [new NodeId("not-an-aggregate", 2)]; + (_, errors) = Read(nm, f.Identity, processed, [node]); + errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadAggregateNotSupported.Code); + access.Calls.ShouldBe(calls); + + // A modified read is never served remotely. + var modified = new ReadRawModifiedDetails { StartTime = T0, EndTime = T0.AddHours(1), NumValuesPerNode = 5, IsReadModified = true }; + (_, errors) = Read(nm, f.Identity, modified, [node]); + errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code); + access.Calls.ShouldBe(calls); + } + + [Fact] + public void Unset_bounds_travel_absent_and_AtTime_carries_its_times() + { + OtOpcUaNodeManager.ToRemoteDetails(new ReadRawModifiedDetails { EndTime = T0, NumValuesPerNode = 3, ReturnBounds = true, IsReadModified = false }) + .ShouldBe(new DataHistoryRawDetails(null, new DateTimeOffset(T0), 3, true)); + var atTime = OtOpcUaNodeManager.ToRemoteDetails(new ReadAtTimeDetails { ReqTimes = [T0], UseSimpleBounds = true }) + .ShouldBeOfType(); + atTime.RequestedTimesUtc.ShouldBe([new DateTimeOffset(T0)]); + atTime.UseSimpleBounds.ShouldBeTrue(); + } + + // ------------------------------------------------------------------------------------------------------------------ + + private static (List Results, List Errors) Raw(OtOpcUaNodeManager nm, IUserIdentity? identity, + NodeId[] nodes, ByteString cp = default) => + Read(nm, identity, new ReadRawModifiedDetails + { + StartTime = T0, EndTime = T0.AddHours(1), NumValuesPerNode = 2, IsReadModified = false, ReturnBounds = false, + }, nodes, cp); + + private static (List Results, List Errors) Read(OtOpcUaNodeManager nm, IUserIdentity? identity, + HistoryReadDetails details, NodeId[] nodes, ByteString cp = default) + { + var context = new OperationContext(new RequestHeader(), null, RequestType.HistoryRead, RequestLifetime.None, identity); + var results = nodes.Select(_ => (SdkHistoryReadResult)null!).ToList(); + var errors = nodes.Select(_ => (ServiceResult)null!).ToList(); + nm.HistoryRead(context, details, TimestampsToReturn.Both, false, + nodes.Select(n => new HistoryReadValueId { NodeId = n, ContinuationPoint = cp }).ToList(), results, errors); + return (results, errors); + } + + private static void Release(OtOpcUaNodeManager nm, IUserIdentity identity, NodeId node, ByteString cp) + { + var context = new OperationContext(new RequestHeader(), null, RequestType.HistoryRead, RequestLifetime.None, identity); + var results = new List { null! }; + var errors = new List { null! }; + nm.HistoryRead(context, new ReadRawModifiedDetails { IsReadModified = false, ReturnBounds = false }, TimestampsToReturn.Both, true, + new List { new() { NodeId = node, ContinuationPoint = cp } }, results, errors); + StatusCode.IsGood(errors[0].StatusCode).ShouldBeTrue(); + } + + private static IReadOnlyList Values(SdkHistoryReadResult result) => + ExtensionObject.ToEncodeable(result.HistoryData) is HistoryData data ? data.DataValues.ToArray() ?? [] : []; + + private static BaseDataVariableState Variable(OtOpcUaNodeManager nm, NodeId id) => + ((NodeHandle)nm.GetManagerHandle(id)!).Node.ShouldBeOfType(); + + private static NodeId Project(OtOpcUaNodeManager nm, Fixture f, string name, bool historizing) + { + var parent = nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; + var origin = new DataAddress("origin", "ns", "string", "Device/" + name); + var view = new DataView(origin, DataRealm.Raw, "mapping-a", 1, "Plant/Mount/" + name); + var metadata = new DataMetadata(view, name, "Tag", DataValueKind.Double, -1, [], false, + DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead, 1, null, null, false, History: new DataHistoryInfo(historizing)); + var identifier = ProjectedDataIds.Identifier("mapping-a", origin); + nm.TryEnsureProjectedVariable(new ProjectedVariableDefinition(DataRealm.Raw, identifier, parent, metadata, 1, () => true) + { Historizing = historizing }, out var node).ShouldBeTrue(); + f.Views[identifier] = view; + return node!.Value; + } + + private async Task<(OtOpcUaNodeManager Nm, Fixture F)> BootAsync(bool aclEnabled, NodePermissions permissions) + { + var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions + { + ApplicationName = "ProjectedHistory", ApplicationUri = $"urn:ProjectedHistory:{Guid.NewGuid():N}", + OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = _pki, + }, NullLogger.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken); + _host = started.Host; + var nm = started.Server.NodeManager!; + nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); + var f = new Fixture(aclEnabled, permissions); + nm.Authorizer = f.Gate; + nm.MappedSubjectResolver = (realm, id) => f.Resolve(realm, id); + return (nm, f); + } + + public async ValueTask DisposeAsync() + { + if (_host is not null) await _host.DisposeAsync(); + if (Directory.Exists(_pki)) + try { Directory.Delete(_pki, recursive: true); } catch (IOException) { } + } + + private sealed class Fixture + { + private readonly DataPlaneAuthorityState _state = new(); + private readonly TestLease _lease = new(); + internal readonly ApiKey Key = new() { ApiKeyId = "key-a", Name = "key-a", Principal = "reader", SecretHash = "hash", Enabled = true, + ExpiresUtc = Now.AddHours(1).UtcDateTime }; + internal readonly DataPlaneAuthorizer Gate; + internal readonly Dictionary Views = new(StringComparer.Ordinal); + internal DataOperations SubjectOperations { get; set; } = + DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead; + + internal Fixture(bool aclEnabled, NodePermissions permissions) + { + Grant(permissions); + var clock = new TestClock(); + Gate = new DataPlaneAuthorizer(_state, new TriePermissionEvaluator(_state.Tries, clock), aclEnabled, NullLogger.Instance, clock); + } + + internal void Grant(NodePermissions permissions) => + _state.Apply("c1", "rev-" + (int)permissions, [Key], + [new NodeAcl { NodeAclId = "acl", ClusterId = "c1", Principal = "reader", ScopeKind = NodeAclScopeKind.RawFolder, + ScopeId = "folder", PermissionFlags = permissions }], + new Dictionary> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant", "Mount"])] }); + + internal RoleCarryingUserIdentity Identity => new(new UserNameIdentityToken { UserName = "apikey" }, [], "reader", Key.ApiKeyId, + DataCallerIdentity.CredentialVersionFor(Key), Now.AddMinutes(2)); + + internal MappedNodeResolution Resolve(AddressSpaceRealm realm, string identifier) + { + if (!Views.TryGetValue(identifier, out var view)) return MappedNodeResolution.Local; + var subject = new MappedNamespaceSubject(view, + new NodeScope { ClusterId = "c1", Kind = NodeHierarchyKind.Raw, Segments = view.Subject.Split('/') }, + ["local-parent", "mapping-a"], _lease.Serving, SubjectOperations, WriteThrough: false); + var resolver = new MappedSubjectResolver([subject], catalogEpoch: 7, new TestCatalogAuthority(_state)); + return MappedNodeResolution.Mapped(view, subject, resolver, _lease); + } + } + + private sealed class FakeAccess : IProjectedHistoryAccess + { + public int Calls; + public IReadOnlyList LastNodes = []; + public readonly List Issued = []; + public bool Paged { get; init; } + public uint Status { get; init; } + public Func Answer { get; init; } = _ => [1.0, 2.0]; + + public Task> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details, + IReadOnlyList nodes, TimeSpan deadline, CancellationToken cancellationToken) + { + Calls++; + LastNodes = nodes; + return Task.FromResult>(nodes.Select(node => + { + FakeCursor? next = null; + if (Paged) + { + var key = node.NodeId.TryGetValue(out string id) ? id : ""; + next = new FakeCursor(key); + Issued.Add(next); + } + var samples = Answer(node).Select((v, i) => new OriginHistorySample(v, 0, T0.AddSeconds(i), null)).ToArray(); + return new ProjectedHistoryOutcome(Status, Status == 0 ? samples : [], next); + }).ToArray()); + } + } + + private sealed class FakeCursor(string identifier) : ProjectedHistoryContinuation(DataRealm.Raw, identifier) + { + public int Released; + protected override void OnRelease() => Interlocked.Increment(ref Released); + } + + private sealed class TestCatalogAuthority(DataPlaneAuthorityState state) : IDataMappedCatalogAuthority + { + public long CatalogEpoch => 1; + public long AuthorityEpoch => state.Current.GenerationId; + public bool IsActive => true; + } + + private sealed class TestLease : IDataAuthorizationLease + { + public ServingIdentity Serving { get; } = new("node-a", "incarnation-a", "Primary", 7, 1); + public bool IsValid => true; + } + + private sealed class TestClock : TimeProvider + { + public override DateTimeOffset GetUtcNow() => Now; + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryRefusalTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs similarity index 100% rename from tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryRefusalTests.cs rename to tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs From 19b8163045f6f547468cd94f8f36affa9de4193e Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 00:28:17 -0500 Subject: [PATCH 02/25] feat(grpc-data): H3 ProjectedHistoryAccess over deployed connections Resolves, authorizes (HistoryRead demand: mapping bit + local grant on the mapping scope, ACLs on or off) and pins each projected node, groups the batch per connection / details / issuing endpoint and forwards through IDataHistoryService. Remote cursors bind caller, mapping id+revision, connection route, projection generation, origin view and serving identity, and resend the ORIGINAL details; any change => BadContinuationPointInvalid with the origin token released. Shared per-request assembly budget (min mapping MaxHistoryAssemblyBytesPerRequest) => BadTooManyOperations for the remaining nodes. Releases coalesce per connection. Replaces the H2 refusal pin with the intended behaviour (granted => served, no grant => BadUserAccessDenied). --- .../DataConnectionRegistration.cs | 7 + .../OpcUa/OtOpcUaServerHostedService.cs | 7 +- .../LocalDataServices.History.cs | 3 + .../DataConnections/OriginHistorySessions.cs | 11 + .../DataConnections/ProjectedDataAccess.cs | 18 +- .../DataConnections/ProjectedHistoryAccess.cs | 448 ++++++++++++++++++ .../ProjectedMappingDeploymentRuntime.cs | 13 + .../ProjectedNamespaceApplier.cs | 6 +- .../RemoteNamespaceResolver.cs | 2 +- .../GrpcDataComposedBrowseWireTests.cs | 10 +- .../GrpcDataLocalConnectionTests.cs | 8 +- .../GrpcDataProjectedHistoryCursorTests.cs | 54 +++ .../GrpcDataProjectedHistoryWireTests.cs | 391 ++++++++++++++- 13 files changed, 949 insertions(+), 29 deletions(-) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryCursorTests.cs 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 a61e184f3..ff33ad910 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs @@ -118,6 +118,13 @@ public static class DataConnectionRegistration (!settings.IsWarm || state.WarmRole == WarmRole.Active), state.Generation); }, renewalSink: sp.GetRequiredService())); services.AddSingleton(sp => sp.GetRequiredService()); + // 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())); + services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(sp => new ConfiguredProjectionDiscovery( sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs index 1d04c3314..7f4b03407 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs @@ -60,6 +60,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl private readonly DriverWriteBounds _writeBounds; private readonly IProjectedBrowseAccess? _projectedBrowseAccess; private readonly IProjectedDataAccess? _projectedDataAccess; + private readonly IProjectedHistoryAccess? _projectedHistoryAccess; private readonly IFederatedProjectionCatalog? _projectedCatalog; private readonly DataConnectionOptions _dataConnectionOptions; @@ -140,6 +141,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl /// Optional caller-bound mapped browse scheduler. /// Optional bounded mapped read, write and subscription gateway. /// Optional live projection catalog used for mapped authorization. + /// Optional HistoryRead gateway for projected variables (H3). public OtOpcUaServerHostedService( IOptions options, DeferredAddressSpaceSink deferredSink, @@ -164,8 +166,10 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl DeferredStandbyProjection? deferredStandby = null, IProjectedBrowseAccess? projectedBrowseAccess = null, IProjectedDataAccess? projectedDataAccess = null, - IFederatedProjectionCatalog? projectedCatalog = null) + IFederatedProjectionCatalog? projectedCatalog = null, + IProjectedHistoryAccess? projectedHistoryAccess = null) { + _projectedHistoryAccess = projectedHistoryAccess; _dataConnectionOptions = configuration.GetSection(DataConnectionOptions.SectionName).Get() ?? new(); _projectedBrowseAccess = projectedBrowseAccess; _projectedDataAccess = projectedDataAccess; @@ -264,6 +268,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl _server.NodeManager.ProjectedBrowseAccess = _projectedBrowseAccess; _server.NodeManager.ProjectedBrowseClock = _time; _server.NodeManager.ProjectedDataAccess = _projectedDataAccess; + _server.NodeManager.ProjectedHistoryAccess = _projectedHistoryAccess; if (_projectedCatalog is { } projectedCatalog) _server.NodeManager.MappedSubjectResolver = (realm, identifier) => projectedCatalog.TryResolveProjected(realm == AddressSpaceRealm.Raw ? DataRealm.Raw : DataRealm.Uns, 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 fb9ba2f42..65c5e8358 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 @@ -43,6 +43,9 @@ public sealed partial class LocalDataServices /// Live history sessions (diagnostics/tests). internal int HistorySessionCount => _historySessions.Count; + /// Open origin continuations (page cursors + chunk remainders) across every session (diagnostics/tests). + internal int HistoryOpenContinuations => _historySessions.OpenContinuations; + /// Remainder bytes retained for a principal across its sessions (diagnostics/tests). internal long HistoryRetainedBytes(string principal) => _historySessions.RetainedBytes(principal); 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 d4a3d5673..aed8567d5 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/OriginHistorySessions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/OriginHistorySessions.cs @@ -194,6 +194,17 @@ 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). + 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); + } + } + /// Remainder bytes retained for across its sessions. public long RetainedBytes(string principal) { lock (_gate) return _retained.GetValueOrDefault(principal); } 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 0a19a2b48..aeae8532b 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs @@ -130,7 +130,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable if (metadata.ValueKind == DataValueKind.Timestamp && value is DateTime timestamp) value = new DateTimeOffset(timestamp.ToUniversalTime()); return ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromScalar(metadata.ValueKind, value); } - private static object? DecodeValue(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue value, DataMetadata metadata) + internal static object? DecodeValue(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue value, DataMetadata metadata) { if (value.Kind == DataValueKind.Null) return null; if (value.Kind != metadata.ValueKind) throw new ArgumentException("Value kind does not match metadata."); @@ -154,13 +154,15 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable public bool TryAcquire(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out IProjectedDemandLease? demand) { demand = null; - if (caller is null || operation is not (DataOperations.Browse or DataOperations.Read or DataOperations.Write or DataOperations.Subscribe)) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireInvalid); return false; } + if (caller is null || operation is not (DataOperations.Browse or DataOperations.Read or DataOperations.Write or DataOperations.Subscribe or DataOperations.HistoryRead)) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireInvalid); return false; } try { if (!_nodes.TryResolve(nodeId, out var definition) || definition is null || !definition.AuthorityIsCurrent() || !_catalog.TryResolveProjected(definition.Realm, definition.LocalIdentifier, out var proof) || proof is null || proof.Generation != definition.ProjectionGeneration || !MetadataMatches(proof.Metadata, definition.Metadata) || ((operation is DataOperations.Read or DataOperations.Subscribe) && proof.MaximumSampleAge <= TimeSpan.Zero) || + // H3: history only on a node projected Historizing (mapping bit AND origin HistoryInfo), whatever the caller holds. + (operation == DataOperations.HistoryRead && (!definition.Historizing || !ProjectedHistoryAccess.Advertises(proof))) || proof.Metadata.View.MappingId is not { } mapping || proof.Lease.Serving.ServingGeneration <= 0 || _connectionForMapping(mapping) is not { Length: > 0 } connectionId) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireDefinition); return false; } var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc); @@ -213,12 +215,24 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable if (lease is Demand demand) await demand.Completion.ConfigureAwait(false); } public bool HasLiveDemand(DataRealm realm, string localIdentifier) { lock (_sync) return _demandCounts.ContainsKey((realm, localIdentifier)); } + /// H3: what a HistoryRead demand is bound to — its mapping, revision, deployed connection and the origin's metadata. + internal bool TryDescribeHistoryDemand(IProjectedDemandLease lease, out ProjectedHistoryTarget? target) + { + target = null; + if (lease is not Demand { RequestedOperation: DataOperations.HistoryRead } demand || !demand.IsValid) return false; + var binding = demand.CurrentBinding; + if (binding.Proof.Metadata.View.MappingId is not { } mapping) return false; + target = new ProjectedHistoryTarget(mapping, binding.Proof.Metadata.View.MappingRevision, binding.ConnectionId, + binding.Proof.OriginMetadata, binding.Proof.Lease.Serving, binding.Proof.Generation); + return true; + } private static OpcUaOperation Operation(DataOperations operation) => operation switch { DataOperations.Browse => OpcUaOperation.Browse, DataOperations.Read => OpcUaOperation.Read, DataOperations.Write => OpcUaOperation.WriteOperate, DataOperations.Subscribe => OpcUaOperation.CreateMonitoredItems, + DataOperations.HistoryRead => OpcUaOperation.HistoryRead, _ => throw new ArgumentOutOfRangeException(nameof(operation)) }; private sealed class Demand(ProjectedDataAccess owner, NodeId nodeId, ProjectedVariableDefinition definition, diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs new file mode 100644 index 000000000..fd4665757 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs @@ -0,0 +1,448 @@ +using Opc.Ua; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// What a projected HistoryRead demand is bound to (H3). +/// The mapping. +/// The deployed mapping revision. +/// The deployed connection the mapping reads through. +/// The origin's metadata (origin view, value kind). +/// The origin serving identity the projection was built under. +/// The projection generation. +internal sealed record ProjectedHistoryTarget(string MappingId, long MappingRevision, string ConnectionId, DataMetadata OriginMetadata, + ServingIdentity Serving, long ProjectionGeneration); + +/// +/// H3 — consumer OPC UA projection of remote history (gRPC data history plan §2.1, §3.2, §3.3). For each projected node: +/// resolve + authorize + pin it through (a +/// demand: the mapping's HistoryRead bit and a local HistoryRead grant on the mapping scope, ACLs on or off), group the +/// batch per deployed connection and per details, and forward through . +/// +/// A fresh read may move endpoint within its deadline (the connection decides); a RESUMED read never moves — +/// its origin token pins the issuing endpoint and serving incarnation, and its cursor re-checks the caller, the +/// mapping revision, the projection generation, the serving identity and the connection lease (route) before any +/// call. Any mismatch ⇒ BadContinuationPointInvalid and the origin token is released. +/// A resume resends the ORIGINAL details verbatim (the origin binds their hash); local SDK resumes ignore details, +/// so the consumer does too. +/// The per-request assembly budget (min MaxHistoryAssemblyBytesPerRequest of the batch's mappings) is shared +/// across the batch; once spent, the remaining nodes are BadTooManyOperations. +/// Deadline per call = min(the consumer's remaining HistoryReadDeadline, the connection's +/// HistoryTimeoutMilliseconds) ⇒ BadTimeout; a cancelled read is never an origin fault. +/// Releases (releaseContinuationPoints, session close, eviction) are coalesced per connection into one +/// best-effort ReleaseHistoryAsync; the origin's idle expiry is the backstop. +/// +/// +public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposable +{ + internal const uint Good = 0, BadContinuationPointInvalid = 0x804A0000u, BadTooManyOperations = 0x80100000u, BadTimeout = 0x800A0000u, + BadNoCommunication = 0x80310000u, BadTypeMismatch = 0x80740000u, BadHistoryOperationUnsupported = 0x80720000u; + internal const long DefaultAssemblyBudget = 16L * 1024 * 1024; + + private readonly ProjectedDataAccess _access; + private readonly IGrpcDataAdapterConnectionSource _connections; + private readonly Func _assemblyBudget; + private readonly TimeProvider _clock; + private readonly object _releaseGate = new(); + private readonly Dictionary> _pendingReleases = new(StringComparer.OrdinalIgnoreCase); + private readonly CancellationTokenSource _stop = new(); + private Task _releaseFlush = Task.CompletedTask; + private int _disposed; + + /// Creates the gateway. + /// The projected data access that resolves, authorizes and pins projected nodes. + /// The deployed connection registry. + /// A mapping's MaxHistoryAssemblyBytesPerRequest; null = not deployed. + /// The clock. + public ProjectedHistoryAccess(ProjectedDataAccess access, IGrpcDataAdapterConnectionSource connections, + Func assemblyBudget, TimeProvider clock) + { + _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)); + } + + /// 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); + + /// Releases queued and not yet sent (tests). + internal int PendingReleasesForTests { get { lock (_releaseGate) return _pendingReleases.Values.Sum(x => x.Count); } } + + /// Release calls sent (tests): one per connection per coalesced flush. + internal int ReleaseCallsForTests => Volatile.Read(ref _releaseCalls); + private int _releaseCalls; + + /// Waits for the queued releases to be sent (tests). + internal async Task FlushReleasesForTestsAsync() + { + Task flush; + lock (_releaseGate) flush = _releaseFlush; + await flush.ConfigureAwait(false); + lock (_releaseGate) flush = _releaseFlush; + await flush.ConfigureAwait(false); + } + + /// + /// 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. + /// + public static bool Advertises(ProjectedNodeProof proof) => + proof is not null && (proof.Subject.AllowedOperations & DataOperations.HistoryRead) != 0 + && (proof.OriginMetadata.AllowedOperations & DataOperations.HistoryRead) != 0 + && proof.OriginMetadata.History is { Historizing: true } && proof.OriginMetadata.NodeKind is "Variable" or "Tag"; + + /// + public async Task> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details, + IReadOnlyList nodes, TimeSpan deadline, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(caller); ArgumentNullException.ThrowIfNull(details); ArgumentNullException.ThrowIfNull(nodes); + var started = _clock.GetTimestamp(); + var outcomes = new ProjectedHistoryOutcome?[nodes.Count]; + var demands = new IProjectedDemandLease?[nodes.Count]; + var targets = new ProjectedHistoryTarget?[nodes.Count]; + var callerKey = CallerKey(caller); + long budget = DefaultAssemblyBudget; + try + { + // 1. Resolve, authorize and pin every node; check each resumed cursor against what it was issued under. + for (var i = 0; i < nodes.Count; i++) + { + var node = nodes[i]; + var cursor = node.Resume as RemoteCursor; + if (node.Resume is not null && (cursor is null || !ReferenceEquals(cursor.Owner, this))) + { + node.Resume.Release(); + outcomes[i] = Fail(BadContinuationPointInvalid); + continue; + } + + if (!_access.TryAcquire(node.NodeId, caller, DataOperations.HistoryRead, out var demand) || demand is null + || !_access.TryDescribeHistoryDemand(demand, out var target) || target is null) + { + demand?.Dispose(); + cursor?.ReleaseOrigin(); + // The node manager already authorized the node: a projection that cannot be pinned now is not servable. + outcomes[i] = Fail(cursor is null ? BadNoCommunication : BadContinuationPointInvalid); + continue; + } + + demands[i] = demand; + targets[i] = target; + if (cursor is not null && !cursor.StillMatches(callerKey, target, demand)) + { + // Mapping revision change, failover, projection rebuild, another caller: the cursor never resumes. + cursor.ReleaseOrigin(); + outcomes[i] = Fail(BadContinuationPointInvalid); + } + } + + // 2. The per-request assembly budget, shared across the batch: the tightest mapping's. + budget = long.MaxValue; + foreach (var target in targets) + if (target is not null) budget = Math.Min(budget, _assemblyBudget(target.MappingId) is { } b and > 0 ? b : DefaultAssemblyBudget); + if (budget == long.MaxValue) budget = DefaultAssemblyBudget; + + // 3. One call per (connection, details, resumed endpoint): a resumed item pins its issuing endpoint, so cursors of + // different endpoints, and fresh items (which may move), never share a call. + var groups = Enumerable.Range(0, nodes.Count).Where(i => outcomes[i] is null) + .GroupBy(i => new GroupKey(targets[i]!.ConnectionId, DetailsOf(nodes[i], details), ResumeKey(nodes[i]))) + .ToArray(); + foreach (var group in groups) + { + var indices = group.ToArray(); + if (cancellationToken.IsCancellationRequested) { FailAll(indices, BadTimeout); continue; } + TimeSpan remaining; + if (deadline > TimeSpan.Zero) + { + remaining = deadline - _clock.GetElapsedTime(started); + if (remaining <= TimeSpan.Zero) { FailAll(indices, BadTimeout); continue; } + } + else remaining = TimeSpan.FromHours(1); // unbounded locally: the connection's HistoryTimeout still caps each call + if (budget <= 0) { FailAll(indices, BadTooManyOperations); continue; } + await ReadGroupAsync(group.Key, indices, remaining, cancellationToken).ConfigureAwait(false); + } + + return outcomes.Select(o => o ?? Fail(BadNoCommunication)).ToArray(); + } + finally + { + foreach (var demand in demands) demand?.Dispose(); + } + + async Task ReadGroupAsync(GroupKey key, int[] indices, TimeSpan remaining, CancellationToken ct) + { + IGrpcDataAdapterConnectionLease? lease = null; + try + { + using var timeout = new CancellationTokenSource(remaining, _clock); + using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, timeout.Token); + lease = await _connections.AcquireAsync(key.ConnectionId, linked.Token).ConfigureAwait(false); + if (lease is null || lease.Connection is not IDataHistoryService history || lease.CancellationToken.IsCancellationRequested) + { + foreach (var i in indices) + { + if (nodes[i].Resume is RemoteCursor c) { c.ReleaseOrigin(); outcomes[i] = Fail(BadContinuationPointInvalid); } + else outcomes[i] = Fail(BadNoCommunication); + } + return; + } + + var route = lease.RouteIdentity; + var items = new List(indices.Length); + var sent = new List(indices.Length); + foreach (var i in indices) + { + if (nodes[i].Resume is RemoteCursor cursor) + { + // The connection lease moved (expiry, redeployment, credential change): its tokens are gone. + if (!Equals(cursor.RouteIdentity, route)) + { + cursor.ReleaseOrigin(); + outcomes[i] = Fail(BadContinuationPointInvalid); + continue; + } + + items.Add(new DataHistoryReadItem(sent.Count.ToString(System.Globalization.CultureInfo.InvariantCulture), + targets[i]!.OriginMetadata.View, cursor.AggregateId, cursor.Token)); + } + else + { + items.Add(new DataHistoryReadItem(sent.Count.ToString(System.Globalization.CultureInfo.InvariantCulture), + targets[i]!.OriginMetadata.View, nodes[i].AggregateId)); + } + + sent.Add(i); + } + + if (items.Count == 0) return; + IReadOnlyList answers; + try + { + answers = await history.ReadAsync(new DataHistoryReadRequest(key.Details, items, + new DataBudget(remaining, items.Count, (int)Math.Min(int.MaxValue, budget))), linked.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + // Our deadline or the SDK request ending: a timeout, never an origin fault (the connection records none). + foreach (var i in sent) outcomes[i] = Fail(BadTimeout); + return; + } + + try + { + if (answers.Count != items.Count) + { + foreach (var i in sent) outcomes[i] = Fail(BadNoCommunication); + return; + } + + for (var k = 0; k < answers.Count; k++) + { + var i = sent[k]; + var answer = answers[k]; + if (answer.CorrelationId != items[k].CorrelationId) + { + outcomes[i] = Fail(BadNoCommunication); + continue; + } + + // The per-request assembly budget, in request order across the whole batch: once a node does not fit, + // it and every later node is BadTooManyOperations (never a partial answer; its origin cursor released). + long nodeBytes = 0; + foreach (var sample in answer.Samples) nodeBytes += sample.Value.EstimatedRetainedBytes; + if (nodeBytes > budget) + { + budget = 0; + if (answer.Continuation is { } dropped) EnqueueRelease(key.ConnectionId, dropped); + outcomes[i] = Fail(BadTooManyOperations); + continue; + } + + budget -= nodeBytes; + + var target = targets[i]!; + RemoteCursor? next = null; + if (answer.Continuation is { } token) + { + next = new RemoteCursor(this, target.OriginMetadata.View.Realm, demands[i]!.LocalIdentifier, token, key.ConnectionId, route, + target, callerKey, key.Details, nodes[i].Resume is RemoteCursor prior ? prior.AggregateId : nodes[i].AggregateId); + } + + outcomes[i] = new ProjectedHistoryOutcome(answer.StatusCode, Convert(answer.Samples, target.OriginMetadata), next); + } + } + finally + { + foreach (var answer in answers) answer.Dispose(); + } + + } + catch (OperationCanceledException) + { + foreach (var i in indices) + { + if (outcomes[i] is not null) continue; + if (nodes[i].Resume is RemoteCursor c) c.ReleaseOrigin(); + outcomes[i] = Fail(BadTimeout); + } + return; + } + catch (Exception ex) when (ex is InvalidOperationException or UnauthorizedAccessException or ArgumentException or ObjectDisposedException) + { + foreach (var i in indices) outcomes[i] ??= Fail(nodes[i].Resume is null ? BadNoCommunication : BadContinuationPointInvalid); + return; + } + finally + { + if (lease is not null) await lease.DisposeAsync().ConfigureAwait(false); + } + } + + void FailAll(int[] indices, uint status) + { + foreach (var i in indices) + { + if (nodes[i].Resume is RemoteCursor c) c.ReleaseOrigin(); + outcomes[i] = Fail(status); + } + } + } + + private static ProjectedHistoryOutcome Fail(uint status) => new(status, []); + + private static DataHistoryDetails DetailsOf(ProjectedHistoryNode node, DataHistoryDetails request) => + node.Resume is RemoteCursor cursor ? cursor.Details : request; + + private static string ResumeKey(ProjectedHistoryNode node) + { + if (node.Resume is not RemoteCursor cursor) return "fresh"; + return GrpcDataConnection.TryUnwrap(cursor.Token, out var endpoint, out var serving, out _) + ? FormattableString.Invariant($"{endpoint}|{serving}") : "resume"; + } + + private static string CallerKey(RoleCarryingUserIdentity caller) => + string.Join('\0', caller.Principal ?? "", caller.ApiKeyId ?? "", caller.CredentialVersion ?? ""); + + /// Values verbatim (status, absent timestamps); a value kind that disagrees with the catalog is BadTypeMismatch. + private static OriginHistorySample[] Convert(IReadOnlyList samples, DataMetadata metadata) + { + var converted = new OriginHistorySample[samples.Count]; + for (var i = 0; i < samples.Count; i++) + { + var sample = samples[i]; + object? value; + var status = sample.StatusCode; + try { value = ProjectedDataAccess.DecodeValue(sample.Value, metadata); } + catch (Exception ex) when (ex is ArgumentException or InvalidCastException or InvalidOperationException) + { + value = null; + status = BadTypeMismatch; + } + + converted[i] = new OriginHistorySample(value, status, sample.SourceTimestampUtc?.UtcDateTime, sample.ServerTimestampUtc?.UtcDateTime); + } + + return converted; + } + + /// Queues an origin token for a coalesced best-effort release on its connection. + private void EnqueueRelease(string connectionId, byte[] token) + { + if (Volatile.Read(ref _disposed) != 0) return; + lock (_releaseGate) + { + if (!_pendingReleases.TryGetValue(connectionId, out var list)) _pendingReleases[connectionId] = list = []; + list.Add(token); + if (!_releaseFlush.IsCompleted) return; + _releaseFlush = Task.Run(FlushReleasesAsync); + } + } + + private async Task FlushReleasesAsync() + { + try { await Task.Delay(ReleaseCoalesce, _stop.Token).ConfigureAwait(false); } + catch (OperationCanceledException) { return; } + Dictionary> batch; + lock (_releaseGate) + { + batch = new(_pendingReleases, StringComparer.OrdinalIgnoreCase); + _pendingReleases.Clear(); + } + + foreach (var (connectionId, tokens) in batch) + { + IGrpcDataAdapterConnectionLease? lease = null; + try + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + using var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, _stop.Token); + lease = await _connections.AcquireAsync(connectionId, linked.Token).ConfigureAwait(false); + if (lease?.Connection is not IDataHistoryService history) continue; + Interlocked.Increment(ref _releaseCalls); + await history.ReleaseAsync(tokens, linked.Token).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OutOfMemoryException) { } // best effort; the origin's idle expiry is the backstop + finally + { + if (lease is not null) try { await lease.DisposeAsync().ConfigureAwait(false); } catch (Exception) { } + } + } + + lock (_releaseGate) + if (_pendingReleases.Count > 0 && Volatile.Read(ref _disposed) == 0) _releaseFlush = Task.Run(FlushReleasesAsync); + } + + /// + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + _stop.Cancel(); + _stop.Dispose(); + } + + /// + /// Whether a cursor issued under for may resume now: same caller + /// (principal, key, credential version), mapping and revision, deployed connection, projection generation, origin view + /// and serving identity (node, incarnation, serving generation, role — a failover or restart changes it). + /// + internal static bool CursorMatches(ProjectedHistoryTarget issued, string issuedCaller, ProjectedHistoryTarget now, string caller) => + string.Equals(caller, issuedCaller, StringComparison.Ordinal) + && string.Equals(now.MappingId, issued.MappingId, StringComparison.Ordinal) && now.MappingRevision == issued.MappingRevision + && string.Equals(now.ConnectionId, issued.ConnectionId, StringComparison.OrdinalIgnoreCase) + && now.ProjectionGeneration == issued.ProjectionGeneration && now.OriginMetadata.View == issued.OriginMetadata.View + && string.Equals(now.Serving.NodeId, issued.Serving.NodeId, StringComparison.Ordinal) + && string.Equals(now.Serving.Incarnation, issued.Serving.Incarnation, StringComparison.Ordinal) + && now.Serving.ServingGeneration == issued.Serving.ServingGeneration + && string.Equals(now.Serving.Role, issued.Serving.Role, StringComparison.Ordinal); + + 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 int _originReleased; + internal ProjectedHistoryAccess Owner => owner; + internal byte[] Token => token; + internal object? RouteIdentity => routeIdentity; + internal DataHistoryDetails Details => details; + internal uint? AggregateId => aggregateId; + + /// The caller, mapping revision, projection generation, serving identity and connection still match. + internal bool StillMatches(string caller, ProjectedHistoryTarget now, IProjectedDemandLease demand) => + demand.Realm == Realm && string.Equals(demand.LocalIdentifier, LocalIdentifier, StringComparison.Ordinal) + && CursorMatches(target, callerKey, now, caller); + + /// Releases the origin token (once), whether the cursor was claimed for a resume or not. + internal void ReleaseOrigin() + { + if (Interlocked.Exchange(ref _originReleased, 1) == 0) owner.EnqueueRelease(connectionId, token); + } + + protected override void OnRelease() => ReleaseOrigin(); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedMappingDeploymentRuntime.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedMappingDeploymentRuntime.cs index 7dcf4a669..aa0310f3d 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedMappingDeploymentRuntime.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedMappingDeploymentRuntime.cs @@ -122,6 +122,19 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable } } + /// H3: the mapping's per-request history assembly budget, while its activated authority is current. + public bool TryGetHistoryAssemblyBudget(string mappingId, out long bytes) + { + bytes = 0; + if (!TryGetConnectionId(mappingId, out _)) return false; + lock (_gate) + { + if (!_byMapping.TryGetValue(mappingId, out var placement)) return false; + bytes = placement.Mapping.MaxHistoryAssemblyBytesPerRequest; + return bytes > 0; + } + } + public void Stage(CatalogAttempt attempt, IReadOnlyList mappings, IReadOnlyList connections) { ArgumentNullException.ThrowIfNull(attempt); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedNamespaceApplier.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedNamespaceApplier.cs index f25055075..551bd6a18 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedNamespaceApplier.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedNamespaceApplier.cs @@ -95,7 +95,8 @@ public sealed class ProjectedNamespaceApplier : IDisposable if (!PageCurrent() || guards.Any(guard => !guard.IsCurrent()) || root is not null && !root.IsCurrent()) return ProjectionPageStatus.Unavailable; var definitions = guards.Select(guard => new ProjectedVariableDefinition(guard.Proof.Metadata.View.Realm, - guard.Proof.LocalIdentifier, exactParent, guard.Proof.Metadata, guard.Proof.Generation, guard.IsCurrent)).ToArray(); + guard.Proof.LocalIdentifier, exactParent, guard.Proof.Metadata, guard.Proof.Generation, guard.IsCurrent) + { Historizing = ProjectedHistoryAccess.Advertises(guard.Proof) }).ToArray(); var rootLeaf = root is not null && ProjectedCatalogCache.IsValueNode(root.Proof.Metadata); if (rootLeaf && (definitions.Length != 0 || !page.Complete)) return ProjectionPageStatus.Unavailable; var attempted = 0; @@ -112,7 +113,8 @@ public sealed class ProjectedNamespaceApplier : IDisposable { accepted = rootLeaf ? _sink.TryApplyRootLeaf(exactParent, new ProjectedVariableDefinition(root!.Proof.Metadata.View.Realm, - root.Proof.LocalIdentifier, exactParent, root.Proof.Metadata, root.Proof.Generation, root.IsCurrent), Commit) + root.Proof.LocalIdentifier, exactParent, root.Proof.Metadata, root.Proof.Generation, root.IsCurrent) + { Historizing = ProjectedHistoryAccess.Advertises(root.Proof) }, Commit) : _sink.TryApply(exactParent, definitions, Commit); return accepted && committed && PageCurrent() ? ProjectionPageStatus.Ready : ProjectionPageStatus.Unavailable; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs index d52ccf107..6bd3be6fa 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs @@ -380,7 +380,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp if (!guard.IsCurrent() || caller is not null && !_policy.AuthorizeMapped(caller, OpcUaOperation.CreateMonitoredItems, mapped.View, serving, subject, resolver, lease)) return false; var newDefinition = new ProjectedVariableDefinition(definition.Realm, definition.LocalIdentifier, definition.Parent, - mapped, generation, guard.IsCurrent) { Lifetime = definition.Lifetime }; + mapped, generation, guard.IsCurrent) { Lifetime = definition.Lifetime, Historizing = ProjectedHistoryAccess.Advertises(renewed) }; return sink.TryRenewExact(nodeId, definition, newDefinition, () => { var duration = Clock.GetElapsedTime(started, Clock.GetTimestamp()); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataComposedBrowseWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataComposedBrowseWireTests.cs index 1b211ae7d..6ee16a0c6 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataComposedBrowseWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataComposedBrowseWireTests.cs @@ -362,7 +362,9 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests bool restrictToPlant = false, Action? onPublished = null, bool mountAtRealmRoot = false, long maxUnaryBytes = 8_000_000, bool allowWrite = false, IGrpcDataAdapterConnectionSource? connectionSource = null, int? staleTimeoutMilliseconds = null, Func? renewalSinkFactory = null, - Action? onCoordinator = null, int? localPermissions = null, bool allowHistory = false) + Action? onCoordinator = null, int? localPermissions = null, bool allowHistory = false, + Action? onHistory = null, + Action? configureMapping = null) { var ct = TestContext.Current.CancellationToken; var pki = Path.Combine(Path.GetTempPath(), $"composed-projection-{Guid.NewGuid():N}"); @@ -401,6 +403,7 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests mapping.AllowedOperations |= DataOperations.Read | DataOperations.Metadata; if (allowWrite) { mapping.AllowedOperations |= DataOperations.Write; mapping.WriteThrough = true; } if (allowHistory) mapping.AllowedOperations |= DataOperations.HistoryRead; + configureMapping?.Invoke(mapping); placements.Stage(attempt, [mapping], [Connection()]); coordinator.Complete(attempt, true).ShouldBeTrue(); var manager = started.Server.NodeManager!; @@ -427,6 +430,11 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests new DataBudget(TimeSpan.FromSeconds(5), 32, 128_000), 8); manager.ProjectedBrowseAccess = browse; manager.ProjectedDataAccess = access; + // H3: projected HistoryRead through the same deployed connections. + using var history = new ProjectedHistoryAccess(access, connections, + id => placements.TryGetHistoryAssemblyBudget(id, out var bytes) ? bytes : null, origin.Clock); + manager.ProjectedHistoryAccess = history; + onHistory?.Invoke(history, manager); var identifier = ProjectedDataIds.Identifier("map", root.Address); ((IProjectedNodeLookup)sink).TryGetNodeId(ProjectedDataIds.NamespaceUri(root.Realm), identifier, out var node).ShouldBeTrue(); var anchor = node.ShouldNotBeNull(); 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 5657a372d..e79f450f3 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 @@ -7,6 +7,8 @@ using ZB.MOM.WW.OtOpcUa.Core.Authorization; using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; + namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; [Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P04")] @@ -131,7 +133,8 @@ internal sealed class LocalDataFixture : IDisposable Func? targetSubscriptions = null, bool advanceAuthority = false, string role = "Primary", long servingGeneration = 0, bool nestedCatalog = false, bool nestedUnsCatalog = false, Func? writes = null, bool denyReadExport = false, - ManualTimeProvider? clock = null, string servingNode = "node-a", string servingIncarnation = "serving-1") + ManualTimeProvider? clock = null, string servingNode = "node-a", string servingIncarnation = "serving-1", + IOriginHistoryPort? history = null) { if (clock is not null) Clock = clock; Serving = Serving with { NodeId = servingNode, Incarnation = servingIncarnation, Role = role, ServingGeneration = servingGeneration }; @@ -158,6 +161,7 @@ internal sealed class LocalDataFixture : IDisposable Context = new("peer", key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(key), Clock.GetUtcNow().AddMinutes(10), Authority.Current.GenerationId); var operations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe; if (denyReadExport) operations &= ~DataOperations.Read; + if (history is not null) operations |= DataOperations.HistoryRead; var rootMetadata = new DataMetadata(Root, "Plant", "Folder", DataValueKind.Null, -1, [], false, operations, 1, null, null, false); var rawMetadata = new DataMetadata(Raw, "Speed", "Variable", DataValueKind.Int32, -1, [], true, operations, 1, Ticket.Key.StableSourceId, "rpm", false); var unsMetadata = rawMetadata with { View = Uns }; @@ -192,7 +196,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); + targetSubscriptions: targetSubscriptions, history: history); } internal IDataConnection Connection() => Services.Create(Context, new(DataTargetMode.Node, "cluster", Serving.NodeId)); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryCursorTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryCursorTests.cs new file mode 100644 index 000000000..b1bb046be --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryCursorTests.cs @@ -0,0 +1,54 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// H3 — the resume rule of a consumer Remote cursor: it resumes only under the caller, mapping revision, deployed +/// connection, projection generation, origin view and serving identity it was issued under. A mapping revision change, +/// a failover / origin restart (serving node, incarnation, generation or role), a projection rebuild or another caller +/// ⇒ the cursor never resumes (BadContinuationPointInvalid, origin token released). +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H3")] +public sealed class GrpcDataProjectedHistoryCursorTests +{ + private static readonly DataView View = new(new DataAddress("origin", "urn:raw", "string", "Plant/Speed"), DataRealm.Raw, null, 0, "Plant/Speed"); + private static readonly DataMetadata Metadata = new(View, "Speed", "Tag", DataValueKind.Int32, -1, [], false, + DataOperations.Read | DataOperations.HistoryRead, 1, null, null, false, History: new DataHistoryInfo(true)); + private static readonly ProjectedHistoryTarget Issued = new("map", 3, "link", Metadata, new ServingIdentity("node-a", "boot-1", "Primary", 5, 6, 2), 7); + private const string Caller = "peer\0key\0v1"; + + private static readonly Dictionary ChangeMap = new() + { + ["mapping revision change"] = (Issued with { MappingRevision = 4 }, Caller), + ["another mapping"] = (Issued with { MappingId = "other" }, Caller), + ["another connection"] = (Issued with { ConnectionId = "link-2" }, Caller), + ["projection rebuild"] = (Issued with { ProjectionGeneration = 8 }, Caller), + ["failover to the pair member"] = (Issued with { Serving = Issued.Serving with { NodeId = "node-b" } }, Caller), + ["origin restart"] = (Issued with { Serving = Issued.Serving with { Incarnation = "boot-2" } }, Caller), + ["serving generation bump"] = (Issued with { Serving = Issued.Serving with { ServingGeneration = 3 } }, Caller), + ["role change"] = (Issued with { Serving = Issued.Serving with { Role = "Secondary" } }, Caller), + ["another origin view"] = (Issued with { OriginMetadata = Metadata with { View = View with { Subject = "Plant/Other" } } }, Caller), + ["another caller"] = (Issued, "intruder\0key\0v1"), + ["a rotated credential"] = (Issued, "peer\0key\0v2"), + }; + + [Fact] + public void The_same_binding_resumes_even_when_only_the_catalog_or_authority_epoch_moved() + { + ProjectedHistoryAccess.CursorMatches(Issued, Caller, Issued, Caller).ShouldBeTrue(); + // A metadata renewal or ACL redeploy at the origin moves epochs, not the serving identity the token is bound to + // (the origin itself still refuses a token its own history epoch no longer matches). + ProjectedHistoryAccess.CursorMatches(Issued, Caller, + Issued with { Serving = Issued.Serving with { CatalogEpoch = 9, AuthorityEpoch = 9 } }, Caller).ShouldBeTrue(); + } + + public static TheoryData Changes => new(ChangeMap.Keys); + + [Theory] + [MemberData(nameof(Changes))] + public void Any_binding_change_refuses_the_resume(string change) => + ProjectedHistoryAccess.CursorMatches(Issued, Caller, ChangeMap[change].Now, ChangeMap[change].Caller).ShouldBeFalse(change); +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs index 2a82ab6b9..b97c47ce6 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs @@ -1,39 +1,390 @@ +using Microsoft.Extensions.Logging.Abstractions; using Opc.Ua; using Opc.Ua.Client; using Shouldly; using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using HistorianRead = ZB.MOM.WW.OtOpcUa.Core.Abstractions.HistoryReadResult; +using SdkDataValue = Opc.Ua.DataValue; namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; +/// +/// H3 — a real consumer OPC UA session HistoryReads a projected node through the real projection stack +/// ( + ) and a real in-process origin +/// ( over a real history port and its +/// PeerHistoryContinuationStore). Replaces the H2 pin that a projected node refused HistoryRead "until H3". +/// public sealed partial class GrpcDataConfiguredDiscoveryWireTests { - /// - /// H2 review 7: DataOperationPolicy now maps OPC UA HistoryRead to the mapping's HistoryRead bit, so a mapped - /// HistoryRead is AUTHORISABLE before H3 projects history. Pin that a projected node with the mapping bit AND a local - /// HistoryRead grant still answers a clean refusal — never data, never a fault — until H3. - /// + private static readonly DateTime HistoryT0 = new(2026, 11, 20, 10, 0, 0, DateTimeKind.Utc); + [Fact(Timeout = 90000)] - [Trait("Phase", "H2")] - public async Task HistoryRead_on_a_projected_node_stays_a_clean_refusal_until_H3() + [Trait("Phase", "H3")] + [Trait("Phase", "H2")] // replaces the H2 pin "a projected node refuses HistoryRead until H3" + public async Task Granted_projected_HistoryRead_is_served_verbatim_and_pages_to_completion_through_the_origin() { - using var origin = new LocalDataFixture(servingGeneration: 1); + await using var originServer = await HistoryOrigin.StartAsync(7); + using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); + var connections = new PersistentConnections(origin); await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => { var client = (SessionClient)session; await BrowseAll(client, anchor, 1); - var details = new ReadRawModifiedDetails + var values = new List(); + var cp = default(ByteString); + var pages = 0; + do { - StartTime = DateTime.UtcNow.AddHours(-1), EndTime = DateTime.UtcNow, NumValuesPerNode = 10, - IsReadModified = false, ReturnBounds = false, - }; - var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(details), TimestampsToReturn.Both, false, - [new HistoryReadValueId { NodeId = anchor }], TestContext.Current.CancellationToken); - var result = response.Results.ToArray()!.Single(); - // Pinned: the projected variable carries no HistoryRead access-level bit, so the SDK refuses before any history code. - result.StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code); - (result.HistoryData.IsNull || ExtensionObject.ToEncodeable(result.HistoryData) is not HistoryData { DataValues.Count: > 0 }) - .ShouldBeTrue("no data is served from a projected node before H3"); + var result = await RawHistory(client, anchor, 3, cp); + StatusCode.IsGood(result.StatusCode).ShouldBeTrue(result.StatusCode.ToString()); + values.AddRange(Values(result)); + cp = result.ContinuationPoint; + pages++; + } while (!cp.IsEmpty && pages < 10); + + values.Select(v => SdkValueBoundary.ToClr(v.WrappedValue)).ShouldBe(Enumerable.Range(0, 7).Cast()); + values.Select(v => v.SourceTimestamp.ToDateTime()).ShouldBe(Enumerable.Range(0, 7).Select(i => HistoryT0.AddSeconds(i))); + pages.ShouldBe(3); + origin.Services.HistoryOpenContinuations.ShouldBe(0, "a page-through to completion leaves nothing open at the origin"); + }, localPermissions: 15, allowHistory: true, connectionSource: connections); + } + + [Fact(Timeout = 90000)] + [Trait("Phase", "H3")] + [Trait("Phase", "H2")] // replaces the H2 pin "a projected node refuses HistoryRead until H3" + public async Task Without_the_local_HistoryRead_grant_on_the_mapping_scope_it_is_BadUserAccessDenied_and_unsent() + { + await using var originServer = await HistoryOrigin.StartAsync(7); + using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var result = await RawHistory(client, anchor, 3, default); + result.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code); result.ContinuationPoint.IsEmpty.ShouldBeTrue(); - }, localPermissions: 15, allowHistory: true); + originServer.Source.Calls.ShouldBe(0); + }, localPermissions: 7, allowHistory: true, connectionSource: new PersistentConnections(origin)); + } + + [Fact(Timeout = 90000)] + [Trait("Phase", "H3")] + public async Task Consumer_session_close_releases_the_origin_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); + var page = await RawHistory(client, anchor, 2, default); + page.ContinuationPoint.IsEmpty.ShouldBeFalse(); + origin.Services.HistoryOpenContinuations.ShouldBe(1); + await session.CloseAsync(TestContext.Current.CancellationToken); + await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0); + origin.Services.HistoryOpenContinuations.ShouldBe(0, "the SDK disposed the Remote point and the release reached the origin"); + history!.ReleaseCallsForTests.ShouldBe(1); + }, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin), + onHistory: (h, _) => history = h); + } + + [Fact(Timeout = 90000)] + [Trait("Phase", "H3")] + public async Task ReleaseContinuationPoints_forwards_one_release_and_the_point_is_then_invalid() + { + 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); + var page = await RawHistory(client, anchor, 2, default); + origin.Services.HistoryOpenContinuations.ShouldBe(1); + var released = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(2)), TimestampsToReturn.Both, true, + [new HistoryReadValueId { NodeId = anchor, ContinuationPoint = page.ContinuationPoint }], TestContext.Current.CancellationToken); + StatusCode.IsGood(released.Results[0].StatusCode).ShouldBeTrue(); + await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0); + origin.Services.HistoryOpenContinuations.ShouldBe(0); + var resumed = await RawHistory(client, anchor, 2, page.ContinuationPoint); + resumed.StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); + }, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin), onHistory: (h, _) => history = h); + } + + [Fact(Timeout = 90000)] + [Trait("Phase", "H3")] + public async Task A_resume_after_lease_expiry_or_an_origin_rebuild_epoch_bump_is_invalid_and_a_fresh_read_succeeds() + { + await using var originServer = await HistoryOrigin.StartAsync(7); + using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); + var connections = new PersistentConnections(origin); + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + + // Lease expiry / redeployment: the deployed connection (route) is replaced — its tokens never resume. + var page = await RawHistory(client, anchor, 2, default); + connections.Rotate(); + (await RawHistory(client, anchor, 2, page.ContinuationPoint)).StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); + var fresh = await RawHistory(client, anchor, 2, default); + StatusCode.IsGood(fresh.StatusCode).ShouldBeTrue(); + + // Origin rebuild: its history epoch moves (a removal), so the origin itself refuses the resumed token. + originServer.BumpEpoch(); + (await RawHistory(client, anchor, 2, fresh.ContinuationPoint)).StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); + StatusCode.IsGood((await RawHistory(client, anchor, 2, default)).StatusCode).ShouldBeTrue(); + }, localPermissions: 15, allowHistory: true, connectionSource: connections); + } + + [Fact(Timeout = 90000)] + [Trait("Phase", "H3")] + public async Task Uncapped_raw_returns_the_origin_continuation_and_aggregates_are_refused_both_ways() + { + await using var originServer = await HistoryOrigin.StartAsync(25, maxRawPerRead: 10); + originServer.Source.Aggregates = new HashSet { HistoryAggregateType.Average }; + using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + // NumValuesPerNode = 0: the origin pages at its ceiling and the consumer hands back its continuation (Part 11). + var uncapped = await RawHistory(client, anchor, 0, default); + StatusCode.IsGood(uncapped.StatusCode).ShouldBeTrue(); + uncapped.ContinuationPoint.IsEmpty.ShouldBeFalse(); + Values(uncapped).Count.ShouldBeLessThan(25); + + // The origin refuses an aggregate its backend does not serve. + var refused = await ProcessedHistory(client, anchor, ObjectIds.AggregateFunction_Count); + refused.StatusCode.Code.ShouldBe(StatusCodes.BadAggregateNotSupported.Code); + // The consumer refuses an aggregate it cannot name, unsent. + var calls = originServer.Source.Calls; + var unknown = await ProcessedHistory(client, anchor, new NodeId("no-such-aggregate", 1)); + unknown.StatusCode.Code.ShouldBe(StatusCodes.BadAggregateNotSupported.Code); + originServer.Source.Calls.ShouldBe(calls); + // A served aggregate passes through. + var average = await ProcessedHistory(client, anchor, ObjectIds.AggregateFunction_Average); + StatusCode.IsGood(average.StatusCode).ShouldBeTrue(average.StatusCode.ToString()); + }, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin)); + } + + [Theory(Timeout = 90000)] + [Trait("Phase", "H3")] + [InlineData(1_000_000, 3)] + [InlineData(25_000, 2)] // ≈ 288 B a value × 40 per node: two nodes fit, the third is refused + [InlineData(15_000, 1)] + [InlineData(1_200, 0)] + public async Task The_per_request_assembly_budget_is_shared_across_the_batch(int budget, int expectedGood) + { + await using var originServer = await HistoryOrigin.StartAsync(7, extra: 2); + using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1, history: originServer.Port); + await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + var children = (await BrowseAll(client, anchor, 10)) + .Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray(); + children.Length.ShouldBe(3); + var details = new ReadAtTimeDetails { ReqTimes = Enumerable.Range(0, 40).Select(i => (DateTimeUtc)HistoryT0.AddSeconds(i)).ToArray() }; + var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(details), TimestampsToReturn.Both, false, + children.Select(c => new HistoryReadValueId { NodeId = c }).ToArray(), TestContext.Current.CancellationToken); + var results = response.Results.ToArray()!; + var statuses = results.Select(r => r.StatusCode.Code).ToArray(); + statuses.Count(s => StatusCode.IsGood(s)).ShouldBe(expectedGood, string.Join(",", statuses.Select(x => x.ToString("X8")))); + foreach (var r in results.Where(r => !StatusCode.IsGood(r.StatusCode))) + { + r.StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code); + Values(r).ShouldBeEmpty("never a partial answer under an error status"); + } + foreach (var r in results.Where(r => StatusCode.IsGood(r.StatusCode))) Values(r).Count.ShouldBe(40); + // The budget is consumed in request order: once a node does not fit, every later node is refused too. + statuses.TakeWhile(x => StatusCode.IsGood(x)).Count().ShouldBe(expectedGood); + }, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin), + configureMapping: m => m.MaxHistoryAssemblyBytesPerRequest = budget); + } + + [Theory(Timeout = 90000)] + [Trait("Phase", "H3")] + [InlineData(false)] + [InlineData(true)] + public async Task Historizing_and_the_HistoryRead_bit_follow_the_mapping_grant_and_never_HistoryWrite(bool granted) + { + await using var originServer = await HistoryOrigin.StartAsync(7); + using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var read = await client.ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Neither, + [new ReadValueId { NodeId = anchor, AttributeId = Attributes.Historizing }, + new ReadValueId { NodeId = anchor, AttributeId = Attributes.AccessLevel }], TestContext.Current.CancellationToken); + read.Results[0].WrappedValue.TryGetValue(out bool historizing).ShouldBeTrue(); + historizing.ShouldBe(granted); + read.Results[1].WrappedValue.TryGetValue(out byte level).ShouldBeTrue(); + ((level & AccessLevels.HistoryRead) != 0).ShouldBe(granted); + (level & AccessLevels.HistoryWrite).ShouldBe((byte)0); + if (granted) return; + var result = await RawHistory(client, anchor, 3, default); + result.StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code); + originServer.Source.Calls.ShouldBe(0); + }, localPermissions: 15, allowHistory: granted, connectionSource: new PersistentConnections(origin)); + } + + // ------------------------------------------------------------------------------------------------------------------ + + private static ReadRawModifiedDetails RawDetails(uint count) => new() + { + StartTime = HistoryT0.AddSeconds(-1), EndTime = HistoryT0.AddHours(1), NumValuesPerNode = count, IsReadModified = false, ReturnBounds = false, + }; + + private static async Task RawHistory(SessionClient client, NodeId node, uint count, ByteString cp) + { + var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(count)), TimestampsToReturn.Both, false, + [new HistoryReadValueId { NodeId = node, ContinuationPoint = cp }], TestContext.Current.CancellationToken); + return response.Results.ToArray()!.Single(); + } + + private static async Task ProcessedHistory(SessionClient client, NodeId node, NodeId aggregate) + { + var details = new ReadProcessedDetails + { + StartTime = HistoryT0, EndTime = HistoryT0.AddMinutes(1), ProcessingInterval = 10_000, AggregateType = [aggregate], + AggregateConfiguration = new AggregateConfiguration { UseServerCapabilitiesDefaults = true }, + }; + var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(details), TimestampsToReturn.Both, false, + [new HistoryReadValueId { NodeId = node }], TestContext.Current.CancellationToken); + return response.Results.ToArray()!.Single(); + } + + private static IReadOnlyList Values(Opc.Ua.HistoryReadResult result) => + result.HistoryData.IsNull || ExtensionObject.ToEncodeable(result.HistoryData) is not HistoryData data ? [] : data.DataValues.ToArray() ?? []; + + private static async Task AwaitReleases(ProjectedHistoryAccess history, Func done) + { + for (var i = 0; i < 200 && !done(); i++) + { + await history.FlushReleasesForTestsAsync(); + if (!done()) await Task.Delay(10, TestContext.Current.CancellationToken); + } + } + + /// One long-lived origin connection, as a deployed gRPC connection is; replaces it (a redeploy). + private sealed class PersistentConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource + { + private (IDataConnection Connection, object Route)? _current; + private readonly object _gate = new(); + + public void Rotate() + { + lock (_gate) + { + if (_current is { } old) _ = old.Connection.DisposeAsync(); + _current = null; + } + } + + public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken) + { + if (connectionId != "link") return ValueTask.FromResult(null); + lock (_gate) + { + _current ??= (peer.Connection(), new object()); + return ValueTask.FromResult(new Borrowed(_current.Value.Connection, _current.Value.Route)); + } + } + + private sealed class Borrowed(IDataConnection connection, object route) : IGrpcDataAdapterConnectionLease + { + public IDataConnection Connection => connection; + public CancellationToken CancellationToken => CancellationToken.None; + public object? RouteIdentity => route; + public ValueTask DisposeAsync() => ValueTask.CompletedTask; // non-owning, like a deployment lease + } + } + + /// A real origin node manager with a historized raw Plant/Driver/Device/Speed behind a real history port. + private sealed class HistoryOrigin : IAsyncDisposable + { + private readonly OpcUaApplicationHost _host; + private readonly string _pki; + private readonly OtOpcUaNodeManager _nm; + public SeriesSource Source { get; } + public OriginHistoryPort Port { get; } + + private HistoryOrigin(OpcUaApplicationHost host, string pki, OtOpcUaNodeManager nm, SeriesSource source) + { _host = host; _pki = pki; _nm = nm; Source = source; Port = new OriginHistoryPort(nm); } + + public static async Task StartAsync(int samples, int maxRawPerRead = 0, int extra = 0) + { + var pki = Path.Combine(Path.GetTempPath(), $"h3-origin-{Guid.NewGuid():N}"); + var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions + { + ApplicationName = "H3Origin", ApplicationUri = $"urn:h3-origin:{Guid.NewGuid():N}", OpcUaPort = port, + PublicHostname = "127.0.0.1", PkiStoreRoot = pki, EnabledSecurityProfiles = [OpcUaSecurityProfile.None], + }, NullLogger.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken); + var nm = started.Server.NodeManager!; + var source = new SeriesSource(Enumerable.Range(0, samples) + .Select(i => new DataValueSnapshot(i, 0, HistoryT0.AddSeconds(i), HistoryT0.AddSeconds(i))).ToArray()) { MaxRawValuesPerRead = maxRawPerRead }; + nm.HistorianDataSource = source; + nm.EnsureVariable("Plant/Driver/Device/Speed", null, "Speed", "Int32", false, AddressSpaceRealm.Raw, historianTagname: "speed"); + nm.EnsureVariable("Plant/Driver/Device/Other", null, "Other", "Int32", false, AddressSpaceRealm.Raw); + for (var i = 0; i < extra; i++) + nm.EnsureVariable("Plant/Driver/Device/Speed" + i, null, "Speed" + i, "Int32", false, AddressSpaceRealm.Raw, historianTagname: "speed" + i); + return new HistoryOrigin(started.Host, pki, nm, source); + } + + public void BumpEpoch() => _nm.RemoveVariableNode("Plant/Driver/Device/Other", AddressSpaceRealm.Raw).ShouldBeTrue(); + + public async ValueTask DisposeAsync() + { + await _host.DisposeAsync(); + if (Directory.Exists(_pki)) try { Directory.Delete(_pki, recursive: true); } catch (IOException) { } + } + } + + private sealed class SeriesSource(IReadOnlyList series) : IHistorianDataSource + { + private int _calls; + public int Calls => Volatile.Read(ref _calls); + public int MaxRawValuesPerRead { get; init; } + public IReadOnlySet Aggregates { get; set; } = HistoryAggregateTypes.All; + public IReadOnlySet SupportedAggregates => Aggregates; + public bool SupportsReverseRaw => true; + + public Task ReadRawAsync(string fullReference, DateTime startUtc, DateTime endUtc, uint maxValuesPerNode, + CancellationToken cancellationToken) + { + Interlocked.Increment(ref _calls); + IEnumerable window = startUtc <= endUtc + ? series.Where(s => s.SourceTimestampUtc >= startUtc && s.SourceTimestampUtc < endUtc) + : series.Where(s => s.SourceTimestampUtc <= startUtc && s.SourceTimestampUtc > endUtc).Reverse(); + return Task.FromResult(new HistorianRead((maxValuesPerNode == 0 ? window : window.Take((int)maxValuesPerNode)).ToList(), null)); + } + + public Task ReadProcessedAsync(string fullReference, DateTime startUtc, DateTime endUtc, TimeSpan interval, + HistoryAggregateType aggregate, CancellationToken cancellationToken) + { + Interlocked.Increment(ref _calls); + return Task.FromResult(new HistorianRead([new DataValueSnapshot(3.0, 0, startUtc, startUtc)], null)); + } + + public Task ReadAtTimeAsync(string fullReference, IReadOnlyList timestampsUtc, CancellationToken cancellationToken) + { + Interlocked.Increment(ref _calls); + return Task.FromResult(new HistorianRead(timestampsUtc.Select(t => new DataValueSnapshot(1, 0, t, t)).ToList(), null)); + } + + public Task ReadEventsAsync( + string? sourceName, DateTime startUtc, DateTime endUtc, int maxEvents, CancellationToken cancellationToken) => + Task.FromResult(new HistoricalEventsResult(Array.Empty(), null)); + + public HistorianHealthSnapshot GetHealthSnapshot() => NullHistorianDataSource.Instance.GetHealthSnapshot(); + + public void Dispose() { } } } From 07eeea2bd572b5f81a0f21594889d8ba56ac8436 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 00:28:36 -0500 Subject: [PATCH 03/25] test(grpc-data): H3 manifest key and OI end-to-end projected history wire tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A real consumer OPC UA session HistoryReads a projected variable whose projected half is forwarded to a real origin node manager's history port: mixed batch keeps slots, page-through to completion, single use, session close returns the origin store count to 0, mapped grant with ACLs on and off. Manifest key H3 (OpcUaServer.Tests + Runtime.Tests; OI runs separately — the runner accepts unit projects only). --- scripts/validation/grpc-data/unit-phases.json | 31 +++ .../GrpcDataProjectedHistoryWireTests.cs | 236 ++++++++++++++++++ 2 files changed, 267 insertions(+) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataProjectedHistoryWireTests.cs diff --git a/scripts/validation/grpc-data/unit-phases.json b/scripts/validation/grpc-data/unit-phases.json index d9e7d4423..9dc13d469 100644 --- a/scripts/validation/grpc-data/unit-phases.json +++ b/scripts/validation/grpc-data/unit-phases.json @@ -888,5 +888,36 @@ "GrpcDataEditorValidationTests" ] } + ], + "H3": [ + { + "project": "tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=H3)|FullyQualifiedName~.HistoryReadPortParityTests.|FullyQualifiedName~.SessionHistoryContinuationStoreTests.|FullyQualifiedName~.NodeManagerHistoryReadTests.|FullyQualifiedName~.NodeManagerHistoryReadPagingTests.|FullyQualifiedName~.NodeManagerAclEnforcementTests.|FullyQualifiedName~.GrpcDataMappedSubjectTests.|FullyQualifiedName~.GrpcDataSdkProjectionTests.", + "new_classes": [ + "ProjectedHistoryReadTests" + ], + "existing_classes": [ + "HistoryReadPortParityTests", + "SessionHistoryContinuationStoreTests", + "NodeManagerHistoryReadTests", + "NodeManagerHistoryReadPagingTests", + "NodeManagerAclEnforcementTests", + "GrpcDataMappedSubjectTests", + "GrpcDataSdkProjectionTests" + ] + }, + { + "project": "tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=H3)|FullyQualifiedName~.GrpcDataHistoryLeaseTests.|FullyQualifiedName~.GrpcDataHistoryClientTests.|FullyQualifiedName~.GrpcDataProjectedAccessTests.", + "new_classes": [ + "GrpcDataProjectedHistoryCursorTests", + "GrpcDataConfiguredDiscoveryWireTests" + ], + "existing_classes": [ + "GrpcDataHistoryLeaseTests", + "GrpcDataHistoryClientTests", + "GrpcDataProjectedAccessTests" + ] + } ] } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataProjectedHistoryWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataProjectedHistoryWireTests.cs new file mode 100644 index 000000000..f92e669a7 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataProjectedHistoryWireTests.cs @@ -0,0 +1,236 @@ +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; +using HistorianRead = ZB.MOM.WW.OtOpcUa.Core.Abstractions.HistoryReadResult; +using SdkDataValue = Opc.Ua.DataValue; +using static ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests.ServerEventRig; +using static ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests.WarmRedundancyWireTests; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests; + +/// +/// H3 end to end over the wire: a real consumer OPC UA session HistoryReads a projected variable on a real consumer SDK +/// server, whose projected half is forwarded to a real in-process ORIGIN node manager through its real history port +/// (, PeerHistoryContinuationStore). Proves the Remote cursor in the real SDK +/// session store (resume, single use, session close ⇒ the origin store count returns to 0), the mapped HistoryRead gate +/// with ACLs on and off, and that a mixed local + projected batch keeps every slot. +/// +[Trait("Category", "Integration"), Trait("Feature", "GrpcData"), Trait("Phase", "H3")] +public sealed class GrpcDataProjectedHistoryWireTests +{ + private static readonly DateTime T0 = new(2026, 11, 20, 10, 0, 0, DateTimeKind.Utc); + + [Theory(Timeout = 90000)] + [InlineData(false)] + [InlineData(true)] + public async Task Projected_history_pages_through_the_origin_and_a_mixed_batch_keeps_its_slots(bool aclEnabled) + { + var ct = Deadline(); + await using var origin = await StartModeAsync("H3Origin", "None", ct); + origin.Nm.HistorianDataSource = new Series(7, offset: 100); + origin.Nm.EnsureVariable("Plant/Speed", null, "Speed", "Int32", false, AddressSpaceRealm.Raw, historianTagname: "speed"); + await using var consumer = await StartModeAsync("H3Consumer", "None", ct); + consumer.Nm.HistorianDataSource = new Series(3, offset: 0); + var mapped = Setup(consumer, aclEnabled, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead); + var bridge = new OriginBridge(origin.Nm, mapped.Identifier, "Plant/Speed"); + consumer.Nm.ProjectedHistoryAccess = bridge; + consumer.Nm.EnsureVariable("Plant/Local", "Plant", "Local", "Int32", false, AddressSpaceRealm.Raw, historianTagname: "local"); + var local = consumer.Nm.TryGetVariable("Plant/Local", AddressSpaceRealm.Raw)!.NodeId; + + using var session = await consumer.ConnectAsync(anonymous: true, ct); + var client = (SessionClient)session; + // A mixed batch [projected, local]: each slot holds its own source's answer. + var mixed = await Raw(client, [mapped.Node, local], 3, [default, default], ct); + IntValues(mixed[0]).ShouldBe([100, 101, 102]); + IntValues(mixed[1]).ShouldBe([0, 1, 2]); + mixed[0].ContinuationPoint.IsEmpty.ShouldBeFalse(); + bridge.Cursors.Count.ShouldBe(1); + + // Resume the projected node to completion through the real SDK session store. + var all = IntValues(mixed[0]).ToList(); + var cp = mixed[0].ContinuationPoint; + while (!cp.IsEmpty) + { + var page = (await Raw(client, [mapped.Node], 3, [cp], ct))[0]; + StatusCode.IsGood(page.StatusCode).ShouldBeTrue(); + all.AddRange(IntValues(page)); + cp = page.ContinuationPoint; + } + all.ShouldBe([100, 101, 102, 103, 104, 105, 106]); + bridge.Cursors.Count.ShouldBe(0); + // Single use: the first page's point is gone. + (await Raw(client, [mapped.Node], 3, [mixed[0].ContinuationPoint], ct))[0].StatusCode.Code + .ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); + } + + [Fact(Timeout = 90000)] + public async Task Closing_the_consumer_session_releases_the_origin_continuations() + { + var ct = Deadline(); + await using var origin = await StartModeAsync("H3OriginClose", "None", ct); + origin.Nm.HistorianDataSource = new Series(7, offset: 0); + origin.Nm.EnsureVariable("Plant/Speed", null, "Speed", "Int32", false, AddressSpaceRealm.Raw, historianTagname: "speed"); + await using var consumer = await StartModeAsync("H3ConsumerClose", "None", ct); + var mapped = Setup(consumer, aclEnabled: true, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead); + var bridge = new OriginBridge(origin.Nm, mapped.Identifier, "Plant/Speed"); + consumer.Nm.ProjectedHistoryAccess = bridge; + + var session = await consumer.ConnectAsync(anonymous: true, ct); + var page = (await Raw((SessionClient)session, [mapped.Node], 2, [default], ct))[0]; + page.ContinuationPoint.IsEmpty.ShouldBeFalse(); + bridge.Cursors.Count.ShouldBe(1, "the origin holds the page cursor"); + await session.CloseAsync(ct); + session.Dispose(); + for (var i = 0; i < 200 && bridge.Cursors.Count != 0; i++) await Task.Delay(10, ct); + bridge.Cursors.Count.ShouldBe(0, "the SDK disposed the Remote point on session close and the release reached the origin"); + bridge.Releases.ShouldBe(1); + } + + [Theory(Timeout = 90000)] + [InlineData(false)] + [InlineData(true)] + public async Task Without_a_local_HistoryRead_grant_on_the_mapping_scope_it_is_BadUserAccessDenied_unsent(bool aclEnabled) + { + var ct = Deadline(); + await using var origin = await StartModeAsync("H3OriginDeny", "None", ct); + origin.Nm.HistorianDataSource = new Series(7, offset: 0); + origin.Nm.EnsureVariable("Plant/Speed", null, "Speed", "Int32", false, AddressSpaceRealm.Raw, historianTagname: "speed"); + await using var consumer = await StartModeAsync("H3ConsumerDeny", "None", ct); + var mapped = Setup(consumer, aclEnabled, NodePermissions.Browse | NodePermissions.Read); + var bridge = new OriginBridge(origin.Nm, mapped.Identifier, "Plant/Speed"); + consumer.Nm.ProjectedHistoryAccess = bridge; + using var session = await consumer.ConnectAsync(anonymous: true, ct); + var result = (await Raw((SessionClient)session, [mapped.Node], 2, [default], ct))[0]; + result.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code); + bridge.Calls.ShouldBe(0); + } + + // ------------------------------------------------------------------------------------------------------------------ + + private static (NodeId Node, string Identifier) Setup(ServerEventRig consumer, bool aclEnabled, NodePermissions permissions) + { + consumer.Nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); + var parent = consumer.Nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; + var scopePaths = new Dictionary> + { + [new(NodeAclScopeKind.RawFolder, "plant")] = [new([NodeAclRealms.Raw, "Plant"])], + }; + var grant = new NodeAcl { NodeAclId = "h3", ClusterId = ServerEventRig.Cluster, Principal = OpcUaPrincipals.Anonymous, + ScopeKind = NodeAclScopeKind.RawFolder, ScopeId = "plant", PermissionFlags = permissions }; + var state = consumer.Enforce(aclEnabled, [Key()], scopePaths, grant); + var origin = new DataAddress("origin", "urn:raw", "string", "Plant/Speed"); + var view = new DataView(origin, DataRealm.Raw, "mapping", 1, "Plant/Speed"); + var metadata = new DataMetadata(view, "Speed", "Tag", DataValueKind.Int32, -1, [], false, + DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead, 1, null, null, false, History: new DataHistoryInfo(true)); + var identifier = ProjectedDataIds.Identifier("mapping", origin); + consumer.Nm.TryEnsureProjectedVariable(new ProjectedVariableDefinition(DataRealm.Raw, identifier, parent, metadata, 1, () => true) + { Historizing = true }, out var node).ShouldBeTrue(); + var lease = new Lease(); + var subject = new MappedNamespaceSubject(view, new NodeScope { ClusterId = ServerEventRig.Cluster, Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Speed"] }, + ["plant", "mapping"], lease.Serving, DataOperations.Browse | DataOperations.Read | DataOperations.HistoryRead, WriteThrough: false); + var resolver = new MappedSubjectResolver([subject], catalogEpoch: 7, new Catalog(state)); + consumer.Nm.MappedSubjectResolver = (realm, id) => realm == AddressSpaceRealm.Raw && id == identifier + ? MappedNodeResolution.Mapped(view, subject, resolver, lease) : MappedNodeResolution.Local; + return (node!.Value, identifier); + } + + private static async Task Raw(SessionClient client, NodeId[] nodes, uint count, ByteString[] cps, CancellationToken ct) + { + var details = new ReadRawModifiedDetails + { + StartTime = T0.AddSeconds(-1), EndTime = T0.AddHours(1), NumValuesPerNode = count, IsReadModified = false, ReturnBounds = false, + }; + var response = await client.HistoryReadAsync(H(), new ExtensionObject(details), TimestampsToReturn.Both, false, + nodes.Select((n, i) => new HistoryReadValueId { NodeId = n, ContinuationPoint = cps[i] }).ToArray(), ct); + return response.Results.ToArray()!; + } + + private static int[] IntValues(Opc.Ua.HistoryReadResult result) => + (result.HistoryData.IsNull || ExtensionObject.ToEncodeable(result.HistoryData) is not HistoryData data ? [] : data.DataValues.ToArray() ?? []) + .Select(v => (int)SdkValueBoundary.ToClr(v.WrappedValue)!).ToArray(); + + /// + /// The consumer's projected half wired straight onto a real origin's history port: one peer cursor store, as one + /// authenticated principal on one connection; a release drops the origin token. + /// + private sealed class OriginBridge(OtOpcUaNodeManager origin, string projectedIdentifier, string originIdentifier) : IProjectedHistoryAccess + { + private readonly OriginHistoryPort _port = new(origin); + private int _calls, _releases; + public OriginHistoryCursors Cursors { get; } = new("peer", "channel-1", 16); + public int Calls => Volatile.Read(ref _calls); + public int Releases => Volatile.Read(ref _releases); + + public async Task> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details, + IReadOnlyList nodes, TimeSpan deadline, CancellationToken cancellationToken) + { + Interlocked.Increment(ref _calls); + var items = nodes.Select(n => new OriginHistoryItem(AddressSpaceRealm.Raw, originIdentifier, "export-view", n.AggregateId, + (n.Resume as Cursor)?.Token)).ToArray(); + // A resume resends the ORIGINAL details (the peer store binds their hash), as ProjectedHistoryAccess does. + var sent = nodes.Select(n => n.Resume).OfType().FirstOrDefault()?.Details ?? details; + var outcomes = await _port.ReadAsync(Cursors, "peer", () => "serving-1", sent, items, cancellationToken); + details = sent; + return outcomes.Select(o => new ProjectedHistoryOutcome(o.StatusCode, o.Samples, + o.Continuation is { } token ? new Cursor(this, projectedIdentifier, token, details) : null)).ToArray(); + } + + private sealed class Cursor(OriginBridge owner, string identifier, byte[] token, DataHistoryDetails details) + : ProjectedHistoryContinuation(DataRealm.Raw, identifier) + { + public byte[] Token => token; + public DataHistoryDetails Details => details; + protected override void OnRelease() + { + Interlocked.Increment(ref owner._releases); + owner.Cursors.Release(token); + } + } + } + + private sealed class Series(int count, int offset) : IHistorianDataSource + { + private readonly DataValueSnapshot[] _series = Enumerable.Range(0, count) + .Select(i => new DataValueSnapshot(offset + i, 0, T0.AddSeconds(i), T0.AddSeconds(i))).ToArray(); + public bool SupportsReverseRaw => true; + + public Task ReadRawAsync(string fullReference, DateTime startUtc, DateTime endUtc, uint maxValuesPerNode, CancellationToken ct) + { + var window = _series.Where(s => s.SourceTimestampUtc >= startUtc && s.SourceTimestampUtc < endUtc); + return Task.FromResult(new HistorianRead((maxValuesPerNode == 0 ? window : window.Take((int)maxValuesPerNode)).ToList(), null)); + } + + public Task ReadProcessedAsync(string fullReference, DateTime startUtc, DateTime endUtc, TimeSpan interval, + HistoryAggregateType aggregate, CancellationToken ct) => Task.FromResult(new HistorianRead([], null)); + + public Task ReadAtTimeAsync(string fullReference, IReadOnlyList timestampsUtc, CancellationToken ct) => + Task.FromResult(new HistorianRead([], null)); + + public Task ReadEventsAsync(string? sourceName, DateTime startUtc, DateTime endUtc, int maxEvents, CancellationToken ct) => + Task.FromResult(new HistoricalEventsResult(Array.Empty(), null)); + + public HistorianHealthSnapshot GetHealthSnapshot() => NullHistorianDataSource.Instance.GetHealthSnapshot(); + public void Dispose() { } + } + + private sealed class Catalog(DataPlaneAuthorityState state) : IDataMappedCatalogAuthority + { + public long CatalogEpoch => 1; + public long AuthorityEpoch => state.Current.GenerationId; + public bool IsActive => true; + } + + private sealed class Lease : IDataAuthorizationLease + { + public ServingIdentity Serving { get; } = new("node-a", "incarnation-a", "Primary", 7, 1); + public bool IsValid => true; + } +} From 3b630ab1a91b99d9277e666d2295ce9f0207944d Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 00:36:47 -0500 Subject: [PATCH 04/25] feat(cli): historyread --page-size/--pause-after-page/--abandon/--release and --at-time Hand-paged raw reads in one session print each page's status and continuation (a refused resume is printed, not thrown), can hold the session across a failover (resume when a file appears, then one fresh read), abandon a point to the session close or release it explicitly. --at-time reads AtTime and prints value types. Backed by IOpcUaClientService.HistoryReadPageAsync (default-throwing interface member so existing fakes compile). Used by the gRPC data H3 live gate on projected nodes. --- docs/Client.CLI.md | 22 +++ .../Commands/HistoryReadCommand.cs | 168 ++++++++++++++++++ .../Adapters/DefaultSessionAdapter.cs | 11 ++ .../Adapters/ISessionAdapter.cs | 13 ++ .../IOpcUaClientService.cs | 14 ++ .../Models/HistoryPage.cs | 13 ++ .../OpcUaClientService.cs | 9 + .../Fakes/FakeOpcUaClientService.cs | 15 ++ .../HistoryReadPagedCommandTests.cs | 126 +++++++++++++ 9 files changed, 391 insertions(+) create mode 100644 src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Models/HistoryPage.cs create mode 100644 tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/HistoryReadPagedCommandTests.cs diff --git a/docs/Client.CLI.md b/docs/Client.CLI.md index 5f71be86b..fa1e131f8 100644 --- a/docs/Client.CLI.md +++ b/docs/Client.CLI.md @@ -259,6 +259,28 @@ continuation points up to `--max`. `--events` cannot be combined with `--modifie | `--events` | Read event history (Part 11 HistoryReadEvents) from an event notifier instead of raw samples | | `--fields` | With `--events`: comma-separated event fields to select (default `EventId,EventType,Time,SourceName,Severity,Message,ConditionName,SourceNode`) | | `--of-type` | With `--events`: keep only events of this type or a subtype (an `OfType` where-clause), e.g. `i=2955` | +| `--at-time` | HistoryRead-AtTime at these comma-separated ISO 8601 UTC times; prints the status, the rows and each value's CLR type | +| `--page-size` | Raw only: page by hand at this `NumValuesPerNode`, printing every page as `Page k: values= continuation=[ resumed]` (a refused page is printed, never thrown) | +| `--pause-after-page` / `--resume-when-file` / `--pause-timeout` | With `--page-size`: after page k hold the session (and its continuation point) until the file exists, then resume | +| `--fresh-after-failure` | With `--page-size`: after a refused resumed page, issue one fresh read of the same window (`Fresh: …`) | +| `--abandon-after-page` | With `--page-size`: stop after page k WITHOUT releasing its continuation point — the disconnect (session close) releases it | +| `--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 | + +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 +`BadContinuationPointInvalid` while `--fresh-after-failure` shows the fresh read moving to the new endpoint. + +```bash +# Page 1 of a projected node, hold the session, resume once /tmp/go exists; then one fresh read if the resume is refused +otopcua-cli historyread -u opc.tcp://localhost:4841/OtOpcUa -U apikey -P "$KEY" -n "$P" \ + --start 2026-11-20T10:00:00Z --end 2026-11-20T11:00:00Z --page-size 5 \ + --pause-after-page 1 --resume-when-file /tmp/go --fresh-after-failure +# AtTime on an integer node +otopcua-cli historyread -u opc.tcp://localhost:4841/OtOpcUa -U apikey -P "$KEY" -n "$P" \ + --at-time 2026-11-20T10:00:00Z,2026-11-20T10:00:05Z +``` ### historyupdate diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/HistoryReadCommand.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/HistoryReadCommand.cs index 7d087c8eb..804faa364 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/HistoryReadCommand.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/HistoryReadCommand.cs @@ -83,6 +83,152 @@ public class HistoryReadCommand : CommandBase [CommandOption("of-type", Description = "With --events: keep only events of this type or a subtype (an OfType where-clause), e.g. i=2955 (LimitAlarmType)")] public string? OfType { get; init; } + /// AtTime: the requested times (ISO 8601 UTC, comma-separated). One page, printed with its status. + [CommandOption("at-time", Description = "HistoryRead-AtTime at these comma-separated ISO 8601 UTC times (instead of raw/aggregate)")] + public string? AtTimes { get; init; } + + /// Raw: page by hand at this NumValuesPerNode, printing each page's status, size and continuation. + [CommandOption("page-size", Description = "Raw: read page by page with this NumValuesPerNode, printing each page's status and continuation (0 = off)")] + public int PageSize { get; init; } + + /// With --page-size: after this page, wait for --resume-when-file before resuming in the SAME session. + [CommandOption("pause-after-page", Description = "With --page-size: pause after this page (holding the session) until --resume-when-file exists, then resume")] + public int PauseAfterPage { get; init; } + + /// The file whose appearance ends a --pause-after-page pause (written by the operator / a live gate). + [CommandOption("resume-when-file", Description = "With --pause-after-page: resume once this file exists (it is not read or deleted)")] + public string? ResumeWhenFile { get; init; } + + /// How long a pause waits for --resume-when-file before giving up. + [CommandOption("pause-timeout", Description = "With --pause-after-page: seconds to wait for --resume-when-file (default 300)")] + public int PauseTimeoutSeconds { get; init; } = 300; + + /// With --page-size: when a resumed page is refused, issue one fresh read of the same window and print it. + [CommandOption("fresh-after-failure", Description = "With --page-size: after a refused resumed page, issue one fresh read of the same window")] + public bool FreshAfterFailure { get; init; } + + /// With --page-size: stop after this page WITHOUT releasing its continuation (the session close releases it). + [CommandOption("abandon-after-page", Description = "With --page-size: stop after this page without releasing its continuation point (disconnect releases it)")] + public int AbandonAfterPage { get; init; } + + /// With --page-size: after this page, send releaseContinuationPoints for its continuation and stop. + [CommandOption("release-after-page", Description = "With --page-size: after this page, release its continuation point (releaseContinuationPoints) and stop")] + public int ReleaseAfterPage { get; init; } + + /// With --abandon-after-page: keep the session open this long before disconnecting. + [CommandOption("hold-seconds", Description = "With --abandon-after-page / --release-after-page: keep the session open this many seconds before disconnecting")] + public int HoldSeconds { get; init; } + + + private static string Format(StatusCode status) + { + var text = status.ToString(); + return text.Contains("[0x", StringComparison.Ordinal) ? text : $"{text} [0x{status.Code:X8}]"; + } + + private static async Task WriteRowsAsync(IConsole console, IReadOnlyList values) + { + foreach (var dv in values) + { + var status = StatusCode.IsGood(dv.StatusCode) ? "Good" : StatusCode.IsBad(dv.StatusCode) ? "Bad" : "Uncertain"; + await console.Output.WriteLineAsync( + $"{dv.SourceTimestamp.ToString("O"),-35} {ValueFormatter.Format(ValueConverter.ToClrObject(dv.WrappedValue)),-15} {status}"); + } + } + + /// HistoryRead-AtTime: one page, its status, then the rows (the value type is printed, so integer nodes show). + private async Task ReadAtTimeAsync(IOpcUaClientService service, IConsole console, NodeId nodeId, CancellationToken ct) + { + DateTime[] times; + try + { + times = AtTimes!.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Select(t => DateTime.Parse(t, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal)) + .ToArray(); + } + catch (FormatException ex) + { + throw new CommandException($"Invalid --at-time value: {ex.Message}"); + } + if (times.Length == 0) throw new CommandException("--at-time needs at least one time."); + var details = new ReadAtTimeDetails { ReqTimes = times.Select(t => (DateTimeUtc)t).ToArray(), UseSimpleBounds = true }; + var page = await service.HistoryReadPageAsync(details, nodeId, null, false, ct); + await console.Output.WriteLineAsync($"AtTime history for {NodeId} ({times.Length} times)"); + await console.Output.WriteLineAsync($"Status: {Format(page.Status)}"); + await console.Output.WriteLineAsync(); + await console.Output.WriteLineAsync($"{"Timestamp",-35} {"Value",-15} {"Status"}"); + await WriteRowsAsync(console, page.Values); + foreach (var dv in page.Values) + await console.Output.WriteLineAsync($"Type: {ValueConverter.ToClrObject(dv.WrappedValue)?.GetType().Name ?? "null"}"); + await console.Output.WriteLineAsync(); + await console.Output.WriteLineAsync($"{page.Values.Count} values returned."); + } + + /// + /// Raw history page by page in ONE session: each page's status, size and continuation are printed, so a resume that + /// the server refuses (BadContinuationPointInvalid) is visible instead of an exception, and a pause holds the + /// session (and its continuation point) open while something else happens (a failover, a rebuild). + /// + private async Task ReadPagesAsync(IOpcUaClientService service, IConsole console, NodeId nodeId, DateTime start, DateTime end, CancellationToken ct) + { + var details = new ReadRawModifiedDetails + { + StartTime = start, EndTime = end, NumValuesPerNode = (uint)PageSize, IsReadModified = false, ReturnBounds = false, + }; + await console.Output.WriteLineAsync($"Paged history for {NodeId} (page size {PageSize})"); + byte[]? cp = null; + var total = 0; + for (var number = 1; ; number++) + { + var resumed = cp is not null; + var page = await service.HistoryReadPageAsync(details, nodeId, cp, false, ct); + await console.Output.WriteLineAsync( + $"Page {number}: {Format(page.Status)} values={page.Values.Count} continuation={(page.ContinuationPoint is null ? "no" : "yes")}{(resumed ? " resumed" : "")}"); + await WriteRowsAsync(console, page.Values); + total += page.Values.Count; + if (StatusCode.IsBad(page.Status)) + { + if (resumed && FreshAfterFailure) + { + var fresh = await service.HistoryReadPageAsync(details, nodeId, null, false, ct); + await console.Output.WriteLineAsync( + $"Fresh: {Format(fresh.Status)} values={fresh.Values.Count} continuation={(fresh.ContinuationPoint is null ? "no" : "yes")}"); + await WriteRowsAsync(console, fresh.Values); + if (fresh.ContinuationPoint is { } freshCp) await service.HistoryReadPageAsync(details, nodeId, freshCp, true, ct); + } + break; + } + cp = page.ContinuationPoint; + if (cp is null || total >= MaxValues) break; + if (number == AbandonAfterPage) + { + await console.Output.WriteLineAsync($"Abandoned after page {number} (continuation not released; holding {HoldSeconds}s)"); + if (HoldSeconds > 0) await Task.Delay(TimeSpan.FromSeconds(HoldSeconds), ct); + return; + } + if (number == ReleaseAfterPage) + { + var released = await service.HistoryReadPageAsync(details, nodeId, cp, true, ct); + await console.Output.WriteLineAsync($"Released after page {number}: {Format(released.Status)}"); + if (HoldSeconds > 0) await Task.Delay(TimeSpan.FromSeconds(HoldSeconds), ct); + return; + } + if (number == PauseAfterPage) + { + await console.Output.WriteLineAsync($"Paused after page {number}; waiting for {ResumeWhenFile}"); + var deadline = DateTime.UtcNow.AddSeconds(PauseTimeoutSeconds); + while (!File.Exists(ResumeWhenFile)) + { + if (DateTime.UtcNow >= deadline) throw new CommandException($"--resume-when-file did not appear within {PauseTimeoutSeconds}s."); + await Task.Delay(200, ct); + } + await console.Output.WriteLineAsync("Resuming"); + } + } + await console.Output.WriteLineAsync(); + await console.Output.WriteLineAsync($"{total} values returned."); + } + /// The event fields an event read selects when --fields is omitted. internal static readonly string[] DefaultEventFields = ["EventId", "EventType", "Time", "SourceName", "Severity", "Message", "ConditionName", "SourceNode"]; @@ -101,6 +247,16 @@ public class HistoryReadCommand : CommandBase throw new CommandException("--events cannot be combined with --modified or --aggregate."); if (!Events && (Fields is not null || OfType is not null)) throw new CommandException("--fields and --of-type apply only to --events."); + if (PageSize < 0 || PauseAfterPage < 0 || AbandonAfterPage < 0 || ReleaseAfterPage < 0 || HoldSeconds < 0 || PauseTimeoutSeconds <= 0) + throw new CommandException("--page-size, --pause-after-page, --abandon-after-page, --release-after-page and --hold-seconds must be >= 0; --pause-timeout > 0."); + if (PageSize == 0 && (PauseAfterPage > 0 || AbandonAfterPage > 0 || ReleaseAfterPage > 0 || FreshAfterFailure)) + throw new CommandException("--pause-after-page, --abandon-after-page, --release-after-page and --fresh-after-failure need --page-size."); + if (PauseAfterPage > 0 && string.IsNullOrWhiteSpace(ResumeWhenFile)) + throw new CommandException("--pause-after-page needs --resume-when-file."); + if ((PageSize > 0 || AtTimes is not null) && (Events || Modified || !string.IsNullOrEmpty(Aggregate))) + throw new CommandException("--page-size and --at-time read raw / AtTime history only."); + if (PageSize > 0 && AtTimes is not null) + throw new CommandException("--page-size and --at-time cannot be combined."); NodeId nodeId; try @@ -220,6 +376,18 @@ public class HistoryReadCommand : CommandBase return; } + if (AtTimes is not null) + { + await ReadAtTimeAsync(service, console, nodeId, ct); + return; + } + + if (PageSize > 0) + { + await ReadPagesAsync(service, console, nodeId, start, end, ct); + return; + } + IReadOnlyList values; if (string.IsNullOrEmpty(Aggregate)) diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSessionAdapter.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSessionAdapter.cs index 8c3710d39..bd929f58f 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSessionAdapter.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSessionAdapter.cs @@ -247,6 +247,17 @@ internal sealed class DefaultSessionAdapter : ISessionAdapter } /// Issues one single-node HistoryRead (or a release of its continuation point). + /// + public async Task HistoryReadPageAsync(HistoryReadDetails details, NodeId nodeId, byte[]? continuationPoint, + bool release, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(details); + var result = await ReadHistoryPageAsync(details, nodeId, continuationPoint, release, TimestampsToReturn.Both, ct).ConfigureAwait(false); + if (result is null) return new Models.HistoryPage(StatusCodes.BadUnexpectedError, [], null); + IReadOnlyList values = result.HistoryData.TryGetValue(out HistoryData? data) ? data.DataValues.ToArray() ?? [] : []; + return new Models.HistoryPage(result.StatusCode, values, result.ContinuationPoint.IsEmpty ? null : result.ContinuationPoint.ToArray()); + } + private async Task ReadHistoryPageAsync( HistoryReadDetails details, NodeId nodeId, byte[]? continuationPoint, bool release, TimestampsToReturn timestamps, CancellationToken ct) diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISessionAdapter.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISessionAdapter.cs index cb1c6c87b..9b216a19d 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISessionAdapter.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISessionAdapter.cs @@ -162,6 +162,19 @@ internal interface ISessionAdapter : IDisposable Task> HistoryReadAggregateAsync(NodeId nodeId, DateTime startTime, DateTime endTime, NodeId aggregateId, double intervalMs, CancellationToken ct = default); + /// + /// Reads (or, with , releases) ONE HistoryRead page for one node, returning the server's + /// status, values and continuation point verbatim — no paging, no refusal exception. + /// + /// Raw, Processed or AtTime details. + /// The node. + /// The point to resume (or release); null = a fresh read. + /// Send releaseContinuationPoints = true. + /// Cancellation. + /// The page. + Task HistoryReadPageAsync(HistoryReadDetails details, NodeId nodeId, byte[]? continuationPoint, bool release, + CancellationToken ct = default) => throw new NotSupportedException(); + /// /// Creates a subscription adapter for this session. /// diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs index b7933f880..4edde2ff3 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs @@ -258,6 +258,20 @@ public interface IOpcUaClientService : IDisposable Task> HistoryReadAggregateAsync(NodeId nodeId, DateTime startTime, DateTime endTime, AggregateType aggregate, double intervalMs = 3600000, CancellationToken ct = default); + /// + /// Reads (or, with , releases) ONE HistoryRead page for one node and returns the server's + /// status, values and continuation point verbatim — for callers that page by hand and must see each page's status + /// (a BadContinuationPointInvalid resume, a refusal) instead of an exception. + /// + /// Raw, Processed or AtTime details. + /// The node. + /// The point to resume (or release); null = a fresh read. + /// Send releaseContinuationPoints = true. + /// Cancellation. + /// The page. + Task HistoryReadPageAsync(HistoryReadDetails details, NodeId nodeId, byte[]? continuationPoint = null, bool release = false, + CancellationToken ct = default) => throw new NotSupportedException(); + /// /// Reads redundancy status data such as redundancy mode, service level, and partner endpoint URIs. /// diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Models/HistoryPage.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Models/HistoryPage.cs new file mode 100644 index 000000000..34f8d27bc --- /dev/null +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Models/HistoryPage.cs @@ -0,0 +1,13 @@ +using Opc.Ua; + +namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Models; + +/// +/// One HistoryRead page exactly as the server answered it: the per-node status (never thrown), its values and the +/// continuation point the server returned (null when the read is complete). Used by callers that page by hand — +/// the CLI's --page-size / --pause-after-page modes and the gRPC data live gate. +/// +/// The per-node operation status. +/// The returned values (empty on a refusal). +/// The next continuation point, or null when the read is complete. +public sealed record HistoryPage(StatusCode Status, IReadOnlyList Values, byte[]? ContinuationPoint); diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/OpcUaClientService.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/OpcUaClientService.cs index d14de8060..89b68bcbf 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/OpcUaClientService.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/OpcUaClientService.cs @@ -711,6 +711,15 @@ public sealed class OpcUaClientService : IOpcUaClientService return await _session!.HistoryReadAggregateAsync(nodeId, startTime, endTime, aggregateNodeId, intervalMs, ct); } + /// + public async Task HistoryReadPageAsync(HistoryReadDetails details, NodeId nodeId, byte[]? continuationPoint = null, + bool release = false, CancellationToken ct = default) + { + ThrowIfDisposed(); + ThrowIfNotConnected(); + return await _session!.HistoryReadPageAsync(details, nodeId, continuationPoint, release, ct); + } + /// public async Task GetRedundancyInfoAsync(CancellationToken ct = default) { diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/Fakes/FakeOpcUaClientService.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/Fakes/FakeOpcUaClientService.cs index 1a9538134..151a58579 100644 --- a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/Fakes/FakeOpcUaClientService.cs +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/Fakes/FakeOpcUaClientService.cs @@ -108,6 +108,21 @@ public sealed class FakeOpcUaClientService : IOpcUaClientService /// public Dictionary> BrowseResultsByParent { get; } = new(); + /// Pages HistoryReadPageAsync answers, in order (a release call consumes nothing). + public Queue HistoryPages { get; } = new(); + + /// Every HistoryReadPageAsync call: details, the continuation point passed, and the release flag. + public List<(HistoryReadDetails Details, byte[]? ContinuationPoint, bool Release)> HistoryPageCalls { get; } = []; + + /// + public Task HistoryReadPageAsync(HistoryReadDetails details, NodeId nodeId, byte[]? continuationPoint = null, + bool release = false, CancellationToken ct = default) + { + HistoryPageCalls.Add((details, continuationPoint, release)); + if (release) return Task.FromResult(new HistoryPage(StatusCodes.Good, [], null)); + return Task.FromResult(HistoryPages.Count > 0 ? HistoryPages.Dequeue() : new HistoryPage(StatusCodes.GoodNoData, [], null)); + } + /// Gets or sets an exception thrown by HistoryReadRawAsync (simulates a refused read). public Exception? HistoryReadException { get; set; } diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/HistoryReadPagedCommandTests.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/HistoryReadPagedCommandTests.cs new file mode 100644 index 000000000..b73402c6a --- /dev/null +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/HistoryReadPagedCommandTests.cs @@ -0,0 +1,126 @@ +using Opc.Ua; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Client.CLI.Commands; +using ZB.MOM.WW.OtOpcUa.Client.CLI.Tests.Fakes; +using ZB.MOM.WW.OtOpcUa.Client.Shared.Models; + +namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Tests; + +/// +/// The hand-paged (--page-size + pause / abandon / release / fresh-after-failure) and AtTime (--at-time) +/// modes of historyread the gRPC data H3 live gate drives against projected nodes. +/// +public class HistoryReadPagedCommandTests +{ + private static readonly DateTime T0 = new(2026, 11, 20, 10, 0, 0, DateTimeKind.Utc); + + private static DataValue Value(int v, int second) => new(new Variant(v), StatusCodes.Good, T0.AddSeconds(second), T0.AddSeconds(second)); + + [Fact] + public async Task Pages_print_each_status_and_resume_with_the_returned_continuation_point() + { + var fake = new FakeOpcUaClientService(); + fake.HistoryPages.Enqueue(new HistoryPage(StatusCodes.Good, [Value(1, 0), Value(2, 1)], [1, 2, 3])); + fake.HistoryPages.Enqueue(new HistoryPage(StatusCodes.Good, [Value(3, 2)], null)); + using var console = TestConsoleHelper.CreateConsole(); + var command = new HistoryReadCommand(new FakeOpcUaClientServiceFactory(fake)) + { + Url = "opc.tcp://localhost:4840", NodeId = "ns=3;s=p1.x", StartTime = "2026-11-20T09:00:00Z", EndTime = "2026-11-20T11:00:00Z", PageSize = 2, + }; + await command.ExecuteAsync(console); + var output = TestConsoleHelper.GetOutput(console); + output.ShouldContain("Page 1: Good [0x00000000] values=2 continuation=yes"); + output.ShouldContain("Page 2: Good [0x00000000] values=1 continuation=no resumed"); + output.ShouldContain("3 values returned."); + fake.HistoryPageCalls.Count.ShouldBe(2); + fake.HistoryPageCalls[0].ContinuationPoint.ShouldBeNull(); + fake.HistoryPageCalls[1].ContinuationPoint.ShouldBe(new byte[] { 1, 2, 3 }); + ((ReadRawModifiedDetails)fake.HistoryPageCalls[0].Details).NumValuesPerNode.ShouldBe(2u); + } + + [Fact] + public async Task A_refused_resume_is_printed_and_followed_by_one_fresh_read() + { + var fake = new FakeOpcUaClientService(); + fake.HistoryPages.Enqueue(new HistoryPage(StatusCodes.Good, [Value(1, 0)], [9])); + fake.HistoryPages.Enqueue(new HistoryPage(StatusCodes.BadContinuationPointInvalid, [], null)); + fake.HistoryPages.Enqueue(new HistoryPage(StatusCodes.Good, [Value(1, 0)], [7])); + var marker = Path.Combine(Path.GetTempPath(), "cli-resume-" + Guid.NewGuid().ToString("N")); + File.WriteAllText(marker, ""); + try + { + using var console = TestConsoleHelper.CreateConsole(); + var command = new HistoryReadCommand(new FakeOpcUaClientServiceFactory(fake)) + { + Url = "opc.tcp://localhost:4840", NodeId = "ns=3;s=p1.x", PageSize = 1, PauseAfterPage = 1, ResumeWhenFile = marker, + FreshAfterFailure = true, + }; + await command.ExecuteAsync(console); + var output = TestConsoleHelper.GetOutput(console); + output.ShouldContain("Paused after page 1"); + output.ShouldContain("Page 2: BadContinuationPointInvalid [0x804A0000] values=0 continuation=no resumed"); + output.ShouldContain("Fresh: Good [0x00000000] values=1 continuation=yes"); + fake.HistoryPageCalls.Last().Release.ShouldBeTrue("the fresh read's own continuation is released"); + } + finally { File.Delete(marker); } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Abandon_leaves_the_point_to_the_session_close_and_release_sends_releaseContinuationPoints(bool release) + { + var fake = new FakeOpcUaClientService(); + fake.HistoryPages.Enqueue(new HistoryPage(StatusCodes.Good, [Value(1, 0)], [5])); + using var console = TestConsoleHelper.CreateConsole(); + var command = new HistoryReadCommand(new FakeOpcUaClientServiceFactory(fake)) + { + Url = "opc.tcp://localhost:4840", NodeId = "ns=3;s=p1.x", PageSize = 1, + AbandonAfterPage = release ? 0 : 1, ReleaseAfterPage = release ? 1 : 0, + }; + await command.ExecuteAsync(console); + var output = TestConsoleHelper.GetOutput(console); + if (release) + { + output.ShouldContain("Released after page 1: Good"); + fake.HistoryPageCalls.Count.ShouldBe(2); + fake.HistoryPageCalls[1].Release.ShouldBeTrue(); + fake.HistoryPageCalls[1].ContinuationPoint.ShouldBe(new byte[] { 5 }); + } + else + { + output.ShouldContain("Abandoned after page 1"); + fake.HistoryPageCalls.Count.ShouldBe(1); + } + } + + [Fact] + public async Task AtTime_reads_the_requested_times_and_prints_the_status_and_value_types() + { + var fake = new FakeOpcUaClientService(); + fake.HistoryPages.Enqueue(new HistoryPage(StatusCodes.Good, [new DataValue(new Variant((ushort)7), StatusCodes.Good, T0, T0)], null)); + using var console = TestConsoleHelper.CreateConsole(); + var command = new HistoryReadCommand(new FakeOpcUaClientServiceFactory(fake)) + { + Url = "opc.tcp://localhost:4840", NodeId = "ns=3;s=p1.x", AtTimes = "2026-11-20T10:00:00Z, 2026-11-20T10:00:01Z", + }; + await command.ExecuteAsync(console); + var output = TestConsoleHelper.GetOutput(console); + output.ShouldContain("Status: Good [0x00000000]"); + output.ShouldContain("Type: UInt16"); + var details = fake.HistoryPageCalls.Single().Details.ShouldBeOfType(); + details.ReqTimes.Count.ShouldBe(2); + } + + [Fact] + public async Task Pause_without_a_resume_file_is_refused() + { + var command = new HistoryReadCommand(new FakeOpcUaClientServiceFactory(new FakeOpcUaClientService())) + { + Url = "opc.tcp://localhost:4840", NodeId = "ns=3;s=p1.x", PageSize = 1, PauseAfterPage = 1, + }; + using var console = TestConsoleHelper.CreateConsole(); + await Should.ThrowAsync(async () => await command.ExecuteAsync(console)); + } +} From b50019db9ccf23eea575b0ff5154762874a06c3b Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 00:42:46 -0500 Subject: [PATCH 05/25] feat(cli): historyread --held-marker-file for hand-paged reads --- docs/Client.CLI.md | 1 + .../Commands/HistoryReadCommand.cs | 7 +++++++ .../HistoryReadPagedCommandTests.cs | 5 ++++- 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/docs/Client.CLI.md b/docs/Client.CLI.md index fa1e131f8..44e5bc4d0 100644 --- a/docs/Client.CLI.md +++ b/docs/Client.CLI.md @@ -262,6 +262,7 @@ continuation points up to `--max`. `--events` cannot be combined with `--modifie | `--at-time` | HistoryRead-AtTime at these comma-separated ISO 8601 UTC times; prints the status, the rows and each value's CLR type | | `--page-size` | Raw only: page by hand at this `NumValuesPerNode`, printing every page as `Page k: values= continuation=[ resumed]` (a refused page is printed, never thrown) | | `--pause-after-page` / `--resume-when-file` / `--pause-timeout` | With `--page-size`: after page k hold the session (and its continuation point) until the file exists, then resume | +| `--held-marker-file` | With `--page-size`: create this (empty) file when the read reaches its pause, abandon or release point | | `--fresh-after-failure` | With `--page-size`: after a refused resumed page, issue one fresh read of the same window (`Fresh: …`) | | `--abandon-after-page` | With `--page-size`: stop after page k WITHOUT releasing its continuation point — the disconnect (session close) releases it | | `--release-after-page` | With `--page-size`: send `releaseContinuationPoints` for page k's point and stop | diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/HistoryReadCommand.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/HistoryReadCommand.cs index 804faa364..b25c99007 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/HistoryReadCommand.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/HistoryReadCommand.cs @@ -99,6 +99,10 @@ public class HistoryReadCommand : CommandBase [CommandOption("resume-when-file", Description = "With --pause-after-page: resume once this file exists (it is not read or deleted)")] public string? ResumeWhenFile { get; init; } + /// Written (empty) once the hand-paged read reaches its pause / abandon / release point, so a driver knows the page is held. + [CommandOption("held-marker-file", Description = "With --page-size: create this file when the read reaches its pause, abandon or release point")] + public string? HeldMarkerFile { get; init; } + /// How long a pause waits for --resume-when-file before giving up. [CommandOption("pause-timeout", Description = "With --pause-after-page: seconds to wait for --resume-when-file (default 300)")] public int PauseTimeoutSeconds { get; init; } = 300; @@ -203,6 +207,7 @@ public class HistoryReadCommand : CommandBase if (number == AbandonAfterPage) { await console.Output.WriteLineAsync($"Abandoned after page {number} (continuation not released; holding {HoldSeconds}s)"); + if (HeldMarkerFile is not null) await File.WriteAllTextAsync(HeldMarkerFile, "", ct); if (HoldSeconds > 0) await Task.Delay(TimeSpan.FromSeconds(HoldSeconds), ct); return; } @@ -210,12 +215,14 @@ public class HistoryReadCommand : CommandBase { var released = await service.HistoryReadPageAsync(details, nodeId, cp, true, ct); await console.Output.WriteLineAsync($"Released after page {number}: {Format(released.Status)}"); + if (HeldMarkerFile is not null) await File.WriteAllTextAsync(HeldMarkerFile, "", ct); if (HoldSeconds > 0) await Task.Delay(TimeSpan.FromSeconds(HoldSeconds), ct); return; } if (number == PauseAfterPage) { await console.Output.WriteLineAsync($"Paused after page {number}; waiting for {ResumeWhenFile}"); + if (HeldMarkerFile is not null) await File.WriteAllTextAsync(HeldMarkerFile, "", ct); var deadline = DateTime.UtcNow.AddSeconds(PauseTimeoutSeconds); while (!File.Exists(ResumeWhenFile)) { diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/HistoryReadPagedCommandTests.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/HistoryReadPagedCommandTests.cs index b73402c6a..6b0d705a3 100644 --- a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/HistoryReadPagedCommandTests.cs +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.CLI.Tests/HistoryReadPagedCommandTests.cs @@ -73,13 +73,16 @@ public class HistoryReadPagedCommandTests { var fake = new FakeOpcUaClientService(); fake.HistoryPages.Enqueue(new HistoryPage(StatusCodes.Good, [Value(1, 0)], [5])); + var held = Path.Combine(Path.GetTempPath(), "cli-held-" + Guid.NewGuid().ToString("N")); using var console = TestConsoleHelper.CreateConsole(); var command = new HistoryReadCommand(new FakeOpcUaClientServiceFactory(fake)) { Url = "opc.tcp://localhost:4840", NodeId = "ns=3;s=p1.x", PageSize = 1, - AbandonAfterPage = release ? 0 : 1, ReleaseAfterPage = release ? 1 : 0, + AbandonAfterPage = release ? 0 : 1, ReleaseAfterPage = release ? 1 : 0, HeldMarkerFile = held, }; await command.ExecuteAsync(console); + File.Exists(held).ShouldBeTrue("the held marker is written at the abandon / release point"); + File.Delete(held); var output = TestConsoleHelper.GetOutput(console); if (release) { From 8341c7f4ae4f60805421af5c6e84c4f423cff7fb Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 00:42:46 -0500 Subject: [PATCH 06/25] test(grpc-data): H3 live gate harness (H01-H06, SqlServer and QuestDB origins) rig.py up --history --history-backend questdb adds a run-owned QuestDB for the SOURCE historian. History seed profile: mappings grant HistoryRead, the CLI principal's CONSUMER HistoryRead comes only from mapping-scoped grants, text is historized (per-type aggregate refusal), new acl_permissions mutation. history_gate.py drives H01-H06 through the Client CLI on projected NodeIds resolved by browse from the mapping anchor, compares with the origin, and restores the baseline after every scenario. The node probe reports the origin's open history continuations (LocalDataServices.HistoryOpenContinuations, now public). --- .../grpc-data/compose.history.questdb.yml | 38 ++ scripts/validation/grpc-data/history_gate.py | 381 ++++++++++++++++++ .../grpc-data/node-probe/NodeProbeStartup.cs | 1 + scripts/validation/grpc-data/rig.py | 17 +- scripts/validation/grpc-data/scenarios.json | 78 ++++ scripts/validation/grpc-data/seed/Program.cs | 27 +- .../LocalDataServices.History.cs | 2 +- 7 files changed, 535 insertions(+), 9 deletions(-) create mode 100644 scripts/validation/grpc-data/compose.history.questdb.yml create mode 100644 scripts/validation/grpc-data/history_gate.py diff --git a/scripts/validation/grpc-data/compose.history.questdb.yml b/scripts/validation/grpc-data/compose.history.questdb.yml new file mode 100644 index 000000000..c436e139e --- /dev/null +++ b/scripts/validation/grpc-data/compose.history.questdb.yml @@ -0,0 +1,38 @@ +# H3 QuestDB origin backend (opt-in: `rig.py up --history --history-backend questdb`), layered AFTER +# compose.history.yml: the SOURCE pair historizes into a run-owned QuestDB container instead of the run's SQL +# container. Same seed profile, same scenarios. The container and its volume carry the run labels, so +# `rig.py down` removes them with everything else. Image pinned as docker-dev/docker-compose.questdb.yml. + +x-labels: &labels + otopcua.grpc-data.run: ${GRPC_DATA_RUN_ID:?run id required} + otopcua.grpc-data.fixture: "v1" + +x-source-questdb-env: &source-questdb-env + ServerHistorian__Backend: QuestDb + ServerHistorian__QuestDb__ConnectionString: "Host=questdb;Port=8812;Username=admin;Password=quest;Database=qdb;ServerCompatibilityMode=NoTypeLoading;Maximum Pool Size=16" + ServerHistorian__QuestDb__TablePrefix: hist_ + ServerHistorian__QuestDb__AutoCreateSchema: "true" + +services: + questdb: + image: questdb/questdb:10.0.1 + labels: *labels + networks: [rig] + volumes: [questdb-data:/var/lib/questdb] + healthcheck: + test: ["CMD-SHELL", "curl -fs http://localhost:9003/status || exit 1"] + interval: 5s + timeout: 5s + retries: 24 + source-1: + environment: *source-questdb-env + depends_on: + questdb: {condition: service_healthy} + source-2: + environment: *source-questdb-env + depends_on: + questdb: {condition: service_healthy} + +volumes: + questdb-data: + labels: *labels diff --git a/scripts/validation/grpc-data/history_gate.py b/scripts/validation/grpc-data/history_gate.py new file mode 100644 index 000000000..c4514f852 --- /dev/null +++ b/scripts/validation/grpc-data/history_gate.py @@ -0,0 +1,381 @@ +"""H3 live gate: scenarios H01–H06 (plan §9 "Scenarios") on a `rig.py up --history [--history-backend questdb]` run. + +Every scenario is driven through the production Client CLI `historyread` against CONSUMER's OPC UA endpoint, on +PROJECTED NodeIds resolved by browsing from the mapping anchor (never constructed `p1.` ids), and is compared with the +same read on the ORIGIN (SOURCE) node. Each scenario restores the baseline (transactional authoring restore + deploy) +whatever its outcome. The rows are declared in `scenarios.json` → `history_scenarios`; evidence lands in the run's +restricted `evidence/` folder (keys redacted by ScenarioRunner.save). +""" +import argparse +import json +import re +import sys +import threading +import time +import uuid +from datetime import datetime, timedelta, timezone +from pathlib import Path + +import history_smoke +import rig +import scenarios + +NODE_PERMISSIONS_ADMIN = 4095 # NodePermissions.Admin = bits 0..11 (HistoryUpdate excluded) +NODE_PERMISSIONS_HISTORY_READ = 1 << 3 +NODE_PERMISSIONS_BROWSE = 1 << 0 +EXPORT_WITHOUT_HISTORY = 31 # Browse | Metadata | Read | Write | Subscribe + + +def _iso(moment): + return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +class HistoryGate: + def __init__(self, run_id, *, pinned_build=False): + if pinned_build: + recorded = scenarios.restricted_json(rig.LocalRig(run_id).path)["source_tree_hash"] + rig.source_tree_hash = lambda: recorded + self.runner = scenarios.ScenarioRunner(run_id) + if self.runner.manifest["fixture"].get("history") is None: + raise SystemExit("run was not brought up with --history") + self.backend = self.runner.rig.environment.get("GRPC_DATA_HISTORY_BACKEND", "sqlserver") + self.catalog = json.loads((rig.HERE / "scenarios.json").read_text())["history_scenarios"] + self.window = None + self.projected = {} + + # ----------------------------------------------------------------------------------------------------------- tools + + def cli(self, node, extra, name, *, timeout=90): + argv = ["dotnet", str(self.runner.cli_dll), "historyread", "-u", self.runner.endpoint(node), "-U", "apikey", + "-P", self.runner.key, *extra] + return self.runner.process(argv, self.runner.active + "-" + name + "-" + uuid.uuid4().hex[:6], timeout=timeout) + + def window_args(self): + return ["--start", _iso(self.window[0]), "--end", _iso(self.window[1])] + + def origin_node(self, realm, name): + source = self.runner.primary("source") + alias = self.runner.manifest["resolved_nodes"][source]["aliases"][realm] + return source, alias.rsplit("/", 1)[0] + "/" + name + + def accumulate(self, seconds=40): + started = datetime.now(timezone.utc) + for _ in range(seconds): + self.runner.device("advance", steps=1) + time.sleep(1) + finished = datetime.now(timezone.utc) + time.sleep(4) + self.window = ((started + timedelta(seconds=5)).replace(microsecond=0), (finished - timedelta(seconds=5)).replace(microsecond=0)) + + def resolve_projected(self): + """Browse CONSUMER from the shared root; keep the projected leaves under the mapping anchors (`remote-source`).""" + consumer = self.runner.primary("consumer") + uris = self.runner.manifest["resolved_nodes"][consumer]["namespace_uris"] + ns = {key: uris.index(uri) for key, uri in self.runner.manifest["fixture"]["namespace_uris"].items()} + argv = ["dotnet", str(self.runner.cli_dll), "browse", "-u", self.runner.endpoint(consumer), "-U", "apikey", "-P", self.runner.key, + "-n", f"ns={ns['raw']};s=OtOpcUa", "-r", "-d", "7"] + result = self.runner.process(argv, "H-browse-" + uuid.uuid4().hex[:6], timeout=120) + self.runner.check(result.returncode == 0, "consumer browse succeeded") + stack, found = [], {} + for line in result.stdout.splitlines(): + match = re.match(r"^( *)\[(\w+)\] (.+?) \(NodeId: (.+)\)$", line) + if match is None: + continue + depth = len(match[1]) // 2 + del stack[depth:] + stack.append(match[3]) + node_id = match[4] + index = int(re.match(r"ns=(\d+);", node_id)[1]) if node_id.startswith("ns=") else -1 + realm = "raw" if index == ns["mapped_raw"] else "uns" if index == ns["mapped_uns"] else None + if realm and "remote-source" in stack[:-1] and match[3] in {"counter", "scalar", "text"}: + self.runner.check((realm, match[3]) not in found, "one projected leaf per realm and name") + found[(realm, match[3])] = node_id + for realm in ("raw", "uns"): + for name in ("counter", "scalar", "text"): + self.runner.check((realm, name) in found, f"projected {realm}/{name} found by browse from the mapping anchor") + self.runner.check(found[(realm, name)].split(";s=", 1)[1].startswith("p1."), "projected ids are opaque p1. ids") + self.projected = found + self.runner.save("H-projected-nodes.json", {f"{k[0]}/{k[1]}": v for k, v in found.items()}) + return consumer + + def held(self, consumer, extra, name, during, *, marker_timeout=60): + """Runs a hand-paged CLI read in the background; `during()` runs once the read reports its held point.""" + marker = self.runner.folder / (name + "-" + uuid.uuid4().hex[:6] + ".held") + resume = self.runner.folder / (name + "-" + uuid.uuid4().hex[:6] + ".resume") + outcome = {} + + def worker(): + outcome["result"] = self.cli(consumer, [*extra, "--held-marker-file", str(marker), "--resume-when-file", str(resume)], + name, timeout=600) + + thread = threading.Thread(target=worker, daemon=True) + thread.start() + end = time.monotonic() + marker_timeout + while not marker.exists() and thread.is_alive() and time.monotonic() < end: + time.sleep(0.1) + self.runner.check(marker.exists(), "the CLI reached its held point") + try: + during() + finally: + resume.write_text("") + thread.join(timeout=600) + self.runner.check("result" in outcome, "held CLI finished") + return outcome["result"] + + @staticmethod + def status_lines(stdout): + return [line for line in stdout.splitlines() if line.startswith(("Page ", "Fresh:", "Status:", "Released", "Abandoned"))] + + @staticmethod + def error_status(result): + combined = result.stdout + "\n" + result.stderr + match = re.search(r"(Bad\w+)", combined) + return match[1] if match else None + + def poll_status(self, consumer, node, expected, name, *, extra=None, timeout=120): + end = time.monotonic() + timeout + attempts = [] + while True: + result = self.cli(consumer, ["-n", node, *self.window_args(), "--max", "50", *(extra or [])], name) + observed = self.error_status(result) if result.returncode != 0 else "Good" + attempts.append(observed) + if observed == expected or time.monotonic() >= end: + return observed, attempts, result + time.sleep(3) + + def origin_state(self): + total = 0 + for node in ("source-1", "source-2"): + observed = self.runner.probe(node, "topology", timeout=30) + total += int(observed.get("originAccounting", {}).get("historyOpenContinuations") or 0) + return total + + # ------------------------------------------------------------------------------------------------------- scenarios + + def scenario_H01(self): + """Raw paging across page boundaries, Raw and UNS mappings, row-for-row equal to the origin.""" + report = {} + consumer = self.runner.primary("consumer") + for realm in ("raw", "uns"): + source, origin = self.origin_node(realm, "counter") + reference = self.cli(source, ["-n", origin, *self.window_args(), "--max", "1000"], f"origin-{realm}") + self.runner.check(reference.returncode == 0, f"origin {realm} read") + origin_rows = history_smoke._cli_rows(reference.stdout) + self.runner.check(len(origin_rows) >= 10, f"origin {realm} window holds history") + paged = self.cli(consumer, ["-n", self.projected[(realm, "counter")], *self.window_args(), "--page-size", "3", "--max", "1000"], + f"paged-{realm}") + pages = [line for line in paged.stdout.splitlines() if line.startswith("Page ")] + self.runner.check(paged.returncode == 0 and len(pages) >= 2, f"{realm}: several pages") + self.runner.check(all("Good" in line for line in pages), f"{realm}: every page Good") + self.runner.check(pages[-1].split("continuation=")[1].startswith("no"), f"{realm}: the last page has no continuation") + rows = history_smoke._cli_rows(paged.stdout) + self.runner.check(rows == origin_rows, f"{realm}: paged projected rows equal the origin row-for-row") + whole = self.cli(consumer, ["-n", self.projected[(realm, "counter")], *self.window_args(), "--max", "1000"], f"whole-{realm}") + self.runner.check(history_smoke._cli_rows(whole.stdout) == origin_rows, f"{realm}: single read equals the origin") + report[realm] = {"pages": len(pages), "rows": len(rows), "first": str(rows[0]), "last": str(rows[-1]), "page_lines": pages} + report["tie_cluster"] = ("not representable on the " + self.backend + " backend: SqlServer hist.Sample PK (TagId, SourceTimeUtc), " + "QuestDB DEDUP UPSERT KEYS(ts, tag) — one stored sample per timestamp; tie paging is proven by the H1 port fuzz") + return report + + def scenario_H02(self): + """Processed: the origin refuses an aggregate for the node's type (#897); a served aggregate equals the origin.""" + consumer = self.runner.primary("consumer") + refused = self.cli(consumer, ["-n", self.projected[("raw", "text")], *self.window_args(), "--aggregate", "Average", "--interval", "10000"], + "text-average") + self.runner.check(refused.returncode != 0 and self.error_status(refused) == "BadAggregateNotSupported", + "Average on a String node is BadAggregateNotSupported from the origin") + source, origin = self.origin_node("raw", "text") + origin_refused = self.cli(source, ["-n", origin, *self.window_args(), "--aggregate", "Average", "--interval", "10000"], "origin-text-average") + self.runner.check(self.error_status(origin_refused) == "BadAggregateNotSupported", "the origin answers the same refusal") + source, origin = self.origin_node("raw", "counter") + reference = self.cli(source, ["-n", origin, *self.window_args(), "--aggregate", "Average", "--interval", "10000"], "origin-average") + served = self.cli(consumer, ["-n", self.projected[("raw", "counter")], *self.window_args(), "--aggregate", "Average", "--interval", "10000"], + "average") + self.runner.check(reference.returncode == 0 and served.returncode == 0, "Average served on both") + rows, origin_rows = history_smoke._cli_rows(served.stdout), history_smoke._cli_rows(reference.stdout) + self.runner.check(len(rows) > 0 and rows == origin_rows, "projected Average equals the origin row-for-row") + return {"refused": self.error_status(refused), "origin_refused": self.error_status(origin_refused), "average_rows": len(rows)} + + def scenario_H03(self): + """AtTime on an integer (UInt16) node: identical values, timestamps, statuses and value types.""" + consumer = self.runner.primary("consumer") + start = self.window[0] + times = ",".join(_iso(start + timedelta(seconds=s)) for s in (3, 7, 11)) + source, origin = self.origin_node("raw", "counter") + reference = self.cli(source, ["-n", origin, "--at-time", times], "origin-attime") + projected = self.cli(consumer, ["-n", self.projected[("raw", "counter")], "--at-time", times], "attime") + self.runner.check(reference.returncode == 0 and projected.returncode == 0, "AtTime served") + rows, origin_rows = history_smoke._cli_rows(projected.stdout), history_smoke._cli_rows(reference.stdout) + types = [line for line in projected.stdout.splitlines() if line.startswith("Type:")] + origin_types = [line for line in reference.stdout.splitlines() if line.startswith("Type:")] + self.runner.check(len(rows) == 3 and rows == origin_rows, "projected AtTime equals the origin row-for-row") + self.runner.check(types == origin_types and all(t == "Type: UInt16" for t in types), "integer values stay UInt16 end to end") + return {"rows": [str(r) for r in rows], "types": types} + + def scenario_H04(self): + """A continuation across an origin failover is BadContinuationPointInvalid; a fresh read moves and succeeds.""" + consumer = self.runner.primary("consumer") + source = self.runner.primary("source") + observed = {} + + def failover(): + with self.runner.stopped(source): + observed["new_primary"] = self.runner.wait_primary("source", exclude=source) + self.runner.wait_connection_ready(consumer, "raw") + # Resume INSIDE the stop window: the issuing endpoint is down, the pinned resume cannot move. + self.held_resume_now() + self.runner.wait_pair_topology("source") + + result = self.held_with_inline_resume(consumer, ["-n", self.projected[("raw", "counter")], *self.window_args(), "--page-size", "3", + "--pause-after-page", "1", "--fresh-after-failure"], "failover", failover) + lines = self.status_lines(result.stdout) + self.runner.check(any(l.startswith("Page 2: BadContinuationPointInvalid") for l in lines), "the resumed page is BadContinuationPointInvalid") + self.runner.check(any(l.startswith("Fresh: Good") for l in lines), "a fresh read succeeds on the new primary") + return {"old_primary": source, "new_primary": observed.get("new_primary"), "lines": lines} + + def held_with_inline_resume(self, consumer, extra, name, during): + """Like held(), but `during` decides WHEN to resume by calling self.held_resume_now().""" + marker = self.runner.folder / (name + "-" + uuid.uuid4().hex[:6] + ".held") + resume = self.runner.folder / (name + "-" + uuid.uuid4().hex[:6] + ".resume") + outcome = {} + + def worker(): + outcome["result"] = self.cli(consumer, [*extra, "--held-marker-file", str(marker), "--resume-when-file", str(resume)], + name, timeout=600) + + thread = threading.Thread(target=worker, daemon=True) + thread.start() + end = time.monotonic() + 60 + while not marker.exists() and thread.is_alive() and time.monotonic() < end: + time.sleep(0.1) + self.runner.check(marker.exists(), "the CLI reached its held point") + resumed = threading.Event() + + def resume_now(): + resume.write_text("") + thread.join(timeout=300) + resumed.set() + + self.held_resume_now = resume_now + try: + during() + finally: + if not resumed.is_set(): + resume_now() + self.runner.check("result" in outcome, "held CLI finished") + return outcome["result"] + + def scenario_H05(self): + """Substitute for "v1 origin (pinned old image)": an origin that no longer advertises history for this principal.""" + consumer = self.runner.primary("consumer") + before, _, _ = self.poll_status(consumer, self.projected[("raw", "counter")], "Good", "before", timeout=30) + self.runner.check(before == "Good", "history served before the change") + self.runner.mutate(export_id="export-raw", export_allowed_operations=EXPORT_WITHOUT_HISTORY) + observed, attempts, result = self.poll_status(consumer, self.projected[("raw", "counter")], "BadHistoryOperationUnsupported", + "not-advertised", timeout=180) + self.runner.check(observed == "BadHistoryOperationUnsupported", "an origin that does not advertise history ⇒ unsupported") + uns, _, _ = self.poll_status(consumer, self.projected[("uns", "counter")], "Good", "uns-still-served", timeout=30) + self.runner.check(uns == "Good", "the other export (UNS) still serves history") + return {"before": before, "after": observed, "attempts": attempts, "uns": uns, + "substitution": "no pinned v1 image is built by the rig; the export drops HistoryRead (bit 32) instead"} + + def scenario_H06(self): + """Denied vs unhistorized indistinguishable; local deny is BadUserAccessDenied; session close releases; rebuild mid-page.""" + consumer = self.runner.primary("consumer") + report = {} + # (a) unhistorized vs origin-ACL-denied: the same refusal, the same text (node ids normalised). + unhistorized, _, unh = self.poll_status(consumer, self.projected[("raw", "scalar")], "BadHistoryOperationUnsupported", "unhistorized", + timeout=30) + self.runner.check(unhistorized == "BadHistoryOperationUnsupported", "unhistorized ⇒ BadHistoryOperationUnsupported") + self.runner.mutate(acl_permissions={"node_acl_id": "source-peer", "permission_flags": NODE_PERMISSIONS_ADMIN & ~NODE_PERMISSIONS_HISTORY_READ}) + denied, attempts, den = self.poll_status(consumer, self.projected[("raw", "counter")], "BadHistoryOperationUnsupported", "origin-denied", + timeout=180) + normalise = lambda text: re.sub(r"ns=\d+;s=\S+", "", "\n".join(l for l in (text.stdout + text.stderr).splitlines() if "Bad" in l)) + self.runner.check(denied == "BadHistoryOperationUnsupported", "origin ACL denial ⇒ BadHistoryOperationUnsupported") + self.runner.check(normalise(unh) == normalise(den), "denied and unhistorized are indistinguishable") + report["indistinguishable"] = {"unhistorized": normalise(unh), "denied": normalise(den), "attempts": attempts} + self.runner.baseline() + # (b) the LOCAL mapping-scope grant: without it, BadUserAccessDenied (a local decision); the other mapping keeps its grant. + self.runner.mutate(acl_permissions={"node_acl_id": "cli-history-map-raw", "permission_flags": NODE_PERMISSIONS_BROWSE}) + local, attempts, _ = self.poll_status(consumer, self.projected[("raw", "counter")], "BadUserAccessDenied", "local-denied", timeout=90) + self.runner.check(local == "BadUserAccessDenied", "no local HistoryRead grant on the mapping scope ⇒ BadUserAccessDenied") + other, _, _ = self.poll_status(consumer, self.projected[("uns", "counter")], "Good", "local-other-mapping", timeout=30) + self.runner.check(other == "Good", "the UNS mapping's own grant still serves") + report["local_deny"] = {"raw": local, "uns": other, "attempts": attempts} + self.runner.baseline() + consumer = self.runner.primary("consumer") + # (c) a consumer session close releases the origin continuation. + self.runner.check(self.origin_state() == 0, "no origin continuation open before") + counts = {} + + def while_held(): + counts["held"] = self.origin_state() + + abandoned = self.held(consumer, ["-n", self.projected[("raw", "counter")], *self.window_args(), "--page-size", "2", + "--abandon-after-page", "1", "--hold-seconds", "10"], "abandon", while_held) + self.runner.check(counts.get("held", 0) >= 1, "the origin holds the page cursor while the consumer session holds the point") + end = time.monotonic() + 30 + after = self.origin_state() + while after != 0 and time.monotonic() < end: + time.sleep(1) + after = self.origin_state() + self.runner.check(after == 0, "the consumer session close released the origin continuation (store count back to 0)") + report["session_close"] = {"held": counts.get("held"), "after": after, "lines": self.status_lines(abandoned.stdout)} + # (d) origin rebuild mid-page: a resumed page after the origin's history epoch moved is BadContinuationPointInvalid. + def rebuild(): + self.runner.mutate(rename_tag={"tag_id": "source-array1", "name": "array1-renamed"}) + rebuilt = self.held(consumer, ["-n", self.projected[("raw", "counter")], *self.window_args(), "--page-size", "3", + "--pause-after-page", "1", "--fresh-after-failure"], "rebuild", rebuild) + lines = self.status_lines(rebuilt.stdout) + self.runner.check(any(l.startswith("Page 2: BadContinuationPointInvalid") for l in lines), "resume after the origin rebuild is invalid") + self.runner.check(any(l.startswith("Fresh: Good") for l in lines), "a fresh read after the rebuild succeeds") + report["rebuild"] = lines + return report + + # ------------------------------------------------------------------------------------------------------------- run + + def run(self, selection): + chosen = [row["id"] for row in self.catalog] if selection == "all" else [selection] + self.runner.publish() + self.runner.rig.seed_helper("snapshot") + self.runner.active, self.runner.deadline = "H00", time.monotonic() + 900 + self.accumulate() + self.resolve_projected() + rows = [] + for name in chosen: + spec = next(row for row in self.catalog if row["id"] == name) + self.runner.active, self.runner.count = name, 0 + self.runner.deadline = time.monotonic() + spec.get("timeout_seconds", 900) + started, error, restored, detail = time.monotonic(), None, False, None + try: + detail = getattr(self, "scenario_" + name)() + except Exception as failure: + error = type(failure).__name__ + ": " + str(failure) + finally: + try: + self.runner.deadline = time.monotonic() + 600 + self.runner.baseline() + restored = True + except Exception as failure: + error = (error + "; " if error else "") + "restoration " + type(failure).__name__ + ": " + str(failure) + row = {"id": name, "backend": self.backend, "passed": error is None and restored, "assertions": self.runner.count, + "restored": restored, "duration_seconds": round(time.monotonic() - started, 1), "failure": error, "detail": detail} + rows.append(row) + self.runner.save(f"H3-history-{self.backend}-results.json", {"rows": rows, "window": [_iso(w) for w in self.window]}) + print(json.dumps({k: row[k] for k in ("id", "backend", "passed", "assertions", "restored", "duration_seconds", "failure")}), flush=True) + return rows + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--run-id", required=True) + parser.add_argument("--scenario", default="all") + parser.add_argument("--pinned-build", action="store_true") + arguments = parser.parse_args(argv) + gate = HistoryGate(arguments.run_id, pinned_build=arguments.pinned_build) + rows = gate.run(arguments.scenario) + return 0 if all(row["passed"] for row in rows) else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/validation/grpc-data/node-probe/NodeProbeStartup.cs b/scripts/validation/grpc-data/node-probe/NodeProbeStartup.cs index 0b9fbb0ea..d6cffebb4 100644 --- a/scripts/validation/grpc-data/node-probe/NodeProbeStartup.cs +++ b/scripts/validation/grpc-data/node-probe/NodeProbeStartup.cs @@ -66,6 +66,7 @@ public sealed partial class NodeProbeWorker(IServiceProvider services) : Backgro acquisitionOwnerSerial = acquisition?.CurrentOwnerSerial, acquisitionControlGeneration = acquisition?.ControlGeneration, workload = composition?.CaptureWorkloadAccounting(), sourceIngressCounters = SourceIngressDiagnostics.Capture(), + historyOpenContinuations = composition?.Services.HistoryOpenContinuations, definition = "actual origin hub resource charges and physical driver reservation owners; driver count is not source count" }; } diff --git a/scripts/validation/grpc-data/rig.py b/scripts/validation/grpc-data/rig.py index 2b32e484c..5b75330ea 100644 --- a/scripts/validation/grpc-data/rig.py +++ b/scripts/validation/grpc-data/rig.py @@ -473,7 +473,9 @@ def require_production_prerequisites(action, available): ROOT = Path(__file__).resolve().parents[3] HERE = Path(__file__).resolve().parent NODES = tuple(f"{pair}-{n}" for pair in ("control", "source", "consumer") for n in (1, 2)) -SERVICES = ("sql", "migrator", "device", "seeder", *NODES) +# `questdb` exists only on a `--history-backend questdb` run (compose.history.questdb.yml); listing it is the DNS allowlist. +SERVICES = ("sql", "migrator", "device", "seeder", "questdb", *NODES) +HISTORY_BACKENDS = ("sqlserver", "questdb") def run_command(argv, *, timeout=120, environment=None): @@ -671,6 +673,8 @@ class LocalRig: files = ["--file", str(HERE / "compose.yml")] if self.environment.get("GRPC_DATA_HISTORY") == "1": files.extend(["--file", str(HERE / "compose.history.yml")]) + if self.environment.get("GRPC_DATA_HISTORY_BACKEND") == "questdb": + files.extend(["--file", str(HERE / "compose.history.questdb.yml")]) return files def compose(self, *args, timeout=120): @@ -841,7 +845,7 @@ class LocalRig: self.save(manifest) return manifest - def up(self, timeout=600, history=False): + def up(self, timeout=600, history=False, history_backend="sqlserver"): import secrets import credentials if self.folder.exists(): @@ -862,7 +866,10 @@ class LocalRig: import base64 settings["GRPC_DATA_SECRETS_KEK"] = base64.b64encode(secrets.token_bytes(32)).decode() if history: + if history_backend not in HISTORY_BACKENDS: + raise RigError("unknown history backend") settings["GRPC_DATA_HISTORY"] = "1" + settings["GRPC_DATA_HISTORY_BACKEND"] = history_backend atomic_write_secret(self.folder / "environment.json", json.dumps(settings)) self.environment.update(settings) credentials.provision_tls(self.folder / "security", NODES[2:]) @@ -1331,6 +1338,8 @@ def main(argv=None): parser.add_argument("--run-id") parser.add_argument("--timeout", type=float, default=None) parser.add_argument("--history", action="store_true", help="up only: add the H2 history overlay (SOURCE historian + history seed profile)") + parser.add_argument("--history-backend", choices=HISTORY_BACKENDS, default=None, + help="up --history only: the SOURCE historian backend (sqlserver = the run's SQL container, default; questdb = a run-owned QuestDB)") arguments = parser.parse_args(argv) try: if arguments.action == "preflight": @@ -1353,6 +1362,10 @@ def main(argv=None): if arguments.action != "up": raise RigError("--history applies to up only; the run remembers it") options["history"] = True + if arguments.history_backend is not None: + options["history_backend"] = arguments.history_backend + elif arguments.history_backend is not None: + raise RigError("--history-backend needs up --history") result = action(**options) print(json.dumps({"run_id": result["run_id"], "state": result.get("state"), "manifest": str(rig.path), "healthy": result.get("healthy")})) return 0 diff --git a/scripts/validation/grpc-data/scenarios.json b/scripts/validation/grpc-data/scenarios.json index aeed6fac9..108a5b6a3 100644 --- a/scripts/validation/grpc-data/scenarios.json +++ b/scripts/validation/grpc-data/scenarios.json @@ -1531,5 +1531,83 @@ "caller_cluster": "CONSUMER", "target_cluster": "SOURCE" } + ], + "history_scenarios": [ + { + "id": "H01", + "title": "Raw paging at page boundaries, Raw and UNS mappings", + "driver": "history_gate.py", + "restores_baseline": true, + "timeout_seconds": 600, + "coverage": [ + "Client CLI --page-size on projected counter", + "pages >= 2, last page no continuation", + "rows equal the origin row-for-row", + "single read equals the origin", + "tie clusters: not storable on SqlServer (PK) or QuestDB (DEDUP UPSERT KEYS(ts, tag)); proven by the H1 fuzz" + ] + }, + { + "id": "H02", + "title": "Processed with an aggregate the origin backend refuses for the node type", + "driver": "history_gate.py", + "restores_baseline": true, + "timeout_seconds": 600, + "coverage": [ + "Average on a String node => BadAggregateNotSupported (origin, #897)", + "the same refusal on the origin", + "Average on counter equals the origin" + ] + }, + { + "id": "H03", + "title": "AtTime, integer node", + "driver": "history_gate.py", + "restores_baseline": true, + "timeout_seconds": 600, + "coverage": [ + "--at-time on projected counter", + "values / timestamps / statuses equal the origin", + "UInt16 value type end to end" + ] + }, + { + "id": "H04", + "title": "Continuation across origin failover => BadContinuationPointInvalid, fresh read succeeds", + "driver": "history_gate.py", + "restores_baseline": true, + "timeout_seconds": 900, + "coverage": [ + "page 1 held in one consumer session", + "SOURCE primary stopped", + "resumed page BadContinuationPointInvalid", + "fresh read on the new primary Good" + ] + }, + { + "id": "H05", + "title": "Origin that does not advertise history => unsupported (substitute for a pinned v1 image)", + "driver": "history_gate.py", + "restores_baseline": true, + "timeout_seconds": 600, + "coverage": [ + "export drops HistoryRead (bit 32)", + "projected node => BadHistoryOperationUnsupported", + "the other export still served" + ] + }, + { + "id": "H06", + "title": "Denied vs unhistorized indistinguishable; session close releases origin continuations; origin rebuild mid-page", + "driver": "history_gate.py", + "restores_baseline": true, + "timeout_seconds": 900, + "coverage": [ + "unhistorized and origin-ACL-denied: identical BadHistoryOperationUnsupported", + "no local mapping-scope HistoryRead => BadUserAccessDenied (the other mapping still served)", + "origin open continuations >= 1 while held, 0 after the consumer session close", + "resume after an origin rebuild BadContinuationPointInvalid, fresh Good" + ] + } ] } diff --git a/scripts/validation/grpc-data/seed/Program.cs b/scripts/validation/grpc-data/seed/Program.cs index 5de18ec6a..ca340455c 100644 --- a/scripts/validation/grpc-data/seed/Program.cs +++ b/scripts/validation/grpc-data/seed/Program.cs @@ -172,7 +172,7 @@ try var root = mutation.RootElement; string[] allowedFields = ["connection_id", "target_mode", "target_node_id", "consistency", "consumer_node_ids", "connection_enabled", "connection_allowed_operations", "mapping_enabled", "write_through", "allowed_operations", "export_id", "export_enabled", "export_allowed_operations", "source_redundancy_mode", "consumer_redundancy_mode", - "control_redundancy_mode", "rename_tag", "upsert_tag", "upsert_reference", "remove_tag_id", "disable_feature", "key_action", "key_expiry_seconds", "upsert_connection", "upsert_mapping", "upsert_export", "remove_mapping_id", "maintenance_mode"]; + "control_redundancy_mode", "rename_tag", "upsert_tag", "upsert_reference", "remove_tag_id", "disable_feature", "key_action", "key_expiry_seconds", "upsert_connection", "upsert_mapping", "upsert_export", "remove_mapping_id", "maintenance_mode", "acl_permissions"]; if (root.ValueKind != JsonValueKind.Object || root.EnumerateObject().Any(property => !allowedFields.Contains(property.Name, StringComparer.Ordinal))) throw new InvalidOperationException("unknown fixture mutation field"); await using var db = await factory.CreateDbContextAsync(); @@ -283,7 +283,13 @@ try await db.UnsTagReferences.Where(x => x.TagId == removeTag.GetString()).ExecuteDeleteAsync(); await db.Tags.Where(x => x.TagId == removeTag.GetString()).ExecuteDeleteAsync(); } - if (root.TryGetProperty("disable_feature", out var disable) && disable.GetBoolean()) + if (root.TryGetProperty("acl_permissions", out var aclPermissions)) + { + // H3: {"node_acl_id": "...", "permission_flags": } — one existing row's flags (baseline restore reverts it). + var acl = await db.NodeAcls.SingleAsync(x => x.NodeAclId == aclPermissions.GetProperty("node_acl_id").GetString()); + acl.PermissionFlags = (NodePermissions)aclPermissions.GetProperty("permission_flags").GetInt32(); + } + if (root.TryGetProperty("disable_feature", out var disable) && disable.GetBoolean()) { foreach (var row in await db.DataConnections.ToListAsync()) { row.Enabled = false; row.Revision++; } foreach (var row in await db.RemoteNamespaceMappings.ToListAsync()) { row.Enabled = false; row.Revision++; } @@ -328,8 +334,11 @@ try foreach (var node in nodes.Where(x => x.StartsWith(cluster.ToLowerInvariant() + "-", StringComparison.Ordinal))) db.ClusterNodes.Add(new() { NodeId = node + ":4053", ClusterId = cluster, Host = node, OpcUaPort = 4840, DashboardPort = 9000, GrpcPort = 4056, ApplicationUri = "urn:OtOpcUa:grpc-data:" + node, CreatedBy = "grpc-data-local-gate" }); + // H3 (history profile): on CONSUMER the CLI principal's HistoryRead comes ONLY from the mapping-scoped grants below, + // so a scenario can take it away per mapping (plan §6: mapped history needs HistoryRead on the mapping scope). db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "cli-" + cluster, ClusterId = cluster, - Principal = "fixture-cli", ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.Admin }); + Principal = "fixture-cli", ScopeKind = NodeAclScopeKind.Cluster, + PermissionFlags = history && cluster == "CONSUMER" ? NodePermissions.Admin & ~NodePermissions.HistoryRead : NodePermissions.Admin }); } db.DriverInstances.Add(new() { DriverInstanceRowId = Guid.NewGuid(), DriverInstanceId = "source-modbus", ClusterId = "SOURCE", Name = "modbus", DriverType = "Modbus", DriverConfig = """{"TimeoutMs":2000,"AutoReconnect":true,"Probe":{"Enabled":true,"ProbeAddress":0}}""" }); @@ -347,7 +356,9 @@ try TagConfig = """{"region":"HoldingRegisters","address":24,"dataType":"UInt16","isArray":true,"arrayLength":3,"writable":true}""" }); db.Tags.Add(new() { TagRowId = Guid.NewGuid(), TagId = "source-text", DeviceId = "source-device", Name = "text", DataType = "String", AccessLevel = TagAccessLevel.ReadWrite, WriteIdempotent = false, PollGroupId = "source-fast", - TagConfig = """{"region":"HoldingRegisters","address":40,"dataType":"String","stringLength":16,"writable":true}""" }); + TagConfig = history + ? """{"region":"HoldingRegisters","address":40,"dataType":"String","stringLength":16,"writable":true,"isHistorized":true}""" + : """{"region":"HoldingRegisters","address":40,"dataType":"String","stringLength":16,"writable":true}""" }); db.UnsAreas.Add(new() { UnsAreaRowId = Guid.NewGuid(), UnsAreaId = "source-area", ClusterId = "SOURCE", Name = "area" }); db.UnsLines.Add(new() { UnsLineRowId = Guid.NewGuid(), UnsLineId = "source-line", UnsAreaId = "source-area", Name = "line" }); var uuid = Guid.NewGuid(); @@ -376,7 +387,10 @@ try ClusterId = "CONSUMER", DataConnectionId = "consumer-source", Enabled = true, ConsumerNodeIds = ["consumer-1:4053", "consumer-2:4053"], Realm = realm, RemoteRealm = realm, LocalParentKind = "Cluster", LocalParentId = "CONSUMER", BranchName = "remote-source", RemoteRootEntityId = entity, RemoteNamespaceUri = realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : V3NodeIds.UnsNamespaceUri, - RemoteIdentifierKind = "string", RemoteIdentifier = realm == DataRealm.Raw ? "modbus/plc" : equipment, AllowedOperations = operations, WriteThrough = true }); + RemoteIdentifierKind = "string", RemoteIdentifier = realm == DataRealm.Raw ? "modbus/plc" : equipment, AllowedOperations = grantedOperations, WriteThrough = true }); + if (history) + db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "cli-history-map-" + name, ClusterId = "CONSUMER", Principal = "fixture-cli", + ScopeKind = NodeAclScopeKind.RemoteNamespaceMapping, ScopeId = "map-" + name, PermissionFlags = NodePermissions.Browse | NodePermissions.HistoryRead }); } if (history) // The second principal's origin ACL also lacks HistoryRead: with its export's HistoryRead off the RPC is refused @@ -403,7 +417,8 @@ try browse_roots = new { raw = "modbus/plc", uns = unsBrowseRoot }, browse_subjects = new { raw = "modbus/plc", uns = "area/line/plc" }, origin_paths = new { raw = "modbus/plc/scalar", uns = "area/line/plc/scalar", raw_array = "modbus/plc/vector", uns_array = "area/line/plc/vector", raw_string = "modbus/plc/text", uns_string = "area/line/plc/text" }, aliases = new[] { "raw", "uns" }, - history = history ? new { historized = new { raw = "modbus/plc/counter", uns = "area/line/plc/counter" }, unhistorized = new { raw = "modbus/plc/scalar", uns = "area/line/plc/scalar" } } : null }); + history = history ? new { historized = new { raw = "modbus/plc/counter", uns = "area/line/plc/counter" }, unhistorized = new { raw = "modbus/plc/scalar", uns = "area/line/plc/scalar" }, + historized_string = new { raw = "modbus/plc/text", uns = "area/line/plc/text" } } : null }); return 0; } catch (Exception error) 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 65c5e8358..b4c47d698 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 @@ -44,7 +44,7 @@ public sealed partial class LocalDataServices internal int HistorySessionCount => _historySessions.Count; /// Open origin continuations (page cursors + chunk remainders) across every session (diagnostics/tests). - internal int HistoryOpenContinuations => _historySessions.OpenContinuations; + public int HistoryOpenContinuations => _historySessions.OpenContinuations; /// Remainder bytes retained for a principal across its sessions (diagnostics/tests). internal long HistoryRetainedBytes(string principal) => _historySessions.RetainedBytes(principal); From 763669562e879b93b4abc05c14c6c984afdcde42 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 00:44:04 -0500 Subject: [PATCH 07/25] docs(grpc-data): H3 OPC UA HistoryRead on projected nodes; rig H3 gate recipe --- docs/DataConnections.md | 63 +++++++++++++++++++++++++- scripts/validation/grpc-data/README.md | 26 +++++++++++ 2 files changed, 87 insertions(+), 2 deletions(-) diff --git a/docs/DataConnections.md b/docs/DataConnections.md index 6f0968576..0d8f7c776 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -192,8 +192,67 @@ local OPC UA clients keep at least one slot. At N = 1 there is no reservation: t **Consistency.** History follows the connection's consistency. `ReadyReplica` is allowed; the newest seconds can lag on a secondary while its continuous-historization outbox drains. -**Not supported yet.** OPC UA clients reading history on projected nodes of the consumer (H3); HistoryReadEvents and -modified-value reads (deferred); **HistoryUpdate is never forwarded**. +**Not supported yet.** HistoryReadEvents and modified-value reads (deferred); **HistoryUpdate is never forwarded**. + +## OPC UA HistoryRead on projected nodes (H3) + +Since H3 an OPC UA client of the CONSUMER can HistoryRead (Raw, Processed, AtTime) a projected variable in the +`https://zb.com/otopcua/mapped/raw|uns` namespaces exactly as it reads a local one; the consumer forwards the read over the +mapping's deployed connection (the runtime path above) and returns the origin's Part 11 answer verbatim — statuses, info bits, +timestamps (absent stays absent), values typed as the catalog says (a disagreeing value kind is `BadTypeMismatch`). + +**What a client sees.** A projected variable is `Historizing = true` with the `HistoryRead` access-level bit **only** when the +mapping grants `HistoryRead` (masked by the export's) **and** the origin's negotiated metadata says the node is historizing for +this principal (`HistoryInfo`, bit 32). Otherwise it carries `CurrentRead` only and the SDK answers +`BadHistoryOperationUnsupported` before any remote call. The `HistoryWrite` bit is never set: HistoryUpdate is not forwarded. + +**Grants** — all default off, and all required **even with `Security:Acl:Enabled=false`**, because mapped nodes always enforce the +mapping gate: + +| Where | What | +|---|---| +| Consumer `DataConnection.AllowedOperations` | `HistoryRead` (32) | +| Consumer `RemoteNamespaceMapping.AllowedOperations` | `HistoryRead` (32) | +| Consumer node ACL | `NodePermissions.HistoryRead` for the client's principal on the `RemoteNamespaceMapping` scope (or a scope above it) | +| Origin `DataExport.AllowedOperations` + origin node ACL | as for the runtime path above | + +Without the local grant (or without the mapping bit) the node answers `BadUserAccessDenied` — a local decision, distinct from the +origin's `BadHistoryOperationUnsupported`. An origin-side denial, an unhistorized node and an unknown node stay indistinguishable +(the origin's metadata does not mark the node historizing, so the consumer refuses it `BadHistoryOperationUnsupported`). + +**Mixed batches.** One HistoryRead may mix local and projected nodes: local nodes are served by the local historian exactly as +before, projected nodes remotely, every result in its own slot. The remote half runs under the same process-wide HistoryRead batch +limiter and never holds the node-manager lock. + +**Continuation points.** A projected read's continuation point lives in the client's OPC UA session like a local one (a `Remote` +cursor; capped by `MaxHistoryContinuationPoints`, oldest evicted). It wraps the origin's token and binds the caller (principal, key, +credential version), the mapping id **and revision**, the deployed connection route, the projection generation, the origin view and +the origin serving identity; a resume resends the **original** request details (the origin binds their hash — a client that changes +details on resume gets what it first asked for, as locally). Rules: + +- **A fresh read may move endpoint** within its deadline (a failed SOURCE node ⇒ the next endpoint); **a resumed read never moves**. +- A mapping revision change, a connection redeploy / lease expiry, a failover or origin restart (serving node / incarnation / + generation / role), a projection rebuild, another caller, or an origin history-epoch bump (an origin address-space removal or + rebuild) ⇒ `BadContinuationPointInvalid`; read again from the start. +- **Release:** `releaseContinuationPoints`, the session's close, an eviction and a refused save each forward one best-effort + `ReleaseHistoryAsync` per connection (releases coalesce for ~25 ms, so a session close sends one call per origin). The origin's + 60 s idle expiry is the backstop. +- Uncapped Raw (`NumValuesPerNode = 0`) returns the origin's continuation point (Part 11 permits a short page + CP): the origin pages + at its `MaxHistoryValuesPerPage` ceiling. + +**Limits.** + +| Limit | Effect | +|---|---| +| `RemoteNamespaceMapping.MaxHistoryAssemblyBytesPerRequest` (16 MiB) | One budget per request, shared across the batch (the tightest mapping in the batch). Nodes are charged in request order; once a node does not fit, it and every later projected node is `BadTooManyOperations` (never a partial answer; its origin cursor is released). | +| `ServerHistorian:HistoryReadDeadline` (consumer, 60 s) | The consumer request's remaining deadline, capped per call by `DataConnection.HistoryTimeoutMilliseconds` ⇒ `BadTimeout`. A cancelled request is never counted as an origin fault. | +| Aggregates | An aggregate the consumer cannot name is `BadAggregateNotSupported` unsent; one the origin's backend refuses (unknown to it, or not valid for the node's type — #897) comes back `BadAggregateNotSupported` from the origin. The consumer's `HistoryServerCapabilities/AggregateFunctions` does not describe remote backends. | + +Modified-value reads (`IsReadModified`) and HistoryReadEvents on projected nodes are refused `BadHistoryOperationUnsupported`. + +**Client CLI.** Resolve projected NodeIds by browsing from the mapping anchor (never construct `p1.` ids), then +`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). ## Feature boundary diff --git a/scripts/validation/grpc-data/README.md b/scripts/validation/grpc-data/README.md index 74607f1f4..003edf5d3 100644 --- a/scripts/validation/grpc-data/README.md +++ b/scripts/validation/grpc-data/README.md @@ -93,6 +93,32 @@ the consumer's connection and exports, and seeds a second principal `fixture-noh the probe's `--scenario history` origin RPCs, the CLI `historyread` and the CONSUMER `history` node-probe operation, and checks value parity. Without `--history` the rig, the seed and every D-scenario are unchanged. +## H3 projected-history gate (opt-in) + +`rig.py up --run-id --history [--history-backend sqlserver|questdb]` — `questdb` layers `compose.history.questdb.yml`: +SOURCE historizes into a run-owned QuestDB container (labelled, removed by `down`) instead of the run's SQL container. The H3 +seed profile also: grants HistoryRead on both mappings; gives the CLI principal its CONSUMER HistoryRead **only** through +`RemoteNamespaceMapping`-scoped grants (`cli-history-map-raw|uns`; the cluster grant is `Admin` minus HistoryRead); historizes +`text` (a String node, for the per-type aggregate refusal); and accepts the mutation +`acl_permissions: {node_acl_id, permission_flags}` (one ACL row's flags; the baseline restore reverts it). + +```bash +python3 scripts/validation/grpc-data/rig.py up --run-id h3-sql --history --timeout 900 +python3 scripts/validation/grpc-data/rig.py seed --run-id h3-sql +sleep 75 # CONTROL's ClusterNode contact refresh before the first deploy +python3 scripts/validation/grpc-data/rig.py deploy --run-id h3-sql --timeout 300 +python3 scripts/validation/grpc-data/history_gate.py --run-id h3-sql # H01..H06, or --scenario H04 +python3 scripts/validation/grpc-data/rig.py down --run-id h3-sql +``` + +`history_gate.py` accumulates `counter` history, resolves the projected NodeIds by a CLI `browse` from the shared root +(leaves under the `remote-source` anchors; never constructed `p1.` ids), then runs each `scenarios.json` → +`history_scenarios` row through the Client CLI `historyread` on CONSUMER and compares with the same read on the SOURCE +primary. The continuation scenarios use the CLI's hand-paged mode (`--page-size`, `--pause-after-page`, +`--abandon-after-page`, `--held-marker-file`); the origin's open continuations come from the `topology` node probe +(`originAccounting.historyOpenContinuations`). Every scenario restores the baseline. Results: +`evidence/H3-history--results.json`. + ## Scenario authoring and node probes The seeder is available through `LocalRig.seed_helper(action, *arguments)`. Its From 0a83c10ef6552f67f130ebce7fd08973bde80838 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 00:55:52 -0500 Subject: [PATCH 08/25] fix(client): processed history reads ask for the server's aggregate defaults Found by the H3 live gate (H02): Client.Shared sent the SDK's default AggregateConfiguration (all false / 0), which the server refuses as a non-default configuration (BadAggregateConfigurationRejected, #677) on local and projected nodes alike, so CLI/UI --aggregate reads never worked against it. Set UseServerCapabilitiesDefaults = true. OI regression test (red without the fix) also covers HistoryReadPageAsync. --- .../Adapters/DefaultSessionAdapter.cs | 5 ++- .../GrpcDataProjectedHistoryWireTests.cs | 38 ++++++++++++++++++- 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSessionAdapter.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSessionAdapter.cs index bd929f58f..f086ab4bb 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSessionAdapter.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSessionAdapter.cs @@ -285,7 +285,10 @@ internal sealed class DefaultSessionAdapter : ISessionAdapter StartTime = startTime, EndTime = endTime, ProcessingInterval = intervalMs, - AggregateType = [aggregateId] + AggregateType = [aggregateId], + // The SDK's default AggregateConfiguration is all-false/0 — a NON-default configuration, which this server + // refuses BadAggregateConfigurationRejected (#677). Ask for the server's own defaults, as Part 13 intends. + AggregateConfiguration = new AggregateConfiguration { UseServerCapabilitiesDefaults = true }, }; ArrayOf nodesToRead = [new HistoryReadValueId { NodeId = nodeId }]; diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataProjectedHistoryWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataProjectedHistoryWireTests.cs index f92e669a7..d709a0e71 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataProjectedHistoryWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataProjectedHistoryWireTests.cs @@ -113,6 +113,41 @@ public sealed class GrpcDataProjectedHistoryWireTests bridge.Calls.ShouldBe(0); } + [Fact(Timeout = 90000)] + public async Task The_shared_client_aggregate_read_asks_for_server_defaults_and_is_served() + { + // Found by the H3 live gate (H02): Client.Shared sent the SDK's default AggregateConfiguration (all false / 0), a + // NON-default configuration this server refuses BadAggregateConfigurationRejected (#677) — on local and projected + // nodes alike, so the CLI's --aggregate never worked against it. + var ct = Deadline(); + await using var rig = await StartModeAsync("H3ClientAggregate", "None", ct); + rig.Nm.HistorianDataSource = new Series(3, offset: 0); + rig.Nm.EnsureVariable("Plant/Speed", null, "Speed", "Int32", false, AddressSpaceRealm.Raw, historianTagname: "speed"); + rig.Enforce(false, [Key()]); + using var client = new ZB.MOM.WW.OtOpcUa.Client.Shared.OpcUaClientService(); + await client.ConnectAsync(new ZB.MOM.WW.OtOpcUa.Client.Shared.Models.ConnectionSettings + { + EndpointUrl = rig.EndpointUrl, + CertificateStorePath = Path.Combine(Path.GetTempPath(), $"otopcua-clientpki-{Guid.NewGuid():N}"), + }, ct); + var node = rig.Nm.TryGetVariable("Plant/Speed", AddressSpaceRealm.Raw)!.NodeId; + var values = await client.HistoryReadAggregateAsync(node, T0, T0.AddMinutes(1), + ZB.MOM.WW.OtOpcUa.Client.Shared.Models.AggregateType.Average, 60_000, ct); + values.Count.ShouldBe(1); + // The hand-paging API returns the server's page verbatim (status, values, continuation). + var page = await client.HistoryReadPageAsync(new ReadRawModifiedDetails + { + StartTime = T0.AddSeconds(-1), EndTime = T0.AddHours(1), NumValuesPerNode = 2, IsReadModified = false, ReturnBounds = false, + }, node, null, false, ct); + StatusCode.IsGood(page.Status).ShouldBeTrue(); + page.Values.Count.ShouldBe(2); + page.ContinuationPoint.ShouldNotBeNull(); + var released = await client.HistoryReadPageAsync(new ReadRawModifiedDetails { IsReadModified = false, ReturnBounds = false }, + node, page.ContinuationPoint, true, ct); + StatusCode.IsGood(released.Status).ShouldBeTrue(); + await client.DisconnectAsync(ct); + } + // ------------------------------------------------------------------------------------------------------------------ private static (NodeId Node, string Identifier) Setup(ServerEventRig consumer, bool aclEnabled, NodePermissions permissions) @@ -209,7 +244,8 @@ public sealed class GrpcDataProjectedHistoryWireTests } public Task ReadProcessedAsync(string fullReference, DateTime startUtc, DateTime endUtc, TimeSpan interval, - HistoryAggregateType aggregate, CancellationToken ct) => Task.FromResult(new HistorianRead([], null)); + HistoryAggregateType aggregate, CancellationToken ct) => + Task.FromResult(new HistorianRead([new DataValueSnapshot(42.0, 0, startUtc, startUtc)], null)); public Task ReadAtTimeAsync(string fullReference, IReadOnlyList timestampsUtc, CancellationToken ct) => Task.FromResult(new HistorianRead([], null)); From af06183412d785e824556bb8205f5e3cbe130689 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 01:04:04 -0500 Subject: [PATCH 09/25] fix(grpc-data): projected Processed values keep their aggregate's type Found by the H3 live gate (H02): a Double Average of a UInt16 node was decoded against the node's catalog kind and came back null + BadTypeMismatch per interval (the result status stayed Good, which is why the wire test missed it). Raw/AtTime values are still checked against the catalog kind; Processed values accept any scalar kind. The wire test now asserts the interval's value. Gate: re-browse the projected leaves after every deploy (a deploy retires cold projected nodes; the same opaque ids come back). --- scripts/validation/grpc-data/history_gate.py | 37 +++++++++++++++---- .../DataConnections/ProjectedHistoryAccess.cs | 18 +++++++-- .../GrpcDataProjectedHistoryWireTests.cs | 5 +++ 3 files changed, 49 insertions(+), 11 deletions(-) diff --git a/scripts/validation/grpc-data/history_gate.py b/scripts/validation/grpc-data/history_gate.py index c4514f852..bc9857530 100644 --- a/scripts/validation/grpc-data/history_gate.py +++ b/scripts/validation/grpc-data/history_gate.py @@ -98,6 +98,29 @@ class HistoryGate: self.runner.save("H-projected-nodes.json", {f"{k[0]}/{k[1]}": v for k, v in found.items()}) return consumer + def rebrowse(self, timeout=90): + """A deploy retires cold projected nodes; browse from the anchor again (the SAME opaque ids come back).""" + end = time.monotonic() + timeout + while True: + try: + previous = dict(self.projected) + self.resolve_projected() + self.runner.check(not previous or previous == self.projected, "projected NodeIds are stable across a deploy") + return + except scenarios.ScenarioError: + if time.monotonic() >= end: + raise + time.sleep(3) + + def change(self, **mutation): + """A production mutation + deploy, then re-materialise the projected leaves by browse.""" + self.runner.mutate(**mutation) + self.rebrowse() + + def restore(self): + self.runner.baseline() + self.rebrowse() + def held(self, consumer, extra, name, during, *, marker_timeout=60): """Runs a hand-paged CLI read in the background; `during()` runs once the read reports its held point.""" marker = self.runner.folder / (name + "-" + uuid.uuid4().hex[:6] + ".held") @@ -270,7 +293,7 @@ class HistoryGate: consumer = self.runner.primary("consumer") before, _, _ = self.poll_status(consumer, self.projected[("raw", "counter")], "Good", "before", timeout=30) self.runner.check(before == "Good", "history served before the change") - self.runner.mutate(export_id="export-raw", export_allowed_operations=EXPORT_WITHOUT_HISTORY) + self.change(export_id="export-raw", export_allowed_operations=EXPORT_WITHOUT_HISTORY) observed, attempts, result = self.poll_status(consumer, self.projected[("raw", "counter")], "BadHistoryOperationUnsupported", "not-advertised", timeout=180) self.runner.check(observed == "BadHistoryOperationUnsupported", "an origin that does not advertise history ⇒ unsupported") @@ -287,22 +310,22 @@ class HistoryGate: unhistorized, _, unh = self.poll_status(consumer, self.projected[("raw", "scalar")], "BadHistoryOperationUnsupported", "unhistorized", timeout=30) self.runner.check(unhistorized == "BadHistoryOperationUnsupported", "unhistorized ⇒ BadHistoryOperationUnsupported") - self.runner.mutate(acl_permissions={"node_acl_id": "source-peer", "permission_flags": NODE_PERMISSIONS_ADMIN & ~NODE_PERMISSIONS_HISTORY_READ}) + self.change(acl_permissions={"node_acl_id": "source-peer", "permission_flags": NODE_PERMISSIONS_ADMIN & ~NODE_PERMISSIONS_HISTORY_READ}) denied, attempts, den = self.poll_status(consumer, self.projected[("raw", "counter")], "BadHistoryOperationUnsupported", "origin-denied", timeout=180) normalise = lambda text: re.sub(r"ns=\d+;s=\S+", "", "\n".join(l for l in (text.stdout + text.stderr).splitlines() if "Bad" in l)) self.runner.check(denied == "BadHistoryOperationUnsupported", "origin ACL denial ⇒ BadHistoryOperationUnsupported") self.runner.check(normalise(unh) == normalise(den), "denied and unhistorized are indistinguishable") report["indistinguishable"] = {"unhistorized": normalise(unh), "denied": normalise(den), "attempts": attempts} - self.runner.baseline() + self.restore() # (b) the LOCAL mapping-scope grant: without it, BadUserAccessDenied (a local decision); the other mapping keeps its grant. - self.runner.mutate(acl_permissions={"node_acl_id": "cli-history-map-raw", "permission_flags": NODE_PERMISSIONS_BROWSE}) + self.change(acl_permissions={"node_acl_id": "cli-history-map-raw", "permission_flags": NODE_PERMISSIONS_BROWSE}) local, attempts, _ = self.poll_status(consumer, self.projected[("raw", "counter")], "BadUserAccessDenied", "local-denied", timeout=90) self.runner.check(local == "BadUserAccessDenied", "no local HistoryRead grant on the mapping scope ⇒ BadUserAccessDenied") other, _, _ = self.poll_status(consumer, self.projected[("uns", "counter")], "Good", "local-other-mapping", timeout=30) self.runner.check(other == "Good", "the UNS mapping's own grant still serves") report["local_deny"] = {"raw": local, "uns": other, "attempts": attempts} - self.runner.baseline() + self.restore() consumer = self.runner.primary("consumer") # (c) a consumer session close releases the origin continuation. self.runner.check(self.origin_state() == 0, "no origin continuation open before") @@ -323,7 +346,7 @@ class HistoryGate: report["session_close"] = {"held": counts.get("held"), "after": after, "lines": self.status_lines(abandoned.stdout)} # (d) origin rebuild mid-page: a resumed page after the origin's history epoch moved is BadContinuationPointInvalid. def rebuild(): - self.runner.mutate(rename_tag={"tag_id": "source-array1", "name": "array1-renamed"}) + self.change(rename_tag={"tag_id": "source-array1", "name": "array1-renamed"}) rebuilt = self.held(consumer, ["-n", self.projected[("raw", "counter")], *self.window_args(), "--page-size", "3", "--pause-after-page", "1", "--fresh-after-failure"], "rebuild", rebuild) lines = self.status_lines(rebuilt.stdout) @@ -354,7 +377,7 @@ class HistoryGate: finally: try: self.runner.deadline = time.monotonic() + 600 - self.runner.baseline() + self.restore() restored = True except Exception as failure: error = (error + "; " if error else "") + "restoration " + type(failure).__name__ + ": " + str(failure) 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 fd4665757..6ac215124 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs @@ -271,7 +271,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl target, callerKey, key.Details, nodes[i].Resume is RemoteCursor prior ? prior.AggregateId : nodes[i].AggregateId); } - outcomes[i] = new ProjectedHistoryOutcome(answer.StatusCode, Convert(answer.Samples, target.OriginMetadata), next); + outcomes[i] = new ProjectedHistoryOutcome(answer.StatusCode, Convert(answer.Samples, target.OriginMetadata, key.Details is DataHistoryProcessedDetails), next); } } finally @@ -326,8 +326,12 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl private static string CallerKey(RoleCarryingUserIdentity caller) => string.Join('\0', caller.Principal ?? "", caller.ApiKeyId ?? "", caller.CredentialVersion ?? ""); - /// Values verbatim (status, absent timestamps); a value kind that disagrees with the catalog is BadTypeMismatch. - private static OriginHistorySample[] Convert(IReadOnlyList samples, DataMetadata metadata) + /// + /// Values verbatim (status, absent timestamps). Raw and AtTime values are the node's own values: a kind that disagrees + /// with the catalog is BadTypeMismatch (plan §3.3), never coerced. A Processed value has its AGGREGATE's type (a + /// Double Average or an Int32 Count of a UInt16 node), so only its shape is checked: any scalar kind is accepted. + /// + private static OriginHistorySample[] Convert(IReadOnlyList samples, DataMetadata metadata, bool processed) { var converted = new OriginHistorySample[samples.Count]; for (var i = 0; i < samples.Count; i++) @@ -335,7 +339,13 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl var sample = samples[i]; object? value; var status = sample.StatusCode; - try { value = ProjectedDataAccess.DecodeValue(sample.Value, metadata); } + try + { + var expected = processed && sample.Value.Kind is not (DataValueKind.Null or DataValueKind.Array) + ? metadata with { ValueKind = sample.Value.Kind, ValueRank = -1, Dimensions = [], ArrayElementKind = null } + : metadata; + value = ProjectedDataAccess.DecodeValue(sample.Value, expected); + } catch (Exception ex) when (ex is ArgumentException or InvalidCastException or InvalidOperationException) { value = null; diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs index b97c47ce6..a6771aa60 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs @@ -171,6 +171,11 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests // A served aggregate passes through. var average = await ProcessedHistory(client, anchor, ObjectIds.AggregateFunction_Average); StatusCode.IsGood(average.StatusCode).ShouldBeTrue(average.StatusCode.ToString()); + // Found by the H3 live gate (H02): an aggregate's value has ITS OWN type (a Double Average of an Int32 node), + // never the node's — it must not be refused BadTypeMismatch against the catalog's value kind. + var interval = Values(average).ShouldHaveSingleItem(); + StatusCode.IsGood(interval.StatusCode).ShouldBeTrue(interval.StatusCode.ToString()); + SdkValueBoundary.ToClr(interval.WrappedValue).ShouldBeOfType().ShouldBe(3.0); }, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin)); } From 99c873e514cafa53fd0f736e99eb4b234cf93654 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 01:21:57 -0500 Subject: [PATCH 10/25] =?UTF-8?q?docs(grpc-data):=20H3=20evidence=20?= =?UTF-8?q?=E2=80=94=20gates=20and=20H01-H06=20live=20on=20SqlServer=20and?= =?UTF-8?q?=20QuestDB=20origins?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/plans/evidence/grpc-data-ext/H3.md | 122 ++++++++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 docs/plans/evidence/grpc-data-ext/H3.md diff --git a/docs/plans/evidence/grpc-data-ext/H3.md b/docs/plans/evidence/grpc-data-ext/H3.md new file mode 100644 index 000000000..64b03f0ae --- /dev/null +++ b/docs/plans/evidence/grpc-data-ext/H3.md @@ -0,0 +1,122 @@ +# H3 evidence — consumer OPC UA projection of remote history + +Phase H3 of `docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md`, 2026-11-24. + +## What changed + +- **Projected access level.** `ProjectedVariableDefinition.Historizing` (set by the applier and the exact-item renewal from + `ProjectedHistoryAccess.Advertises(proof)` = mapping∧export grant `HistoryRead` **and** the origin's negotiated + `HistoryInfo.Historizing`). Only then is the node `Historizing` with `CurrentRead | HistoryRead`; it follows renewals in place + (`ApplyProjectedHistorizing`, under `Lock`, a change-mask notify). `HistoryWrite` is never set. +- **`OpcUaServer/IProjectedHistoryAccess.cs`**: SDK-free contract — `ReadAsync(caller, DataHistoryDetails, nodes, deadline, ct)`, + `ProjectedHistoryNode(NodeId, AggregateId, Resume)`, `ProjectedHistoryOutcome(status, OriginHistorySample[], next)` and the + opaque `ProjectedHistoryContinuation` (idempotent `Release`, `TryClaimForResume`). +- **Override split** (`OpcUaServer/ProjectedHistoryRead.cs`, a NM partial). Raw/Processed/AtTime overrides authorize as before, + then `ServeHistoryReadSplit`: with no projected handle the H1 adapter is called exactly as before; otherwise local handles go to + the H1 port and projected handles (mapped/raw, mapped/uns namespaces) to `ProjectedHistoryAccess`, every outcome written to its + handle's own `results[i]`/`errors[i]`. The remote half runs under the same process-wide batch limiter, block-bridged once per + batch; the SDK has released `Lock` before it dispatches the overrides and nothing here takes it. Modified reads ⇒ + `BadHistoryOperationUnsupported`; an aggregate the consumer cannot name ⇒ `BadAggregateNotSupported`, unsent. +- **`HistoryCursorKind.Remote`** + `HistoryContinuationState.Remote`: the cursor lives in the SDK session store, bound to the + node (realm, identifier, namespace tag) and the consumer's history epoch. A take marks the SDK point `Taken`; **any other + dispose** of the point (session close, oldest-eviction, `releaseContinuationPoints` → `ReleaseHistory`, a faulted request) + calls `Remote.Release()` (decompiled SDK 2.0.1 `SessionContinuationPoints`: `Clear`, `AddHistoryContinuationPoint` eviction, + `ReleaseHistory`, `ReleaseSavedHistory` all dispose the stored value). A cursor of another node/kind/epoch is refused + `BadContinuationPointInvalid` and released. +- **`Runtime/DataConnections/ProjectedHistoryAccess.cs`**: per node a `DataOperations.HistoryRead` demand through + `ProjectedDataAccess.TryAcquire` (allowlist extended; requires `definition.Historizing`; policy `AuthorizeMapped(HistoryRead)` ⇒ + mapping bit + local `NodePermissions.HistoryRead` on the mapping scope, ACLs on or off), described by + `TryDescribeHistoryDemand` (mapping id/revision, connection, origin metadata, serving, generation). Groups = + (connection, details, resumed endpoint|fresh) so a resumed item never shares a call with items that may move. The + `RemoteCursor` binds caller key (principal, key, credential version), mapping id+revision, connection id + lease `RouteIdentity`, + projection generation, origin view, serving (node, incarnation, serving generation, role), the ORIGINAL details and aggregate; + `CursorMatches` re-checks all of it on resume, and the route identity before the call; any change ⇒ `BadContinuationPointInvalid` + and the origin token released. Per-request assembly budget = min `MaxHistoryAssemblyBytesPerRequest` of the batch's mappings, + charged in request order across groups; a node that does not fit and every later node ⇒ `BadTooManyOperations` (its origin + cursor released). Deadline = min(remaining `HistoryReadDeadline`, `HistoryTimeoutMilliseconds` — the connection applies the + latter) ⇒ `BadTimeout`; a cancel is never an origin fault. Releases coalesce per connection (25 ms) into one + `ReleaseHistoryAsync`. Values: Raw/AtTime checked against the catalog kind (`BadTypeMismatch`); Processed values keep their + aggregate's own scalar kind. +- **`DataPlaneAuthorizer`**: mapped HistoryRead opened deliberately via an explicit allowlist (Browse/Read/Write*/TransferSubscriptions/ + HistoryRead); every other mapped operation stays closed. **DI/host**: `ProjectedHistoryAccess` registered beside + `ProjectedDataAccess`; `OtOpcUaServerHostedService` wires `NodeManager.ProjectedHistoryAccess`. +- **H2 pin replaced**: `HistoryRead_on_a_projected_node_stays_a_clean_refusal_until_H3` (Runtime) became + `Granted_projected_HistoryRead_is_served_verbatim…` (granted ⇒ served) and `Without_the_local_HistoryRead_grant…` (⇒ + `BadUserAccessDenied`, unsent), both tagged H2 + H3. +- **Client.** `IOpcUaClientService.HistoryReadPageAsync` (one page verbatim) and CLI `historyread --page-size / --pause-after-page / + --resume-when-file / --held-marker-file / --fresh-after-failure / --abandon-after-page / --release-after-page / --hold-seconds / + --at-time`. **Defect found by the gate (H02, pre-existing):** Client.Shared processed reads sent the SDK's default + `AggregateConfiguration` (all false/0), which this server refuses `BadAggregateConfigurationRejected` (#677) — CLI/UI + `--aggregate` never worked against OtOpcUa; now `UseServerCapabilitiesDefaults = true` (OI regression test, red without). +- **Defect found by the gate (H02, H3):** projected Processed values were decoded against the node's catalog kind (a Double + Average of a UInt16 node ⇒ null + `BadTypeMismatch` per interval under a Good result). Fixed; the wire test now asserts the value. + +## Tests + +| Suite | What | +|---|---| +| O `ProjectedHistoryReadTests` (7) | access bit only when historizing, never HistoryWrite; allow/deny with ACLs **off and on** (no local grant, no mapping bit, no identity ⇒ `BadUserAccessDenied`, unsent); mixed local+projected batch keeps slots (one remote call); Remote cursor resumes once (same object), single use, wrong node ⇒ invalid + released, `releaseContinuationPoints` and session close (store `Clear`) release; bad remote answer keeps no cursor; consumer-unknown aggregate and modified read unsent; absent bounds | +| R `GrpcDataConfiguredDiscoveryWireTests` H3 (12) | real consumer SDK session + real projection stack + real origin (`LocalDataServices` over a real NM history port and `PeerHistoryContinuationStore`): page-through verbatim to completion (origin store 0); no local grant ⇒ `BadUserAccessDenied` unsent; session close ⇒ origin continuations 0 and exactly one release call; `releaseContinuationPoints`; resume after lease expiry (route rotated) and after an origin epoch bump ⇒ invalid, fresh read Good; uncapped Raw returns the origin CP; `BadAggregateNotSupported` both ways + a served Average's value; Historizing/AccessLevel follow the grant; assembly budget shared across the batch (25 kB ⇒ 2 of 3, 15 kB ⇒ 1, 1.2 kB ⇒ 0, refused in request order, never partial) | +| R `GrpcDataProjectedHistoryCursorTests` (12) | resume rule: mapping revision change, another mapping/connection, projection rebuild, failover (node), origin restart (incarnation), serving generation, role, origin view, another caller, rotated credential ⇒ refused; epoch-only change resumes | +| OI `GrpcDataProjectedHistoryWireTests` (6) | real consumer session → real origin NM history port: mixed batch slots + page-through (ACL off/on), single use, session close ⇒ origin cursor store 0 (one release), no grant ⇒ denied unsent (ACL off/on); Client.Shared aggregate + page API | +| CLI `HistoryReadPagedCommandTests` (6) | paging, pause/resume + fresh, abandon/release + held marker, AtTime, option validation | + +## Gates + +| Gate | Result | +|---|---| +| `dotnet build ZB.MOM.WW.OtOpcUa.slnx` | 0 warnings, 0 errors | +| `run-unit-phase.py H3` (new key: OpcUaServer.Tests + Runtime.Tests) | passed (at `af0618341`) | +| `run-unit-phase.py H2` | passed (at `af0618341`) | +| `run-unit-phase.py H1, X0, P01–P09` | all passed (at `07eeea2bd`; later commits touch Client/CLI/rig and one Runtime decode path covered by H3/H2 reruns) | +| Full unit suites (`Category!=E2E&Category!=LiveIntegration`) | OpcUaServer 1415 (+1 skip), Runtime 1882 (+3 skips), Host 479, Client.CLI 224, Client.Shared 361, Client.UI 131 — all green | +| OpcUaServer.IntegrationTests `Feature=GrpcData` + history classes | 87 passed, 2 skips (AVEVA live) | +| Rig harness unit tests (`scripts/validation/grpc-data/tests`) | 296 passed | + +The runner accepts unit projects only, so OI is run separately (as H1 did). + +## Live gate — H01–H06 on both origin backends + +Standalone rig (`scripts/validation/grpc-data`, OrbStack, macOS), fresh run per backend at `af0618341`, normal build-hash checks +(no `--pinned-build`), recipe in the rig README §"H3 projected-history gate": + +```bash +python3 scripts/validation/grpc-data/rig.py up --run-id h3f- --history --history-backend --timeout 900 +python3 scripts/validation/grpc-data/rig.py seed --run-id h3f- +sleep 75 +python3 scripts/validation/grpc-data/rig.py deploy --run-id h3f- --timeout 300 +python3 scripts/validation/grpc-data/history_gate.py --run-id h3f- +python3 scripts/validation/grpc-data/rig.py down --run-id h3f- +``` + +Every read goes through the Client CLI `historyread` on CONSUMER's OPC UA endpoint, on projected NodeIds resolved by a CLI +`browse` from the shared root (leaves under the `remote-source` anchors; the same opaque `p1.` ids come back after every +deploy — re-browsed, never constructed), and is compared with the same read on the SOURCE primary. Every scenario restored the +baseline. + +| ID | SqlServer (`h3f-sqlserver`, 06:05–06:15 UTC) | QuestDB (`h3f-questdb`, 06:14–06:21 UTC) | +|---|---|---| +| H01 Raw paging, Raw + UNS | PASS (38): page size 3 ⇒ 11 pages, 31 rows per realm, last page no CP, row-for-row = origin; single read = origin | PASS (38): 10 pages, 29 rows per realm, = origin (µs timestamps) | +| H02 Processed, aggregate refused for the node type | PASS (28): Average on String `text` ⇒ `BadAggregateNotSupported` (origin answers the same); Average on `counter` 4 intervals = origin | PASS (28): same; 3 intervals = origin | +| H03 AtTime, integer node | PASS (26): 3 times, values 7/11/15 = origin, `UInt16` on both | PASS (26): 8/12/16 = origin, `UInt16` | +| H04 continuation across origin failover | PASS (38): page 1 held; `source-1` stopped ⇒ `source-2` primary; resumed page `BadContinuationPointInvalid`; fresh read Good on the new primary | PASS (38): identical | +| H05 v1 origin ⇒ unsupported (**substituted**) | PASS (46): Good ⇒ `BadHistoryOperationUnsupported` once the export drops HistoryRead; the UNS export still Good | PASS (46): identical | +| H06 denied vs unhistorized; session close; rebuild mid-page | PASS (154): unhistorized `scalar` and origin-ACL-denied `counter` ⇒ identical `HistoryRead of failed: BadHistoryOperationUnsupported (0x80720000).`; no local mapping grant ⇒ `BadUserAccessDenied` (UNS mapping still Good); origin open continuations 1 while the CLI held page 1, 0 after its session closed; resume after an origin rename (epoch bump) `BadContinuationPointInvalid`, fresh Good | PASS (154): identical | + +Teardown: `rig.py down` after each run; label-filtered `docker container ls -a / volume / network / image ls` ⇒ 0/0/0/0 for both +runs (the QuestDB container and volume carry the run labels). Results files: `evidence/H3-history--results.json` in each +(removed) run folder; copies taken before `down`. + +Earlier passes on `h3-sql` (pre-fix builds, same rig, `down` 0/0/0/0) found the two H02 defects above and that a deploy retires +cold projected nodes (`BadNodeIdUnknown` until re-browsed — the gate now re-browses after every deploy; a client reading a +projected node it has not browsed since a deploy sees the same; pre-existing v1 projection behaviour). + +## Not verified / substitutions + +- **H05**: the rig builds no pinned v1 image, so "v1 origin" is substituted by an origin that does not advertise history for the + principal (export without bit 32). The v1 wire shape itself is covered by the H2 recorded-v1-client gates. +- **H01 tie clusters**: not representable live on either backend — SqlServer `hist.Sample` PK `(TagId, SourceTimeUtc)`, QuestDB + `DEDUP UPSERT KEYS(ts, tag)` keep one sample per timestamp. Tie paging is proven by the H1 port fuzz (10k seeds). +- **ReadyReplica consistency** on projected history and the Gateway backend (H4) were not run. +- **ACL-off on the live rig**: the rig runs `Security:Acl:Enabled=true`; ACL-off is covered by O and OI tests. +- Diagnostics/metrics for projected history are H4. From 585d5079eb50fe51c6aae898fae95747d44dbaa7 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 01:40:18 -0500 Subject: [PATCH 11/25] =?UTF-8?q?fix(grpc-data):=20H3=20review=20D2/D3/D5?= =?UTF-8?q?=20=E2=80=94=20claimed=20cursors=20never=20leak;=20projected=20?= =?UTF-8?q?slot=20sub-limit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit D2: Release() after TryClaimForResume() was a no-op, so a claimed cursor leaked its origin continuation on every exit that never sent it (no gateway/identity, deadline spent after the local half, limiter rejection, a gateway fault). New ReleaseEvenIfClaimed() (at most once) on every post-claim exit; any exception from the gateway now fails the projected half per node instead of escaping. D3: projected reads hold at most N - max(1, N/4) of the N shared history batch slots (OriginHistoryPort.RemoteSlots), Wait(0) => BadTooManyOperations for the projected half, so a slow origin cannot starve local HistoryRead/HistoryUpdate. D5: a Remote cursor presented to a local node (raw/modified/events take paths) is released when it is taken. Red/green: each test fails with its fix reverted. --- .../HistoryReadPort.cs | 11 +- .../IProjectedHistoryAccess.cs | 24 +++- .../OtOpcUaNodeManager.cs | 2 + .../ProjectedHistoryRead.cs | 103 ++++++++++----- .../ProjectedHistoryReadTests.cs | 125 +++++++++++++++++- 5 files changed, 222 insertions(+), 43 deletions(-) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryReadPort.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryReadPort.cs index 53a57d358..0d4802ee8 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryReadPort.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryReadPort.cs @@ -462,7 +462,14 @@ public sealed partial class OtOpcUaNodeManager public byte[]? Save(HistoryContinuationState state, HistoryContinuationBinding binding) => nm._historyContinuationStore.Save(session, state); - public HistoryContinuationState? TryTake(byte[] continuationPoint, HistoryContinuationBinding binding) => - nm._historyContinuationStore.TryTake(session, continuationPoint); + public HistoryContinuationState? TryTake(byte[] continuationPoint, HistoryContinuationBinding binding) + { + var state = nm._historyContinuationStore.TryTake(session, continuationPoint); + if (state?.Remote is not { } remote) return state; + // H3 review D5: a projected node's Remote cursor presented to a LOCAL node is invalid here (the port refuses an + // unknown/mismatched cursor) — but it was taken out of the session, so release its origin continuation now. + remote.Release(); + return null; + } } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs index 35cc08751..dc050e9ef 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedHistoryAccess.cs @@ -12,7 +12,7 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; /// public abstract class ProjectedHistoryContinuation { - private int _released; + private int _claimed, _released; /// Creates a cursor bound to one projected node. /// The projected node's realm. @@ -31,20 +31,34 @@ public abstract class ProjectedHistoryContinuation public string LocalIdentifier { get; } /// True once the cursor was released or handed back for a resume (it is single-use either way). - public bool IsSpent => Volatile.Read(ref _released) != 0; + public bool IsSpent => Volatile.Read(ref _released) != 0 || Volatile.Read(ref _claimed) != 0; /// /// Best-effort, idempotent, non-blocking release of the origin continuation (releaseContinuationPoints, session - /// close, eviction, a store refusal). The origin's idle expiry is the backstop. + /// close, eviction, a store refusal). A no-op once the cursor was claimed for a resume: the resume owns it from then on + /// (and uses on every exit that does not send it). The origin's idle expiry is the + /// backstop. /// public void Release() { - if (Interlocked.Exchange(ref _released, 1) == 0) OnRelease(); + if (Volatile.Read(ref _claimed) != 0) return; + ReleaseOnce(); } + /// + /// Releases the origin continuation whether or not the cursor was claimed for a resume — for every post-claim exit that + /// never sends it (refused, limiter-rejected, timed out, faulted). Never releases twice. + /// + public void ReleaseEvenIfClaimed() => ReleaseOnce(); + /// 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() => Interlocked.Exchange(ref _released, 1) == 0; + public bool TryClaimForResume() => Volatile.Read(ref _released) == 0 && Interlocked.Exchange(ref _claimed, 1) == 0; + + private void ReleaseOnce() + { + if (Interlocked.Exchange(ref _released, 1) == 0) OnRelease(); + } /// Forwards the release to the origin (called at most once). protected abstract void OnRelease(); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index 6e2247825..d4a4aac1b 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -9045,6 +9045,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage // Single-use take. A miss (unknown / evicted / malformed / a RAW cursor) ⇒ BadContinuationPointInvalid // for THIS node only. var state = _historyContinuationStore.TryTake(session, inboundCp.ToArray()); + // H3: a projected node's Remote cursor taken here is a miss — release its origin continuation. + state?.Remote?.Release(); // A point is bound to the node that issued it: another node's source name is a miss too. var boundKey = MapKey(handle.NodeId); if (state is null || !HistoryContinuationMatches(state, boundKey.Realm, boundKey.Id, HistoryBindingTag(handle.NodeId), historyEpoch) || state.Kind != HistoryCursorKind.Events || state.Tagname != sourceName) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs index bc5c78f45..c50f6f9b3 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs @@ -26,6 +26,20 @@ public sealed partial class OtOpcUaNodeManager set => Volatile.Write(ref _projectedHistoryAccess, value); } + private volatile SemaphoreSlim? _projectedHistoryLimiter; + private readonly Lock _projectedHistoryLimiterGate = new(); + + /// + /// The projected share of the history batch slots, sized once from at first + /// use (as the shared limiter is): . + /// + internal SemaphoreSlim GetProjectedHistoryLimiter() + { + if (_projectedHistoryLimiter is { } gate) return gate; + lock (_projectedHistoryLimiterGate) + return _projectedHistoryLimiter ??= new SemaphoreSlim(OriginHistoryPort.RemoteSlots(Math.Max(1, MaxConcurrentHistoryReadBatches))); + } + /// Serves local handles through the port (unchanged) and projected handles remotely, each into its own slot. private void ServeHistoryReadSplit( ServerSystemContext context, @@ -94,7 +108,7 @@ public sealed partial class OtOpcUaNodeManager if (access is null || identity is null || remote is null) { // No projection gateway, no session identity, or a variant a remote read never serves (a modified read). - resume?.Release(); + resume?.ReleaseEvenIfClaimed(); SetProjectedStatus(handle, results, errors, StatusCodes.BadHistoryOperationUnsupported); continue; } @@ -119,46 +133,69 @@ public sealed partial class OtOpcUaNodeManager if (pending.Count == 0) return; var nodes = pending.Select(p => p.Node).ToArray(); IReadOnlyList? outcomes = null; - // The same process-wide batch limiter as local reads: a remote read also holds an SDK request thread. - WithHistoryBatchLimiter(pending, () => + void ReleaseResumes() { - TimeSpan remaining; - if (HistoryReadDeadline > TimeSpan.Zero) - { - remaining = HistoryReadDeadline - Stopwatch.GetElapsedTime(started); - if (remaining <= TimeSpan.Zero) - { - outcomes = nodes.Select(_ => new ProjectedHistoryOutcome(StatusCodes.BadTimeout.Code, [])).ToArray(); - foreach (var node in nodes) node.Resume?.Release(); - return; - } - } - else remaining = TimeSpan.Zero; + foreach (var node in nodes) node.Resume?.ReleaseEvenIfClaimed(); + } - try - { - outcomes = access!.ReadAsync(identity!, remote!, nodes, remaining, - context.OperationContext?.CancellationToken ?? CancellationToken.None).GetAwaiter().GetResult(); - } - catch (OperationCanceledException) - { - // The SDK request ended: a timeout for this caller, never an origin fault (the access owns the resumes). - outcomes = nodes.Select(_ => new ProjectedHistoryOutcome(StatusCodes.BadTimeout.Code, [])).ToArray(); - } - catch (Exception ex) when (ex is InvalidOperationException or ArgumentException or ObjectDisposedException) - { - outcomes = nodes.Select(_ => new ProjectedHistoryOutcome(StatusCodes.BadNoCommunication.Code, [])).ToArray(); - } - }, p => + // H3 review D3: projected reads may hold at most N - max(1, N/4) of the N process-wide history batch slots (the rule + // OriginHistoryPort.RemoteSlots applies to remote peers), so a slow origin can never starve local HistoryRead / + // HistoryUpdate. Exhausted => BadTooManyOperations for the projected half, unsent; the local half is unaffected. + var projectedSlots = GetProjectedHistoryLimiter(); + if (!projectedSlots.Wait(0)) { - p.Node.Resume?.Release(); - SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadTooManyOperations); - }); + ReleaseResumes(); + foreach (var p in pending) SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadTooManyOperations); + return; + } + + try + { + // The same process-wide batch limiter as local reads: a remote read also holds an SDK request thread. + WithHistoryBatchLimiter(pending, () => + { + TimeSpan remaining; + if (HistoryReadDeadline > TimeSpan.Zero) + { + remaining = HistoryReadDeadline - Stopwatch.GetElapsedTime(started); + if (remaining <= TimeSpan.Zero) + { + outcomes = nodes.Select(_ => new ProjectedHistoryOutcome(StatusCodes.BadTimeout.Code, [])).ToArray(); + ReleaseResumes(); + return; + } + } + else remaining = TimeSpan.Zero; + + try + { + outcomes = access!.ReadAsync(identity!, remote!, nodes, remaining, + context.OperationContext?.CancellationToken ?? CancellationToken.None).GetAwaiter().GetResult(); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + // Whatever escaped the gateway — the SDK request ending is a timeout, never an origin fault. The gateway + // normally owns the resumes; releasing them again is idempotent, so nothing claimed can leak (H3 review D2). + var status = ex is OperationCanceledException ? StatusCodes.BadTimeout.Code : StatusCodes.BadNoCommunication.Code; + outcomes = nodes.Select(_ => new ProjectedHistoryOutcome(status, [])).ToArray(); + ReleaseResumes(); + } + }, p => + { + p.Node.Resume?.ReleaseEvenIfClaimed(); + SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadTooManyOperations); + }); + } + finally + { + projectedSlots.Release(); + } if (outcomes is null) return; // the limiter rejected the batch if (outcomes.Count != pending.Count) { foreach (var o in outcomes) o.Continuation?.Release(); + ReleaseResumes(); foreach (var p in pending) SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadInternalError); return; } 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 7bceeb877..2ea1d6ce9 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 @@ -206,6 +206,115 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable atTime.UseSimpleBounds.ShouldBeTrue(); } + [Fact] + public async Task A_claimed_cursor_is_released_on_every_exit_that_never_sends_it() + { + // H3 review D2: Release() after a claim is a no-op, so each post-claim exit must use ReleaseEvenIfClaimed — exactly once. + var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead); + var store = new InMemoryHistoryContinuationStore(); + nm.HistoryContinuationStore = store; + var node = Project(nm, f, "Leak", historizing: true); + var paging = new FakeAccess { Paged = true }; + nm.ProjectedHistoryAccess = paging; + + (FakeCursor Cursor, ByteString Cp) HeldPoint() + { + var (results, _) = Raw(nm, f.Identity, [node]); + results[0].ContinuationPoint.IsEmpty.ShouldBeFalse(); + return (paging.Issued[^1], results[0].ContinuationPoint); + } + + // (a) the gateway disappears between the issue and the resume. + var (cursor, cp) = HeldPoint(); + nm.ProjectedHistoryAccess = null; + Raw(nm, f.Identity, [node], cp).Errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code); + cursor.Released.ShouldBe(1); + nm.ProjectedHistoryAccess = paging; + + // (b) the gateway throws (anything): BadNoCommunication, the resume released, nothing escapes. + (cursor, cp) = HeldPoint(); + nm.ProjectedHistoryAccess = new FakeAccess { Throw = new InvalidCastException("boom") }; + Raw(nm, f.Identity, [node], cp).Errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadNoCommunication.Code); + cursor.Released.ShouldBe(1); + nm.ProjectedHistoryAccess = paging; + + // (c) the request deadline was spent by the time the projected half starts. + (cursor, cp) = HeldPoint(); + nm.HistoryReadDeadline = TimeSpan.FromTicks(1); + Raw(nm, f.Identity, [node], cp).Errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code); + cursor.Released.ShouldBe(1); + nm.HistoryReadDeadline = TimeSpan.FromSeconds(60); + + // (d) the projected sub-limit is exhausted (limiter rejection). + (cursor, cp) = HeldPoint(); + var limiter = nm.GetProjectedHistoryLimiter(); + var taken = 0; + while (limiter.Wait(0, TestContext.Current.CancellationToken)) taken++; + try + { + Raw(nm, f.Identity, [node], cp).Errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code); + cursor.Released.ShouldBe(1); + } + finally { limiter.Release(taken); } + + // Positive control: a normal resume claims the cursor and does NOT release it (the read owns the token). + (cursor, cp) = HeldPoint(); + Raw(nm, f.Identity, [node], cp).Errors[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code); + cursor.Released.ShouldBe(0); + paging.Issued.Where(c => !ReferenceEquals(c, paging.Issued[^1])).ShouldAllBe(c => c.Released <= 1, "never released twice"); + } + + [Fact] + public async Task Projected_reads_cannot_take_every_history_slot_local_history_is_still_served() + { + // H3 review D3: projected reads hold at most N - max(1, N/4) of the N shared batch slots. + var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead); + nm.MaxConcurrentHistoryReadBatches = 4; // => 3 projected slots, 1 always left for local history + nm.EnsureVariable("Plant/LocalSlot", "Plant", "LocalSlot", "Double", false, AddressSpaceRealm.Raw, historianTagname: "L.slot"); + var local = nm.TryGetVariable("Plant/LocalSlot", AddressSpaceRealm.Raw)!.NodeId; + var node = Project(nm, f, "Slow", historizing: true); + var hold = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var slow = new FakeAccess { Hold = hold }; + nm.ProjectedHistoryAccess = slow; + var held = Enumerable.Range(0, 3).Select(_ => Task.Run(() => Raw(nm, f.Identity, [node]))).ToArray(); + var deadline = DateTime.UtcNow.AddSeconds(10); + while (Volatile.Read(ref slow.Entries) < 3 && DateTime.UtcNow < deadline) await Task.Delay(10, TestContext.Current.CancellationToken); + slow.Entries.ShouldBe(3, "three projected reads hold the three projected slots"); + try + { + // A fourth projected read is refused at once, unsent; local history is still served. + // (Bounded: without the sub-limit this read would take the 4th shared slot and wait on the held gateway.) + var (_, refused) = await Task.Run(() => Raw(nm, f.Identity, [node])) + .WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + refused[0].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code); + slow.Entries.ShouldBe(3); + var (localResults, localErrors) = Raw(nm, f.Identity, [local]); + StatusCode.IsGood(localErrors[0].StatusCode).ShouldBeTrue(localErrors[0].StatusCode.ToString()); + localResults[0].StatusCode.Code.ShouldBe(StatusCodes.GoodNoData.Code); + } + finally { hold.SetResult(); } + foreach (var (_, errors) in await Task.WhenAll(held)) StatusCode.IsGood(errors[0].StatusCode).ShouldBeTrue(); + } + + [Fact] + public async Task A_remote_cursor_presented_to_a_local_node_is_invalid_and_released() + { + // H3 review D5: the local take removes the SDK slot, so it must release the origin continuation. + var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead); + var store = new InMemoryHistoryContinuationStore(); + nm.HistoryContinuationStore = store; + nm.EnsureVariable("Plant/LocalCp", "Plant", "LocalCp", "Double", false, AddressSpaceRealm.Raw, historianTagname: "L.cp"); + var local = nm.TryGetVariable("Plant/LocalCp", AddressSpaceRealm.Raw)!.NodeId; + var node = Project(nm, f, "Remote", historizing: true); + var access = new FakeAccess { Paged = true }; + nm.ProjectedHistoryAccess = access; + var (results, _) = Raw(nm, f.Identity, [node]); + var (_, errors) = Raw(nm, f.Identity, [local], results[0].ContinuationPoint); + errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); + access.Issued.Single().Released.ShouldBe(1); + store.Count.ShouldBe(0); + } + // ------------------------------------------------------------------------------------------------------------------ private static (List Results, List Errors) Raw(OtOpcUaNodeManager nm, IUserIdentity? identity, @@ -326,12 +435,22 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable public uint Status { get; init; } public Func Answer { get; init; } = _ => [1.0, 2.0]; - public Task> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details, + /// When set, every call waits on it (a projected read holding its slot). + public TaskCompletionSource? Hold { get; set; } + public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + /// 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; + + public async Task> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details, IReadOnlyList nodes, TimeSpan deadline, CancellationToken cancellationToken) { - Calls++; + Interlocked.Increment(ref Calls); LastNodes = nodes; - return Task.FromResult>(nodes.Select(node => + 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 => { FakeCursor? next = null; if (Paged) From 1237e9e6d1d7e42fbebdf7d18f30ce7d5e23772d Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 01:48:12 -0500 Subject: [PATCH 12/25] =?UTF-8?q?fix(grpc-data):=20H3=20review=20D1/D4/D6/?= =?UTF-8?q?D7=20=E2=80=94=20probe=20cancel,=20sub-batches,=20flush=20wake-?= =?UTF-8?q?up,=20request-order=20budget?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit D1: a caller cancel (the projected deadline) during the connection's capability probe escaped as RpcException(Cancelled) and faulted the whole HistoryRead; it is now OperationCanceledException, the probe is capped by HistoryTimeout, and ProjectedHistoryAccess fails any escaping fault per node (BadTimeout when the deadline fired) and releases every cursor it owns. D4: calls are sub-batched at min(the deployed connection's batch, the origin's advertised MaxBatchItems) and at most one item per 256 B of the remaining assembly budget; a shortfall is BadTooManyOperations per node, never an endpoint failure. D6: the release flush is re-armed from a flag under its gate (no lost wake-up) and the stop source is never disposed under a running flush. D7: calls are runs of consecutive request positions read in request order, then the budget is charged in request order. Float32 node over a Double-returning backend reads Good Singles end to end (no KindMatches defect). Red/green for D1/D4/D7 by mutation; D6's race did not reproduce red. --- .../DataConnectionDeploymentRuntime.cs | 2 + .../GrpcDataConnection.History.cs | 11 +- .../DataConnections/ProjectedHistoryAccess.cs | 271 +++++++++++------- .../GrpcDataHistoryClientTests.cs | 31 ++ .../GrpcDataLocalConnectionTests.cs | 6 +- .../GrpcDataProjectedHistoryWireTests.cs | 222 +++++++++++++- 6 files changed, 437 insertions(+), 106 deletions(-) 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 684a41759..05ae4cab2 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs @@ -583,6 +583,8 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistor internal Func RouteCurrent => _routeCurrent; /// The configured row's operations, already masked to the understood set. internal DataOperations AllowedOperations => _allowed; + /// The connection row's batch size: a history request with more items is refused (H3 splits below it). + internal int MaxBatchItems => _batch; public IDataConnection Connection => this; public CancellationToken CancellationToken => _scope; public DataTarget Target => _inner.Target; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs index 71971f68c..2aa93be69 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs @@ -89,7 +89,13 @@ public sealed partial class GrpcDataConnection : IDataHistoryService Check(); cancellationToken.ThrowIfCancellationRequested(); Selected selected; - try { selected = await SelectAsync(_endpoints[index], start, request.Budget, false, cancellationToken).ConfigureAwait(false); ProbeSucceeded(); } + // The capability probe is capped by HistoryTimeout too (H3 review), like every history call. + try { selected = await SelectAsync(_endpoints[index], start, ProbeBudget(request.Budget), false, cancellationToken).ConfigureAwait(false); ProbeSucceeded(); } + catch (Exception ex) when (cancellationToken.IsCancellationRequested && ex is RpcException or OperationCanceledException) + { + // A caller cancel (a deadline) during the probe is a cancel, never an escaping RpcException (H3 review D1). + throw new OperationCanceledException("History read cancelled by the caller.", ex, cancellationToken); + } catch (Exception ex) when (!cancellationToken.IsCancellationRequested && ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException or TimeoutException or ArgumentException) { failure = ex; RecordFailure(ex); continue; } @@ -291,6 +297,9 @@ public sealed partial class GrpcDataConnection : IDataHistoryService catch (Exception ex) when (ex is RpcException or OperationCanceledException or InvalidOperationException) { } } + /// The capability probe's budget: the caller's, capped by . + private DataBudget ProbeBudget(DataBudget budget) => budget.Timeout <= HistoryTimeout ? budget : budget with { Timeout = HistoryTimeout }; + private static DataHistoryReadResult[] All(DataHistoryReadRequest request, uint status) => request.Items.Select(x => new DataHistoryReadResult(x.CorrelationId, status, [], null)).ToArray(); 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 6ac215124..47ef06202 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs @@ -49,6 +49,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl private readonly Dictionary> _pendingReleases = new(StringComparer.OrdinalIgnoreCase); private readonly CancellationTokenSource _stop = new(); private Task _releaseFlush = Task.CompletedTask; + private bool _flushScheduled; private int _disposed; /// Creates the gateway. @@ -103,8 +104,10 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl var outcomes = new ProjectedHistoryOutcome?[nodes.Count]; var demands = new IProjectedDemandLease?[nodes.Count]; var targets = new ProjectedHistoryTarget?[nodes.Count]; + var assembled = new long[nodes.Count]; + var assemblyRefused = new bool[nodes.Count]; var callerKey = CallerKey(caller); - long budget = DefaultAssemblyBudget; + long budget = DefaultAssemblyBudget, received = 0; try { // 1. Resolve, authorize and pin every node; check each resumed cursor against what it was issued under. @@ -114,7 +117,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl var cursor = node.Resume as RemoteCursor; if (node.Resume is not null && (cursor is null || !ReferenceEquals(cursor.Owner, this))) { - node.Resume.Release(); + node.Resume.ReleaseEvenIfClaimed(); outcomes[i] = Fail(BadContinuationPointInvalid); continue; } @@ -145,38 +148,77 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl if (target is not null) budget = Math.Min(budget, _assemblyBudget(target.MappingId) is { } b and > 0 ? b : DefaultAssemblyBudget); if (budget == long.MaxValue) budget = DefaultAssemblyBudget; - // 3. One call per (connection, details, resumed endpoint): a resumed item pins its issuing endpoint, so cursors of - // different endpoints, and fresh items (which may move), never share a call. - var groups = Enumerable.Range(0, nodes.Count).Where(i => outcomes[i] is null) - .GroupBy(i => new GroupKey(targets[i]!.ConnectionId, DetailsOf(nodes[i], details), ResumeKey(nodes[i]))) - .ToArray(); - foreach (var group in groups) + // 3. Calls per (connection, details, resumed endpoint): a resumed item pins its issuing endpoint, so cursors of + // different endpoints, and fresh items (which may move), never share a call. Calls are RUNS of consecutive + // request positions with one key, read in request order (H3 review D7), so the assembly budget is consumed in + // request order and a budget shortfall only ever refuses nodes later in the request. Each run is sub-batched. + var runs = new List<(GroupKey Key, List Indices)>(); + for (var i = 0; i < nodes.Count; i++) { - var indices = group.ToArray(); - if (cancellationToken.IsCancellationRequested) { FailAll(indices, BadTimeout); continue; } - TimeSpan remaining; - if (deadline > TimeSpan.Zero) + if (outcomes[i] is not null) continue; + var key = new GroupKey(targets[i]!.ConnectionId, DetailsOf(nodes[i], details), ResumeKey(nodes[i])); + if (runs.Count > 0 && runs[^1].Key == key) runs[^1].Indices.Add(i); + else runs.Add((key, [i])); + } + + foreach (var (key, list) in runs) + { + var indices = list.ToArray(); + if (cancellationToken.IsCancellationRequested || Remaining() <= TimeSpan.Zero) { FailAll(indices, BadTimeout); continue; } + if (received >= budget) { FailAll(indices, BadTooManyOperations); continue; } + await ReadGroupAsync(key, indices, cancellationToken).ConfigureAwait(false); + } + + // 4. Charge the assembly budget in REQUEST order (H3 review D7): the first node that does not fit, and every later + // node with data, is BadTooManyOperations; its next origin cursor is released. + var left = budget; + var exhausted = false; + for (var i = 0; i < nodes.Count; i++) + { + if (assemblyRefused[i]) { exhausted = true; continue; } + if (outcomes[i] is not { } outcome || assembled[i] == 0 && !exhausted) continue; + if (exhausted || assembled[i] > left) { - remaining = deadline - _clock.GetElapsedTime(started); - if (remaining <= TimeSpan.Zero) { FailAll(indices, BadTimeout); continue; } + exhausted = true; + (outcome.Continuation as RemoteCursor)?.ReleaseOrigin(); + outcomes[i] = Fail(BadTooManyOperations); + continue; } - else remaining = TimeSpan.FromHours(1); // unbounded locally: the connection's HistoryTimeout still caps each call - if (budget <= 0) { FailAll(indices, BadTooManyOperations); continue; } - await ReadGroupAsync(group.Key, indices, remaining, cancellationToken).ConfigureAwait(false); + + left -= assembled[i]; } return outcomes.Select(o => o ?? Fail(BadNoCommunication)).ToArray(); } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + // Last resort (H3 review D1): whatever escaped, fail per node — a timeout when the deadline fired — and release every + // origin cursor this request still owns. Nothing escapes to the SDK override. + var timedOut = cancellationToken.IsCancellationRequested || Remaining() <= TimeSpan.Zero || ex is OperationCanceledException; + for (var i = 0; i < nodes.Count; i++) + { + if (outcomes[i] is not null) continue; + nodes[i].Resume?.ReleaseEvenIfClaimed(); + outcomes[i] = Fail(timedOut ? BadTimeout : BadNoCommunication); + } + + return outcomes.Select(o => o!).ToArray(); + } finally { foreach (var demand in demands) demand?.Dispose(); } - async Task ReadGroupAsync(GroupKey key, int[] indices, TimeSpan remaining, CancellationToken ct) + TimeSpan Remaining() => deadline > TimeSpan.Zero + ? deadline - _clock.GetElapsedTime(started) + : TimeSpan.FromHours(1); // unbounded locally: the connection's HistoryTimeout still caps each call + + async Task ReadGroupAsync(GroupKey key, int[] indices, CancellationToken ct) { IGrpcDataAdapterConnectionLease? lease = null; try { + var remaining = Remaining(); using var timeout = new CancellationTokenSource(remaining, _clock); using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, timeout.Token); lease = await _connections.AcquireAsync(key.ConnectionId, linked.Token).ConfigureAwait(false); @@ -191,109 +233,106 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl } var route = lease.RouteIdentity; - var items = new List(indices.Length); - var sent = new List(indices.Length); + var sendable = new List(indices.Length); foreach (var i in indices) { - if (nodes[i].Resume is RemoteCursor cursor) + // The connection lease moved (expiry, redeployment, credential change): its tokens are gone. + if (nodes[i].Resume is RemoteCursor cursor && !Equals(cursor.RouteIdentity, route)) { - // The connection lease moved (expiry, redeployment, credential change): its tokens are gone. - if (!Equals(cursor.RouteIdentity, route)) - { - cursor.ReleaseOrigin(); - outcomes[i] = Fail(BadContinuationPointInvalid); - continue; - } - - items.Add(new DataHistoryReadItem(sent.Count.ToString(System.Globalization.CultureInfo.InvariantCulture), - targets[i]!.OriginMetadata.View, cursor.AggregateId, cursor.Token)); - } - else - { - items.Add(new DataHistoryReadItem(sent.Count.ToString(System.Globalization.CultureInfo.InvariantCulture), - targets[i]!.OriginMetadata.View, nodes[i].AggregateId)); + cursor.ReleaseOrigin(); + outcomes[i] = Fail(BadContinuationPointInvalid); + continue; } - sent.Add(i); + sendable.Add(i); } - if (items.Count == 0) return; - IReadOnlyList answers; - try + if (sendable.Count == 0) return; + var batch = await BatchSizeAsync(lease.Connection, sendable.Count, remaining, linked.Token).ConfigureAwait(false); + for (var offset = 0; offset < sendable.Count;) { - answers = await history.ReadAsync(new DataHistoryReadRequest(key.Details, items, - new DataBudget(remaining, items.Count, (int)Math.Min(int.MaxValue, budget))), linked.Token).ConfigureAwait(false); - } - catch (OperationCanceledException) - { - // Our deadline or the SDK request ending: a timeout, never an origin fault (the connection records none). - foreach (var i in sent) outcomes[i] = Fail(BadTimeout); - return; - } - - try - { - if (answers.Count != items.Count) + var now = Remaining(); + if (ct.IsCancellationRequested || now <= TimeSpan.Zero) { FailAll(sendable.Skip(offset).ToArray(), BadTimeout); return; } + // A budget shortfall refuses the remaining nodes unsent — never an endpoint failure (H3 review D4). A call may + // carry at most one item per MinimumBytesPerItem of its byte budget (the origin's admission rule). + var fitting = (int)Math.Min(int.MaxValue, (budget - received) / MinimumBytesPerItem); + if (fitting <= 0) { FailAll(sendable.Skip(offset).ToArray(), BadTooManyOperations); return; } + var from = offset; + var chunk = sendable.Skip(from).Take(Math.Min(batch, fitting)).ToArray(); + offset += chunk.Length; + var items = chunk.Select((i, k) => new DataHistoryReadItem(k.ToString(System.Globalization.CultureInfo.InvariantCulture), + targets[i]!.OriginMetadata.View, + nodes[i].Resume is RemoteCursor c ? c.AggregateId : nodes[i].AggregateId, + (nodes[i].Resume as RemoteCursor)?.Token)).ToArray(); + IReadOnlyList answers; + try { - foreach (var i in sent) outcomes[i] = Fail(BadNoCommunication); + answers = await history.ReadAsync(new DataHistoryReadRequest(key.Details, items, + new DataBudget(now, items.Length, budget - received)), linked.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + // Our deadline or the SDK request ending: a timeout, never an origin fault (the connection records none). + FailAll(sendable.Skip(from).ToArray(), BadTimeout); return; } - for (var k = 0; k < answers.Count; k++) + try { - var i = sent[k]; - var answer = answers[k]; - if (answer.CorrelationId != items[k].CorrelationId) + if (answers.Count != items.Length) { - outcomes[i] = Fail(BadNoCommunication); + FailAll(chunk, BadNoCommunication); continue; } - // The per-request assembly budget, in request order across the whole batch: once a node does not fit, - // it and every later node is BadTooManyOperations (never a partial answer; its origin cursor released). - long nodeBytes = 0; - foreach (var sample in answer.Samples) nodeBytes += sample.Value.EstimatedRetainedBytes; - if (nodeBytes > budget) + for (var k = 0; k < answers.Count; k++) { - budget = 0; - if (answer.Continuation is { } dropped) EnqueueRelease(key.ConnectionId, dropped); - outcomes[i] = Fail(BadTooManyOperations); - continue; + var i = chunk[k]; + var answer = answers[k]; + if (answer.CorrelationId != items[k].CorrelationId) + { + if (answer.Continuation is { } stray) EnqueueRelease(key.ConnectionId, stray); + outcomes[i] = Fail(BadNoCommunication); + continue; + } + + if (answer.StatusCode == BadTooManyOperations && answer.Diagnostic?.Contains("budget", StringComparison.OrdinalIgnoreCase) == true) + assemblyRefused[i] = true; // the connection's own share of the assembly budget ran out + long nodeBytes = 0; + foreach (var sample in answer.Samples) nodeBytes += sample.Value.EstimatedRetainedBytes; + assembled[i] = nodeBytes; + received += nodeBytes; + var target = targets[i]!; + RemoteCursor? next = null; + if (answer.Continuation is { } token) + { + next = new RemoteCursor(this, target.OriginMetadata.View.Realm, demands[i]!.LocalIdentifier, token, key.ConnectionId, route, + target, callerKey, key.Details, nodes[i].Resume is RemoteCursor prior ? prior.AggregateId : nodes[i].AggregateId); + } + + outcomes[i] = new ProjectedHistoryOutcome(answer.StatusCode, + Convert(answer.Samples, target.OriginMetadata, key.Details is DataHistoryProcessedDetails), next); } - - budget -= nodeBytes; - - var target = targets[i]!; - RemoteCursor? next = null; - if (answer.Continuation is { } token) - { - next = new RemoteCursor(this, target.OriginMetadata.View.Realm, demands[i]!.LocalIdentifier, token, key.ConnectionId, route, - target, callerKey, key.Details, nodes[i].Resume is RemoteCursor prior ? prior.AggregateId : nodes[i].AggregateId); - } - - outcomes[i] = new ProjectedHistoryOutcome(answer.StatusCode, Convert(answer.Samples, target.OriginMetadata, key.Details is DataHistoryProcessedDetails), next); + } + finally + { + foreach (var answer in answers) answer.Dispose(); } } - finally - { - foreach (var answer in answers) answer.Dispose(); - } - } catch (OperationCanceledException) { - foreach (var i in indices) - { - if (outcomes[i] is not null) continue; - if (nodes[i].Resume is RemoteCursor c) c.ReleaseOrigin(); - outcomes[i] = Fail(BadTimeout); - } - return; + FailAll(indices.Where(i => outcomes[i] is null).ToArray(), BadTimeout); } - catch (Exception ex) when (ex is InvalidOperationException or UnauthorizedAccessException or ArgumentException or ObjectDisposedException) + catch (Exception ex) when (ex is not OutOfMemoryException) { - foreach (var i in indices) outcomes[i] ??= Fail(nodes[i].Resume is null ? BadNoCommunication : BadContinuationPointInvalid); - return; + // An unexpected fault (an escaping RpcException, a malformed answer): per node, never out of the batch. + var timedOut = ct.IsCancellationRequested || Remaining() <= TimeSpan.Zero; + foreach (var i in indices.Where(i => outcomes[i] is null).ToArray()) + { + if (nodes[i].Resume is RemoteCursor c) c.ReleaseOrigin(); + outcomes[i] = Fail(timedOut ? BadTimeout : nodes[i].Resume is null ? BadNoCommunication : BadContinuationPointInvalid); + } } finally { @@ -311,6 +350,32 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl } } + /// + /// The sub-batch size of one call (H3 review D4): the deployed connection's own batch size, and — when more than one node + /// is sent — the origin's advertised MaxBatchItems (best effort: a failed probe keeps the connection's size). + /// + private static async Task BatchSizeAsync(IDataConnection connection, int count, TimeSpan remaining, CancellationToken ct) + { + var batch = connection is DataConnectionDeploymentLease lease ? lease.MaxBatchItems : DefaultBatchItems; + if (count > 1) + { + try + { + var capabilities = await connection.GetCapabilitiesAsync(new DataBudget(remaining, 1, 1L << 20), ct).ConfigureAwait(false); + if (capabilities.Limits.MaxBatchItems > 0) batch = Math.Min(batch, capabilities.Limits.MaxBatchItems); + } + catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException) { } + } + + return Math.Max(1, batch); + } + + /// The sub-batch size when the connection is not a deployment lease (tests, direct facades). + internal const int DefaultBatchItems = 100; + + /// An origin admits at most one item per this many bytes of a request's byte budget. + internal const long MinimumBytesPerItem = 256; + private static ProjectedHistoryOutcome Fail(uint status) => new(status, []); private static DataHistoryDetails DetailsOf(ProjectedHistoryNode node, DataHistoryDetails request) => @@ -358,6 +423,9 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl return converted; } + /// Queues a release directly (tests: the flush's wake-up under concurrent enqueues). + internal void EnqueueReleaseForTests(string connectionId, byte[] token) => EnqueueRelease(connectionId, token); + /// Queues an origin token for a coalesced best-effort release on its connection. private void EnqueueRelease(string connectionId, byte[] token) { @@ -366,7 +434,10 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl { if (!_pendingReleases.TryGetValue(connectionId, out var list)) _pendingReleases[connectionId] = list = []; list.Add(token); - if (!_releaseFlush.IsCompleted) return; + // H3 review D6: a flag under the gate, not Task.IsCompleted — a flush past its last check but not yet completed + // would otherwise swallow this token (a lost wakeup). The flush clears the flag under the same gate. + if (_flushScheduled) return; + _flushScheduled = true; _releaseFlush = Task.Run(FlushReleasesAsync); } } @@ -374,7 +445,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl private async Task FlushReleasesAsync() { try { await Task.Delay(ReleaseCoalesce, _stop.Token).ConfigureAwait(false); } - catch (OperationCanceledException) { return; } + catch (OperationCanceledException) { lock (_releaseGate) _flushScheduled = false; return; } Dictionary> batch; lock (_releaseGate) { @@ -402,15 +473,19 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl } lock (_releaseGate) + { if (_pendingReleases.Count > 0 && Volatile.Read(ref _disposed) == 0) _releaseFlush = Task.Run(FlushReleasesAsync); + else _flushScheduled = false; + } } /// public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + // Cancel only: a flush still running reads _stop.Token, so it is never disposed under it (H3 review D6). The source + // has no timer, so leaving it to the GC releases nothing. _stop.Cancel(); - _stop.Dispose(); } /// diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs index a246ccf00..cf78f7ddb 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs @@ -193,6 +193,31 @@ public sealed class GrpcDataHistoryClientTests await Should.ThrowAsync(() => connection.ReadHistoryAsync(Request(), cancel.Token)); } + [Fact] + [Trait("Phase", "H3")] + public async Task A_caller_cancel_during_the_capability_probe_is_an_OperationCanceledException_never_an_RpcException() + { + // H3 review D1: the probe that never answers used to surface RpcException(Cancelled) and fault the consumer's HistoryRead. + var a = new Endpoint("a") { ProbeDelay = TimeSpan.FromSeconds(30) }; + await using var connection = Connect([a]); + using var cancel = new CancellationTokenSource(TimeSpan.FromMilliseconds(200)); + var error = await Should.ThrowAsync(() => connection.ReadHistoryAsync(Request(), cancel.Token)); + error.ShouldNotBeAssignableTo(); + a.HistoryCalls.ShouldBe(0); + } + + [Fact] + [Trait("Phase", "H3")] + public async Task The_capability_probe_is_capped_by_HistoryTimeout_too() + { + var a = new Endpoint("a"); + await using var connection = Connect([a], historyTimeout: TimeSpan.FromSeconds(2)); + var request = Request() with { Budget = Request().Budget with { Timeout = TimeSpan.FromMinutes(10) } }; + (await connection.ReadHistoryAsync(request, TestContext.Current.CancellationToken)).Single().StatusCode.ShouldBe(0u); + a.LastProbeTimeout.ShouldNotBeNull(); + a.LastProbeTimeout!.Value.ShouldBeLessThanOrEqualTo(TimeSpan.FromSeconds(2)); + } + [Fact] public async Task A_failure_mid_assembly_releases_the_origin_chunk_tokens_it_holds() { @@ -225,6 +250,10 @@ public sealed class GrpcDataHistoryClientTests public bool Malformed { get; set; } /// Delay before answering a HistoryRead (honours the request's token). public TimeSpan? Delay { get; set; } + /// Delay before answering the capability probe (honours the request's token). + public TimeSpan? ProbeDelay { get; set; } + /// The grpc-timeout of the last capability probe. + public TimeSpan? LastProbeTimeout { get; private set; } /// Fail every HistoryRead after the first with this status. public Grpc.Core.StatusCode? FailAfterFirst { get; set; } public int Chunks { get; init; } = 1; @@ -247,6 +276,8 @@ public sealed class GrpcDataHistoryClientTests IMessage message; if (path.EndsWith("/GetCapabilities", StringComparison.Ordinal)) { + if (request.Headers.TryGetValues("grpc-timeout", out var probeTimeouts)) LastProbeTimeout = ParseTimeout(probeTimeouts.Single()); + if (ProbeDelay is { } probeDelay) await Task.Delay(probeDelay, token); var asked = request.Headers.Contains("x-otopcua-data-features"); var caps = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 5, Serving, Ready ? DataReadiness.Ready : DataReadiness.Unavailable, !Ready ? DataOperations.None : DataOperationSets.V1 | (history && asked && Granted ? DataOperations.HistoryRead : DataOperations.None), 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 e79f450f3..5b89a1f11 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 @@ -134,7 +134,7 @@ internal sealed class LocalDataFixture : IDisposable bool advanceAuthority = false, string role = "Primary", long servingGeneration = 0, bool nestedCatalog = false, bool nestedUnsCatalog = false, Func? writes = null, bool denyReadExport = false, ManualTimeProvider? clock = null, string servingNode = "node-a", string servingIncarnation = "serving-1", - IOriginHistoryPort? history = null) + IOriginHistoryPort? history = null, DataValueKind rawValueKind = DataValueKind.Int32, int maxBatchItems = 100) { if (clock is not null) Clock = clock; Serving = Serving with { NodeId = servingNode, Incarnation = servingIncarnation, Role = role, ServingGeneration = servingGeneration }; @@ -163,7 +163,7 @@ internal sealed class LocalDataFixture : IDisposable if (denyReadExport) operations &= ~DataOperations.Read; if (history is not null) operations |= DataOperations.HistoryRead; var rootMetadata = new DataMetadata(Root, "Plant", "Folder", DataValueKind.Null, -1, [], false, operations, 1, null, null, false); - var rawMetadata = new DataMetadata(Raw, "Speed", "Variable", DataValueKind.Int32, -1, [], true, operations, 1, Ticket.Key.StableSourceId, "rpm", false); + var rawMetadata = new DataMetadata(Raw, "Speed", "Variable", rawValueKind, -1, [], true, operations, 1, Ticket.Key.StableSourceId, "rpm", false); var unsMetadata = rawMetadata with { View = Uns }; var folder = Root with { Address = Root.Address with { Identifier = "Plant/Driver" }, Subject = "Plant/Driver" }; var unsRoot = Uns with { Address = Uns.Address with { Identifier = "Area" }, Subject = "Area" }; @@ -192,7 +192,7 @@ internal sealed class LocalDataFixture : IDisposable Catalog = new LocalExportCatalog("cluster", Serving, Activation.CaptureAuthority(), nodes, [new() { DataExportId = "raw-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw, RootKind = "RawFolder", RootEntityId = "folder", PrincipalId = "peer", AllowedOperations = operations }, new() { DataExportId = "uns-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = nestedUnsCatalog ? "UnsArea" : "UnsTagReference", RootEntityId = nestedUnsCatalog ? "area" : "reference", PrincipalId = "peer", AllowedOperations = operations }]); - var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000, TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1)); + var limits = new DataLimits(100, maxBatchItems, 1_000_000, 100, 10, 1_000_000, TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1)); 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, diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs index a6771aa60..d991e70ed 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs @@ -240,6 +240,151 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests }, localPermissions: 15, allowHistory: granted, connectionSource: new PersistentConnections(origin)); } + [Fact(Timeout = 90000)] + [Trait("Phase", "H3")] + public async Task A_Float32_node_whose_backend_returns_Double_reads_Good_through_the_projection_as_it_does_locally() + { + // H3 review: SQL backends store every float as a Double. The origin port normalises Raw / AtTime to the node's type + // (Single) before the wire, so the projected rows are Good Singles — never a BadTypeMismatch per row while local works. + await using var originServer = await HistoryOrigin.StartAsync(5, dataType: "Float", value: i => i + 0.5); + using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port, rawValueKind: DataValueKind.Float); + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var raw = await RawHistory(client, anchor, 0, default); + StatusCode.IsGood(raw.StatusCode).ShouldBeTrue(raw.StatusCode.ToString()); + var values = Values(raw); + values.Count.ShouldBe(5); + values.ShouldAllBe(v => StatusCode.IsGood(v.StatusCode)); + values.Select(v => SdkValueBoundary.ToClr(v.WrappedValue)).ShouldBe(Enumerable.Range(0, 5).Select(i => (object?)(float)(i + 0.5))); + var details = new ReadAtTimeDetails { ReqTimes = [(DateTimeUtc)HistoryT0.AddSeconds(2)] }; + var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(details), TimestampsToReturn.Both, false, + [new HistoryReadValueId { NodeId = anchor }], TestContext.Current.CancellationToken); + var atTime = Values(response.Results.ToArray()!.Single()).ShouldHaveSingleItem(); + StatusCode.IsGood(atTime.StatusCode).ShouldBeTrue(atTime.StatusCode.ToString()); + SdkValueBoundary.ToClr(atTime.WrappedValue).ShouldBeOfType().ShouldBe(2.5f); + }, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin)); + } + + [Theory(Timeout = 90000)] + [Trait("Phase", "H3")] + [InlineData(HistoryMode.Hang)] + [InlineData(HistoryMode.Throw)] + public async Task A_history_call_that_never_answers_or_faults_fails_only_the_projected_half_and_releases_its_cursor(HistoryMode mode) + { + // H3 review D1: a deadline during the connection's capability probe used to escape as an RpcException and fault the + // whole HistoryRead. Now the projected half fails per node (BadTimeout when the deadline fired), the local half of the + // same batch is served, and the claimed origin cursor is released (positive control: the origin store returns to 0). + await using var originServer = await HistoryOrigin.StartAsync(7); + using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); + var connections = new HistorySwitchConnections(origin); + ProjectedHistoryAccess? history = null; + OtOpcUaNodeManager? manager = null; + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + manager!.HistorianDataSource = new SeriesSource(Enumerable.Range(0, 3) + .Select(i => new DataValueSnapshot(i, 0, HistoryT0.AddSeconds(i), HistoryT0.AddSeconds(i))).ToArray()); + manager.EnsureVariable("Plant/LocalH", "Plant", "LocalH", "Int32", false, AddressSpaceRealm.Raw, historianTagname: "local"); + var local = manager.TryGetVariable("Plant/LocalH", AddressSpaceRealm.Raw)!.NodeId; + var page = await RawHistory(client, anchor, 2, default); + page.ContinuationPoint.IsEmpty.ShouldBeFalse(); + origin.Services.HistoryOpenContinuations.ShouldBe(1); + + connections.Mode = mode; + manager.HistoryReadDeadline = TimeSpan.FromSeconds(1); + var response = await client.HistoryReadAsync(new RequestHeader { TimeoutHint = 20_000 }, new ExtensionObject(RawDetails(2)), + TimestampsToReturn.Both, false, + [new HistoryReadValueId { NodeId = local }, new HistoryReadValueId { NodeId = anchor, ContinuationPoint = page.ContinuationPoint }], + TestContext.Current.CancellationToken); + var results = response.Results.ToArray()!; + StatusCode.IsGood(results[0].StatusCode).ShouldBeTrue("the local half of the batch is still served"); + Values(results[0]).Count.ShouldBe(2); + results[1].StatusCode.Code.ShouldBe(mode == HistoryMode.Hang ? StatusCodes.BadTimeout.Code : StatusCodes.BadContinuationPointInvalid.Code); + await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0); + origin.Services.HistoryOpenContinuations.ShouldBe(0, "the claimed cursor's origin continuation was released"); + }, localPermissions: 15, allowHistory: true, connectionSource: connections, onHistory: (h, m) => { history = h; manager = m; }); + } + + [Fact(Timeout = 90000)] + [Trait("Phase", "H3")] + public async Task A_group_larger_than_the_origin_batch_is_split_into_sub_batches() + { + // H3 review D4: three projected nodes against an origin that admits two items per request. + await using var originServer = await HistoryOrigin.StartAsync(7, extra: 2); + using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1, history: originServer.Port, maxBatchItems: 2); + var connections = new HistorySwitchConnections(origin); + await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray(); + children.Length.ShouldBe(3); + var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(3)), TimestampsToReturn.Both, false, + children.Select(c => new HistoryReadValueId { NodeId = c }).ToArray(), TestContext.Current.CancellationToken); + var results = response.Results.ToArray()!; + results.ShouldAllBe(r => StatusCode.IsGood(r.StatusCode)); + results.ShouldAllBe(r => Values(r).Count == 3); + connections.HistoryCallSizes.ShouldBe([2, 1]); + foreach (var r in results) await RawHistory(client, children[Array.IndexOf(results, r)], 3, r.ContinuationPoint); + }, localPermissions: 15, allowHistory: true, connectionSource: connections); + } + + [Fact(Timeout = 90000)] + [Trait("Phase", "H3")] + public async Task The_assembly_budget_is_charged_in_request_order_across_groups() + { + // H3 review D7: request [A fresh, B resumed, C fresh] runs as two groups ({A, C} then {B}); with room for two nodes the + // refused one must be C — the last in REQUEST order — not B. + await using var originServer = await HistoryOrigin.StartAsync(7, extra: 2); + using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1, history: originServer.Port); + await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray(); + children.Length.ShouldBe(3); + var first = await RawHistory(client, children[1], 3, default); + first.ContinuationPoint.IsEmpty.ShouldBeFalse(); + var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(3)), TimestampsToReturn.Both, false, + [new HistoryReadValueId { NodeId = children[0] }, new HistoryReadValueId { NodeId = children[1], ContinuationPoint = first.ContinuationPoint }, + new HistoryReadValueId { NodeId = children[2] }], TestContext.Current.CancellationToken); + var results = response.Results.ToArray()!; + StatusCode.IsGood(results[0].StatusCode).ShouldBeTrue(results[0].StatusCode.ToString()); + StatusCode.IsGood(results[1].StatusCode).ShouldBeTrue("the resumed node is second in request order: it fits"); + results[2].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code); + Values(results[2]).ShouldBeEmpty(); + }, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin), + configureMapping: m => m.MaxHistoryAssemblyBytesPerRequest = 2 * 3 * 288 + 100); // ≈ 288 B a value: two 3-value nodes fit + } + + [Fact(Timeout = 90000)] + [Trait("Phase", "H3")] + public async Task Releases_queued_while_a_flush_is_finishing_are_never_lost() + { + // H3 review D6: the flush used to be re-armed from Task.IsCompleted, so a token queued after its last check but before it + // completed waited for the NEXT release — or forever. Many concurrent enqueues must all reach the connection. + await using var originServer = await HistoryOrigin.StartAsync(1); + using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); + var connections = new HistorySwitchConnections(origin); + ProjectedHistoryAccess? history = null; + await WithComposedServer(origin, origin.Raw, async (_, _, _, _, _, _, _) => + { + const int count = 2000; + await Task.WhenAll(Enumerable.Range(0, 8).Select(t => Task.Run(() => + { + for (var i = t; i < count; i += 8) history!.EnqueueReleaseForTests("link", BitConverter.GetBytes(i)); + }))); + var deadline = DateTime.UtcNow.AddSeconds(20); + while (connections.ReleasedTokens < count && DateTime.UtcNow < deadline) + { + await history!.FlushReleasesForTestsAsync(); + await Task.Delay(10, TestContext.Current.CancellationToken); + } + connections.ReleasedTokens.ShouldBe(count); + }, localPermissions: 15, allowHistory: true, connectionSource: connections, onHistory: (h, _) => history = h); + } + // ------------------------------------------------------------------------------------------------------------------ private static ReadRawModifiedDetails RawDetails(uint count) => new() @@ -278,6 +423,73 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests } } + public enum HistoryMode { Pass, Hang, Throw } + + /// + /// One long-lived origin connection whose HISTORY path can be switched to never answer (then fault as a cancelled gRPC call, + /// as a probe cancelled by its deadline did) or to fault at once; releases always pass through and are counted. + /// + private sealed class HistorySwitchConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource + { + private IDataConnection? _inner; + private readonly object _gate = new(); + private int _released; + private readonly List _sizes = []; + public HistoryMode Mode { get; set; } + public int ReleasedTokens => Volatile.Read(ref _released); + public IReadOnlyList HistoryCallSizes { get { lock (_sizes) return _sizes.ToArray(); } } + + public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken) + { + if (connectionId != "link") return ValueTask.FromResult(null); + lock (_gate) _inner ??= peer.Connection(); + return ValueTask.FromResult(new Borrowed(new Switch(_inner, this), _gate)); + } + + private sealed class Borrowed(IDataConnection connection, object route) : IGrpcDataAdapterConnectionLease + { + public IDataConnection Connection => connection; + public CancellationToken CancellationToken => CancellationToken.None; + public object? RouteIdentity => route; + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + + private sealed class Switch(IDataConnection inner, HistorySwitchConnections owner) : IDataConnection, IDataHistoryService + { + public DataTarget Target => inner.Target; + public TimeProvider Clock => inner.Clock; + public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => inner.GetCapabilitiesAsync(budget, cancellationToken); + public Task BrowseAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest request, CancellationToken cancellationToken) => inner.BrowseAsync(request, cancellationToken); + public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => inner.GetMetadataAsync(request, cancellationToken); + public Task> ReadAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest request, CancellationToken cancellationToken) => inner.ReadAsync(request, cancellationToken); + public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => inner.WriteAsync(request, cancellationToken); + public Task SubscribeAsync(CancellationToken cancellationToken) => inner.SubscribeAsync(cancellationToken); + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + + public async Task> ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) + { + lock (owner._sizes) owner._sizes.Add(request.Items.Count); + switch (owner.Mode) + { + case HistoryMode.Hang: + try { await Task.Delay(Timeout.Infinite, cancellationToken); } + catch (OperationCanceledException ex) + { throw new Grpc.Core.RpcException(new Grpc.Core.Status(Grpc.Core.StatusCode.Cancelled, "probe cancelled", ex)); } + break; + case HistoryMode.Throw: + throw new Grpc.Core.RpcException(new Grpc.Core.Status(Grpc.Core.StatusCode.Internal, "boom")); + } + return await ((IDataHistoryService)inner).ReadAsync(request, cancellationToken); + } + + public async Task ReleaseAsync(IReadOnlyList continuations, CancellationToken cancellationToken) + { + Interlocked.Add(ref owner._released, continuations.Count); + await ((IDataHistoryService)inner).ReleaseAsync(continuations, cancellationToken); + } + } + } + /// One long-lived origin connection, as a deployed gRPC connection is; replaces it (a redeploy). private sealed class PersistentConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource { @@ -324,7 +536,8 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests private HistoryOrigin(OpcUaApplicationHost host, string pki, OtOpcUaNodeManager nm, SeriesSource source) { _host = host; _pki = pki; _nm = nm; Source = source; Port = new OriginHistoryPort(nm); } - public static async Task StartAsync(int samples, int maxRawPerRead = 0, int extra = 0) + public static async Task StartAsync(int samples, int maxRawPerRead = 0, int extra = 0, string dataType = "Int32", + Func? value = null) { var pki = Path.Combine(Path.GetTempPath(), $"h3-origin-{Guid.NewGuid():N}"); var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions @@ -334,9 +547,9 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests }, NullLogger.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken); var nm = started.Server.NodeManager!; var source = new SeriesSource(Enumerable.Range(0, samples) - .Select(i => new DataValueSnapshot(i, 0, HistoryT0.AddSeconds(i), HistoryT0.AddSeconds(i))).ToArray()) { MaxRawValuesPerRead = maxRawPerRead }; + .Select(i => new DataValueSnapshot(value?.Invoke(i) ?? i, 0, HistoryT0.AddSeconds(i), HistoryT0.AddSeconds(i))).ToArray()) { MaxRawValuesPerRead = maxRawPerRead }; nm.HistorianDataSource = source; - nm.EnsureVariable("Plant/Driver/Device/Speed", null, "Speed", "Int32", false, AddressSpaceRealm.Raw, historianTagname: "speed"); + nm.EnsureVariable("Plant/Driver/Device/Speed", null, "Speed", dataType, false, AddressSpaceRealm.Raw, historianTagname: "speed"); nm.EnsureVariable("Plant/Driver/Device/Other", null, "Other", "Int32", false, AddressSpaceRealm.Raw); for (var i = 0; i < extra; i++) nm.EnsureVariable("Plant/Driver/Device/Speed" + i, null, "Speed" + i, "Int32", false, AddressSpaceRealm.Raw, historianTagname: "speed" + i); @@ -381,7 +594,8 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests public Task ReadAtTimeAsync(string fullReference, IReadOnlyList timestampsUtc, CancellationToken cancellationToken) { Interlocked.Increment(ref _calls); - return Task.FromResult(new HistorianRead(timestampsUtc.Select(t => new DataValueSnapshot(1, 0, t, t)).ToList(), null)); + return Task.FromResult(new HistorianRead(timestampsUtc.Select(t => series.LastOrDefault(s => s.SourceTimestampUtc <= t) + ?? new DataValueSnapshot(null, 0x809B0000u, t, t)).Select(s => s with { SourceTimestampUtc = s.SourceTimestampUtc }).ToList(), null)); } public Task ReadEventsAsync( From 86c0934ad6d863bfc8c950b909343badd377bf43 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 01:49:46 -0500 Subject: [PATCH 13/25] refactor(client): HistoryReadPageAsync is abstract; docs for the H3 review fixes The page API is a required member of IOpcUaClientService / ISessionAdapter (the fakes implement it). DataConnections.md: projected slot sub-limit, per-node fault handling, request-order runs and sub-batches. Client.CLI.md: --aggregate now asks for the server's default aggregate configuration. --- docs/Client.CLI.md | 2 +- docs/DataConnections.md | 10 ++++++++-- .../Adapters/ISessionAdapter.cs | 2 +- .../IOpcUaClientService.cs | 2 +- .../Fakes/FakeSessionAdapter.cs | 11 +++++++++++ .../Fakes/FakeOpcUaClientService.cs | 5 +++++ 6 files changed, 27 insertions(+), 5 deletions(-) diff --git a/docs/Client.CLI.md b/docs/Client.CLI.md index 44e5bc4d0..900b37d08 100644 --- a/docs/Client.CLI.md +++ b/docs/Client.CLI.md @@ -253,7 +253,7 @@ continuation points up to `--max`. `--events` cannot be combined with `--modifie | `--start` | Start time in ISO 8601 UTC format, e.g. `2026-01-15T08:00:00Z` (default: 24 hours ago) | | `--end` | End time in ISO 8601 UTC format, e.g. `2026-01-15T09:00:00Z` (default: now) | | `--max` | Maximum number of values (default: 1000) | -| `--aggregate` | Aggregate function: Average, Minimum, Maximum, Count, Start, End, StandardDeviation, TimeAverage, TimeAverage2, Total, Total2, Interpolative | +| `--aggregate` | Aggregate function: Average, Minimum, Maximum, Count, Start, End, StandardDeviation, TimeAverage, TimeAverage2, Total, Total2, Interpolative. Since H3 the request asks for the server's default aggregate configuration (`AggregateConfiguration.UseServerCapabilitiesDefaults = true`); it used to send the SDK's all-zero configuration, which OtOpcUa refuses (`BadAggregateConfigurationRejected`, #677) — a behaviour change against a third-party server that honoured the all-zero settings | | `--interval` | Processing interval in milliseconds for aggregates (default: 3600000) | | `--modified` | Read modified-value history (Part 11 `IsReadModified`) instead of raw samples | | `--events` | Read event history (Part 11 HistoryReadEvents) from an event notifier instead of raw samples | diff --git a/docs/DataConnections.md b/docs/DataConnections.md index 0d8f7c776..d1f935483 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -222,7 +222,13 @@ origin's `BadHistoryOperationUnsupported`. An origin-side denial, an unhistorize **Mixed batches.** One HistoryRead may mix local and projected nodes: local nodes are served by the local historian exactly as before, projected nodes remotely, every result in its own slot. The remote half runs under the same process-wide HistoryRead batch -limiter and never holds the node-manager lock. +limiter (`ServerHistorian:MaxConcurrentHistoryReadBatches`, N) and never holds the node-manager lock; projected reads hold at most +N − max(1, N/4) of the N slots (as remote peers do at an origin), so a slow origin cannot starve local HistoryRead/HistoryUpdate — +past that the projected half is `BadTooManyOperations`, unsent. A fault or timeout of the remote call (including the connection's +capability probe) fails only the projected half, per node (`BadTimeout` when the deadline fired), and releases its continuation +points. Remote calls are runs of consecutive request positions that share a connection, details and (for resumes) the issuing +endpoint, read in request order and split into sub-batches of at most min(the connection's batch size, the origin's advertised +`MaxBatchItems`) — a large batch is never refused as a whole. **Continuation points.** A projected read's continuation point lives in the client's OPC UA session like a local one (a `Remote` cursor; capped by `MaxHistoryContinuationPoints`, oldest evicted). It wraps the origin's token and binds the caller (principal, key, @@ -244,7 +250,7 @@ details on resume gets what it first asked for, as locally). Rules: | Limit | Effect | |---|---| -| `RemoteNamespaceMapping.MaxHistoryAssemblyBytesPerRequest` (16 MiB) | One budget per request, shared across the batch (the tightest mapping in the batch). Nodes are charged in request order; once a node does not fit, it and every later projected node is `BadTooManyOperations` (never a partial answer; its origin cursor is released). | +| `RemoteNamespaceMapping.MaxHistoryAssemblyBytesPerRequest` (16 MiB) | One budget per request, shared across the batch (the tightest mapping in the batch). Nodes are charged in request order (calls run in request order, and at most one node per 256 B of the remaining budget is sent); once a node does not fit, it and every later projected node with data is `BadTooManyOperations` (never a partial answer; its origin cursor is released). | | `ServerHistorian:HistoryReadDeadline` (consumer, 60 s) | The consumer request's remaining deadline, capped per call by `DataConnection.HistoryTimeoutMilliseconds` ⇒ `BadTimeout`. A cancelled request is never counted as an origin fault. | | Aggregates | An aggregate the consumer cannot name is `BadAggregateNotSupported` unsent; one the origin's backend refuses (unknown to it, or not valid for the node's type — #897) comes back `BadAggregateNotSupported` from the origin. The consumer's `HistoryServerCapabilities/AggregateFunctions` does not describe remote backends. | diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISessionAdapter.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISessionAdapter.cs index 9b216a19d..e59ddb9fb 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISessionAdapter.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/ISessionAdapter.cs @@ -173,7 +173,7 @@ internal interface ISessionAdapter : IDisposable /// Cancellation. /// The page. Task HistoryReadPageAsync(HistoryReadDetails details, NodeId nodeId, byte[]? continuationPoint, bool release, - CancellationToken ct = default) => throw new NotSupportedException(); + CancellationToken ct = default); /// /// Creates a subscription adapter for this session. diff --git a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs index 4edde2ff3..c19f3210b 100644 --- a/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs +++ b/src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/IOpcUaClientService.cs @@ -270,7 +270,7 @@ public interface IOpcUaClientService : IDisposable /// Cancellation. /// The page. Task HistoryReadPageAsync(HistoryReadDetails details, NodeId nodeId, byte[]? continuationPoint = null, bool release = false, - CancellationToken ct = default) => throw new NotSupportedException(); + CancellationToken ct = default); /// /// Reads redundancy status data such as redundancy mode, service level, and partner endpoint URIs. diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/Fakes/FakeSessionAdapter.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/Fakes/FakeSessionAdapter.cs index ea9f28985..8226cda7d 100644 --- a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/Fakes/FakeSessionAdapter.cs +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/Fakes/FakeSessionAdapter.cs @@ -188,6 +188,17 @@ internal sealed class FakeSessionAdapter : ISessionAdapter return Task.FromResult>(HistoryReadRawResponse); } + /// Every HistoryReadPageAsync call (details, continuation point, release flag). + public List<(HistoryReadDetails Details, byte[]? ContinuationPoint, bool Release)> HistoryPageCalls { get; } = []; + + /// + public Task HistoryReadPageAsync(HistoryReadDetails details, NodeId nodeId, + byte[]? continuationPoint, bool release, CancellationToken ct = default) + { + HistoryPageCalls.Add((details, continuationPoint, release)); + return Task.FromResult(new ZB.MOM.WW.OtOpcUa.Client.Shared.Models.HistoryPage(StatusCodes.GoodNoData, [], null)); + } + /// public Task> HistoryReadAggregateAsync( NodeId nodeId, DateTime startTime, DateTime endTime, NodeId aggregateId, double intervalMs, diff --git a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.UI.Tests/Fakes/FakeOpcUaClientService.cs b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.UI.Tests/Fakes/FakeOpcUaClientService.cs index 1142d3d27..a8a94adff 100644 --- a/tests/Client/ZB.MOM.WW.OtOpcUa.Client.UI.Tests/Fakes/FakeOpcUaClientService.cs +++ b/tests/Client/ZB.MOM.WW.OtOpcUa.Client.UI.Tests/Fakes/FakeOpcUaClientService.cs @@ -350,6 +350,11 @@ public sealed class FakeOpcUaClientService : IOpcUaClientService return Task.FromResult(HistoryRawResult); } + /// + public Task HistoryReadPageAsync(HistoryReadDetails details, NodeId nodeId, byte[]? continuationPoint = null, + bool release = false, CancellationToken ct = default) => + Task.FromResult(new HistoryPage(StatusCodes.GoodNoData, [], null)); + /// public Task> HistoryReadAggregateAsync(NodeId nodeId, DateTime startTime, DateTime endTime, AggregateType aggregate, double intervalMs = 3600000, CancellationToken ct = default) From f26b12085f917bf6e89a16a7a40b86a6d397648d Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 01:51:01 -0500 Subject: [PATCH 14/25] =?UTF-8?q?test(grpc-data):=20H3=20gate=20=E2=80=94?= =?UTF-8?q?=20Float32=20legs=20in=20H01/H03,=20H06=20origin=20refusal=20ov?= =?UTF-8?q?er=20the=20wire?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Seed profile historizes a Float32 (registers 30..31) driven through two values; H01/H03 compare its projected rows/types with the origin (Good Singles). H06(a) also reads the denied and the unhistorized node through the consumer's deployed connection (node probe) so the origin's per-item refusal itself is compared, not only the metadata that drops the access bit. --- scripts/validation/grpc-data/history_gate.py | 44 ++++++++++++++++++-- scripts/validation/grpc-data/seed/Program.cs | 8 +++- 2 files changed, 47 insertions(+), 5 deletions(-) diff --git a/scripts/validation/grpc-data/history_gate.py b/scripts/validation/grpc-data/history_gate.py index bc9857530..6b1f85277 100644 --- a/scripts/validation/grpc-data/history_gate.py +++ b/scripts/validation/grpc-data/history_gate.py @@ -60,8 +60,11 @@ class HistoryGate: def accumulate(self, seconds=40): started = datetime.now(timezone.utc) - for _ in range(seconds): + self.runner.device("set", address=30, value=16480) # flt = 3.5f (0x40600000, big-endian words) + for second in range(seconds): self.runner.device("advance", steps=1) + if second == seconds // 2: + self.runner.device("set", address=30, value=16616) # flt = 7.25f (0x40E80000) time.sleep(1) finished = datetime.now(timezone.utc) time.sleep(4) @@ -87,11 +90,11 @@ class HistoryGate: node_id = match[4] index = int(re.match(r"ns=(\d+);", node_id)[1]) if node_id.startswith("ns=") else -1 realm = "raw" if index == ns["mapped_raw"] else "uns" if index == ns["mapped_uns"] else None - if realm and "remote-source" in stack[:-1] and match[3] in {"counter", "scalar", "text"}: + if realm and "remote-source" in stack[:-1] and match[3] in {"counter", "scalar", "text", "flt"}: self.runner.check((realm, match[3]) not in found, "one projected leaf per realm and name") found[(realm, match[3])] = node_id for realm in ("raw", "uns"): - for name in ("counter", "scalar", "text"): + for name in ("counter", "scalar", "text", "flt"): self.runner.check((realm, name) in found, f"projected {realm}/{name} found by browse from the mapping anchor") self.runner.check(found[(realm, name)].split(";s=", 1)[1].startswith("p1."), "projected ids are opaque p1. ids") self.projected = found @@ -196,6 +199,14 @@ class HistoryGate: whole = self.cli(consumer, ["-n", self.projected[(realm, "counter")], *self.window_args(), "--max", "1000"], f"whole-{realm}") self.runner.check(history_smoke._cli_rows(whole.stdout) == origin_rows, f"{realm}: single read equals the origin") report[realm] = {"pages": len(pages), "rows": len(rows), "first": str(rows[0]), "last": str(rows[-1]), "page_lines": pages} + # H3 review: a Float32 node whose backend stores Double reads the same Good rows through the projection. + source, origin = self.origin_node("raw", "flt") + reference = self.cli(source, ["-n", origin, *self.window_args(), "--max", "1000"], "origin-flt") + floats = self.cli(consumer, ["-n", self.projected[("raw", "flt")], *self.window_args(), "--max", "1000"], "flt") + origin_rows, rows = history_smoke._cli_rows(reference.stdout), history_smoke._cli_rows(floats.stdout) + self.runner.check(reference.returncode == 0 and floats.returncode == 0 and len(rows) >= 1, "Float32 history served on both") + self.runner.check(rows == origin_rows and all(q == "Good" for _, _, q in rows), "Float32 rows Good and equal to the origin") + report["float32"] = {"rows": [str(r) for r in rows]} report["tie_cluster"] = ("not representable on the " + self.backend + " backend: SqlServer hist.Sample PK (TagId, SourceTimeUtc), " "QuestDB DEDUP UPSERT KEYS(ts, tag) — one stored sample per timestamp; tie paging is proven by the H1 port fuzz") return report @@ -233,7 +244,17 @@ class HistoryGate: origin_types = [line for line in reference.stdout.splitlines() if line.startswith("Type:")] self.runner.check(len(rows) == 3 and rows == origin_rows, "projected AtTime equals the origin row-for-row") self.runner.check(types == origin_types and all(t == "Type: UInt16" for t in types), "integer values stay UInt16 end to end") - return {"rows": [str(r) for r in rows], "types": types} + source, origin = self.origin_node("raw", "flt") + float_times = ",".join(_iso(start + timedelta(seconds=sec)) for sec in (2, 20)) + reference_f = self.cli(source, ["-n", origin, "--at-time", float_times], "origin-attime-flt") + projected_f = self.cli(consumer, ["-n", self.projected[("raw", "flt")], "--at-time", float_times], "attime-flt") + rows_f, origin_rows_f = history_smoke._cli_rows(projected_f.stdout), history_smoke._cli_rows(reference_f.stdout) + types_f = [line for line in projected_f.stdout.splitlines() if line.startswith("Type:")] + origin_types_f = [line for line in reference_f.stdout.splitlines() if line.startswith("Type:")] + self.runner.check(projected_f.returncode == 0 and rows_f == origin_rows_f and all(q == "Good" for _, _, q in rows_f), + "Float32 AtTime equals the origin, Good") + self.runner.check(types_f == origin_types_f and all(t == "Type: Single" for t in types_f), "Float32 values stay Single end to end") + return {"rows": [str(r) for r in rows], "types": types, "float32": {"rows": [str(r) for r in rows_f], "types": types_f}} def scenario_H04(self): """A continuation across an origin failover is BadContinuationPointInvalid; a fresh read moves and succeeds.""" @@ -316,6 +337,21 @@ class HistoryGate: normalise = lambda text: re.sub(r"ns=\d+;s=\S+", "", "\n".join(l for l in (text.stdout + text.stderr).splitlines() if "Bad" in l)) self.runner.check(denied == "BadHistoryOperationUnsupported", "origin ACL denial ⇒ BadHistoryOperationUnsupported") self.runner.check(normalise(unh) == normalise(den), "denied and unhistorized are indistinguishable") + # H3 review: the per-item refusal itself, OVER THE WIRE (the consumer's deployed connection → the origin's ingress), + # not only the metadata that drops the access bit: both answers identical 0x80720000, and the origin counted the calls. + paths = self.runner.manifest["fixture"]["history"] + primary = self.runner.primary("source") + before = self.runner.probe(primary, "topology", timeout=30).get("inboundDataRequests") + wire_denied = self.runner.probe(consumer, "history", "raw", path=paths["historized"]["raw"], historyNumValues=5, + expected_state="Unsupported", timeout=60) + wire_unhistorized = self.runner.probe(consumer, "history", "raw", path=paths["unhistorized"]["raw"], historyNumValues=5, + expected_state="Unsupported", timeout=60) + after = self.runner.probe(primary, "topology", timeout=30).get("inboundDataRequests") + strip = lambda pages: [{k: v for k, v in page.items()} for page in pages] + self.runner.check(strip(wire_denied["pages"]) == strip(wire_unhistorized["pages"]), + "origin-ACL-denied and unhistorized answers are identical over the wire") + report["wire"] = {"denied": wire_denied["pages"], "unhistorized": wire_unhistorized["pages"], + "origin_inbound_requests": {"before": before, "after": after}} report["indistinguishable"] = {"unhistorized": normalise(unh), "denied": normalise(den), "attempts": attempts} self.restore() # (b) the LOCAL mapping-scope grant: without it, BadUserAccessDenied (a local decision); the other mapping keeps its grant. diff --git a/scripts/validation/grpc-data/seed/Program.cs b/scripts/validation/grpc-data/seed/Program.cs index ca340455c..e72964e7d 100644 --- a/scripts/validation/grpc-data/seed/Program.cs +++ b/scripts/validation/grpc-data/seed/Program.cs @@ -359,12 +359,18 @@ try TagConfig = history ? """{"region":"HoldingRegisters","address":40,"dataType":"String","stringLength":16,"writable":true,"isHistorized":true}""" : """{"region":"HoldingRegisters","address":40,"dataType":"String","stringLength":16,"writable":true}""" }); + if (history) + // H3 review: a historized Float32 (two registers 30..31, big-endian), so the gate proves a backend that stores Double + // still reads Good Singles through the projection. + db.Tags.Add(new() { TagRowId = Guid.NewGuid(), TagId = "source-flt", DeviceId = "source-device", Name = "flt", DataType = "Float", + AccessLevel = TagAccessLevel.ReadWrite, WriteIdempotent = false, PollGroupId = "source-fast", + TagConfig = """{"region":"HoldingRegisters","address":30,"dataType":"Float32","writable":true,"isHistorized":true}""" }); db.UnsAreas.Add(new() { UnsAreaRowId = Guid.NewGuid(), UnsAreaId = "source-area", ClusterId = "SOURCE", Name = "area" }); db.UnsLines.Add(new() { UnsLineRowId = Guid.NewGuid(), UnsLineId = "source-line", UnsAreaId = "source-area", Name = "line" }); var uuid = Guid.NewGuid(); var equipment = DraftValidator.DeriveEquipmentId(uuid); db.Equipment.Add(new() { EquipmentRowId = Guid.NewGuid(), EquipmentId = equipment, EquipmentUuid = uuid, UnsLineId = "source-line", Name = "plc", MachineCode = "fixture-plc" }); - foreach (var name in new[] { "counter", "scalar", "array0", "array1", "array2", "vector", "text" }) + foreach (var name in new[] { "counter", "scalar", "array0", "array1", "array2", "vector", "text" }.Concat(history ? ["flt"] : [])) db.UnsTagReferences.Add(new() { UnsTagReferenceRowId = Guid.NewGuid(), UnsTagReferenceId = "ref-" + name, EquipmentId = equipment, TagId = "source-" + name }); db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "source-peer", ClusterId = "SOURCE", Principal = "fixture-consumer", ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.Admin }); From 8f630bec980620bd094201d0ace90e10441b3db9 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 02:02:49 -0500 Subject: [PATCH 15/25] test(grpc-data): H3 gate re-browses before held reads (projection authority lapses with the metadata lease) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Found on the review re-run (H06d, SqlServer): a projected node read more than MetadataLeaseMilliseconds (15 s) after its last browse/renewal is BadUserAccessDenied — the same for a value Read (pre-existing v1 projection behaviour, confirmed in the Runtime harness), not an H3 defect. The gate now re-browses before each held read. --- scripts/validation/grpc-data/history_gate.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/scripts/validation/grpc-data/history_gate.py b/scripts/validation/grpc-data/history_gate.py index 6b1f85277..96cfa6a0c 100644 --- a/scripts/validation/grpc-data/history_gate.py +++ b/scripts/validation/grpc-data/history_gate.py @@ -266,7 +266,9 @@ class HistoryGate: with self.runner.stopped(source): observed["new_primary"] = self.runner.wait_primary("source", exclude=source) self.runner.wait_connection_ready(consumer, "raw") - # Resume INSIDE the stop window: the issuing endpoint is down, the pinned resume cannot move. + # Resume INSIDE the stop window: the issuing endpoint is down, the pinned resume cannot move. Re-browse first so + # the node's projection authority is current (it lapses with the 15 s metadata lease, as for a value Read). + self.rebrowse() self.held_resume_now() self.runner.wait_pair_topology("source") @@ -363,7 +365,9 @@ class HistoryGate: report["local_deny"] = {"raw": local, "uns": other, "attempts": attempts} self.restore() consumer = self.runner.primary("consumer") - # (c) a consumer session close releases the origin continuation. + # (c) a consumer session close releases the origin continuation. A projected node's authority lapses with its metadata + # lease (15 s) unless something renews it — the same for a value Read (pre-existing v1 behaviour) — so re-browse first. + self.rebrowse() self.runner.check(self.origin_state() == 0, "no origin continuation open before") counts = {} @@ -381,6 +385,7 @@ class HistoryGate: self.runner.check(after == 0, "the consumer session close released the origin continuation (store count back to 0)") report["session_close"] = {"held": counts.get("held"), "after": after, "lines": self.status_lines(abandoned.stdout)} # (d) origin rebuild mid-page: a resumed page after the origin's history epoch moved is BadContinuationPointInvalid. + self.rebrowse() def rebuild(): self.change(rename_tag={"tag_id": "source-array1", "name": "array1-renamed"}) rebuilt = self.held(consumer, ["-n", self.projected[("raw", "counter")], *self.window_args(), "--page-size", "3", From 60e594ddddc4a5cfd3d012c8e8a06cdfa7340108 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 02:19:03 -0500 Subject: [PATCH 16/25] test(grpc-data): H06 held legs start right after a deploy (idle projection authority lapses) The review re-run showed a re-browse served from the cached page does not renew an idle projected node's 15 s metadata lease (value Read is refused the same way; pre-existing v1 projection behaviour). Each held H06 leg now starts right after a baseline restore + re-browse. --- scripts/validation/grpc-data/history_gate.py | 27 ++++++++++---------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/scripts/validation/grpc-data/history_gate.py b/scripts/validation/grpc-data/history_gate.py index 96cfa6a0c..5a5dc2587 100644 --- a/scripts/validation/grpc-data/history_gate.py +++ b/scripts/validation/grpc-data/history_gate.py @@ -365,9 +365,20 @@ class HistoryGate: report["local_deny"] = {"raw": local, "uns": other, "attempts": attempts} self.restore() consumer = self.runner.primary("consumer") - # (c) a consumer session close releases the origin continuation. A projected node's authority lapses with its metadata - # lease (15 s) unless something renews it — the same for a value Read (pre-existing v1 behaviour) — so re-browse first. - self.rebrowse() + # (d) origin rebuild mid-page: a resumed page after the origin's history epoch moved is BadContinuationPointInvalid. + def rebuild(): + self.change(rename_tag={"tag_id": "source-array1", "name": "array1-renamed"}) + rebuilt = self.held(consumer, ["-n", self.projected[("raw", "counter")], *self.window_args(), "--page-size", "3", + "--pause-after-page", "1", "--fresh-after-failure"], "rebuild", rebuild) + lines = self.status_lines(rebuilt.stdout) + self.runner.check(any(l.startswith("Page 2: BadContinuationPointInvalid") for l in lines), "resume after the origin rebuild is invalid") + self.runner.check(any(l.startswith("Fresh: Good") for l in lines), "a fresh read after the rebuild succeeds") + report["rebuild"] = lines + # (c) a consumer session close releases the origin continuation. Each held read starts right after a deploy + re-browse: + # an idle projected node's authority lapses with its 15 s metadata lease and a re-browse served from the cached page + # does not renew it (a value Read is refused the same way — pre-existing v1 projection behaviour, reported). + self.restore() + consumer = self.runner.primary("consumer") self.runner.check(self.origin_state() == 0, "no origin continuation open before") counts = {} @@ -384,16 +395,6 @@ class HistoryGate: after = self.origin_state() self.runner.check(after == 0, "the consumer session close released the origin continuation (store count back to 0)") report["session_close"] = {"held": counts.get("held"), "after": after, "lines": self.status_lines(abandoned.stdout)} - # (d) origin rebuild mid-page: a resumed page after the origin's history epoch moved is BadContinuationPointInvalid. - self.rebrowse() - def rebuild(): - self.change(rename_tag={"tag_id": "source-array1", "name": "array1-renamed"}) - rebuilt = self.held(consumer, ["-n", self.projected[("raw", "counter")], *self.window_args(), "--page-size", "3", - "--pause-after-page", "1", "--fresh-after-failure"], "rebuild", rebuild) - lines = self.status_lines(rebuilt.stdout) - self.runner.check(any(l.startswith("Page 2: BadContinuationPointInvalid") for l in lines), "resume after the origin rebuild is invalid") - self.runner.check(any(l.startswith("Fresh: Good") for l in lines), "a fresh read after the rebuild succeeds") - report["rebuild"] = lines return report # ------------------------------------------------------------------------------------------------------------- run From 022b2978360a8fbff8757cde3d096737f6a4519e Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 02:35:25 -0500 Subject: [PATCH 17/25] =?UTF-8?q?docs(grpc-data):=20H3=20evidence=20?= =?UTF-8?q?=E2=80=94=20review=20fixes,=20gates=20and=20the=20H01-H06=20re-?= =?UTF-8?q?run=20on=20both=20backends?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/plans/evidence/grpc-data-ext/H3.md | 33 ++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/docs/plans/evidence/grpc-data-ext/H3.md b/docs/plans/evidence/grpc-data-ext/H3.md index 64b03f0ae..08bec4998 100644 --- a/docs/plans/evidence/grpc-data-ext/H3.md +++ b/docs/plans/evidence/grpc-data-ext/H3.md @@ -111,10 +111,41 @@ Earlier passes on `h3-sql` (pre-fix builds, same rig, `down` 0/0/0/0) found the cold projected nodes (`BadNodeIdUnknown` until re-browsed — the gate now re-browses after every deploy; a client reading a projected node it has not browsed since a deploy sees the same; pre-existing v1 projection behaviour). +## Review (Fable, approve-with-changes) — fixes + +Each fix is a new commit; red/green by reverting the fix (mutation) and re-running its test, unless noted. + +| # | Finding | Resolution | Red/green | +|---|---|---|---| +| D1 | A deadline during the connection's capability probe faulted the whole HistoryRead (`RpcException(Cancelled)` escaped) | `GrpcDataConnection` turns a caller cancel during the probe into `OperationCanceledException` and caps the probe by `HistoryTimeout`; `ProjectedHistoryAccess` fails any escaping fault per node (`BadTimeout` when the deadline fired) and releases every cursor it owns; the node manager's catch is total | client probe tests; wire test (`Hang`/`Throw`): local half of a mixed batch served, projected `BadTimeout` / `BadContinuationPointInvalid`, origin store back to 0 — both red on revert | +| D2 | `Release()` after `TryClaimForResume()` was a no-op ⇒ claimed cursors leaked on post-claim exits | `ProjectedHistoryContinuation.ReleaseEvenIfClaimed()` (at most once) on every such exit: no gateway/identity, deadline spent, limiter rejection, gateway fault, count mismatch | O test over all four exits + a positive control (a normal resume does not release) — red on revert | +| D3 | Projected reads could hold every history batch slot for up to 60 s | projected sub-limit N − max(1, N/4) (`OriginHistoryPort.RemoteSlots`), `Wait(0)` ⇒ `BadTooManyOperations` for the projected half | O test: 3 held projected reads at N=4, a 4th refused at once, a local read still served — red (hangs, bounded to 5 s) on revert | +| D4 | A group larger than the lease/origin batch failed entirely | sub-batches ≤ min(lease batch, origin's advertised `MaxBatchItems`) and ≤ one item per 256 B of the remaining budget; shortfall ⇒ `BadTooManyOperations` per node | wire test: 3 nodes vs an origin batch of 2 ⇒ calls `[2, 1]`, all Good — red on revert | +| D5 | A Remote cursor presented to a local node was taken and dropped | released in the local (raw/modified) and events take paths | O test — red on revert | +| D6 | Release flush lost wake-up; `_stop` disposed under a running flush | `_flushScheduled` flag under the gate; `_stop` only cancelled | 2,000 concurrent enqueues all released — **not shown red** (the race did not reproduce with the fix reverted); kept as a regression check | +| D7 | Budget charged in group order | calls are runs of consecutive request positions read in request order, then charged in request order | wire test [A fresh, B resumed, C fresh] with room for two: C refused, not B — red on revert | +| Float32 | Double from the backend for a Float32 node | **no defect**: the origin port normalises Raw/AtTime to the node's type (Single) before the wire; Runtime test + live legs (H01/H03: Good Singles = origin) | — | +| H06(a) | Origin-ACL denial exercised only via metadata | also read through the consumer's deployed connection (node probe): denied and unhistorized both `0x80720000`, identical pages; the origin's inbound data requests 73 ⇒ 79 | live | +| Nits | page API default-throwing; probe uncapped; `int` cast; CLI doc | `HistoryReadPageAsync` abstract (fakes implement it); probe capped by `HistoryTimeout`; budgets stay `long`; `Client.CLI.md` notes `--aggregate` now sends `UseServerCapabilitiesDefaults = true` | — | + +**Gates after the fixes** (HEAD `60e594ddd`): build 0/0; `run-unit-phase.py` H3, H2, H1, X0 passed; OI `Feature=GrpcData` + history +87 passed (2 AVEVA skips); OpcUaServer 1418 (+1 skip), Runtime 1890 (+3 skips), Host 479, Client.CLI 224, Client.Shared 361, Client.UI 131; +rig harness tests OK. + +**Live re-run** (fresh `h3r3-sqlserver` 07:19–07:28 and `h3r3-questdb` 07:28–07:35 UTC at `60e594ddd`, normal build checks): H01–H06 +**all PASS on both backends** (H06 238 assertions each); Float32 legs Good Singles equal to the origin; H06(c) origin continuations 1 +while held, 0 after the session closed; `down` ⇒ 0/0/0/0 for both runs. + +**Found on the re-run (pre-existing v1 projection behaviour, not an H3 defect — for a follow-up):** an idle projected node's +authority lapses with its 15 s `MetadataLeaseMilliseconds`; any read after that is `BadUserAccessDenied` — a value Read exactly as a +HistoryRead (reproduced in the Runtime harness) — and a re-browse served from the still-cached browse page does not renew it +(live: the H06 rebuild leg denied right after a re-browse). The gate now starts each held leg right after a deploy + re-browse. + ## Not verified / substitutions - **H05**: the rig builds no pinned v1 image, so "v1 origin" is substituted by an origin that does not advertise history for the - principal (export without bit 32). The v1 wire shape itself is covered by the H2 recorded-v1-client gates. + principal (export without bit 32). The v1 wire shape itself is covered by the H2 recorded-v1-client gates; the live v1-origin + path is follow-up **#921**. - **H01 tie clusters**: not representable live on either backend — SqlServer `hist.Sample` PK `(TagId, SourceTimeUtc)`, QuestDB `DEDUP UPSERT KEYS(ts, tag)` keep one sample per timestamp. Tie paging is proven by the H1 port fuzz (10k seeds). - **ReadyReplica consistency** on projected history and the Gateway backend (H4) were not run. From 37cbeff480a8fffc47343affe415ec36057b8120 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 06:25:19 -0500 Subject: [PATCH 18/25] =?UTF-8?q?fix(grpc-data):=20H3=20review=20round=202?= =?UTF-8?q?=20=E2=80=94=20one=20non-local=20history=20slot=20share;=20clai?= =?UTF-8?q?m=20loop=20never=20leaks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remote peers reading this node (OriginHistoryPort) and this node's projected reads now draw on ONE N - max(1, N/4) semaphore, created together with the N-slot batch limiter from the same N, so both together can never take the last (local) slot (two independent first-use sizings could also disagree — which made OriginHistoryLimiterTests order-dependent and hang the earlier run). The projected claim loop releases every claimed cursor if anything throws while the batch is assembled. Red/green: the shared-slot assertion fails with a per-port semaphore. --- .../OriginHistoryPort.cs | 15 +-- .../OtOpcUaNodeManager.cs | 20 +++- .../ProjectedHistoryRead.cs | 104 +++++++++--------- .../ProjectedHistoryReadTests.cs | 12 +- .../OriginHistoryLimiterTests.cs | 13 ++- 5 files changed, 93 insertions(+), 71 deletions(-) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginHistoryPort.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginHistoryPort.cs index e673787f3..e655f0fff 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginHistoryPort.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OriginHistoryPort.cs @@ -89,23 +89,18 @@ public sealed class OriginHistoryPort(OtOpcUaNodeManager nodeManager) : IOriginH private readonly OtOpcUaNodeManager _nm = nodeManager ?? throw new ArgumentNullException(nameof(nodeManager)); private (IHistorianDataSource Source, OriginHistoryServing? Serving)? _serving; - private SemaphoreSlim? _remoteSlots; - private readonly Lock _slotsGate = new(); - /// /// The share of the node manager's process-wide history batch limiter (N = MaxConcurrentHistoryReadBatches) - /// remote peers may hold: N - max(1, N/4), at least 1. The rest stays free for local OPC UA HistoryRead. + /// NON-LOCAL reads may hold: N - max(1, N/4), at least 1. The rest stays free for local OPC UA HistoryRead. /// public static int RemoteSlots(int batches) => Math.Max(1, batches - Math.Max(1, batches / 4)); - /// Remote slots currently free (diagnostics/tests). + /// Non-local slots currently free (diagnostics/tests) — shared with the node's projected reads (H3 review round 2). public int AvailableRemoteSlots => Slots().CurrentCount; - private SemaphoreSlim Slots() - { - if (_remoteSlots is { } slots) return slots; - lock (_slotsGate) return _remoteSlots ??= new SemaphoreSlim(RemoteSlots(Math.Max(1, _nm.MaxConcurrentHistoryReadBatches))); - } + // ONE semaphore for every non-local history read of this node manager: remote peers here AND projected reads to other + // origins. Two independent N - max(1, N/4) shares would still let both together starve local history. + private SemaphoreSlim Slots() => _nm.GetNonLocalHistoryLimiter(); /// /// Cached per historian source instance: the catalog asks per node, so this is a reference compare, not a rebuild. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index d4a4aac1b..749fe7248 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -9961,10 +9961,28 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage if (gate is not null) return gate; lock (_historyReadBatchLimiterLock) { - return _historyReadBatchLimiter ??= new SemaphoreSlim(Math.Max(1, MaxConcurrentHistoryReadBatches)); + if (_historyReadBatchLimiter is { } created) return created; + // H3 review round 2: the NON-LOCAL share is sized from the SAME N at the same moment, so it can never exceed + // N - max(1, N/4) of the limiter that actually exists (two independent first-use sizings could disagree). + var batches = Math.Max(1, MaxConcurrentHistoryReadBatches); + _nonLocalHistoryLimiter = new SemaphoreSlim(OriginHistoryPort.RemoteSlots(batches)); + return _historyReadBatchLimiter = new SemaphoreSlim(batches); } } + private volatile SemaphoreSlim? _nonLocalHistoryLimiter; + + /// + /// The NON-LOCAL share of the history batch slots — remote peers reading this origin () and + /// this node's projected reads to other origins, together: of the N the shared + /// limiter was created with (both are created together, at first use). + /// + internal SemaphoreSlim GetNonLocalHistoryLimiter() + { + GetHistoryReadBatchLimiter(); + return _nonLocalHistoryLimiter!; + } + /// Link the SDK request lifetime to the application's per-batch history deadline. /// The request's server context. /// The linked deadline source, or null when neither request nor application can cancel. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs index c50f6f9b3..d78d130b3 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs @@ -26,20 +26,6 @@ public sealed partial class OtOpcUaNodeManager set => Volatile.Write(ref _projectedHistoryAccess, value); } - private volatile SemaphoreSlim? _projectedHistoryLimiter; - private readonly Lock _projectedHistoryLimiterGate = new(); - - /// - /// The projected share of the history batch slots, sized once from at first - /// use (as the shared limiter is): . - /// - internal SemaphoreSlim GetProjectedHistoryLimiter() - { - if (_projectedHistoryLimiter is { } gate) return gate; - lock (_projectedHistoryLimiterGate) - return _projectedHistoryLimiter ??= new SemaphoreSlim(OriginHistoryPort.RemoteSlots(Math.Max(1, MaxConcurrentHistoryReadBatches))); - } - /// Serves local handles through the port (unchanged) and projected handles remotely, each into its own slot. private void ServeHistoryReadSplit( ServerSystemContext context, @@ -83,51 +69,63 @@ public sealed partial class OtOpcUaNodeManager var aggregates = details is ReadProcessedDetails processed ? processed.AggregateType : default; var pending = new List<(NodeHandle Handle, ProjectedHistoryNode Node)>(handles.Count); - foreach (var handle in handles) + ProjectedHistoryContinuation? claimed = null; + try { - var key = MapKey(handle.NodeId); - var tag = HistoryBindingTag(handle.NodeId); - var cp = nodesToRead[handle.Index].ContinuationPoint; - ProjectedHistoryContinuation? resume = null; - if (cp.Length > 0) + foreach (var handle in handles) { - // Single-use: the take removes the SDK slot. A cursor of another node / kind / epoch is refused AND released. - var state = store.TryTake(session, cp.ToArray()); - if (state is not { Kind: HistoryCursorKind.Remote, Remote: { } cursor } - || !HistoryContinuationMatches(state, key.Realm, key.Id, tag, epoch) - || !cursor.TryClaimForResume()) + var key = MapKey(handle.NodeId); + var tag = HistoryBindingTag(handle.NodeId); + var cp = nodesToRead[handle.Index].ContinuationPoint; + ProjectedHistoryContinuation? resume = null; + if (cp.Length > 0) { - state?.Remote?.Release(); - SetProjectedStatus(handle, results, errors, StatusCodes.BadContinuationPointInvalid); + // Single-use: the take removes the SDK slot. A cursor of another node / kind / epoch is refused AND released. + var state = store.TryTake(session, cp.ToArray()); + if (state is not { Kind: HistoryCursorKind.Remote, Remote: { } cursor } + || !HistoryContinuationMatches(state, key.Realm, key.Id, tag, epoch) + || !cursor.TryClaimForResume()) + { + state?.Remote?.Release(); + SetProjectedStatus(handle, results, errors, StatusCodes.BadContinuationPointInvalid); + continue; + } + + resume = cursor; + claimed = cursor; + } + + if (access is null || identity is null || remote is null) + { + // 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); continue; } - resume = cursor; - } - - if (access is null || identity is null || remote is null) - { - // 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); - continue; - } - - uint? aggregateId = null; - if (remote is DataHistoryProcessedDetails && resume is null) - { - // Consumer-side unknown aggregate: refused up front, unsent (the origin refuses what IT cannot serve). - var aggregate = aggregates[handle.Index]; - if (AggregateFunctionMap.Map(aggregate) is null || aggregate.NamespaceIndex != 0 || !aggregate.TryGetValue(out uint numeric)) + uint? aggregateId = null; + if (remote is DataHistoryProcessedDetails && resume is null) { - SetProjectedStatus(handle, results, errors, StatusCodes.BadAggregateNotSupported); - continue; + // Consumer-side unknown aggregate: refused up front, unsent (the origin refuses what IT cannot serve). + 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); + continue; + } + + aggregateId = numeric; } - aggregateId = numeric; + pending.Add((handle, new ProjectedHistoryNode(handle.NodeId, aggregateId, resume))); } - - pending.Add((handle, new ProjectedHistoryNode(handle.NodeId, aggregateId, resume))); + } + catch + { + // H3 review round 2: whatever throws while the batch is assembled, no claimed cursor leaks its origin continuation. + claimed?.ReleaseEvenIfClaimed(); + foreach (var p in pending) p.Node.Resume?.ReleaseEvenIfClaimed(); + throw; } if (pending.Count == 0) return; @@ -138,10 +136,10 @@ public sealed partial class OtOpcUaNodeManager foreach (var node in nodes) node.Resume?.ReleaseEvenIfClaimed(); } - // H3 review D3: projected reads may hold at most N - max(1, N/4) of the N process-wide history batch slots (the rule - // OriginHistoryPort.RemoteSlots applies to remote peers), so a slow origin can never starve local HistoryRead / - // HistoryUpdate. Exhausted => BadTooManyOperations for the projected half, unsent; the local half is unaffected. - var projectedSlots = GetProjectedHistoryLimiter(); + // H3 review D3: projected reads and remote peers TOGETHER hold at most N - max(1, N/4) of the N process-wide history batch + // slots (OriginHistoryPort.RemoteSlots; one shared semaphore), so neither a slow origin nor busy peers can starve local + // HistoryRead / HistoryUpdate. Exhausted => BadTooManyOperations for the projected half, unsent; the local half is unaffected. + var projectedSlots = GetNonLocalHistoryLimiter(); if (!projectedSlots.Wait(0)) { ReleaseResumes(); 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 2ea1d6ce9..93b276111 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 @@ -247,7 +247,7 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable // (d) the projected sub-limit is exhausted (limiter rejection). (cursor, cp) = HeldPoint(); - var limiter = nm.GetProjectedHistoryLimiter(); + var limiter = nm.GetNonLocalHistoryLimiter(); var taken = 0; while (limiter.Wait(0, TestContext.Current.CancellationToken)) taken++; try @@ -265,7 +265,7 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable } [Fact] - public async Task Projected_reads_cannot_take_every_history_slot_local_history_is_still_served() + public async Task Projected_reads_and_remote_peers_together_cannot_take_every_history_slot_local_history_is_still_served() { // H3 review D3: projected reads hold at most N - max(1, N/4) of the N shared batch slots. var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead); @@ -288,6 +288,14 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable .WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); refused[0].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code); slow.Entries.ShouldBe(3); + // H3 review round 2: remote peers reading THIS node share the same non-local slots — refused too, unsent — so the + // origin port and the projected path together can never take the last (local) slot. + var port = new OriginHistoryPort(nm); + port.AvailableRemoteSlots.ShouldBe(0); + var peer = await port.ReadAsync(new OriginHistoryCursors("peer", "channel", 4), "peer", () => "serving", + new DataHistoryRawDetails(new DateTimeOffset(T0), new DateTimeOffset(T0.AddHours(1)), 5, false), + [new OriginHistoryItem(AddressSpaceRealm.Raw, "Plant/LocalSlot", "tag", null, null)], TestContext.Current.CancellationToken); + peer.Single().StatusCode.ShouldBe(StatusCodes.BadTooManyOperations.Code); var (localResults, localErrors) = Raw(nm, f.Identity, [local]); StatusCode.IsGood(localErrors[0].StatusCode).ShouldBeTrue(localErrors[0].StatusCode.ToString()); localResults[0].StatusCode.Code.ShouldBe(StatusCodes.GoodNoData.Code); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/OriginHistoryLimiterTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/OriginHistoryLimiterTests.cs index 52a248965..36c9dd7d6 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/OriginHistoryLimiterTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/OriginHistoryLimiterTests.cs @@ -24,22 +24,25 @@ public sealed class OriginHistoryLimiterTests(HistoryReadPortServerFixture fx) : var source = new BlockingSource(); try { - fx.Nm.MaxConcurrentHistoryReadBatches = 4; // the limiter is sized at first use; this fixture is fresh + // The limiter is sized ONCE per node manager, at first use: with the shared fixture another test may have sized it + // already (H3 review round 2: the non-local share is now one node-manager semaphore), so saturate what exists. + fx.Nm.MaxConcurrentHistoryReadBatches = 4; fx.Nm.HistorianDataSource = source; var port = new OriginHistoryPort(fx.Nm); OriginHistoryPort.RemoteSlots(4).ShouldBe(3); + var slots = port.AvailableRemoteSlots; var details = new DataHistoryRawDetails(new DateTimeOffset(T0), new DateTimeOffset(T0.AddSeconds(5)), 1, false); var item = new OriginHistoryItem(AddressSpaceRealm.Uns, "port/dbl", "peer:uns", null, null); - var remote = Enumerable.Range(0, 3).Select(i => port.ReadAsync(new OriginHistoryCursors("peer", "c" + i, 4), "peer", () => "inc", + var remote = Enumerable.Range(0, slots).Select(i => port.ReadAsync(new OriginHistoryCursors("peer", "c" + i, 4), "peer", () => "inc", details, [item], CancellationToken.None)).ToArray(); - await source.WaitForCalls(3); + await source.WaitForCalls(slots); var refused = (await port.ReadAsync(new OriginHistoryCursors("peer", "c9", 4), "peer", () => "inc", details, [item], CancellationToken.None)).Single(); refused.StatusCode.ShouldBe(StatusCodes.BadTooManyOperations.Code, "the remote share is full"); // A local (SDK-path) read still gets the reserved slot. var local = Task.Run(() => fx.Nm.ReadHistory(OriginHistoryPort.ToVariant(details), [new HistoryReadPortItem(AddressSpaceRealm.Uns, "port/dbl", null, default, "urn:local")], fx.Nm.SessionHistoryContinuationScope(null), CancellationToken.None)); - await source.WaitForCalls(4); + await source.WaitForCalls(slots + 1); source.Release.TrySetResult(); (await local).Single().Status.Code.ShouldNotBe(StatusCodes.BadTooManyOperations.Code); foreach (var r in await Task.WhenAll(remote)) r.Single().StatusCode.ShouldNotBe(StatusCodes.BadTooManyOperations.Code); @@ -64,7 +67,7 @@ public sealed class OriginHistoryLimiterTests(HistoryReadPortServerFixture fx) : var port = new OriginHistoryPort(fx.Nm); var details = new DataHistoryRawDetails(new DateTimeOffset(T0), new DateTimeOffset(T0.AddSeconds(5)), 1, false); var item = new OriginHistoryItem(AddressSpaceRealm.Uns, "port/dbl", "peer:uns", null, null); - var slots = OriginHistoryPort.RemoteSlots(fx.Nm.MaxConcurrentHistoryReadBatches); + var slots = port.AvailableRemoteSlots; // the node manager's non-local share, sized once at first use using var cancelled = new CancellationTokenSource(); await cancelled.CancelAsync(); for (var i = 0; i < slots + 3; i++) From 7aaa98751ab1af7f1892b49ea31c1c1f0d8911cc Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 06:25:19 -0500 Subject: [PATCH 19/25] =?UTF-8?q?fix(grpc-data):=20H3=20review=20round=202?= =?UTF-8?q?=20=E2=80=94=20no=20batch=20probe;=20budget=20stop;=20orphan=20?= =?UTF-8?q?tokens;=20lease-retired=20status?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1: the separate capability probe is gone (through the unary path a cancelled probe recorded an endpoint failure and put the connection into discovery backoff). Projected calls split at the deployed connection's batch size; GrpcDataConnection splits again at the origin's advertised MaxBatchItems from the capabilities the history call already negotiated, sharing the assembly budget across sub-batches. 3: once the connection reports the assembly budget spent, no further origin call is made. 4: an answer that never became an outcome (mismatch, exception mid-answer) releases its new origin token. 5: a cancel that is neither the caller's nor the deadline (a lease retired by a redeploy) is BadNoCommunication / BadContinuationPointInvalid, not BadTimeout. Flush delay on the access's clock. Docs: the request deadline covers the local half too; shared non-local slots; split. Red/green for each by mutation. --- docs/DataConnections.md | 10 +-- .../DataConnectionDeploymentRuntime.cs | 5 +- .../GrpcDataConnection.History.cs | 45 +++++++++- .../DataConnections/ProjectedHistoryAccess.cs | 82 ++++++++++-------- .../GrpcDataComposedBrowseWireTests.cs | 3 +- .../GrpcDataHistoryClientTests.cs | 40 ++++++++- .../GrpcDataProjectedHistoryWireTests.cs | 85 +++++++++++++++++-- 7 files changed, 221 insertions(+), 49 deletions(-) diff --git a/docs/DataConnections.md b/docs/DataConnections.md index d1f935483..18e1727f7 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -222,13 +222,13 @@ origin's `BadHistoryOperationUnsupported`. An origin-side denial, an unhistorize **Mixed batches.** One HistoryRead may mix local and projected nodes: local nodes are served by the local historian exactly as before, projected nodes remotely, every result in its own slot. The remote half runs under the same process-wide HistoryRead batch -limiter (`ServerHistorian:MaxConcurrentHistoryReadBatches`, N) and never holds the node-manager lock; projected reads hold at most -N − max(1, N/4) of the N slots (as remote peers do at an origin), so a slow origin cannot starve local HistoryRead/HistoryUpdate — +limiter (`ServerHistorian:MaxConcurrentHistoryReadBatches`, N) and never holds the node-manager lock; projected reads and remote peers +reading this node hold, TOGETHER (one shared semaphore), at most N − max(1, N/4) of the N slots, so a slow origin cannot starve local HistoryRead/HistoryUpdate — past that the projected half is `BadTooManyOperations`, unsent. A fault or timeout of the remote call (including the connection's capability probe) fails only the projected half, per node (`BadTimeout` when the deadline fired), and releases its continuation points. Remote calls are runs of consecutive request positions that share a connection, details and (for resumes) the issuing -endpoint, read in request order and split into sub-batches of at most min(the connection's batch size, the origin's advertised -`MaxBatchItems`) — a large batch is never refused as a whole. +endpoint, read in request order and split into sub-batches at the connection's batch size; the gRPC connection splits again at the origin's advertised +`MaxBatchItems` from the capabilities each call negotiates (no extra probe) — a large batch is never refused as a whole. **Continuation points.** A projected read's continuation point lives in the client's OPC UA session like a local one (a `Remote` cursor; capped by `MaxHistoryContinuationPoints`, oldest evicted). It wraps the origin's token and binds the caller (principal, key, @@ -251,7 +251,7 @@ details on resume gets what it first asked for, as locally). Rules: | Limit | Effect | |---|---| | `RemoteNamespaceMapping.MaxHistoryAssemblyBytesPerRequest` (16 MiB) | One budget per request, shared across the batch (the tightest mapping in the batch). Nodes are charged in request order (calls run in request order, and at most one node per 256 B of the remaining budget is sent); once a node does not fit, it and every later projected node with data is `BadTooManyOperations` (never a partial answer; its origin cursor is released). | -| `ServerHistorian:HistoryReadDeadline` (consumer, 60 s) | The consumer request's remaining deadline, capped per call by `DataConnection.HistoryTimeoutMilliseconds` ⇒ `BadTimeout`. A cancelled request is never counted as an origin fault. | +| `ServerHistorian:HistoryReadDeadline` (consumer, 60 s) | ONE deadline per request, covering the local half too: the local nodes of a mixed batch are served first, so a slow local historian leaves the projected nodes less (or no) time — they answer `BadTimeout`. Each remote call is capped by the remaining deadline and `DataConnection.HistoryTimeoutMilliseconds` ⇒ `BadTimeout`. A cancelled request is never counted as an origin fault; a cancel that is neither the caller's nor the deadline (a connection redeployed mid-read) is `BadNoCommunication` / `BadContinuationPointInvalid`. | | Aggregates | An aggregate the consumer cannot name is `BadAggregateNotSupported` unsent; one the origin's backend refuses (unknown to it, or not valid for the node's type — #897) comes back `BadAggregateNotSupported` from the origin. The consumer's `HistoryServerCapabilities/AggregateFunctions` does not describe remote backends. | Modified-value reads (`IsReadModified`) and HistoryReadEvents on projected nodes are refused `BadHistoryOperationUnsupported`. 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 05ae4cab2..42a3e3d6b 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs @@ -511,7 +511,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable } /// A non-owning handle with the deployed operation and resource policy. -public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistoryService, IDisposable +public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistoryService, IHistoryBatchLimit, IDisposable { /// /// H2 remote history through the deployed connection: needs the connection row's HistoryRead bit (masked to the @@ -585,6 +585,9 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistor internal DataOperations AllowedOperations => _allowed; /// The connection row's batch size: a history request with more items is refused (H3 splits below it). internal int MaxBatchItems => _batch; + + /// + int IHistoryBatchLimit.MaxHistoryBatchItems => _batch; public IDataConnection Connection => this; public CancellationToken CancellationToken => _scope; public DataTarget Target => _inner.Target; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs index 2aa93be69..fd0811b01 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs @@ -114,7 +114,7 @@ public sealed partial class GrpcDataConnection : IDataHistoryService continue; } DataHistoryReadResult[]? served; - try { served = await ServeAsync(selected, index, request, items, pending, start, cancellationToken).ConfigureAwait(false); } + try { served = await ServeSplitAsync(selected, index, request, items, pending, start, cancellationToken).ConfigureAwait(false); } catch (Exception ex) when (!cancellationToken.IsCancellationRequested && ex is InvalidOperationException or ArgumentException or RpcException or HttpRequestException) { @@ -132,6 +132,49 @@ public sealed partial class GrpcDataConnection : IDataHistoryService finally { if (admitted) _unaryCapacity.Release(); ExitWork(); } } + /// + /// Reads on one selected endpoint in sub-batches of at most the endpoint's advertised MaxBatchItems — taken from the + /// capabilities this call already negotiated, so no extra probe (H3 review round 2). The assembly budget is shared across + /// the sub-batches; once it is spent the remaining items are BadTooManyOperations, unsent. Null = the endpoint failed + /// before answering the FIRST sub-batch (a fresh read may move); a later failure answers the rest + /// BadNoCommunication (resumed items BadContinuationPointInvalid), never moving a half-served request. + /// + private async Task ServeSplitAsync(Selected selected, int endpoint, DataHistoryReadRequest request, + DataHistoryReadItem[] items, int[] pending, long start, CancellationToken cancellationToken) + { + var batch = Math.Max(1, selected.Capabilities.Limits.MaxBatchItems); + if (pending.Length <= batch) return await ServeAsync(selected, endpoint, request, items, pending, start, cancellationToken).ConfigureAwait(false); + var answers = new DataHistoryReadResult[pending.Length]; + long used = 0; + for (var offset = 0; offset < pending.Length; offset += batch) + { + var chunk = pending.Skip(offset).Take(batch).ToArray(); + var left = request.Budget.MaxBytes - used; + DataHistoryReadResult[]? served = null; + if (left > 0) + { + try + { + served = await ServeAsync(selected, endpoint, request with { Budget = request.Budget with { MaxBytes = left } }, items, chunk, start, + cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (offset > 0 && ex is not OutOfMemoryException && !cancellationToken.IsCancellationRequested) { served = null; } + if (served is null && offset == 0) return null; + } + + for (var k = 0; k < chunk.Length; k++) + { + var item = request.Items[chunk[k]]; + var answer = served?[k] ?? new(item.CorrelationId, + left <= 0 ? BadTooManyOperations : item.Continuation is not null ? BadContinuationPointInvalid : BadNoCommunication, [], null); + foreach (var sample in answer.Samples) used += sample.Value.EstimatedRetainedBytes; + answers[offset + k] = answer; + } + } + + return answers; + } + /// Reads on one selected endpoint and assembles its chunks; null = the endpoint failed before answering (a fresh read may move). private async Task ServeAsync(Selected selected, int endpoint, DataHistoryReadRequest request, DataHistoryReadItem[] items, int[] pending, long start, CancellationToken cancellationToken) 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 47ef06202..9ef6da40e 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs @@ -5,6 +5,12 @@ using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +/// A connection's own history batch size (the deployed connection row's batch); a larger request is refused. +internal interface IHistoryBatchLimit +{ + int MaxHistoryBatchItems { get; } +} + /// What a projected HistoryRead demand is bound to (H3). /// The mapping. /// The deployed mapping revision. @@ -108,6 +114,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl var assemblyRefused = new bool[nodes.Count]; var callerKey = CallerKey(caller); long budget = DefaultAssemblyBudget, received = 0; + var budgetExhausted = false; try { // 1. Resolve, authorize and pin every node; check each resumed cursor against what it was issued under. @@ -165,7 +172,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl { var indices = list.ToArray(); if (cancellationToken.IsCancellationRequested || Remaining() <= TimeSpan.Zero) { FailAll(indices, BadTimeout); continue; } - if (received >= budget) { FailAll(indices, BadTooManyOperations); continue; } + if (received >= budget || budgetExhausted) { FailAll(indices, BadTooManyOperations); continue; } await ReadGroupAsync(key, indices, cancellationToken).ConfigureAwait(false); } @@ -248,14 +255,14 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl } if (sendable.Count == 0) return; - var batch = await BatchSizeAsync(lease.Connection, sendable.Count, remaining, linked.Token).ConfigureAwait(false); + var batch = BatchSize(lease.Connection); for (var offset = 0; offset < sendable.Count;) { var now = Remaining(); if (ct.IsCancellationRequested || now <= TimeSpan.Zero) { FailAll(sendable.Skip(offset).ToArray(), BadTimeout); return; } // A budget shortfall refuses the remaining nodes unsent — never an endpoint failure (H3 review D4). A call may // carry at most one item per MinimumBytesPerItem of its byte budget (the origin's admission rule). - var fitting = (int)Math.Min(int.MaxValue, (budget - received) / MinimumBytesPerItem); + var fitting = budgetExhausted ? 0 : (int)Math.Min(int.MaxValue, (budget - received) / MinimumBytesPerItem); if (fitting <= 0) { FailAll(sendable.Skip(offset).ToArray(), BadTooManyOperations); return; } var from = offset; var chunk = sendable.Skip(from).Take(Math.Min(batch, fitting)).ToArray(); @@ -273,10 +280,12 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl catch (OperationCanceledException) { // Our deadline or the SDK request ending: a timeout, never an origin fault (the connection records none). - FailAll(sendable.Skip(from).ToArray(), BadTimeout); + // Any other cancel (the deployed lease retired by a redeploy) is not a timeout. + FailCancelled(sendable.Skip(from).ToArray()); return; } + var assigned = new bool[answers.Count]; try { if (answers.Count != items.Length) @@ -291,38 +300,42 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl var answer = answers[k]; if (answer.CorrelationId != items[k].CorrelationId) { - if (answer.Continuation is { } stray) EnqueueRelease(key.ConnectionId, stray); outcomes[i] = Fail(BadNoCommunication); - continue; + continue; // its token (if any) is released in the finally } if (answer.StatusCode == BadTooManyOperations && answer.Diagnostic?.Contains("budget", StringComparison.OrdinalIgnoreCase) == true) - assemblyRefused[i] = true; // the connection's own share of the assembly budget ran out + { + assemblyRefused[i] = true; // the connection's own share of the assembly budget ran out: + budgetExhausted = true; // no further origin call in this request (H3 review round 2) + } long nodeBytes = 0; foreach (var sample in answer.Samples) nodeBytes += sample.Value.EstimatedRetainedBytes; assembled[i] = nodeBytes; received += nodeBytes; var target = targets[i]!; - RemoteCursor? next = null; - if (answer.Continuation is { } token) - { - next = new RemoteCursor(this, target.OriginMetadata.View.Realm, demands[i]!.LocalIdentifier, token, key.ConnectionId, route, - target, callerKey, key.Details, nodes[i].Resume is RemoteCursor prior ? prior.AggregateId : nodes[i].AggregateId); - } - - outcomes[i] = new ProjectedHistoryOutcome(answer.StatusCode, - Convert(answer.Samples, target.OriginMetadata, key.Details is DataHistoryProcessedDetails), next); + var samples = Convert(answer.Samples, target.OriginMetadata, key.Details is DataHistoryProcessedDetails); + var next = answer.Continuation is { } token + ? new RemoteCursor(this, target.OriginMetadata.View.Realm, demands[i]!.LocalIdentifier, token, key.ConnectionId, route, + target, callerKey, key.Details, nodes[i].Resume is RemoteCursor prior ? prior.AggregateId : nodes[i].AggregateId) + : null; + outcomes[i] = new ProjectedHistoryOutcome(answer.StatusCode, samples, next); + assigned[k] = true; } } finally { + // H3 review round 2: a new origin token whose answer never became an outcome (a mismatched answer, or an + // exception mid-answer) is released, never stranded at the origin until its idle expiry. + for (var k = 0; k < answers.Count; k++) + if (!assigned[k] && answers[k].Continuation is { } orphan) EnqueueRelease(key.ConnectionId, orphan); foreach (var answer in answers) answer.Dispose(); } } } catch (OperationCanceledException) { - FailAll(indices.Where(i => outcomes[i] is null).ToArray(), BadTimeout); + FailCancelled(indices.Where(i => outcomes[i] is null).ToArray()); } catch (Exception ex) when (ex is not OutOfMemoryException) { @@ -340,6 +353,16 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl } } + void FailCancelled(int[] indices) + { + if (cancellationToken.IsCancellationRequested || Remaining() <= TimeSpan.Zero) { FailAll(indices, BadTimeout); return; } + foreach (var i in indices) + { + if (nodes[i].Resume is RemoteCursor c) { c.ReleaseOrigin(); outcomes[i] = Fail(BadContinuationPointInvalid); } + else outcomes[i] = Fail(BadNoCommunication); + } + } + void FailAll(int[] indices, uint status) { foreach (var i in indices) @@ -351,24 +374,13 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl } /// - /// The sub-batch size of one call (H3 review D4): the deployed connection's own batch size, and — when more than one node - /// is sent — the origin's advertised MaxBatchItems (best effort: a failed probe keeps the connection's size). + /// The sub-batch size of one call (H3 review D4): the deployed connection's own batch size. No separate capability probe + /// (H3 review round 2): a probe through the connection's unary path records a cancelled probe as an endpoint failure and + /// puts the connection into discovery backoff. The ORIGIN's advertised batch is applied by the gRPC connection itself, + /// from the capabilities each history call already negotiates. /// - private static async Task BatchSizeAsync(IDataConnection connection, int count, TimeSpan remaining, CancellationToken ct) - { - var batch = connection is DataConnectionDeploymentLease lease ? lease.MaxBatchItems : DefaultBatchItems; - if (count > 1) - { - try - { - var capabilities = await connection.GetCapabilitiesAsync(new DataBudget(remaining, 1, 1L << 20), ct).ConfigureAwait(false); - if (capabilities.Limits.MaxBatchItems > 0) batch = Math.Min(batch, capabilities.Limits.MaxBatchItems); - } - catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException) { } - } - - return Math.Max(1, batch); - } + private static int BatchSize(IDataConnection connection) => + Math.Max(1, connection is IHistoryBatchLimit limit ? limit.MaxHistoryBatchItems : DefaultBatchItems); /// The sub-batch size when the connection is not a deployment lease (tests, direct facades). internal const int DefaultBatchItems = 100; @@ -444,7 +456,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl private async Task FlushReleasesAsync() { - try { await Task.Delay(ReleaseCoalesce, _stop.Token).ConfigureAwait(false); } + try { await Task.Delay(ReleaseCoalesce, _clock, _stop.Token).ConfigureAwait(false); } catch (OperationCanceledException) { lock (_releaseGate) _flushScheduled = false; return; } Dictionary> batch; lock (_releaseGate) diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataComposedBrowseWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataComposedBrowseWireTests.cs index 6ee16a0c6..c56b311b3 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataComposedBrowseWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataComposedBrowseWireTests.cs @@ -432,7 +432,8 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests manager.ProjectedDataAccess = access; // H3: projected HistoryRead through the same deployed connections. using var history = new ProjectedHistoryAccess(access, connections, - id => placements.TryGetHistoryAssemblyBudget(id, out var bytes) ? bytes : null, origin.Clock); + id => placements.TryGetHistoryAssemblyBudget(id, out var bytes) ? bytes : null, origin.Clock) + { ReleaseCoalesce = TimeSpan.Zero }; // the flush delay runs on the (manual) fixture clock manager.ProjectedHistoryAccess = history; onHistory?.Invoke(history, manager); var identifier = ProjectedDataIds.Identifier("map", root.Address); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs index cf78f7ddb..965d96590 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs @@ -218,6 +218,39 @@ public sealed class GrpcDataHistoryClientTests a.LastProbeTimeout!.Value.ShouldBeLessThanOrEqualTo(TimeSpan.FromSeconds(2)); } + [Fact] + [Trait("Phase", "H3")] + public async Task A_request_larger_than_the_endpoints_advertised_batch_is_split_from_the_negotiated_capabilities() + { + // H3 review round 2: the split uses the capabilities the history call itself negotiated — no extra probe. + var a = new Endpoint("a") { BatchItems = 2 }; + await using var connection = Connect([a]); + var request = new DataHistoryReadRequest(Request().Details, + Enumerable.Range(0, 5).Select(i => new DataHistoryReadItem("n" + i, View)).ToArray(), Budget); + var results = await connection.ReadHistoryAsync(request, TestContext.Current.CancellationToken); + results.Select(r => r.CorrelationId).ShouldBe(["n0", "n1", "n2", "n3", "n4"]); + results.ShouldAllBe(r => r.StatusCode == 0u && r.Samples.Count == 2); + a.CallSizes.ShouldBe([2, 2, 1]); + a.Headers.Count(h => h.Path.EndsWith("/GetCapabilities", StringComparison.Ordinal)).ShouldBe(1, "one negotiation for the whole request"); + foreach (var r in results) r.Dispose(); + } + + [Fact] + [Trait("Phase", "H3")] + public async Task A_cancel_during_a_multi_node_read_leaves_the_connection_usable_without_backoff() + { + var a = new Endpoint("a") { ProbeDelay = TimeSpan.FromSeconds(30) }; + await using var connection = Connect([a]); + var request = new DataHistoryReadRequest(Request().Details, + Enumerable.Range(0, 3).Select(i => new DataHistoryReadItem("n" + i, View)).ToArray(), Budget); + using (var cancel = new CancellationTokenSource(TimeSpan.FromMilliseconds(200))) + await Should.ThrowAsync(() => connection.ReadHistoryAsync(request, cancel.Token)); + a.ProbeDelay = null; + var again = await connection.ReadHistoryAsync(request, TestContext.Current.CancellationToken); + again.ShouldAllBe(r => r.StatusCode == 0u, "a cancel is not an endpoint failure: no discovery backoff"); + foreach (var r in again) r.Dispose(); + } + [Fact] public async Task A_failure_mid_assembly_releases_the_origin_chunk_tokens_it_holds() { @@ -252,6 +285,10 @@ public sealed class GrpcDataHistoryClientTests public TimeSpan? Delay { get; set; } /// Delay before answering the capability probe (honours the request's token). public TimeSpan? ProbeDelay { get; set; } + /// The advertised MaxBatchItems (default: the shared limits'). + public int? BatchItems { get; set; } + /// The item count of every HistoryRead call. + public List CallSizes { get; } = []; /// The grpc-timeout of the last capability probe. public TimeSpan? LastProbeTimeout { get; private set; } /// Fail every HistoryRead after the first with this status. @@ -281,7 +318,7 @@ public sealed class GrpcDataHistoryClientTests var asked = request.Headers.Contains("x-otopcua-data-features"); var caps = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 5, Serving, Ready ? DataReadiness.Ready : DataReadiness.Unavailable, !Ready ? DataOperations.None : DataOperationSets.V1 | (history && asked && Granted ? DataOperations.HistoryRead : DataOperations.None), - new HashSet { DataValueKind.Double }, Limits, false, 0, "c", true, true, true, true, true, + new HashSet { DataValueKind.Double }, BatchItems is { } b ? Limits with { MaxBatchItems = b } : Limits, false, 0, "c", true, true, true, true, true, history && asked ? Caps : null)); message = caps; } @@ -294,6 +331,7 @@ public sealed class GrpcDataHistoryClientTests var bytes = await request.Content!.ReadAsByteArrayAsync(token); var wire = W.HistoryReadRequest.Parser.ParseFrom(bytes.AsSpan(5).ToArray()); LastBudgetTimeout = TimeSpan.FromTicks(wire.Budget.TimeoutTicks); + if (!wire.ReleaseContinuations) lock (CallSizes) CallSizes.Add(wire.Items.Count); var response = new W.HistoryReadResponse { Serving = DataProtoMapper.EncodeServing(Serving) }; if (!wire.ReleaseContinuations && call > 1 && FailAfterFirst is { } later) { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs index d991e70ed..eb624f742 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs @@ -315,7 +315,7 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests // H3 review D4: three projected nodes against an origin that admits two items per request. await using var originServer = await HistoryOrigin.StartAsync(7, extra: 2); using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1, history: originServer.Port, maxBatchItems: 2); - var connections = new HistorySwitchConnections(origin); + var connections = new HistorySwitchConnections(origin) { BatchItems = 2 }; await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) => { var client = (SessionClient)session; @@ -328,6 +328,12 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests results.ShouldAllBe(r => Values(r).Count == 3); connections.HistoryCallSizes.ShouldBe([2, 1]); foreach (var r in results) await RawHistory(client, children[Array.IndexOf(results, r)], 3, r.ContinuationPoint); + // H3 review round 2: the batch size is the deployed connection's own — no separate capability probe (a cancelled + // probe put the gRPC connection into discovery backoff). + var before = Volatile.Read(ref connections.CapabilityCalls); + await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(3)), TimestampsToReturn.Both, false, + children.Select(c => new HistoryReadValueId { NodeId = c }).ToArray(), TestContext.Current.CancellationToken); + Volatile.Read(ref connections.CapabilityCalls).ShouldBe(before, "a projected history read sends no capability probe"); }, localPermissions: 15, allowHistory: true, connectionSource: connections); } @@ -385,6 +391,58 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests }, localPermissions: 15, allowHistory: true, connectionSource: connections, onHistory: (h, _) => history = h); } + [Fact(Timeout = 90000)] + [Trait("Phase", "H3")] + public async Task A_retired_lease_is_not_a_timeout_and_a_fault_mid_answer_releases_the_new_origin_token() + { + // H3 review round 2 (5): a cancel that is neither the caller's nor the deadline (a lease retired by a redeploy) is + // BadContinuationPointInvalid for a resume / BadNoCommunication for a fresh node — never BadTimeout. + // (4): an exception mid-answer leaves no new origin token behind (positive control: the origin store returns to 0). + await using var originServer = await HistoryOrigin.StartAsync(7); + using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); + var connections = new HistorySwitchConnections(origin); + ProjectedHistoryAccess? history = null; + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var page = await RawHistory(client, anchor, 2, default); + connections.Mode = HistoryMode.Retired; + (await RawHistory(client, anchor, 2, page.ContinuationPoint)).StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); + (await RawHistory(client, anchor, 2, default)).StatusCode.Code.ShouldBe(StatusCodes.BadNoCommunication.Code); + await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0); + origin.Services.HistoryOpenContinuations.ShouldBe(0); + + connections.Mode = HistoryMode.Poison; + (await RawHistory(client, anchor, 2, default)).StatusCode.Code.ShouldBe(StatusCodes.BadNoCommunication.Code); + await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0); + origin.Services.HistoryOpenContinuations.ShouldBe(0, "the new origin token of the faulted answer was released"); + }, localPermissions: 15, allowHistory: true, connectionSource: connections, onHistory: (h, _) => history = h); + } + + [Fact(Timeout = 90000)] + [Trait("Phase", "H3")] + public async Task Once_the_connection_reports_the_assembly_budget_spent_no_further_origin_call_is_made() + { + // H3 review round 2 (3): [A fresh, B resumed] is two calls; when the first comes back budget-refused, B is refused unsent. + await using var originServer = await HistoryOrigin.StartAsync(7, extra: 1); + using var origin = new LocalDataFixture(additionalRawNodes: 1, servingGeneration: 1, history: originServer.Port); + var connections = new HistorySwitchConnections(origin); + await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray(); + var first = await RawHistory(client, children[1], 3, default); + connections.Mode = HistoryMode.BudgetRefused; + var calls = connections.HistoryCallSizes.Count; + var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(3)), TimestampsToReturn.Both, false, + [new HistoryReadValueId { NodeId = children[0] }, new HistoryReadValueId { NodeId = children[1], ContinuationPoint = first.ContinuationPoint }], + TestContext.Current.CancellationToken); + response.Results.ToArray()!.ShouldAllBe(r => r.StatusCode.Code == StatusCodes.BadTooManyOperations.Code); + (connections.HistoryCallSizes.Count - calls).ShouldBe(1, "the second run is refused unsent"); + }, localPermissions: 15, allowHistory: true, connectionSource: connections); + } + // ------------------------------------------------------------------------------------------------------------------ private static ReadRawModifiedDetails RawDetails(uint count) => new() @@ -423,7 +481,7 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests } } - public enum HistoryMode { Pass, Hang, Throw } + public enum HistoryMode { Pass, Hang, Throw, Retired, Poison, BudgetRefused } /// /// One long-lived origin connection whose HISTORY path can be switched to never answer (then fault as a cancelled gRPC call, @@ -436,6 +494,9 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests private int _released; private readonly List _sizes = []; public HistoryMode Mode { get; set; } + /// The deployed connection's own batch size the lease reports. + public int? BatchItems { get; set; } + public int CapabilityCalls; public int ReleasedTokens => Volatile.Read(ref _released); public IReadOnlyList HistoryCallSizes { get { lock (_sizes) return _sizes.ToArray(); } } @@ -454,11 +515,16 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests public ValueTask DisposeAsync() => ValueTask.CompletedTask; } - private sealed class Switch(IDataConnection inner, HistorySwitchConnections owner) : IDataConnection, IDataHistoryService + private sealed class Switch(IDataConnection inner, HistorySwitchConnections owner) : IDataConnection, IDataHistoryService, IHistoryBatchLimit { + public int MaxHistoryBatchItems => owner.BatchItems ?? ProjectedHistoryAccess.DefaultBatchItems; public DataTarget Target => inner.Target; public TimeProvider Clock => inner.Clock; - public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => inner.GetCapabilitiesAsync(budget, cancellationToken); + public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) + { + Interlocked.Increment(ref owner.CapabilityCalls); + return inner.GetCapabilitiesAsync(budget, cancellationToken); + } public Task BrowseAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest request, CancellationToken cancellationToken) => inner.BrowseAsync(request, cancellationToken); public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => inner.GetMetadataAsync(request, cancellationToken); public Task> ReadAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest request, CancellationToken cancellationToken) => inner.ReadAsync(request, cancellationToken); @@ -478,8 +544,17 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests break; case HistoryMode.Throw: throw new Grpc.Core.RpcException(new Grpc.Core.Status(Grpc.Core.StatusCode.Internal, "boom")); + case HistoryMode.Retired: + // A deployment lease retired by a redeploy: its scope token cancels, not the caller's. + throw new OperationCanceledException("lease retired"); + case HistoryMode.BudgetRefused: + return request.Items.Select(i => new DataHistoryReadResult(i.CorrelationId, 0x80100000u, [], null, + "History assembly budget exceeded.")).ToArray(); } - return await ((IDataHistoryService)inner).ReadAsync(request, cancellationToken); + var answers = await ((IDataHistoryService)inner).ReadAsync(request, cancellationToken); + if (owner.Mode == HistoryMode.Poison) + foreach (var answer in answers) if (answer.Samples.Count > 0) answer.Samples[^1].Dispose(); // faults the reader mid-answer + return answers; } public async Task ReleaseAsync(IReadOnlyList continuations, CancellationToken cancellationToken) From 34e72de3d8a71cb28595402911e4a3f4b74b196f Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 07:01:28 -0500 Subject: [PATCH 20/25] =?UTF-8?q?fix(grpc-data):=20H3=20review=20round=203?= =?UTF-8?q?=20S4=20=E2=80=94=20budget=20stop=20keys=20on=20a=20typed=20con?= =?UTF-8?q?sumer=20marker,=20not=20the=20diagnostic?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ProjectedHistoryAccess stopped the request on any BadTooManyOperations whose diagnostic contained "budget", which also matched the ORIGIN's "remainder budget is full" refusal and then refused later nodes, including Good ones. DataHistoryReadResult gains an internal ConsumerBudgetRefused flag (never on the wire) set only by the gRPC connection's own assembly refusal. Red on revert: the origin refusal of A refused B. --- .../DataConnections/IDataServices.cs | 8 +++++ ...ZB.MOM.WW.OtOpcUa.Core.Abstractions.csproj | 1 + .../GrpcDataConnection.History.cs | 2 +- .../DataConnections/ProjectedHistoryAccess.cs | 9 +++-- .../GrpcDataProjectedHistoryWireTests.cs | 36 +++++++++++++++++-- 5 files changed, 50 insertions(+), 6 deletions(-) diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs index 575b0ecc3..cf9514bf7 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs @@ -262,6 +262,14 @@ public sealed record DataHistoryReadResult(string CorrelationId, uint StatusCode string? Diagnostic = null, bool ChunkContinues = false) : IDisposable { + /// + /// Consumer-side only, never on the wire (H3 review round 3): this BadTooManyOperations is the CONSUMER's own + /// assembly-budget refusal (the gRPC connection's chunk assembly or sub-batch split ran out of the request's byte + /// budget) — not an origin's refusal (e.g. its remainder budget), whose text may also mention a budget. A caller that + /// stops the request on a spent budget keys on this flag, never on . + /// + internal bool ConsumerBudgetRefused { get; init; } + public void Dispose() { foreach (var sample in Samples) sample.Dispose(); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/ZB.MOM.WW.OtOpcUa.Core.Abstractions.csproj b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/ZB.MOM.WW.OtOpcUa.Core.Abstractions.csproj index 4d2e7ef50..7eef12725 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/ZB.MOM.WW.OtOpcUa.Core.Abstractions.csproj +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/ZB.MOM.WW.OtOpcUa.Core.Abstractions.csproj @@ -13,6 +13,7 @@ + diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs index fd0811b01..365da1766 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs @@ -259,7 +259,7 @@ public sealed partial class GrpcDataConnection : IDataHistoryService { // The per-request assembly budget is exhausted: this and every later node is BadTooManyOperations. _ = ReleaseOnEndpointAsync(selected, result.Continuation); - final[target] = new(result.CorrelationId, BadTooManyOperations, [], null, "History assembly budget exceeded."); + final[target] = new(result.CorrelationId, BadTooManyOperations, [], null, "History assembly budget exceeded.") { ConsumerBudgetRefused = true }; continue; } if (result.ChunkContinues) 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 9ef6da40e..987634c86 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs @@ -304,10 +304,13 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl continue; // its token (if any) is released in the finally } - if (answer.StatusCode == BadTooManyOperations && answer.Diagnostic?.Contains("budget", StringComparison.OrdinalIgnoreCase) == true) + if (answer.StatusCode == BadTooManyOperations && answer.ConsumerBudgetRefused) { - assemblyRefused[i] = true; // the connection's own share of the assembly budget ran out: - budgetExhausted = true; // no further origin call in this request (H3 review round 2) + // The connection's own share of the assembly budget ran out: no further origin call in this + // request (H3 review round 2). A typed marker, never the diagnostic text — an ORIGIN's refusal + // ("remainder budget is full") is a per-node answer, not a spent request (round 3, S4). + assemblyRefused[i] = true; + budgetExhausted = true; } long nodeBytes = 0; foreach (var sample in answer.Samples) nodeBytes += sample.Value.EstimatedRetainedBytes; diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs index eb624f742..da07939cb 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs @@ -443,6 +443,34 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests }, localPermissions: 15, allowHistory: true, connectionSource: connections); } + [Fact(Timeout = 90000)] + [Trait("Phase", "H3")] + public async Task An_origins_budget_refusal_is_a_per_node_answer_and_never_stops_the_request() + { + // H3 review round 3 (S4): the stop keys on the consumer's typed marker, not on "budget" in the diagnostic — the origin's + // "remainder budget is full" refusal of A must not refuse B (sent in the next run) nor a Good answer after it. + await using var originServer = await HistoryOrigin.StartAsync(7, extra: 1); + using var origin = new LocalDataFixture(additionalRawNodes: 1, servingGeneration: 1, history: originServer.Port); + var connections = new HistorySwitchConnections(origin); + await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray(); + var first = await RawHistory(client, children[1], 3, default); + connections.Mode = HistoryMode.OriginRefusedFresh; + var calls = connections.HistoryCallSizes.Count; + var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(3)), TimestampsToReturn.Both, false, + [new HistoryReadValueId { NodeId = children[0] }, new HistoryReadValueId { NodeId = children[1], ContinuationPoint = first.ContinuationPoint }], + TestContext.Current.CancellationToken); + var results = response.Results.ToArray()!; + results[0].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code, "the origin refused A"); + StatusCode.IsGood(results[1].StatusCode).ShouldBeTrue("B is still read: an origin refusal is not a spent consumer budget"); + Values(results[1]).Count.ShouldBeGreaterThan(0); + (connections.HistoryCallSizes.Count - calls).ShouldBe(2, "both runs are sent"); + connections.Mode = HistoryMode.Pass; + }, localPermissions: 15, allowHistory: true, connectionSource: connections); + } + // ------------------------------------------------------------------------------------------------------------------ private static ReadRawModifiedDetails RawDetails(uint count) => new() @@ -481,7 +509,7 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests } } - public enum HistoryMode { Pass, Hang, Throw, Retired, Poison, BudgetRefused } + public enum HistoryMode { Pass, Hang, Throw, Retired, Poison, BudgetRefused, OriginRefusedFresh } /// /// One long-lived origin connection whose HISTORY path can be switched to never answer (then fault as a cancelled gRPC call, @@ -549,7 +577,11 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests throw new OperationCanceledException("lease retired"); case HistoryMode.BudgetRefused: return request.Items.Select(i => new DataHistoryReadResult(i.CorrelationId, 0x80100000u, [], null, - "History assembly budget exceeded.")).ToArray(); + "History assembly budget exceeded.") { ConsumerBudgetRefused = true }).ToArray(); + case HistoryMode.OriginRefusedFresh when request.Items.All(i => i.Continuation is null): + // The ORIGIN's own refusal, whose text also mentions a budget (LocalDataServices.History). + return request.Items.Select(i => new DataHistoryReadResult(i.CorrelationId, 0x80100000u, [], null, + "Origin history remainder budget is full; retry with a lower NumValuesPerNode.")).ToArray(); } var answers = await ((IDataHistoryService)inner).ReadAsync(request, cancellationToken); if (owner.Mode == HistoryMode.Poison) From 9c2d6273aa0beb9a6415a612d2d21954ab06f9f3 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 07:08:12 -0500 Subject: [PATCH 21/25] =?UTF-8?q?fix(grpc-data):=20H3=20review=20round=203?= =?UTF-8?q?=20S1/S2/S3/S6=20=E2=80=94=20sub-batch=20split=20never=20strand?= =?UTF-8?q?s=20tokens=20or=20breaks=20the=20origin's=20admission?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GrpcDataConnection.ServeSplitAsync / ServeAsync: - S2: each sub-batch carries at most one item per 256 B of the budget left (the origin's count <= MaxBytes/256 admission rule); the rest is BadTooManyOperations marked ConsumerBudgetRefused, unsent, and an unsent resumed item's origin token is released. Was: an RpcException, a recorded endpoint failure and BadNoCommunication. - S3: a budget refusal inside a sub-batch's own assembly latches the budget spent; nothing more is sent. - S1: anything escaping a later sub-batch (a caller cancel, a fault) disposes the collected answers and releases their new continuations. - S6: an escape from the assembly (Verify failure, item mismatch) releases finished nodes' continuations, held chunk tokens and the rejected response's tokens; a later sub-batch's endpoint fault is RecordFailure'd, never swallowed. - Nit a: after a sub-batch endpoint failure nothing more is sent to that endpoint; the rest is BadNoCommunication / BadContinuationPointInvalid. Each test is red on revert of its fix (mutation). --- .../GrpcDataConnection.History.cs | 133 ++++++++++++++---- .../DataConnections/ProjectedHistoryAccess.cs | 2 +- .../GrpcDataHistoryClientTests.cs | 123 +++++++++++++++- 3 files changed, 222 insertions(+), 36 deletions(-) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs index 365da1766..39d37782a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs @@ -23,6 +23,8 @@ public sealed partial class GrpcDataConnection : IDataHistoryService internal const uint BadTooManyOperations = 0x80100000u; internal const uint BadTimeout = 0x800A0000u; internal const uint BadNoCommunication = 0x80310000u; + /// An origin admits at most one item per this many bytes of a request's byte budget (LocalDataServices.CheckBudget). + internal const long MinimumBytesPerItem = 256; private const byte EnvelopeTag = 0xC7, EnvelopeVersion = 1; private TimeSpan _historyTimeout = TimeSpan.FromSeconds(30); @@ -135,48 +137,104 @@ public sealed partial class GrpcDataConnection : IDataHistoryService /// /// Reads on one selected endpoint in sub-batches of at most the endpoint's advertised MaxBatchItems — taken from the /// capabilities this call already negotiated, so no extra probe (H3 review round 2). The assembly budget is shared across - /// the sub-batches; once it is spent the remaining items are BadTooManyOperations, unsent. Null = the endpoint failed - /// before answering the FIRST sub-batch (a fresh read may move); a later failure answers the rest - /// BadNoCommunication (resumed items BadContinuationPointInvalid), never moving a half-served request. + /// the sub-batches, and each sub-batch carries at most one item per of what is left + /// (the origin's admission rule, round 3 S2). Once the budget is spent — exhausted, too small for one more item, or a + /// sub-batch's own assembly refused (S3) — the remaining items are BadTooManyOperations marked + /// , unsent. Null = the endpoint failed before answering the + /// FIRST sub-batch (a fresh read may move); a later failure is recorded, nothing more is sent to that endpoint, and the + /// rest is BadNoCommunication (resumed items BadContinuationPointInvalid), never moving a half-served + /// request. A resumed item answered unsent has its origin token released (it is still live there). Anything that + /// escapes (a caller cancel, a fault) first disposes the collected answers and releases their new continuations (S1). /// private async Task ServeSplitAsync(Selected selected, int endpoint, DataHistoryReadRequest request, DataHistoryReadItem[] items, int[] pending, long start, CancellationToken cancellationToken) { var batch = Math.Max(1, selected.Capabilities.Limits.MaxBatchItems); - if (pending.Length <= batch) return await ServeAsync(selected, endpoint, request, items, pending, start, cancellationToken).ConfigureAwait(false); - var answers = new DataHistoryReadResult[pending.Length]; + if (pending.Length <= batch) return (await ServeAsync(selected, endpoint, request, items, pending, start, cancellationToken).ConfigureAwait(false)).Results; + var answers = new DataHistoryReadResult?[pending.Length]; long used = 0; - for (var offset = 0; offset < pending.Length; offset += batch) + bool spent = false, failed = false; + try { - var chunk = pending.Skip(offset).Take(batch).ToArray(); - var left = request.Budget.MaxBytes - used; - DataHistoryReadResult[]? served = null; - if (left > 0) + for (var offset = 0; offset < pending.Length;) { + var left = request.Budget.MaxBytes - used; + var fitting = spent || failed ? 0 : (int)Math.Min(batch, Math.Max(0, left) / MinimumBytesPerItem); + if (fitting <= 0) + { + for (var k = offset; k < pending.Length; k++) + { + var item = request.Items[pending[k]]; + var resumed = item.Continuation is not null; + if (resumed) _ = ReleaseOnEndpointAsync(selected, items[pending[k]].Continuation); // unsent: still live at the origin + answers[k] = failed + ? new(item.CorrelationId, resumed ? BadContinuationPointInvalid : BadNoCommunication, [], null) + : new(item.CorrelationId, BadTooManyOperations, [], null, "History assembly budget exceeded.") { ConsumerBudgetRefused = true }; + } + break; + } + + var chunk = pending.Skip(offset).Take(fitting).ToArray(); + DataHistoryReadResult[]? served; try { - served = await ServeAsync(selected, endpoint, request with { Budget = request.Budget with { MaxBytes = left } }, items, chunk, start, + var call = await ServeAsync(selected, endpoint, request with { Budget = request.Budget with { MaxBytes = left } }, items, chunk, start, cancellationToken).ConfigureAwait(false); + served = call.Results; + failed = call.EndpointFailed; // answered, but the endpoint failed mid-way: send it nothing more (nit a) } - catch (Exception ex) when (offset > 0 && ex is not OutOfMemoryException && !cancellationToken.IsCancellationRequested) { served = null; } - if (served is null && offset == 0) return null; + catch (Exception ex) when (offset > 0 && !cancellationToken.IsCancellationRequested + && ex is InvalidOperationException or ArgumentException or RpcException or HttpRequestException) + { + // An endpoint fault after a served sub-batch: recorded like any endpoint failure (round 3 S6), and the + // request stays on this endpoint (half served) with nothing more sent to it (nit a). + RecordFailure(ex); + served = null; + } + if (served is null) + { + if (offset == 0) return null; + failed = true; + continue; + } + + for (var k = 0; k < chunk.Length; k++) + { + var answer = served[k]; + foreach (var sample in answer.Samples) used += sample.Value.EstimatedRetainedBytes; + if (answer.ConsumerBudgetRefused) spent = true; + answers[offset + k] = answer; + } + offset += chunk.Length; } - for (var k = 0; k < chunk.Length; k++) - { - var item = request.Items[chunk[k]]; - var answer = served?[k] ?? new(item.CorrelationId, - left <= 0 ? BadTooManyOperations : item.Continuation is not null ? BadContinuationPointInvalid : BadNoCommunication, [], null); - foreach (var sample in answer.Samples) used += sample.Value.EstimatedRetainedBytes; - answers[offset + k] = answer; - } + return answers.Select(x => x!).ToArray(); + } + catch + { + Abandon(selected, answers); + throw; } - - return answers; } - /// Reads on one selected endpoint and assembles its chunks; null = the endpoint failed before answering (a fresh read may move). - private async Task ServeAsync(Selected selected, int endpoint, DataHistoryReadRequest request, + /// Disposes answers that will never be handed out and releases the new origin continuations they carry. + private void Abandon(Selected selected, IEnumerable answers) + { + foreach (var answer in answers) + { + if (answer is null) continue; + answer.Dispose(); + if (answer.Continuation is { } wrapped && TryUnwrap(wrapped, out _, out _, out var token)) _ = ReleaseOnEndpointAsync(selected, token); + } + } + + /// + /// Reads on one selected endpoint and assembles its chunks. Results null = the endpoint failed before answering (a fresh + /// read may move); EndpointFailed = it answered (per node) but failed on the way, so a caller splitting a + /// request sends it nothing more. Anything that escapes first releases every origin token this assembly holds — finished + /// nodes' continuations, chunk tokens, and the tokens of a response it rejected (H3 review round 3 S6). + /// + private async Task<(DataHistoryReadResult[]? Results, bool EndpointFailed)> ServeAsync(Selected selected, int endpoint, DataHistoryReadRequest request, DataHistoryReadItem[] items, int[] pending, long start, CancellationToken cancellationToken) { var batch = pending.Select(i => items[i]).ToArray(); @@ -187,6 +245,10 @@ public sealed partial class GrpcDataConnection : IDataHistoryService var current = batch; var map = Enumerable.Range(0, batch.Length).ToArray(); var first = true; + var endpointFailed = false; + var chunkTokensReleased = false; + W.HistoryReadResponse? unprocessed = null; // a received response whose tokens are not yet owned by final[] / current + IReadOnlyList? decoded = null; try { while (current.Length > 0) @@ -211,6 +273,7 @@ public sealed partial class GrpcDataConnection : IDataHistoryService { // A caller cancel is never an outcome: surface it as cancellation, and let go of held chunk tokens. if (!first) ReleaseChunkTokens(selected, current); + chunkTokensReleased = true; throw new OperationCanceledException("History read cancelled by the caller.", ex, cancellationToken); } catch (RpcException ex) when (ex.StatusCode is StatusCode.FailedPrecondition or StatusCode.Unimplemented) @@ -229,23 +292,22 @@ public sealed partial class GrpcDataConnection : IDataHistoryService } catch (RpcException ex) when (first && ex.StatusCode is StatusCode.Unavailable or StatusCode.Unauthenticated or StatusCode.PermissionDenied && !cancellationToken.IsCancellationRequested) - { RecordFailure(ex); return null; } + { RecordFailure(ex); chunkTokensReleased = true; return (null, true); } catch (RpcException ex) { RecordFailure(ex); if (!first) ReleaseChunkTokens(selected, current); // the origin still holds their remainders foreach (var k in map) final[k] ??= new(batch[k].CorrelationId, BadNoCommunication, [], null); + endpointFailed = true; break; } first = false; + unprocessed = response; Verify(response.Serving, selected); - var decoded = DataHistoryProtoMapper.DecodeResponse(response, Limits(request.Budget, selected.Capabilities) with + decoded = DataHistoryProtoMapper.DecodeResponse(response, Limits(request.Budget, selected.Capabilities) with { MaxValueElements = int.MaxValue, MaxBytes = _maxMessageBytes }); if (decoded.Count != current.Length || decoded.Where((r, k) => r.CorrelationId != current[k].CorrelationId).Any()) - { - foreach (var r in decoded) r.Dispose(); throw new InvalidOperationException("History response has unexpected items."); - } var nextItems = new List(); var nextMap = new List(); for (var k = 0; k < decoded.Count; k++) @@ -274,6 +336,7 @@ public sealed partial class GrpcDataConnection : IDataHistoryService } current = nextItems.ToArray(); map = nextMap.ToArray(); + unprocessed = null; decoded = null; // every token of this response is now in final[] or current } var answers = new DataHistoryReadResult[batch.Length]; for (var k = 0; k < batch.Length; k++) @@ -288,15 +351,23 @@ public sealed partial class GrpcDataConnection : IDataHistoryService } answers[k] = result with { Samples = (IReadOnlyList?)assembled[k] ?? [] }; } - return answers; + return (answers, endpointFailed); } catch { foreach (var list in assembled) foreach (var sample in list ?? []) sample.Dispose(); + foreach (var r in decoded ?? []) r.Dispose(); + // Nothing this assembly holds is handed out: release every origin token it owns (round 3 S6). + foreach (var r in final) + if (r?.Continuation is { } wrapped && TryUnwrap(wrapped, out _, out _, out var token)) _ = ReleaseOnEndpointAsync(selected, token); + if (!first && !chunkTokensReleased) ReleaseChunkTokens(selected, current); + foreach (var item in unprocessed?.Items ?? []) + if (item.HasContinuation) _ = ReleaseOnEndpointAsync(selected, item.Continuation.ToByteArray()); throw; } } + /// Releases continuations on their issuing endpoints (); best effort. public async Task ReleaseHistoryAsync(IReadOnlyList continuations, CancellationToken cancellationToken) { 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 987634c86..a68f634ee 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs @@ -389,7 +389,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl internal const int DefaultBatchItems = 100; /// An origin admits at most one item per this many bytes of a request's byte budget. - internal const long MinimumBytesPerItem = 256; + internal const long MinimumBytesPerItem = GrpcDataConnection.MinimumBytesPerItem; private static ProjectedHistoryOutcome Fail(uint status) => new(status, []); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs index 965d96590..de76e9f29 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs @@ -251,6 +251,106 @@ public sealed class GrpcDataHistoryClientTests foreach (var r in again) r.Dispose(); } + // ---- H3 review round 3 ------------------------------------------------------------------------------------------- + + private static readonly long SampleBytes = new DataHistorySample(DataValue.FromScalar(DataValueKind.Double, 1.0), 0, null, null) + .Value.EstimatedRetainedBytes; // the fake answers two Double samples per item per chunk + + private static DataHistoryReadRequest Many(int count, long? maxBytes = null) => new(Request().Details, + Enumerable.Range(0, count).Select(i => new DataHistoryReadItem("n" + i, View)).ToArray(), maxBytes is { } b ? Budget with { MaxBytes = b } : Budget); + + private static async Task AwaitReleased(Endpoint a, Func done) + { + var deadline = DateTime.UtcNow.AddSeconds(10); + while (DateTime.UtcNow < deadline) + { + byte[][] released; + lock (a.Released) released = a.Released.ToArray(); + if (done(released)) return; + await Task.Delay(20, TestContext.Current.CancellationToken); + } + } + + private static int ReleasedCount(Endpoint a, byte[] token) { lock (a.Released) return a.Released.Count(t => t.SequenceEqual(token)); } + + [Fact] + [Trait("Phase", "H3")] + public async Task A_cancel_in_a_later_sub_batch_releases_the_earlier_sub_batches_new_continuations() + { + // S1: sub-batch 1 answered (two new page continuations); the caller cancels during sub-batch 2 — nothing is stranded. + var a = new Endpoint("a") { BatchItems = 2, PageToken = [9, 9, 9], HangOnDataCall = 2 }; + await using var connection = Connect([a]); + using var cancel = new CancellationTokenSource(); + var read = connection.ReadHistoryAsync(Many(4), cancel.Token); + var deadline = DateTime.UtcNow.AddSeconds(10); + while (Volatile.Read(ref a.DataCalls) < 2 && DateTime.UtcNow < deadline) await Task.Delay(10, TestContext.Current.CancellationToken); + await cancel.CancelAsync(); + await Should.ThrowAsync(() => read); + await AwaitReleased(a, r => r.Count(t => t.SequenceEqual(new byte[] { 9, 9, 9 })) >= 2); + ReleasedCount(a, [9, 9, 9]).ShouldBe(2, "both continuations sub-batch 1 opened are released"); + } + + [Fact] + [Trait("Phase", "H3")] + public async Task A_later_sub_batch_is_trimmed_to_the_origins_byte_admission_and_the_rest_is_a_consumer_budget_refusal() + { + // S2: after sub-batch 1 only room for ONE item is left (256 B); sending two would break the origin's count <= MaxBytes/256 + // rule (an RpcException ⇒ a recorded endpoint failure). Trimmed: [2, 1], the rest refused unsent, no endpoint failure. + var a = new Endpoint("a") { BatchItems = 2, EnforceAdmission = true }; + await using var connection = Connect([a]); + var results = await connection.ReadHistoryAsync(Many(4, 4 * SampleBytes + 256), TestContext.Current.CancellationToken); + results.Take(2).ShouldAllBe(r => r.StatusCode == 0u && r.Samples.Count == 2); + results.Skip(2).ShouldAllBe(r => r.StatusCode == 0x80100000u && r.ConsumerBudgetRefused); + a.CallSizes.ShouldBe([2, 1]); + foreach (var r in results) r.Dispose(); + var again = await connection.ReadHistoryAsync(Many(1), TestContext.Current.CancellationToken); + again.Single().StatusCode.ShouldBe(0u, "a budget refusal is not an endpoint failure"); + foreach (var r in again) r.Dispose(); + } + + [Fact] + [Trait("Phase", "H3")] + public async Task A_sub_batch_whose_assembly_overflows_spends_the_budget_and_nothing_more_is_sent() + { + // S3: sub-batch 2 refuses n3 inside its own assembly while what was KEPT is still below the budget — n4, n5 unsent. + var a = new Endpoint("a") { BatchItems = 2 }; + await using var connection = Connect([a]); + var results = await connection.ReadHistoryAsync(Many(6, 7 * SampleBytes), TestContext.Current.CancellationToken); + results.Take(3).ShouldAllBe(r => r.StatusCode == 0u); + results.Skip(3).ShouldAllBe(r => r.StatusCode == 0x80100000u && r.ConsumerBudgetRefused); + a.CallSizes.ShouldBe([2, 2]); + foreach (var r in results) r.Dispose(); + } + + [Fact] + [Trait("Phase", "H3")] + public async Task After_a_sub_batch_endpoint_failure_nothing_more_is_sent_to_that_endpoint() + { + // Nit (a): sub-batch 2 fails (recorded); sub-batch 3 is answered unsent. + var a = new Endpoint("a") { BatchItems = 2, FailAfterFirst = Grpc.Core.StatusCode.Internal }; + await using var connection = Connect([a]); + var results = await connection.ReadHistoryAsync(Many(5), TestContext.Current.CancellationToken); + results.Take(2).ShouldAllBe(r => r.StatusCode == 0u); + results.Skip(2).ShouldAllBe(r => r.StatusCode == 0x80310000u); + a.CallSizes.ShouldBe([2, 2]); + foreach (var r in results) r.Dispose(); + } + + [Fact] + [Trait("Phase", "H3")] + public async Task A_rejected_follow_up_chunk_releases_every_token_the_assembly_holds() + { + // S6: n0 completes on call 1 (a new page continuation in final[]); n1 continues; call 2's answer is malformed. + var a = new Endpoint("a") { PageToken = [9, 9, 9], Chunks = 3, MalformedFromDataCall = 2 }; + a.ChunksByItem["n0"] = 1; + await using var connection = Connect([a]); + var results = await connection.ReadHistoryAsync(Many(2), TestContext.Current.CancellationToken); + results.ShouldAllBe(r => r.StatusCode == 0x80310000u); + await AwaitReleased(a, r => r.Any(t => t.SequenceEqual(new byte[] { 9, 9, 9 })) && r.Any(t => t.SequenceEqual(new byte[] { 7, 7 }))); + ReleasedCount(a, [9, 9, 9]).ShouldBe(1, "n0's finished continuation is released"); + ReleasedCount(a, [7, 7]).ShouldBeGreaterThan(0, "n1's chunk tokens are released"); + } + [Fact] public async Task A_failure_mid_assembly_releases_the_origin_chunk_tokens_it_holds() { @@ -262,9 +362,10 @@ public sealed class GrpcDataHistoryClientTests a.Released.ShouldContain(t => t.SequenceEqual(new byte[] { 7, 7 }), "the chunk token the failed follow-up carried is released"); } - private static GrpcDataConnection Connect(Endpoint[] endpoints, TimeSpan? historyTimeout = null) + private static GrpcDataConnection Connect(Endpoint[] endpoints, TimeSpan? historyTimeout = null, Action? onManager = null) { var manager = new DataConnectionManager("consumer", 1); + onManager?.Invoke(manager); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); var router = new Router(endpoints); return new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), endpoints.Select(e => new Uri($"https://{e.Name}.test")), @@ -294,6 +395,15 @@ public sealed class GrpcDataHistoryClientTests /// Fail every HistoryRead after the first with this status. public Grpc.Core.StatusCode? FailAfterFirst { get; set; } public int Chunks { get; init; } = 1; + /// Per correlation id chunk counts (overrides ). + public Dictionary ChunksByItem { get; } = new(); + /// Refuse a call carrying more than one item per 256 B of its byte budget (the origin's admission rule). + public bool EnforceAdmission { get; set; } + /// The data (non-release) HistoryRead call that never answers (honours the request's token). + public int? HangOnDataCall { get; set; } + /// From this data call on, answers carry unexpected correlation ids. + public int? MalformedFromDataCall { get; set; } + public int DataCalls; public byte[]? PageToken { get; init; } public int HistoryCalls; public List<(string Path, string? Features)> Headers { get; } = []; @@ -332,6 +442,10 @@ public sealed class GrpcDataHistoryClientTests var wire = W.HistoryReadRequest.Parser.ParseFrom(bytes.AsSpan(5).ToArray()); LastBudgetTimeout = TimeSpan.FromTicks(wire.Budget.TimeoutTicks); if (!wire.ReleaseContinuations) lock (CallSizes) CallSizes.Add(wire.Items.Count); + var dataCall = wire.ReleaseContinuations ? 0 : Interlocked.Increment(ref DataCalls); + if (EnforceAdmission && !wire.ReleaseContinuations && wire.Items.Count > wire.Budget.MaxBytes / 256) + return Status(Grpc.Core.StatusCode.InvalidArgument); + if (dataCall != 0 && dataCall == HangOnDataCall) await Task.Delay(Timeout.Infinite, token); var response = new W.HistoryReadResponse { Serving = DataProtoMapper.EncodeServing(Serving) }; if (!wire.ReleaseContinuations && call > 1 && FailAfterFirst is { } later) { @@ -340,7 +454,7 @@ public sealed class GrpcDataHistoryClientTests } if (wire.ReleaseContinuations) { - foreach (var item in wire.Items) Released.Add(item.Continuation.ToByteArray()); + lock (Released) foreach (var item in wire.Items) Released.Add(item.Continuation.ToByteArray()); foreach (var item in wire.Items) response.Items.Add(new W.HistoryReadResult { CorrelationId = item.CorrelationId }); } else @@ -350,12 +464,13 @@ public sealed class GrpcDataHistoryClientTests { var key = item.CorrelationId; int left; - lock (_chunkLeft) left = _chunkLeft[key] = item.HasContinuation && _chunkLeft.TryGetValue(key, out var l) && l > 0 ? l - 1 : Chunks - 1; + lock (_chunkLeft) left = _chunkLeft[key] = item.HasContinuation && _chunkLeft.TryGetValue(key, out var l) && l > 0 ? l - 1 + : (ChunksByItem.TryGetValue(key, out var c) ? c : Chunks) - 1; using var s1 = new DataHistorySample(DataValue.FromScalar(DataValueKind.Double, 1.0), 0, DateTimeOffset.UnixEpoch, null); using var s2 = new DataHistorySample(DataValue.FromScalar(DataValueKind.Double, 2.0), 0, null, null); var result = new DataHistoryReadResult(key, 0, [s1, s2], left > 0 ? [7, 7] : PageToken, null, left > 0); response.Items.Add(DataHistoryProtoMapper.EncodeResult(result)); - if (Malformed) response.Items[^1].CorrelationId = "not-" + key; + if (Malformed || dataCall >= MalformedFromDataCall) response.Items[^1].CorrelationId = "not-" + key; } } message = response; From 30d66fdc7cada1a3d51a0625f2a3bc3cbf569a17 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 07:11:06 -0500 Subject: [PATCH 22/25] =?UTF-8?q?fix(grpc-data):=20H3=20review=20round=203?= =?UTF-8?q?=20S5=20=E2=80=94=20a=20cancel=20by=20redeploy/shutdown=20is=20?= =?UTF-8?q?not=20a=20timeout?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GrpcDataConnection.ServeAsync mapped RpcException(Cancelled) without a caller cancel to BadTimeout even when the linked channel-retired / scope / shutdown token fired. That case is now BadNoCommunication (resumed: BadContinuationPointInvalid), releases held chunk tokens and stops a split request sending further sub-batches. ProjectedHistoryAccess's outer catch no longer reads any escaped OperationCanceledException as a timeout: only the caller's cancel or the deadline is BadTimeout, otherwise classified as FailCancelled does. Red on revert (client test: scope moved mid-call); the outer-catch change has no dedicated test (nothing reachable throws past ReadGroupAsync's own catch). --- .../GrpcDataConnection.History.cs | 17 +++++++++++++++-- .../DataConnections/ProjectedHistoryAccess.cs | 8 +++++--- .../GrpcDataHistoryClientTests.cs | 19 +++++++++++++++++++ 3 files changed, 39 insertions(+), 5 deletions(-) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs index 39d37782a..c61bfc20c 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs @@ -181,7 +181,7 @@ public sealed partial class GrpcDataConnection : IDataHistoryService var call = await ServeAsync(selected, endpoint, request with { Budget = request.Budget with { MaxBytes = left } }, items, chunk, start, cancellationToken).ConfigureAwait(false); served = call.Results; - failed = call.EndpointFailed; // answered, but the endpoint failed mid-way: send it nothing more (nit a) + failed = call.EndpointFailed; // answered, but the endpoint failed or retired mid-way: send it nothing more (nit a) } catch (Exception ex) when (offset > 0 && !cancellationToken.IsCancellationRequested && ex is InvalidOperationException or ArgumentException or RpcException or HttpRequestException) @@ -230,7 +230,7 @@ public sealed partial class GrpcDataConnection : IDataHistoryService /// /// Reads on one selected endpoint and assembles its chunks. Results null = the endpoint failed before answering (a fresh - /// read may move); EndpointFailed = it answered (per node) but failed on the way, so a caller splitting a + /// read may move); EndpointFailed = it answered (per node) but failed or retired on the way, so a caller splitting a /// request sends it nothing more. Anything that escapes first releases every origin token this assembly holds — finished /// nodes' continuations, chunk tokens, and the tokens of a response it rejected (H3 review round 3 S6). /// @@ -282,6 +282,16 @@ public sealed partial class GrpcDataConnection : IDataHistoryService foreach (var k in map) final[k] ??= new(batch[k].CorrelationId, BadHistoryOperationUnsupported, [], null); break; } + catch (Exception ex) when (!cancellationToken.IsCancellationRequested && Retiring(selected) + && ex is OperationCanceledException or RpcException { StatusCode: StatusCode.Cancelled }) + { + // Not the caller and not a deadline: the channel retired, the scope moved or the connection is shutting down + // (a redeploy). Not a timeout and not an endpoint fault (round 3 S5): the read cannot continue here. + if (!first) ReleaseChunkTokens(selected, current); + foreach (var k in map) final[k] ??= new(batch[k].CorrelationId, batch[k].Continuation is not null ? BadContinuationPointInvalid : BadNoCommunication, [], null); + endpointFailed = true; + break; + } catch (RpcException ex) when (ex.StatusCode is StatusCode.DeadlineExceeded or StatusCode.Cancelled && !cancellationToken.IsCancellationRequested) { // The call's own deadline, or the origin cancelling it at ITS unary timeout (the effective ceiling is @@ -367,6 +377,9 @@ public sealed partial class GrpcDataConnection : IDataHistoryService } } + /// The call was cancelled by the connection itself: its channel retired, its scope moved, or it is shutting down. + private bool Retiring(Selected selected) => + selected.Channel.Retired.IsCancellationRequested || _scope.CancellationToken.IsCancellationRequested || _shutdown.IsCancellationRequested; /// Releases continuations on their issuing endpoints (); best effort. public async Task ReleaseHistoryAsync(IReadOnlyList continuations, CancellationToken cancellationToken) 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 a68f634ee..d79634496 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs @@ -199,14 +199,16 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl } catch (Exception ex) when (ex is not OutOfMemoryException) { - // Last resort (H3 review D1): whatever escaped, fail per node — a timeout when the deadline fired — and release every + // Last resort (H3 review D1): whatever escaped, fail per node — a timeout only when the caller or the deadline + // cancelled; any other cancel (a retired lease) is classified as FailCancelled does (round 3 S5) — and release every // origin cursor this request still owns. Nothing escapes to the SDK override. - var timedOut = cancellationToken.IsCancellationRequested || Remaining() <= TimeSpan.Zero || ex is OperationCanceledException; + var timedOut = cancellationToken.IsCancellationRequested || Remaining() <= TimeSpan.Zero; for (var i = 0; i < nodes.Count; i++) { if (outcomes[i] is not null) continue; + var resumed = nodes[i].Resume is RemoteCursor; nodes[i].Resume?.ReleaseEvenIfClaimed(); - outcomes[i] = Fail(timedOut ? BadTimeout : BadNoCommunication); + outcomes[i] = Fail(timedOut ? BadTimeout : ex is OperationCanceledException && resumed ? BadContinuationPointInvalid : BadNoCommunication); } return outcomes.Select(o => o!).ToArray(); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs index de76e9f29..95be22d99 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs @@ -351,6 +351,25 @@ public sealed class GrpcDataHistoryClientTests ReleasedCount(a, [7, 7]).ShouldBeGreaterThan(0, "n1's chunk tokens are released"); } + [Fact] + [Trait("Phase", "H3")] + public async Task A_call_cancelled_by_a_scope_move_is_not_a_timeout() + { + // S5: neither the caller nor the deadline cancelled the call — the connection's scope moved (a redeploy). + DataConnectionManager? manager = null; + var a = new Endpoint("a") { HangOnDataCall = 1 }; + await using var connection = Connect([a], onManager: m => manager = m); + var request = new DataHistoryReadRequest(Request().Details, + [new("fresh", View), new("resumed", View, null, GrpcDataConnection.Wrap(0, "boot-a", [1, 2]))], Budget); + var read = connection.ReadHistoryAsync(request, TestContext.Current.CancellationToken); + var deadline = DateTime.UtcNow.AddSeconds(10); + while (Volatile.Read(ref a.DataCalls) < 1 && DateTime.UtcNow < deadline) await Task.Delay(10, TestContext.Current.CancellationToken); + manager!.ApplyScope(new Dictionary>()); + var results = await read; + results[0].StatusCode.ShouldBe(0x80310000u, "fresh: BadNoCommunication, not BadTimeout"); + results[1].StatusCode.ShouldBe(0x804A0000u, "resumed: BadContinuationPointInvalid"); + } + [Fact] public async Task A_failure_mid_assembly_releases_the_origin_chunk_tokens_it_holds() { From f1b23abcb42bc3cbdcff849edcc5850d7ff9ca4b Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 07:15:16 -0500 Subject: [PATCH 23/25] =?UTF-8?q?fix(grpc-data):=20H3=20review=20round=203?= =?UTF-8?q?=20nits=20b/c/d=20=E2=80=94=20no=20origin=20cursor=20stranded?= =?UTF-8?q?=20on=20Bad,=20scope=20moves=20or=20a=20serve-time=20throw?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - b: ProjectedHistoryAccess releases the prior origin cursor on any Bad answer to a resumed node (and on a mismatched answer) — an unsent refusal left it open at the origin; idempotent. - c: DataConnectionDeploymentLease, when its scope moves while a history answer is in flight, releases the dropped answer's new continuations (best effort); resumed items are BadContinuationPointInvalid, fresh ones BadNoCommunication. - d: ProjectedHistoryRead: a throw while serving outcome i (FromClr on an unconvertible value, a store fault) releases outcome i's cursor unless the store already owns it, and every later outcome's. Each red on revert (mutation). --- .../ProjectedHistoryRead.cs | 27 ++++++-- .../DataConnectionDeploymentRuntime.cs | 16 ++++- .../DataConnections/ProjectedHistoryAccess.cs | 4 ++ .../ProjectedHistoryReadTests.cs | 22 +++++++ .../GrpcDataDeployedHistoryLeaseTests.cs | 66 +++++++++++++++++++ .../GrpcDataProjectedHistoryWireTests.cs | 29 +++++++- 6 files changed, 157 insertions(+), 7 deletions(-) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeployedHistoryLeaseTests.cs diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs index d78d130b3..53ffdb3be 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs @@ -198,16 +198,34 @@ public sealed partial class OtOpcUaNodeManager return; } - for (var i = 0; i < pending.Count; i++) + var done = 0; // outcomes [0, done) are fully handed over (a continuation saved to the store, or released) + ProjectedHistoryContinuation? handedOver = null; // outcome `done`'s continuation once the store owns it (or released it) + try + { + for (var i = 0; i < pending.Count; i++) + { + handedOver = null; + ServeProjectedOutcome(pending[i].Handle, outcomes[i]); + done = i + 1; + } + } + catch + { + // H3 review round 3 nit (d): a throw for outcome i (FromClr on an unconvertible value, a store fault) strands no + // origin cursor: outcome i's — unless the store already owns it — and every later outcome's are released. + for (var j = done; j < outcomes.Count; j++) + if (outcomes[j].Continuation is { } c && !ReferenceEquals(c, handedOver)) c.Release(); + throw; + } + + void ServeProjectedOutcome(NodeHandle handle, ProjectedHistoryOutcome outcome) { - var handle = pending[i].Handle; - var outcome = outcomes[i]; var status = new StatusCode(outcome.StatusCode); if (StatusCode.IsBad(status)) { outcome.Continuation?.Release(); SetProjectedStatus(handle, results, errors, status); - continue; + return; } byte[]? cp = null; @@ -215,6 +233,7 @@ public sealed partial class OtOpcUaNodeManager { var key = MapKey(handle.NodeId); cp = SaveRemoteContinuation(session, store, key.Realm, key.Id, HistoryBindingTag(handle.NodeId), epoch, next); + handedOver = next; // saved (store-owned) or already released by SaveRemoteContinuation } var values = new List(outcome.Samples.Count); 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 42a3e3d6b..96cce8cf0 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs @@ -541,13 +541,25 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistor catch (Exception ex) when (ex is InvalidOperationException or UnauthorizedAccessException or OperationCanceledException && !cancellationToken.IsCancellationRequested) { + // The scope moved while the answer was in flight: the answer is dropped, so the new origin continuations it carries are + // released (best effort) rather than stranded until the origin's idle expiry (H3 review round 3 nit c). + var orphans = value.Select(x => x.Continuation).OfType().ToArray(); foreach (var item in value) item.Dispose(); - return Unavailable(request); // the scope moved while the answer was in flight + if (orphans.Length > 0) _ = ReleaseQuietlyAsync(history, orphans); + return Unavailable(request); } } + private static async Task ReleaseQuietlyAsync(IDataHistoryService history, byte[][] continuations) + { + try { await history.ReleaseAsync(continuations, CancellationToken.None).ConfigureAwait(false); } + catch (Exception ex) when (ex is not OutOfMemoryException) { } // best effort; the origin's idle expiry is the backstop + } + + /// A resumed item's token cannot be presented again: BadContinuationPointInvalid; a fresh one BadNoCommunication. private static DataHistoryReadResult[] Unavailable(DataHistoryReadRequest request) => request.Items - .Select(x => new DataHistoryReadResult(x.CorrelationId, GrpcDataConnection.BadNoCommunication, [], null)).ToArray(); + .Select(x => new DataHistoryReadResult(x.CorrelationId, + x.Continuation is not null ? GrpcDataConnection.BadContinuationPointInvalid : GrpcDataConnection.BadNoCommunication, [], null)).ToArray(); Task> IDataHistoryService.ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) => ReadHistoryAsync(request, cancellationToken); 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 d79634496..e2ca73cb9 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs @@ -302,6 +302,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl var answer = answers[k]; if (answer.CorrelationId != items[k].CorrelationId) { + (nodes[i].Resume as RemoteCursor)?.ReleaseOrigin(); outcomes[i] = Fail(BadNoCommunication); continue; // its token (if any) is released in the finally } @@ -326,6 +327,9 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl : null; outcomes[i] = new ProjectedHistoryOutcome(answer.StatusCode, samples, next); assigned[k] = true; + // Round 3 nit (b): a Bad answer to a resume may have left the prior origin cursor unconsumed (refused + // unsent, a failed call) — release it; idempotent, and a no-op at the origin when it was consumed. + if ((answer.StatusCode & 0x80000000u) != 0 && nodes[i].Resume is RemoteCursor resumedFrom) resumedFrom.ReleaseOrigin(); } } finally 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 93b276111..ac9afe89f 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 @@ -195,6 +195,25 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable access.Calls.ShouldBe(calls); } + [Fact] + [Trait("Phase", "H3")] + public async Task A_throw_while_serving_one_outcome_releases_every_later_outcomes_cursor() + { + // H3 review round 3 nit (d): outcome 0's value cannot cross the SDK boundary (FromClr throws) — outcome 1's origin cursor + // must not be stranded; outcome 0's is already the session store's (saved before the throw), so it is not released twice. + 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 { Paged = true, FirstValue = new object() }; + nm.ProjectedHistoryAccess = access; + try { Raw(nm, f.Identity, [a, b]); } + catch (ArgumentException) { } // the fault itself is the node manager's to surface; only the cursors matter here + access.Issued.Count.ShouldBe(2); + access.Issued[1].Released.ShouldBe(1, "the later outcome's cursor is released"); + access.Issued[0].Released.ShouldBe(0, "the store owns the saved cursor"); + } + [Fact] public void Unset_bounds_travel_absent_and_AtTime_carries_its_times() { @@ -442,6 +461,8 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable public bool Paged { get; init; } public uint Status { get; init; } public Func Answer { get; init; } = _ => [1.0, 2.0]; + /// When set, the FIRST node's first sample carries this value (e.g. one the SDK boundary cannot convert). + public object? FirstValue { get; init; } /// When set, every call waits on it (a projected read holding its slot). public TaskCompletionSource? Hold { get; set; } @@ -468,6 +489,7 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable Issued.Add(next); } var samples = Answer(node).Select((v, i) => new OriginHistorySample(v, 0, T0.AddSeconds(i), null)).ToArray(); + if (FirstValue is { } poison && ReferenceEquals(node, nodes[0]) && samples.Length > 0) samples[0] = samples[0] with { Value = poison }; return new ProjectedHistoryOutcome(Status, Status == 0 ? samples : [], next); }).ToArray()); } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeployedHistoryLeaseTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeployedHistoryLeaseTests.cs new file mode 100644 index 000000000..9bc3c8f0c --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeployedHistoryLeaseTests.cs @@ -0,0 +1,66 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// H3 review round 3 nit (c): the deployment lease drops a history answer when its scope moves while the answer is in flight — +/// the new origin continuations that answer carries are released (not stranded), and a resumed item is +/// BadContinuationPointInvalid (its token cannot be presented again), a fresh one BadNoCommunication. +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H3")] +public sealed class GrpcDataDeployedHistoryLeaseTests +{ + private static readonly DataView View = new(new("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "x"); + + [Fact] + public async Task A_scope_move_during_the_answer_releases_its_new_continuations() + { + var current = true; + var inner = new Inner { OnRead = () => current = false }; + var lease = new DataConnectionDeploymentLease(inner, CancellationToken.None, DataOperations.HistoryRead, TimeSpan.FromSeconds(5), + 16, 16, 1 << 20, 1, 1, 1 << 20, () => current, () => { }); + var request = new DataHistoryReadRequest(new DataHistoryRawDetails(null, DateTimeOffset.UnixEpoch.AddDays(1), 2, false), + [new("fresh", View), new("resumed", View, null, [1])], new DataBudget(TimeSpan.FromSeconds(5), 16, 1 << 20)); + var results = await lease.ReadHistoryAsync(request, TestContext.Current.CancellationToken); + results[0].StatusCode.ShouldBe(0x80310000u); + results[1].StatusCode.ShouldBe(0x804A0000u); + var deadline = DateTime.UtcNow.AddSeconds(5); + while (inner.ReleasedCount == 0 && DateTime.UtcNow < deadline) await Task.Delay(10, TestContext.Current.CancellationToken); + inner.Released.ShouldBe([[8], [9]], ignoreOrder: true); + } + + private sealed class Inner : IDataConnection, IDataHistoryService + { + public Action OnRead { get; init; } = () => { }; + private readonly List _released = []; + public int ReleasedCount { get { lock (_released) return _released.Count; } } + public byte[][] Released { get { lock (_released) return _released.ToArray(); } } + public DataTarget Target => new(DataTargetMode.Cluster, "c", null); + public TimeProvider Clock => TimeProvider.System; + + public Task> ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) + { + OnRead(); + byte k = 8; + return Task.FromResult>(request.Items + .Select(i => new DataHistoryReadResult(i.CorrelationId, 0, [], [k++])).ToArray()); + } + + public Task ReleaseAsync(IReadOnlyList continuations, CancellationToken cancellationToken) + { + lock (_released) _released.AddRange(continuations); + return Task.CompletedTask; + } + + public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task> ReadAsync(ReadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task SubscribeAsync(CancellationToken cancellationToken) => throw new NotSupportedException(); + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs index da07939cb..5589cd552 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs @@ -443,6 +443,30 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests }, localPermissions: 15, allowHistory: true, connectionSource: connections); } + [Fact(Timeout = 90000)] + [Trait("Phase", "H3")] + public async Task A_bad_answer_to_a_resume_releases_the_prior_origin_cursor() + { + // H3 review round 3 nit (b): the connection answered the resume Bad without sending it — the origin still holds page 1's + // cursor; the consumer releases it (positive control: the store returns to 0). + await using var originServer = await HistoryOrigin.StartAsync(7); + using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); + var connections = new HistorySwitchConnections(origin); + ProjectedHistoryAccess? history = null; + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var page = await RawHistory(client, anchor, 2, default); + origin.Services.HistoryOpenContinuations.ShouldBe(1); + connections.Mode = HistoryMode.RefuseResumedUnsent; + (await RawHistory(client, anchor, 2, page.ContinuationPoint)).StatusCode.Code.ShouldBe(StatusCodes.BadNoCommunication.Code); + await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0); + origin.Services.HistoryOpenContinuations.ShouldBe(0, "the unconsumed prior cursor was released"); + connections.Mode = HistoryMode.Pass; + }, localPermissions: 15, allowHistory: true, connectionSource: connections, onHistory: (h, _) => history = h); + } + [Fact(Timeout = 90000)] [Trait("Phase", "H3")] public async Task An_origins_budget_refusal_is_a_per_node_answer_and_never_stops_the_request() @@ -509,7 +533,7 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests } } - public enum HistoryMode { Pass, Hang, Throw, Retired, Poison, BudgetRefused, OriginRefusedFresh } + public enum HistoryMode { Pass, Hang, Throw, Retired, Poison, BudgetRefused, OriginRefusedFresh, RefuseResumedUnsent } /// /// One long-lived origin connection whose HISTORY path can be switched to never answer (then fault as a cancelled gRPC call, @@ -578,6 +602,9 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests case HistoryMode.BudgetRefused: return request.Items.Select(i => new DataHistoryReadResult(i.CorrelationId, 0x80100000u, [], null, "History assembly budget exceeded.") { ConsumerBudgetRefused = true }).ToArray(); + case HistoryMode.RefuseResumedUnsent when request.Items.Any(i => i.Continuation is not null): + // Answered Bad without the origin ever seeing the resume: its cursor is still open there. + return request.Items.Select(i => new DataHistoryReadResult(i.CorrelationId, 0x80310000u, [], null)).ToArray(); case HistoryMode.OriginRefusedFresh when request.Items.All(i => i.Continuation is null): // The ORIGIN's own refusal, whose text also mentions a budget (LocalDataServices.History). return request.Items.Select(i => new DataHistoryReadResult(i.CorrelationId, 0x80100000u, [], null, From 713cbfb2122d50f16151eae5731c9c60b7690881 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 07:30:30 -0500 Subject: [PATCH 24/25] =?UTF-8?q?docs(grpc-data):=20H3=20evidence=20?= =?UTF-8?q?=E2=80=94=20review=20round=203=20fixes=20and=20gates?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/plans/evidence/grpc-data-ext/H3.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/docs/plans/evidence/grpc-data-ext/H3.md b/docs/plans/evidence/grpc-data-ext/H3.md index 08bec4998..f1954802c 100644 --- a/docs/plans/evidence/grpc-data-ext/H3.md +++ b/docs/plans/evidence/grpc-data-ext/H3.md @@ -141,6 +141,27 @@ authority lapses with its 15 s `MetadataLeaseMilliseconds`; any read after that HistoryRead (reproduced in the Runtime harness) — and a re-browse served from the still-cached browse page does not renew it (live: the H06 rebuild leg denied right after a re-browse). The gate now starts each held leg right after a deploy + re-browse. +## Review round 3 (approve-with-changes) — fixes + +Review of `37cbeff48` + `7aaa98751`. Every finding verified before fixing; none skipped. Red/green by reverting the fix (mutation) +and re-running its test, unless noted. Commits `34e72de3d` (S4), `9c2d6273a` (S1/S2/S3/S6/a), `30d66fdc7` (S5), `f1b23abcb` (b/c/d). + +| # | Finding | Resolution | Red/green | +|---|---|---|---| +| S1 | `ServeSplitAsync`: an escape (caller cancel, fault) in sub-batch k>0 stranded earlier sub-batches' answers (continuations never released, samples never disposed) | any escape disposes the collected answers and releases their new continuations on the endpoint (`Abandon`) | client test: cancel during sub-batch 2 ⇒ both sub-batch-1 page tokens released — red on revert | +| S2 | later sub-batches sent with `MaxBytes = left` could break the origin's `count <= MaxBytes/256` admission ⇒ RpcException ⇒ `RecordFailure` + `BadNoCommunication`, claimed cursors lost | each sub-batch trimmed to `left / MinimumBytesPerItem` (shared constant 256); the rest `BadTooManyOperations` with `ConsumerBudgetRefused`, unsent; an unsent resumed item's origin token released (still live there) | client test, fake origin enforcing the rule: `[2, 1]`, rest consumer-refused, next read Good (no backoff) — red on revert (`[2, 2]`, `BadNoCommunication`) | +| S3 | an assembly overflow inside a sub-batch left `used` below `MaxBytes`, so further sub-batches were still sent | any consumer budget refusal latches `spent`; the rest answered unsent | client test: calls `[2, 2]` (was `[2, 2, 1, 1]`) — red on revert | +| S4 | budget stop keyed on `Diagnostic.Contains("budget")`, which matched the ORIGIN's "remainder budget is full" and refused later nodes, incl. Good ones | internal `DataHistoryReadResult.ConsumerBudgetRefused` (never on the wire), set only by the connection's own assembly / split refusal; `ProjectedHistoryAccess` keys on it | wire test: origin refuses A ⇒ B still read (two runs sent) — red on revert | +| S5 | `RpcException(Cancelled)` without a caller cancel ⇒ `BadTimeout` even when the channel-retired / scope / shutdown token fired; the access's outer catch read any escaped OCE as a timeout | that case ⇒ `BadNoCommunication` (resumed `BadContinuationPointInvalid`), chunk tokens released, no further sub-batches; outer catch: `BadTimeout` only for the caller's cancel or the deadline, else `FailCancelled` classification | client test: scope moved mid-call ⇒ fresh `BadNoCommunication`, resumed `BadContinuationPointInvalid` — red on revert. Outer catch: no dedicated test (nothing reachable throws past `ReadGroupAsync`'s own catch) | +| S6 | a Verify failure / item mismatch on a follow-up chunk released nothing but samples; `ServeSplitAsync` swallowed later sub-batch faults silently | the assembly's catch releases finished nodes' continuations (`final[]`), held chunk tokens and the rejected response's tokens; a later sub-batch's endpoint fault is `RecordFailure`d | client test: n0 done on call 1, call 2 malformed ⇒ n0's page token and n1's chunk token released — red on revert | +| a | after a sub-batch endpoint failure further sub-batches were still sent | `ServeAsync` reports `EndpointFailed`; nothing more is sent, rest `BadNoCommunication` / resumed `BadContinuationPointInvalid` | client test: calls `[2, 2]` (was `[2, 2, 1]`) — red on revert | +| b | a Bad answer to a resumed node left the prior origin cursor open (refused unsent) | `ReleaseOrigin()` on the prior cursor for any Bad answer (and a mismatched one); idempotent | wire test: resume answered Bad unsent ⇒ origin open continuations 1 ⇒ 0 — red on revert | +| c | lease dropped an in-flight answer on a scope move without releasing its new continuations; resumed items `BadNoCommunication` | dropped answers' continuations released (best effort); resumed `BadContinuationPointInvalid` | `GrpcDataDeployedHistoryLeaseTests` — red on revert | +| d | a throw from `SaveRemoteContinuation` / `FromClr` for outcome i stranded outcomes i+1.. | the loop's catch releases outcome i's cursor unless the store owns it, and every later outcome's | `ProjectedHistoryReadTests` (unconvertible value on outcome 0 ⇒ outcome 1's cursor released once, outcome 0's left to the store) — red on revert | + +**Gates after round 3** (HEAD `f1b23abcb`): build 0/0; `run-unit-phase.py` H3, H2, H1, X0 passed (H3 107 + 144); OI `Feature=GrpcData` ++ history 87 passed (2 AVEVA skips); OpcUaServer 1419 (+1 skip), Runtime 1903 (+3 skips) (`Category!=E2E&Category!=LiveIntegration`); no `GrpcDataConfiguredDiscoveryWireTests` (#920) flake this run. Live rig not re-run in this round. + ## Not verified / substitutions - **H05**: the rig builds no pinned v1 image, so "v1 origin" is substituted by an origin that does not advertise history for the From 0afef2694180530c4003a0348db6f99e23b211d8 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 07:48:03 -0500 Subject: [PATCH 25/25] =?UTF-8?q?docs(grpc-data):=20H3=20evidence=20?= =?UTF-8?q?=E2=80=94=20live=20H01-H06=20re-runs=20after=20review=20rounds?= =?UTF-8?q?=202=20and=203?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/plans/evidence/grpc-data-ext/H3.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/plans/evidence/grpc-data-ext/H3.md b/docs/plans/evidence/grpc-data-ext/H3.md index f1954802c..f27bfbe42 100644 --- a/docs/plans/evidence/grpc-data-ext/H3.md +++ b/docs/plans/evidence/grpc-data-ext/H3.md @@ -160,7 +160,14 @@ and re-running its test, unless noted. Commits `34e72de3d` (S4), `9c2d6273a` (S1 | d | a throw from `SaveRemoteContinuation` / `FromClr` for outcome i stranded outcomes i+1.. | the loop's catch releases outcome i's cursor unless the store owns it, and every later outcome's | `ProjectedHistoryReadTests` (unconvertible value on outcome 0 ⇒ outcome 1's cursor released once, outcome 0's left to the store) — red on revert | **Gates after round 3** (HEAD `f1b23abcb`): build 0/0; `run-unit-phase.py` H3, H2, H1, X0 passed (H3 107 + 144); OI `Feature=GrpcData` -+ history 87 passed (2 AVEVA skips); OpcUaServer 1419 (+1 skip), Runtime 1903 (+3 skips) (`Category!=E2E&Category!=LiveIntegration`); no `GrpcDataConfiguredDiscoveryWireTests` (#920) flake this run. Live rig not re-run in this round. ++ history 87 passed (2 AVEVA skips); OpcUaServer 1419 (+1 skip), Runtime 1903 (+3 skips) (`Category!=E2E&Category!=LiveIntegration`); no `GrpcDataConfiguredDiscoveryWireTests` (#920) flake this run. + +**Live re-run after round 2** (`h3r5-sqlserver`, `h3r5-questdb` at `7aaa98751`) and **after round 3** (`h3r6-sqlserver`, +`h3r6-questdb` at `713cbfb21`, 2026-11-24, fresh rig per run, normal build checks): H01–H06 **all PASS on both backends, both +rounds** (H01 47, H02 34, H03 35, H04 71, H05 58, H06 238 assertions); `down` ⇒ 0 run containers left. (A first `h3r4-sqlserver` +attempt failed in `seed` after an interrupted earlier seed on the same run; torn down and replaced by `h3r5`.) + +Round 3 was itself an independent (Fable) verification of the round-2 commits — approve-with-changes, every finding above fixed. ## Not verified / substitutions