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:
Joseph Doherty
2026-11-24 07:08:12 -05:00
parent 34e72de3d8
commit 9c2d6273aa
3 changed files with 222 additions and 36 deletions
@@ -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, []);
@@ -251,6 +251,106 @@ public sealed class GrpcDataHistoryClientTests
foreach (var r in again) r.Dispose();
}
// ---- H3 review round 3 -------------------------------------------------------------------------------------------
private static readonly long SampleBytes = new DataHistorySample(DataValue.FromScalar(DataValueKind.Double, 1.0), 0, null, null)
.Value.EstimatedRetainedBytes; // the fake answers two Double samples per item per chunk
private static DataHistoryReadRequest Many(int count, long? maxBytes = null) => new(Request().Details,
Enumerable.Range(0, count).Select(i => new DataHistoryReadItem("n" + i, View)).ToArray(), maxBytes is { } b ? Budget with { MaxBytes = b } : Budget);
private static async Task AwaitReleased(Endpoint a, Func<byte[][], bool> done)
{
var deadline = DateTime.UtcNow.AddSeconds(10);
while (DateTime.UtcNow < deadline)
{
byte[][] released;
lock (a.Released) released = a.Released.ToArray();
if (done(released)) return;
await Task.Delay(20, TestContext.Current.CancellationToken);
}
}
private static int ReleasedCount(Endpoint a, byte[] token) { lock (a.Released) return a.Released.Count(t => t.SequenceEqual(token)); }
[Fact]
[Trait("Phase", "H3")]
public async Task A_cancel_in_a_later_sub_batch_releases_the_earlier_sub_batches_new_continuations()
{
// S1: sub-batch 1 answered (two new page continuations); the caller cancels during sub-batch 2 — nothing is stranded.
var a = new Endpoint("a") { BatchItems = 2, PageToken = [9, 9, 9], HangOnDataCall = 2 };
await using var connection = Connect([a]);
using var cancel = new CancellationTokenSource();
var read = connection.ReadHistoryAsync(Many(4), cancel.Token);
var deadline = DateTime.UtcNow.AddSeconds(10);
while (Volatile.Read(ref a.DataCalls) < 2 && DateTime.UtcNow < deadline) await Task.Delay(10, TestContext.Current.CancellationToken);
await cancel.CancelAsync();
await Should.ThrowAsync<OperationCanceledException>(() => read);
await AwaitReleased(a, r => r.Count(t => t.SequenceEqual(new byte[] { 9, 9, 9 })) >= 2);
ReleasedCount(a, [9, 9, 9]).ShouldBe(2, "both continuations sub-batch 1 opened are released");
}
[Fact]
[Trait("Phase", "H3")]
public async Task A_later_sub_batch_is_trimmed_to_the_origins_byte_admission_and_the_rest_is_a_consumer_budget_refusal()
{
// S2: after sub-batch 1 only room for ONE item is left (256 B); sending two would break the origin's count <= MaxBytes/256
// rule (an RpcException ⇒ a recorded endpoint failure). Trimmed: [2, 1], the rest refused unsent, no endpoint failure.
var a = new Endpoint("a") { BatchItems = 2, EnforceAdmission = true };
await using var connection = Connect([a]);
var results = await connection.ReadHistoryAsync(Many(4, 4 * SampleBytes + 256), TestContext.Current.CancellationToken);
results.Take(2).ShouldAllBe(r => r.StatusCode == 0u && r.Samples.Count == 2);
results.Skip(2).ShouldAllBe(r => r.StatusCode == 0x80100000u && r.ConsumerBudgetRefused);
a.CallSizes.ShouldBe([2, 1]);
foreach (var r in results) r.Dispose();
var again = await connection.ReadHistoryAsync(Many(1), TestContext.Current.CancellationToken);
again.Single().StatusCode.ShouldBe(0u, "a budget refusal is not an endpoint failure");
foreach (var r in again) r.Dispose();
}
[Fact]
[Trait("Phase", "H3")]
public async Task A_sub_batch_whose_assembly_overflows_spends_the_budget_and_nothing_more_is_sent()
{
// S3: sub-batch 2 refuses n3 inside its own assembly while what was KEPT is still below the budget — n4, n5 unsent.
var a = new Endpoint("a") { BatchItems = 2 };
await using var connection = Connect([a]);
var results = await connection.ReadHistoryAsync(Many(6, 7 * SampleBytes), TestContext.Current.CancellationToken);
results.Take(3).ShouldAllBe(r => r.StatusCode == 0u);
results.Skip(3).ShouldAllBe(r => r.StatusCode == 0x80100000u && r.ConsumerBudgetRefused);
a.CallSizes.ShouldBe([2, 2]);
foreach (var r in results) r.Dispose();
}
[Fact]
[Trait("Phase", "H3")]
public async Task After_a_sub_batch_endpoint_failure_nothing_more_is_sent_to_that_endpoint()
{
// Nit (a): sub-batch 2 fails (recorded); sub-batch 3 is answered unsent.
var a = new Endpoint("a") { BatchItems = 2, FailAfterFirst = Grpc.Core.StatusCode.Internal };
await using var connection = Connect([a]);
var results = await connection.ReadHistoryAsync(Many(5), TestContext.Current.CancellationToken);
results.Take(2).ShouldAllBe(r => r.StatusCode == 0u);
results.Skip(2).ShouldAllBe(r => r.StatusCode == 0x80310000u);
a.CallSizes.ShouldBe([2, 2]);
foreach (var r in results) r.Dispose();
}
[Fact]
[Trait("Phase", "H3")]
public async Task A_rejected_follow_up_chunk_releases_every_token_the_assembly_holds()
{
// S6: n0 completes on call 1 (a new page continuation in final[]); n1 continues; call 2's answer is malformed.
var a = new Endpoint("a") { PageToken = [9, 9, 9], Chunks = 3, MalformedFromDataCall = 2 };
a.ChunksByItem["n0"] = 1;
await using var connection = Connect([a]);
var results = await connection.ReadHistoryAsync(Many(2), TestContext.Current.CancellationToken);
results.ShouldAllBe(r => r.StatusCode == 0x80310000u);
await AwaitReleased(a, r => r.Any(t => t.SequenceEqual(new byte[] { 9, 9, 9 })) && r.Any(t => t.SequenceEqual(new byte[] { 7, 7 })));
ReleasedCount(a, [9, 9, 9]).ShouldBe(1, "n0's finished continuation is released");
ReleasedCount(a, [7, 7]).ShouldBeGreaterThan(0, "n1's chunk tokens are released");
}
[Fact]
public async Task A_failure_mid_assembly_releases_the_origin_chunk_tokens_it_holds()
{
@@ -262,9 +362,10 @@ public sealed class GrpcDataHistoryClientTests
a.Released.ShouldContain(t => t.SequenceEqual(new byte[] { 7, 7 }), "the chunk token the failed follow-up carried is released");
}
private static GrpcDataConnection Connect(Endpoint[] endpoints, TimeSpan? historyTimeout = null)
private static GrpcDataConnection Connect(Endpoint[] endpoints, TimeSpan? historyTimeout = null, Action<DataConnectionManager>? onManager = null)
{
var manager = new DataConnectionManager("consumer", 1);
onManager?.Invoke(manager);
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
var router = new Router(endpoints);
return new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), endpoints.Select(e => new Uri($"https://{e.Name}.test")),
@@ -294,6 +395,15 @@ public sealed class GrpcDataHistoryClientTests
/// <summary>Fail every HistoryRead after the first with this status.</summary>
public Grpc.Core.StatusCode? FailAfterFirst { get; set; }
public int Chunks { get; init; } = 1;
/// <summary>Per correlation id chunk counts (overrides <see cref="Chunks"/>).</summary>
public Dictionary<string, int> ChunksByItem { get; } = new();
/// <summary>Refuse a call carrying more than one item per 256 B of its byte budget (the origin's admission rule).</summary>
public bool EnforceAdmission { get; set; }
/// <summary>The data (non-release) HistoryRead call that never answers (honours the request's token).</summary>
public int? HangOnDataCall { get; set; }
/// <summary>From this data call on, answers carry unexpected correlation ids.</summary>
public int? MalformedFromDataCall { get; set; }
public int DataCalls;
public byte[]? PageToken { get; init; }
public int HistoryCalls;
public List<(string Path, string? Features)> Headers { get; } = [];
@@ -332,6 +442,10 @@ public sealed class GrpcDataHistoryClientTests
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 dataCall = wire.ReleaseContinuations ? 0 : Interlocked.Increment(ref DataCalls);
if (EnforceAdmission && !wire.ReleaseContinuations && wire.Items.Count > wire.Budget.MaxBytes / 256)
return Status(Grpc.Core.StatusCode.InvalidArgument);
if (dataCall != 0 && dataCall == HangOnDataCall) await Task.Delay(Timeout.Infinite, token);
var response = new W.HistoryReadResponse { Serving = DataProtoMapper.EncodeServing(Serving) };
if (!wire.ReleaseContinuations && call > 1 && FailAfterFirst is { } later)
{
@@ -340,7 +454,7 @@ public sealed class GrpcDataHistoryClientTests
}
if (wire.ReleaseContinuations)
{
foreach (var item in wire.Items) Released.Add(item.Continuation.ToByteArray());
lock (Released) foreach (var item in wire.Items) Released.Add(item.Continuation.ToByteArray());
foreach (var item in wire.Items) response.Items.Add(new W.HistoryReadResult { CorrelationId = item.CorrelationId });
}
else
@@ -350,12 +464,13 @@ public sealed class GrpcDataHistoryClientTests
{
var key = item.CorrelationId;
int left;
lock (_chunkLeft) left = _chunkLeft[key] = item.HasContinuation && _chunkLeft.TryGetValue(key, out var l) && l > 0 ? l - 1 : Chunks - 1;
lock (_chunkLeft) left = _chunkLeft[key] = item.HasContinuation && _chunkLeft.TryGetValue(key, out var l) && l > 0 ? l - 1
: (ChunksByItem.TryGetValue(key, out var c) ? c : Chunks) - 1;
using var s1 = new DataHistorySample(DataValue.FromScalar(DataValueKind.Double, 1.0), 0, DateTimeOffset.UnixEpoch, null);
using var s2 = new DataHistorySample(DataValue.FromScalar(DataValueKind.Double, 2.0), 0, null, null);
var result = new DataHistoryReadResult(key, 0, [s1, s2], left > 0 ? [7, 7] : PageToken, null, left > 0);
response.Items.Add(DataHistoryProtoMapper.EncodeResult(result));
if (Malformed) response.Items[^1].CorrelationId = "not-" + key;
if (Malformed || dataCall >= MalformedFromDataCall) response.Items[^1].CorrelationId = "not-" + key;
}
}
message = response;