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.
This commit is contained in:
Joseph Doherty
2026-11-23 20:09:01 -05:00
parent 6c70c93c62
commit 100dd5ca44
5 changed files with 170 additions and 32 deletions
@@ -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`,
@@ -10708,6 +10708,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
/// <summary>Transport failures are retryable; unsupported operations retain their distinct status.</summary>
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;
@@ -78,7 +78,11 @@ internal sealed class PeerHistoryContinuationStore
/// <summary>The principal this instance serves.</summary>
public string Principal { get; }
/// <summary>The connection's incarnation (which connection this store belongs to).</summary>
/// <summary>
/// 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 <see cref="PeerHistoryContinuationScope"/>.
/// </summary>
public string ConnectionIncarnation { get; }
/// <summary>The most live records.</summary>
@@ -111,16 +115,18 @@ internal sealed class PeerHistoryContinuationStore
/// <param name="servingIncarnation">The serving incarnation current at save.</param>
/// <param name="detailsHash">The request's details hash.</param>
/// <returns>The 16-byte token.</returns>
/// <exception cref="ArgumentException">An unbound state, or a principal other than the owner.</exception>
/// <exception cref="ArgumentException">An unbound state.</exception>
/// <exception cref="PeerHistoryContinuationWiringException">A principal other than the owner, or a blank incarnation.</exception>
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
/// <param name="token">The token the peer handed back.</param>
/// <param name="expected">What the resume must match.</param>
/// <returns>The state, or null (unknown, expired, evicted, malformed or mismatched).</returns>
public HistoryContinuationState? TryTake(byte[]? token, PeerHistoryContinuationKey expected)
public HistoryContinuationState? TryTake(byte[]? token, PeerHistoryContinuationKey expected) =>
TryTake(token, () => expected);
/// <summary>
/// <see cref="TryTake(byte[], PeerHistoryContinuationKey)"/> with the expectation computed only AFTER the record is
/// consumed: if <paramref name="expected"/> throws (the incarnation source is down), the token is already gone and the
/// take is a miss — never a token left replayable.
/// </summary>
/// <param name="token">The token the peer handed back.</param>
/// <param name="expected">Computes what the resume must match.</param>
/// <returns>The state, or null.</returns>
public HistoryContinuationState? TryTake(byte[]? token, Func<PeerHistoryContinuationKey> 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
}
/// <summary>
/// The port's continuation scope for one remote peer: saves and takes through that peer's
/// <see cref="PeerHistoryContinuationStore"/>, binding the caller's principal, the serving incarnation CURRENT at the
/// save and at the take (read live from <paramref name="currentServingIncarnation"/>, 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
/// <c>BadInternalError</c> for the node (never <c>BadHistoryOperationUnsupported</c>), and H2 must surface it distinctly.
/// </summary>
internal sealed class PeerHistoryContinuationWiringException : InvalidOperationException
{
/// <summary>Creates the exception.</summary>
/// <param name="message">What is miswired.</param>
/// <param name="inner">The incarnation source's own failure, if any.</param>
public PeerHistoryContinuationWiringException(string message, Exception? inner = null) : base(message, inner) { }
}
/// <summary>
/// The port's continuation scope for one remote peer's ONE request (create a new scope per <c>ReadHistory</c> call):
/// saves and takes through that peer's <see cref="PeerHistoryContinuationStore"/>, 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.
/// <para>
/// The serving incarnation is read from <paramref name="currentServingIncarnation"/> 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
/// <c>BadContinuationPointInvalid</c>), 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
/// <see cref="PeerHistoryContinuationWiringException"/>. Save never answers <c>null</c> (that would read as a
/// complete read and truncate).
/// </para>
/// </summary>
/// <param name="store">The (principal, connection) store.</param>
/// <param name="principal">The caller's authenticated principal.</param>
@@ -208,13 +257,30 @@ internal sealed class PeerHistoryContinuationStore
internal sealed class PeerHistoryContinuationScope(
PeerHistoryContinuationStore store, string principal, Func<string> currentServingIncarnation) : IHistoryContinuationScope
{
private readonly Lazy<string> _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);
/// <inheritdoc />
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);
/// <inheritdoc />
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));
}
@@ -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<IHistoryContinuationScope> scope)
{
var parts = new List<string>();
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;
});
}
@@ -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<ArgumentException>(() => other.Save(State(), binding), "a store never holds another principal's cursor");
Should.Throw<PeerHistoryContinuationWiringException>(() => 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<string>)[]
{
("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<PeerHistoryContinuationWiringException>(
() => new PeerHistoryContinuationScope(store, Principal, source).Save(State(), binding), name);
}
}
[Fact]
public void Wiring_errors_have_their_own_exception_type()
{
var store = Store();
Should.Throw<PeerHistoryContinuationWiringException>(() => store.Save(State(), "someone-else", Incarnation, Hash));
Should.Throw<PeerHistoryContinuationWiringException>(() => 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()
{