fix(grpc-data): H3 review round 3 S1/S2/S3/S6 — sub-batch split never strands tokens or breaks the origin's admission
GrpcDataConnection.ServeSplitAsync / ServeAsync: - S2: each sub-batch carries at most one item per 256 B of the budget left (the origin's count <= MaxBytes/256 admission rule); the rest is BadTooManyOperations marked ConsumerBudgetRefused, unsent, and an unsent resumed item's origin token is released. Was: an RpcException, a recorded endpoint failure and BadNoCommunication. - S3: a budget refusal inside a sub-batch's own assembly latches the budget spent; nothing more is sent. - S1: anything escaping a later sub-batch (a caller cancel, a fault) disposes the collected answers and releases their new continuations. - S6: an escape from the assembly (Verify failure, item mismatch) releases finished nodes' continuations, held chunk tokens and the rejected response's tokens; a later sub-batch's endpoint fault is RecordFailure'd, never swallowed. - Nit a: after a sub-batch endpoint failure nothing more is sent to that endpoint; the rest is BadNoCommunication / BadContinuationPointInvalid. Each test is red on revert of its fix (mutation).
This commit is contained in:
+102
-31
@@ -23,6 +23,8 @@ public sealed partial class GrpcDataConnection : IDataHistoryService
|
||||
internal const uint BadTooManyOperations = 0x80100000u;
|
||||
internal const uint BadTimeout = 0x800A0000u;
|
||||
internal const uint BadNoCommunication = 0x80310000u;
|
||||
/// <summary>An origin admits at most one item per this many bytes of a request's byte budget (<c>LocalDataServices.CheckBudget</c>).</summary>
|
||||
internal const long MinimumBytesPerItem = 256;
|
||||
private const byte EnvelopeTag = 0xC7, EnvelopeVersion = 1;
|
||||
|
||||
private TimeSpan _historyTimeout = TimeSpan.FromSeconds(30);
|
||||
@@ -135,48 +137,104 @@ public sealed partial class GrpcDataConnection : IDataHistoryService
|
||||
/// <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.
|
||||
/// the sub-batches, and each sub-batch carries at most one item per <see cref="MinimumBytesPerItem"/> of what is left
|
||||
/// (the origin's admission rule, round 3 S2). Once the budget is spent — exhausted, too small for one more item, or a
|
||||
/// sub-batch's own assembly refused (S3) — the remaining items are <c>BadTooManyOperations</c> marked
|
||||
/// <see cref="DataHistoryReadResult.ConsumerBudgetRefused"/>, unsent. Null = the endpoint failed before answering the
|
||||
/// FIRST sub-batch (a fresh read may move); a later failure is recorded, nothing more is sent to that endpoint, and the
|
||||
/// rest is <c>BadNoCommunication</c> (resumed items <c>BadContinuationPointInvalid</c>), never moving a half-served
|
||||
/// request. A resumed item answered unsent has its origin token released (it is still live there). Anything that
|
||||
/// escapes (a caller cancel, a fault) first disposes the collected answers and releases their new continuations (S1).
|
||||
/// </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];
|
||||
if (pending.Length <= batch) return (await ServeAsync(selected, endpoint, request, items, pending, start, cancellationToken).ConfigureAwait(false)).Results;
|
||||
var answers = new DataHistoryReadResult?[pending.Length];
|
||||
long used = 0;
|
||||
for (var offset = 0; offset < pending.Length; offset += batch)
|
||||
bool spent = false, failed = false;
|
||||
try
|
||||
{
|
||||
var chunk = pending.Skip(offset).Take(batch).ToArray();
|
||||
var left = request.Budget.MaxBytes - used;
|
||||
DataHistoryReadResult[]? served = null;
|
||||
if (left > 0)
|
||||
for (var offset = 0; offset < pending.Length;)
|
||||
{
|
||||
var left = request.Budget.MaxBytes - used;
|
||||
var fitting = spent || failed ? 0 : (int)Math.Min(batch, Math.Max(0, left) / MinimumBytesPerItem);
|
||||
if (fitting <= 0)
|
||||
{
|
||||
for (var k = offset; k < pending.Length; k++)
|
||||
{
|
||||
var item = request.Items[pending[k]];
|
||||
var resumed = item.Continuation is not null;
|
||||
if (resumed) _ = ReleaseOnEndpointAsync(selected, items[pending[k]].Continuation); // unsent: still live at the origin
|
||||
answers[k] = failed
|
||||
? new(item.CorrelationId, resumed ? BadContinuationPointInvalid : BadNoCommunication, [], null)
|
||||
: new(item.CorrelationId, BadTooManyOperations, [], null, "History assembly budget exceeded.") { ConsumerBudgetRefused = true };
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
var chunk = pending.Skip(offset).Take(fitting).ToArray();
|
||||
DataHistoryReadResult[]? served;
|
||||
try
|
||||
{
|
||||
served = await ServeAsync(selected, endpoint, request with { Budget = request.Budget with { MaxBytes = left } }, items, chunk, start,
|
||||
var call = await ServeAsync(selected, endpoint, request with { Budget = request.Budget with { MaxBytes = left } }, items, chunk, start,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
served = call.Results;
|
||||
failed = call.EndpointFailed; // answered, but the endpoint failed mid-way: send it nothing more (nit a)
|
||||
}
|
||||
catch (Exception ex) when (offset > 0 && ex is not OutOfMemoryException && !cancellationToken.IsCancellationRequested) { served = null; }
|
||||
if (served is null && offset == 0) return null;
|
||||
catch (Exception ex) when (offset > 0 && !cancellationToken.IsCancellationRequested
|
||||
&& ex is InvalidOperationException or ArgumentException or RpcException or HttpRequestException)
|
||||
{
|
||||
// An endpoint fault after a served sub-batch: recorded like any endpoint failure (round 3 S6), and the
|
||||
// request stays on this endpoint (half served) with nothing more sent to it (nit a).
|
||||
RecordFailure(ex);
|
||||
served = null;
|
||||
}
|
||||
if (served is null)
|
||||
{
|
||||
if (offset == 0) return null;
|
||||
failed = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
for (var k = 0; k < chunk.Length; k++)
|
||||
{
|
||||
var answer = served[k];
|
||||
foreach (var sample in answer.Samples) used += sample.Value.EstimatedRetainedBytes;
|
||||
if (answer.ConsumerBudgetRefused) spent = true;
|
||||
answers[offset + k] = answer;
|
||||
}
|
||||
offset += chunk.Length;
|
||||
}
|
||||
|
||||
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.Select(x => x!).ToArray();
|
||||
}
|
||||
catch
|
||||
{
|
||||
Abandon(selected, answers);
|
||||
throw;
|
||||
}
|
||||
|
||||
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,
|
||||
/// <summary>Disposes answers that will never be handed out and releases the new origin continuations they carry.</summary>
|
||||
private void Abandon(Selected selected, IEnumerable<DataHistoryReadResult?> answers)
|
||||
{
|
||||
foreach (var answer in answers)
|
||||
{
|
||||
if (answer is null) continue;
|
||||
answer.Dispose();
|
||||
if (answer.Continuation is { } wrapped && TryUnwrap(wrapped, out _, out _, out var token)) _ = ReleaseOnEndpointAsync(selected, token);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads on one selected endpoint and assembles its chunks. Results null = the endpoint failed before answering (a fresh
|
||||
/// read may move); <c>EndpointFailed</c> = it answered (per node) but failed on the way, so a caller splitting a
|
||||
/// request sends it nothing more. Anything that escapes first releases every origin token this assembly holds — finished
|
||||
/// nodes' continuations, chunk tokens, and the tokens of a response it rejected (H3 review round 3 S6).
|
||||
/// </summary>
|
||||
private async Task<(DataHistoryReadResult[]? Results, bool EndpointFailed)> ServeAsync(Selected selected, int endpoint, DataHistoryReadRequest request,
|
||||
DataHistoryReadItem[] items, int[] pending, long start, CancellationToken cancellationToken)
|
||||
{
|
||||
var batch = pending.Select(i => items[i]).ToArray();
|
||||
@@ -187,6 +245,10 @@ public sealed partial class GrpcDataConnection : IDataHistoryService
|
||||
var current = batch;
|
||||
var map = Enumerable.Range(0, batch.Length).ToArray();
|
||||
var first = true;
|
||||
var endpointFailed = false;
|
||||
var chunkTokensReleased = false;
|
||||
W.HistoryReadResponse? unprocessed = null; // a received response whose tokens are not yet owned by final[] / current
|
||||
IReadOnlyList<DataHistoryReadResult>? decoded = null;
|
||||
try
|
||||
{
|
||||
while (current.Length > 0)
|
||||
@@ -211,6 +273,7 @@ public sealed partial class GrpcDataConnection : IDataHistoryService
|
||||
{
|
||||
// A caller cancel is never an outcome: surface it as cancellation, and let go of held chunk tokens.
|
||||
if (!first) ReleaseChunkTokens(selected, current);
|
||||
chunkTokensReleased = true;
|
||||
throw new OperationCanceledException("History read cancelled by the caller.", ex, cancellationToken);
|
||||
}
|
||||
catch (RpcException ex) when (ex.StatusCode is StatusCode.FailedPrecondition or StatusCode.Unimplemented)
|
||||
@@ -229,23 +292,22 @@ public sealed partial class GrpcDataConnection : IDataHistoryService
|
||||
}
|
||||
catch (RpcException ex) when (first && ex.StatusCode is StatusCode.Unavailable or StatusCode.Unauthenticated or StatusCode.PermissionDenied
|
||||
&& !cancellationToken.IsCancellationRequested)
|
||||
{ RecordFailure(ex); return null; }
|
||||
{ RecordFailure(ex); chunkTokensReleased = true; return (null, true); }
|
||||
catch (RpcException ex)
|
||||
{
|
||||
RecordFailure(ex);
|
||||
if (!first) ReleaseChunkTokens(selected, current); // the origin still holds their remainders
|
||||
foreach (var k in map) final[k] ??= new(batch[k].CorrelationId, BadNoCommunication, [], null);
|
||||
endpointFailed = true;
|
||||
break;
|
||||
}
|
||||
first = false;
|
||||
unprocessed = response;
|
||||
Verify(response.Serving, selected);
|
||||
var decoded = DataHistoryProtoMapper.DecodeResponse(response, Limits(request.Budget, selected.Capabilities) with
|
||||
decoded = DataHistoryProtoMapper.DecodeResponse(response, Limits(request.Budget, selected.Capabilities) with
|
||||
{ MaxValueElements = int.MaxValue, MaxBytes = _maxMessageBytes });
|
||||
if (decoded.Count != current.Length || decoded.Where((r, k) => r.CorrelationId != current[k].CorrelationId).Any())
|
||||
{
|
||||
foreach (var r in decoded) r.Dispose();
|
||||
throw new InvalidOperationException("History response has unexpected items.");
|
||||
}
|
||||
var nextItems = new List<DataHistoryReadItem>();
|
||||
var nextMap = new List<int>();
|
||||
for (var k = 0; k < decoded.Count; k++)
|
||||
@@ -274,6 +336,7 @@ public sealed partial class GrpcDataConnection : IDataHistoryService
|
||||
}
|
||||
current = nextItems.ToArray();
|
||||
map = nextMap.ToArray();
|
||||
unprocessed = null; decoded = null; // every token of this response is now in final[] or current
|
||||
}
|
||||
var answers = new DataHistoryReadResult[batch.Length];
|
||||
for (var k = 0; k < batch.Length; k++)
|
||||
@@ -288,15 +351,23 @@ public sealed partial class GrpcDataConnection : IDataHistoryService
|
||||
}
|
||||
answers[k] = result with { Samples = (IReadOnlyList<DataHistorySample>?)assembled[k] ?? [] };
|
||||
}
|
||||
return answers;
|
||||
return (answers, endpointFailed);
|
||||
}
|
||||
catch
|
||||
{
|
||||
foreach (var list in assembled) foreach (var sample in list ?? []) sample.Dispose();
|
||||
foreach (var r in decoded ?? []) r.Dispose();
|
||||
// Nothing this assembly holds is handed out: release every origin token it owns (round 3 S6).
|
||||
foreach (var r in final)
|
||||
if (r?.Continuation is { } wrapped && TryUnwrap(wrapped, out _, out _, out var token)) _ = ReleaseOnEndpointAsync(selected, token);
|
||||
if (!first && !chunkTokensReleased) ReleaseChunkTokens(selected, current);
|
||||
foreach (var item in unprocessed?.Items ?? [])
|
||||
if (item.HasContinuation) _ = ReleaseOnEndpointAsync(selected, item.Continuation.ToByteArray());
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>Releases continuations on their issuing endpoints (<see cref="IDataHistoryService.ReleaseAsync"/>); best effort.</summary>
|
||||
public async Task ReleaseHistoryAsync(IReadOnlyList<byte[]> continuations, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -389,7 +389,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl
|
||||
internal const int DefaultBatchItems = 100;
|
||||
|
||||
/// <summary>An origin admits at most one item per this many bytes of a request's byte budget.</summary>
|
||||
internal const long MinimumBytesPerItem = 256;
|
||||
internal const long MinimumBytesPerItem = GrpcDataConnection.MinimumBytesPerItem;
|
||||
|
||||
private static ProjectedHistoryOutcome Fail(uint status) => new(status, []);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user