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
+5 -5
View File
@@ -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`.
@@ -511,7 +511,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
}
/// <summary>A non-owning handle with the deployed operation and resource policy.</summary>
public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistoryService, IDisposable
public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistoryService, IHistoryBatchLimit, IDisposable
{
/// <summary>
/// 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;
/// <summary>The connection row's batch size: a history request with more items is refused (H3 splits below it).</summary>
internal int MaxBatchItems => _batch;
/// <inheritdoc />
int IHistoryBatchLimit.MaxHistoryBatchItems => _batch;
public IDataConnection Connection => this;
public CancellationToken CancellationToken => _scope;
public DataTarget Target => _inner.Target;
@@ -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(); }
}
/// <summary>
/// Reads on one selected endpoint in sub-batches of at most the endpoint's advertised <c>MaxBatchItems</c> — 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 <c>BadTooManyOperations</c>, unsent. Null = the endpoint failed
/// before answering the FIRST sub-batch (a fresh read may move); a later failure answers the rest
/// <c>BadNoCommunication</c> (resumed items <c>BadContinuationPointInvalid</c>), never moving a half-served request.
/// </summary>
private async Task<DataHistoryReadResult[]?> 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;
}
/// <summary>Reads on one selected endpoint and assembles its chunks; null = the endpoint failed before answering (a fresh read may move).</summary>
private async Task<DataHistoryReadResult[]?> ServeAsync(Selected selected, int endpoint, DataHistoryReadRequest request,
DataHistoryReadItem[] items, int[] pending, long start, CancellationToken cancellationToken)
@@ -5,6 +5,12 @@ using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>A connection's own history batch size (the deployed connection row's batch); a larger request is refused.</summary>
internal interface IHistoryBatchLimit
{
int MaxHistoryBatchItems { get; }
}
/// <summary>What a projected HistoryRead demand is bound to (H3).</summary>
/// <param name="MappingId">The mapping.</param>
/// <param name="MappingRevision">The deployed mapping revision.</param>
@@ -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
}
/// <summary>
/// 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 <c>MaxBatchItems</c> (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.
/// </summary>
private static async Task<int> 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);
/// <summary>The sub-batch size when the connection is not a deployment lease (tests, direct facades).</summary>
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<string, List<byte[]>> batch;
lock (_releaseGate)
@@ -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)