From 100dd5ca44e4c3b63b798718313896a1088422dc Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Mon, 23 Nov 2026 20:09:01 -0500 Subject: [PATCH] fix(grpc-data): H1 peer takes consume before verifying, scopes snapshot the incarnation per request, wiring faults are BadInternalError (verification 1-3, 7b) - a take computes its expectation only after consuming the record, so a throwing incarnation source cannot leave a token replayable; - a PeerHistoryContinuationScope is per request and reads the serving incarnation once, so a request straddling a failover binds its next token to the incarnation it started under (Save never answers null); - a non-owner principal or a blank/throwing incarnation source raises PeerHistoryContinuationWiringException, answered BadInternalError (not BadHistoryOperationUnsupported); plan H2 note added; - ConnectionIncarnation documented as identity only. --- ...pc-data-connections-history-alarms-plan.md | 7 +- .../OtOpcUaNodeManager.cs | 2 + .../PeerHistoryContinuationStore.cs | 94 ++++++++++++++++--- .../HistoryReadPortParityTests.cs | 30 +++--- .../PeerHistoryContinuationStoreTests.cs | 69 +++++++++++++- 5 files changed, 170 insertions(+), 32 deletions(-) diff --git a/docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md b/docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md index 314bef00a..981550ae8 100644 --- a/docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md +++ b/docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md @@ -1087,8 +1087,11 @@ settle windows are calibrated at the A1 exit (L4), before `state_known` ships. - origin over the H1 port (H1 review notes): `ReadHistory` is synchronous (it block-bridges like the SDK overrides), so run it off the RPC thread; it and `PeerHistoryContinuationStore`/`Scope` are `internal` to OpcUaServer, so add `InternalsVisibleTo` for the serving project or a public facade implementing `IDataHistoryService`; one store per - (principal, connection incarnation), `Clear()`ed on connection close; the scope's serving incarnation comes from the - connection (read live, so an in-process failover invalidates tokens); items carry a view `BindingTag` (mapping id/kind); + (principal, connection incarnation), `Clear()`ed on connection close; ONE `PeerHistoryContinuationScope` per RPC — it + snapshots the serving incarnation (from the connection) at first use, so a later request after an in-process failover + is refused and a request straddling one binds its next token to the incarnation it started under; a miswired scope + (non-owner principal, blank/throwing incarnation source) raises `PeerHistoryContinuationWiringException`, which the + port answers `BadInternalError` — H2 must surface it distinctly (a server fault, never "unsupported" or "denied"); items carry a view `BindingTag` (mapping id/kind); Processed/AtTime chunking and the consumer's assembly budget live in the transport, not the port; history capabilities are an additive H2 capabilities field. - Files: proto/mapper, `Host/Grpc/DataConnectionGrpcService.cs`, diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index b2849e66c..4616d6e2a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -10708,6 +10708,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage /// Transport failures are retryable; unsupported operations retain their distinct status. private static StatusCode HistoryReadFailureStatus(Exception error) { + // A miswired peer continuation scope (H1/H2) is a server fault, never "this node has no history". + if (error is PeerHistoryContinuationWiringException) return StatusCodes.BadInternalError; for (Exception? ex = error; ex is not null; ex = ex.InnerException) if (ex is System.IO.IOException or System.Net.Sockets.SocketException or System.Net.Http.HttpRequestException or TimeoutException) return StatusCodes.BadNoCommunication; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/PeerHistoryContinuationStore.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/PeerHistoryContinuationStore.cs index 8b09a7714..74d0aff4b 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/PeerHistoryContinuationStore.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/PeerHistoryContinuationStore.cs @@ -78,7 +78,11 @@ internal sealed class PeerHistoryContinuationStore /// The principal this instance serves. public string Principal { get; } - /// The connection's incarnation (which connection this store belongs to). + /// + /// The connection's incarnation — IDENTITY ONLY (which connection this store belongs to, for diagnostics and H2's + /// per-connection bookkeeping). It is never part of a binding: the serving incarnation a cursor binds is supplied per + /// request by . + /// public string ConnectionIncarnation { get; } /// The most live records. @@ -111,16 +115,18 @@ internal sealed class PeerHistoryContinuationStore /// The serving incarnation current at save. /// The request's details hash. /// The 16-byte token. - /// An unbound state, or a principal other than the owner. + /// An unbound state. + /// A principal other than the owner, or a blank incarnation. public byte[] Save(HistoryContinuationState state, string principal, string servingIncarnation, string detailsHash) { ArgumentNullException.ThrowIfNull(state); - ArgumentException.ThrowIfNullOrWhiteSpace(servingIncarnation); ArgumentNullException.ThrowIfNull(detailsHash); if (state.BoundIdentifier is null) throw new ArgumentException("A peer continuation must be bound to its view.", nameof(state)); + if (string.IsNullOrWhiteSpace(servingIncarnation)) + throw new PeerHistoryContinuationWiringException("A peer continuation needs the serving incarnation it is issued under."); if (!string.Equals(principal, Principal, StringComparison.Ordinal)) - throw new ArgumentException("A peer continuation store holds only its owning principal's cursors.", nameof(principal)); + throw new PeerHistoryContinuationWiringException("A peer continuation store holds only its owning principal's cursors."); var token = RandomNumberGenerator.GetBytes(TokenLength); var key = new PeerHistoryContinuationKey( @@ -144,16 +150,38 @@ internal sealed class PeerHistoryContinuationStore /// The token the peer handed back. /// What the resume must match. /// The state, or null (unknown, expired, evicted, malformed or mismatched). - public HistoryContinuationState? TryTake(byte[]? token, PeerHistoryContinuationKey expected) + public HistoryContinuationState? TryTake(byte[]? token, PeerHistoryContinuationKey expected) => + TryTake(token, () => expected); + + /// + /// with the expectation computed only AFTER the record is + /// consumed: if throws (the incarnation source is down), the token is already gone and the + /// take is a miss — never a token left replayable. + /// + /// The token the peer handed back. + /// Computes what the resume must match. + /// The state, or null. + public HistoryContinuationState? TryTake(byte[]? token, Func expected) { + ArgumentNullException.ThrowIfNull(expected); if (token is not { Length: TokenLength }) return null; + Entry taken; lock (_gate) { var now = _clock.GetTimestamp(); Sweep(now); if (!_entries.TryGetValue(new Guid(token), out var node)) return null; Remove(node); - return node.Value.Key == expected ? node.Value.State : null; + taken = node.Value; + } + + try + { + return taken.Key == expected() ? taken.State : null; + } + catch (Exception) + { + return null; // consumed, unverifiable ⇒ a miss (BadContinuationPointInvalid at the port) } } @@ -196,11 +224,32 @@ internal sealed class PeerHistoryContinuationStore } /// -/// The port's continuation scope for one remote peer: saves and takes through that peer's -/// , binding the caller's principal, the serving incarnation CURRENT at the -/// save and at the take (read live from , so an in-process failover or role -/// change on a still-open connection invalidates its tokens), and the request's details hash, on top of the view and -/// epoch the port itself re-checks. +/// A peer continuation store or scope was wired wrongly — a scope for a principal the store does not belong to, or a +/// serving-incarnation source that is blank or throws. A server fault, not a property of the request: the port answers +/// BadInternalError for the node (never BadHistoryOperationUnsupported), and H2 must surface it distinctly. +/// +internal sealed class PeerHistoryContinuationWiringException : InvalidOperationException +{ + /// Creates the exception. + /// What is miswired. + /// The incarnation source's own failure, if any. + public PeerHistoryContinuationWiringException(string message, Exception? inner = null) : base(message, inner) { } +} + +/// +/// The port's continuation scope for one remote peer's ONE request (create a new scope per ReadHistory call): +/// saves and takes through that peer's , binding the caller's principal, the +/// request's details hash and the serving incarnation, on top of the view and epoch the port itself re-checks. +/// +/// The serving incarnation is read from ONCE, at the scope's first use, +/// and that snapshot is used for every take and save of the request: a request resumed under incarnation A binds its +/// next token to A even when a failover lands mid-request (the resume under B then fails +/// BadContinuationPointInvalid), and a later request reads the then-current incarnation, so an in-process +/// failover or role change on a still-open connection invalidates the connection's tokens. A take whose snapshot +/// cannot be read (blank / throwing source) is a miss with the token consumed; a save is a +/// . Save never answers null (that would read as a +/// complete read and truncate). +/// /// /// The (principal, connection) store. /// The caller's authenticated principal. @@ -208,13 +257,30 @@ internal sealed class PeerHistoryContinuationStore internal sealed class PeerHistoryContinuationScope( PeerHistoryContinuationStore store, string principal, Func currentServingIncarnation) : IHistoryContinuationScope { + private readonly Lazy _incarnation = new(() => + { + string value; + try + { + value = currentServingIncarnation(); + } + catch (Exception ex) + { + throw new PeerHistoryContinuationWiringException("The serving-incarnation source failed.", ex); + } + + return string.IsNullOrWhiteSpace(value) + ? throw new PeerHistoryContinuationWiringException("The serving-incarnation source answered a blank incarnation.") + : value; + }, LazyThreadSafetyMode.ExecutionAndPublication); + /// public byte[]? Save(HistoryContinuationState state, HistoryContinuationBinding binding) => - store.Save(state, principal, currentServingIncarnation(), binding.Details?.ComputeDetailsHash() ?? string.Empty); + store.Save(state, principal, _incarnation.Value, binding.Details?.ComputeDetailsHash() ?? string.Empty); /// public HistoryContinuationState? TryTake(byte[] continuationPoint, HistoryContinuationBinding binding) => - store.TryTake(continuationPoint, new PeerHistoryContinuationKey( - principal, currentServingIncarnation(), binding.Epoch, binding.Realm, binding.Identifier, binding.Tag, + store.TryTake(continuationPoint, () => new PeerHistoryContinuationKey( + principal, _incarnation.Value, binding.Epoch, binding.Realm, binding.Identifier, binding.Tag, binding.Details?.ComputeDetailsHash() ?? string.Empty)); } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/HistoryReadPortParityTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/HistoryReadPortParityTests.cs index 4d76be191..667b48bda 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/HistoryReadPortParityTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/HistoryReadPortParityTests.cs @@ -386,18 +386,19 @@ public sealed class HistoryReadPortParityTests(HistoryReadPortServerFixture fx) var details = new HistoryReadRawVariant(T(0), T(100), 2, ReturnBounds: false); var store = new PeerHistoryContinuationStore("svc-consumer", "conn-1", capacity: 4); var incarnation = "inc-1"; - var peer = new PeerHistoryContinuationScope(store, "svc-consumer", () => incarnation); + // One scope per request (it snapshots the serving incarnation at first use), as H2 creates per RPC. + IHistoryContinuationScope Peer() => new PeerHistoryContinuationScope(store, "svc-consumer", () => incarnation); HistoryReadNodeOutcome Read(IHistoryContinuationScope scope, HistoryReadVariant d, byte[]? cp) => fx.Nm.ReadHistory(d, [new HistoryReadPortItem(realm, id, cp)], scope, CancellationToken.None)[0]; - string DrainWith(IHistoryContinuationScope scope) + string DrainWith(Func scope) { var parts = new List(); byte[]? cp = null; do { - var o = Read(scope, details, cp); + var o = Read(scope(), details, cp); o.Status.Code.ShouldBe(StatusCodes.Good.Code); parts.AddRange(o.Values.Select(Render)); cp = o.ContinuationPoint; @@ -406,27 +407,32 @@ public sealed class HistoryReadPortParityTests(HistoryReadPortServerFixture fx) return string.Join(" | ", parts); } - DrainWith(peer).ShouldBe(DrainWith(fx.Nm.SessionHistoryContinuationScope(session: null))); + DrainWith(Peer).ShouldBe(DrainWith(() => fx.Nm.SessionHistoryContinuationScope(session: null))); store.Count.ShouldBe(0, "every page's token was taken"); // A resume under other details, by another incarnation, or after an epoch bump is refused. - var cp1 = Read(peer, details, null).ContinuationPoint!; - Read(peer, details with { NumValuesPerNode = 3 }, cp1).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); + var cp1 = Read(Peer(), details, null).ContinuationPoint!; + Read(Peer(), details with { NumValuesPerNode = 3 }, cp1).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); // A serving-incarnation change on the SAME live connection (in-process failover) is a key mismatch in one store. - var cp2 = Read(peer, details, null).ContinuationPoint!; + var cp2 = Read(Peer(), details, null).ContinuationPoint!; incarnation = "inc-2"; - Read(peer, details, cp2).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); + Read(Peer(), details, cp2).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); // Another principal's scope over the store cannot resume the owner's cursor. - var cpOther = Read(peer, details, null).ContinuationPoint!; + var cpOther = Read(Peer(), details, null).ContinuationPoint!; var intruder = new PeerHistoryContinuationScope(store, "someone-else", () => incarnation); Read(intruder, details, cpOther).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); - var cp3 = Read(peer, details, null).ContinuationPoint!; + var cp3 = Read(Peer(), details, null).ContinuationPoint!; fx.Add("victim2", "port/victim-" + Guid.NewGuid().ToString("N"), "Double", AddressSpaceRealm.Uns); fx.Nm.RemoveVariableNode(fx.Nodes["victim2"].Id, AddressSpaceRealm.Uns).ShouldBeTrue(); - Read(peer, details, cp3).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); + Read(Peer(), details, cp3).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); // The take was single-use: the same token again is still a miss, and nothing is left behind. - Read(peer, details, cp1).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); + Read(Peer(), details, cp1).Status.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code); store.Count.ShouldBe(0, "every presented token was consumed, matched or not"); + + // A wiring fault (a scope for a principal the store does not belong to) is its own status, never "unsupported". + var miswired = Read(new PeerHistoryContinuationScope(store, "someone-else", () => incarnation), details, null); + miswired.Status.Code.ShouldBe(StatusCodes.BadInternalError.Code); + miswired.Error!.StatusCode.Code.ShouldBe(StatusCodes.BadInternalError.Code); await Task.CompletedTask; }); } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/PeerHistoryContinuationStoreTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/PeerHistoryContinuationStoreTests.cs index e9127b8e2..1c1da0b68 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/PeerHistoryContinuationStoreTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/PeerHistoryContinuationStoreTests.cs @@ -237,10 +237,13 @@ public sealed class PeerHistoryContinuationStoreTests var token = scope.Save(State(), binding)!; incarnation = "inc-2"; - scope.TryTake(token, binding).ShouldBeNull("issued under inc-1, resumed under inc-2"); + // A scope is per request: the resume is a NEW request, so it reads inc-2. + var resume = new PeerHistoryContinuationScope(store, Principal, () => incarnation); + resume.TryTake(token, binding).ShouldBeNull("issued under inc-1, resumed under inc-2"); - token = scope.Save(State(), binding)!; - scope.TryTake(token, binding).ShouldNotBeNull("issued and resumed under inc-2"); + token = new PeerHistoryContinuationScope(store, Principal, () => incarnation).Save(State(), binding)!; + new PeerHistoryContinuationScope(store, Principal, () => incarnation).TryTake(token, binding) + .ShouldNotBeNull("issued and resumed under inc-2"); } [Fact] @@ -251,12 +254,70 @@ public sealed class PeerHistoryContinuationStoreTests var other = new PeerHistoryContinuationScope(store, "someone-else", () => Incarnation); var binding = new HistoryContinuationBinding(AddressSpaceRealm.Raw, "Plant/dev/t1", 3, null, Tag: "view-1"); - Should.Throw(() => other.Save(State(), binding), "a store never holds another principal's cursor"); + Should.Throw(() => other.Save(State(), binding), "a store never holds another principal's cursor"); var token = owner.Save(State(), binding)!; other.TryTake(token, binding).ShouldBeNull(); owner.TryTake(token, binding).ShouldBeNull("the foreign take consumed it"); } + [Fact] + public void A_take_whose_expectation_throws_still_consumes_the_token() + { + var store = Store(); + var token = store.Save(State(), Principal, Incarnation, Hash); + store.TryTake(token, () => throw new InvalidOperationException("incarnation source down")).ShouldBeNull(); + store.Count.ShouldBe(0); + store.TryTake(token, Key()).ShouldBeNull("the token is gone"); + } + + [Fact] + public void A_scope_whose_incarnation_source_throws_or_is_blank_takes_nothing_and_fails_wiring_on_save() + { + var binding = new HistoryContinuationBinding(AddressSpaceRealm.Raw, "Plant/dev/t1", 3, null, Tag: "view-1"); + foreach (var (name, source) in new (string, Func)[] + { + ("throws", () => throw new InvalidOperationException("incarnation source down")), + ("blank", () => " "), + }) + { + var store = Store(); + var token = store.Save(State(), Principal, Incarnation, Hash); + var broken = new PeerHistoryContinuationScope(store, Principal, source); + broken.TryTake(token, binding).ShouldBeNull(name); + store.Count.ShouldBe(0, $"{name}: the take consumed the token"); + Should.Throw( + () => new PeerHistoryContinuationScope(store, Principal, source).Save(State(), binding), name); + } + } + + [Fact] + public void Wiring_errors_have_their_own_exception_type() + { + var store = Store(); + Should.Throw(() => store.Save(State(), "someone-else", Incarnation, Hash)); + Should.Throw(() => store.Save(State(), Principal, "", Hash)); + } + + [Fact] + public void A_request_that_straddles_an_incarnation_change_binds_the_incarnation_it_started_under() + { + // One scope per request: the incarnation is snapshotted at its first use, so a failover that lands between the + // request's take and its save cannot re-bind the next token to the NEW incarnation. + var store = Store(); + var incarnation = Incarnation; + var binding = new HistoryContinuationBinding(AddressSpaceRealm.Raw, "Plant/dev/t1", 3, null, Tag: "view-1"); + var first = new PeerHistoryContinuationScope(store, Principal, () => incarnation).Save(State(), binding)!; + + var request = new PeerHistoryContinuationScope(store, Principal, () => incarnation); + request.TryTake(first, binding).ShouldNotBeNull(); + incarnation = "inc-2"; // failover mid-request + var next = request.Save(State(), binding); + next.ShouldNotBeNull("a save never answers null (that would read as a complete read)"); + + new PeerHistoryContinuationScope(store, Principal, () => incarnation).TryTake(next!, binding) + .ShouldBeNull("the next token is bound to inc-1, so the resume under inc-2 is refused"); + } + [Fact] public void The_details_hash_is_culture_invariant() {