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
@@ -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)