fix(grpc-data): H3 review round 2 — no batch probe; budget stop; orphan tokens; lease-retired status

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.
This commit is contained in:
Joseph Doherty
2026-11-24 06:25:19 -05:00
parent 37cbeff480
commit 7aaa98751a
7 changed files with 221 additions and 49 deletions
@@ -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);
@@ -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<OperationCanceledException>(() => 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; }
/// <summary>Delay before answering the capability probe (honours the request's token).</summary>
public TimeSpan? ProbeDelay { get; set; }
/// <summary>The advertised MaxBatchItems (default: the shared limits').</summary>
public int? BatchItems { get; set; }
/// <summary>The item count of every HistoryRead call.</summary>
public List<int> CallSizes { get; } = [];
/// <summary>The grpc-timeout of the last capability probe.</summary>
public TimeSpan? LastProbeTimeout { get; private set; }
/// <summary>Fail every HistoryRead after the first with this status.</summary>
@@ -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> { DataValueKind.Double }, Limits, false, 0, "c", true, true, true, true, true,
new HashSet<DataValueKind> { 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)
{
@@ -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 }
/// <summary>
/// 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<int> _sizes = [];
public HistoryMode Mode { get; set; }
/// <summary>The deployed connection's own batch size the lease reports.</summary>
public int? BatchItems { get; set; }
public int CapabilityCalls;
public int ReleasedTokens => Volatile.Read(ref _released);
public IReadOnlyList<int> 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<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => inner.GetCapabilitiesAsync(budget, cancellationToken);
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken)
{
Interlocked.Increment(ref owner.CapabilityCalls);
return inner.GetCapabilitiesAsync(budget, cancellationToken);
}
public Task<DataBrowseBranch> BrowseAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest request, CancellationToken cancellationToken) => inner.BrowseAsync(request, cancellationToken);
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => inner.GetMetadataAsync(request, cancellationToken);
public Task<IReadOnlyList<ReadResult>> 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<byte[]> continuations, CancellationToken cancellationToken)