fix(grpc-data): H3 review D1/D4/D6/D7 — probe cancel, sub-batches, flush wake-up, request-order budget

D1: a caller cancel (the projected deadline) during the connection's capability
probe escaped as RpcException(Cancelled) and faulted the whole HistoryRead; it
is now OperationCanceledException, the probe is capped by HistoryTimeout, and
ProjectedHistoryAccess fails any escaping fault per node (BadTimeout when the
deadline fired) and releases every cursor it owns. D4: calls are sub-batched at
min(the deployed connection's batch, the origin's advertised MaxBatchItems) and
at most one item per 256 B of the remaining assembly budget; a shortfall is
BadTooManyOperations per node, never an endpoint failure. D6: the release flush
is re-armed from a flag under its gate (no lost wake-up) and the stop source is
never disposed under a running flush. D7: calls are runs of consecutive request
positions read in request order, then the budget is charged in request order.
Float32 node over a Double-returning backend reads Good Singles end to end (no
KindMatches defect). Red/green for D1/D4/D7 by mutation; D6's race did not
reproduce red.
This commit is contained in:
Joseph Doherty
2026-11-24 01:48:12 -05:00
parent 585d5079eb
commit 1237e9e6d1
6 changed files with 437 additions and 106 deletions
@@ -583,6 +583,8 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistor
internal Func<bool> RouteCurrent => _routeCurrent;
/// <summary>The configured row's operations, already masked to the understood set.</summary>
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;
public IDataConnection Connection => this;
public CancellationToken CancellationToken => _scope;
public DataTarget Target => _inner.Target;
@@ -89,7 +89,13 @@ public sealed partial class GrpcDataConnection : IDataHistoryService
Check();
cancellationToken.ThrowIfCancellationRequested();
Selected selected;
try { selected = await SelectAsync(_endpoints[index], start, request.Budget, false, cancellationToken).ConfigureAwait(false); ProbeSucceeded(); }
// The capability probe is capped by HistoryTimeout too (H3 review), like every history call.
try { selected = await SelectAsync(_endpoints[index], start, ProbeBudget(request.Budget), false, cancellationToken).ConfigureAwait(false); ProbeSucceeded(); }
catch (Exception ex) when (cancellationToken.IsCancellationRequested && ex is RpcException or OperationCanceledException)
{
// A caller cancel (a deadline) during the probe is a cancel, never an escaping RpcException (H3 review D1).
throw new OperationCanceledException("History read cancelled by the caller.", ex, cancellationToken);
}
catch (Exception ex) when (!cancellationToken.IsCancellationRequested
&& ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException or TimeoutException or ArgumentException)
{ failure = ex; RecordFailure(ex); continue; }
@@ -291,6 +297,9 @@ public sealed partial class GrpcDataConnection : IDataHistoryService
catch (Exception ex) when (ex is RpcException or OperationCanceledException or InvalidOperationException) { }
}
/// <summary>The capability probe's budget: the caller's, capped by <see cref="HistoryTimeout"/>.</summary>
private DataBudget ProbeBudget(DataBudget budget) => budget.Timeout <= HistoryTimeout ? budget : budget with { Timeout = HistoryTimeout };
private static DataHistoryReadResult[] All(DataHistoryReadRequest request, uint status) =>
request.Items.Select(x => new DataHistoryReadResult(x.CorrelationId, status, [], null)).ToArray();
@@ -49,6 +49,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl
private readonly Dictionary<string, List<byte[]>> _pendingReleases = new(StringComparer.OrdinalIgnoreCase);
private readonly CancellationTokenSource _stop = new();
private Task _releaseFlush = Task.CompletedTask;
private bool _flushScheduled;
private int _disposed;
/// <summary>Creates the gateway.</summary>
@@ -103,8 +104,10 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl
var outcomes = new ProjectedHistoryOutcome?[nodes.Count];
var demands = new IProjectedDemandLease?[nodes.Count];
var targets = new ProjectedHistoryTarget?[nodes.Count];
var assembled = new long[nodes.Count];
var assemblyRefused = new bool[nodes.Count];
var callerKey = CallerKey(caller);
long budget = DefaultAssemblyBudget;
long budget = DefaultAssemblyBudget, received = 0;
try
{
// 1. Resolve, authorize and pin every node; check each resumed cursor against what it was issued under.
@@ -114,7 +117,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl
var cursor = node.Resume as RemoteCursor;
if (node.Resume is not null && (cursor is null || !ReferenceEquals(cursor.Owner, this)))
{
node.Resume.Release();
node.Resume.ReleaseEvenIfClaimed();
outcomes[i] = Fail(BadContinuationPointInvalid);
continue;
}
@@ -145,38 +148,77 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl
if (target is not null) budget = Math.Min(budget, _assemblyBudget(target.MappingId) is { } b and > 0 ? b : DefaultAssemblyBudget);
if (budget == long.MaxValue) budget = DefaultAssemblyBudget;
// 3. One call per (connection, details, resumed endpoint): a resumed item pins its issuing endpoint, so cursors of
// different endpoints, and fresh items (which may move), never share a call.
var groups = Enumerable.Range(0, nodes.Count).Where(i => outcomes[i] is null)
.GroupBy(i => new GroupKey(targets[i]!.ConnectionId, DetailsOf(nodes[i], details), ResumeKey(nodes[i])))
.ToArray();
foreach (var group in groups)
// 3. Calls per (connection, details, resumed endpoint): a resumed item pins its issuing endpoint, so cursors of
// different endpoints, and fresh items (which may move), never share a call. Calls are RUNS of consecutive
// request positions with one key, read in request order (H3 review D7), so the assembly budget is consumed in
// request order and a budget shortfall only ever refuses nodes later in the request. Each run is sub-batched.
var runs = new List<(GroupKey Key, List<int> Indices)>();
for (var i = 0; i < nodes.Count; i++)
{
var indices = group.ToArray();
if (cancellationToken.IsCancellationRequested) { FailAll(indices, BadTimeout); continue; }
TimeSpan remaining;
if (deadline > TimeSpan.Zero)
if (outcomes[i] is not null) continue;
var key = new GroupKey(targets[i]!.ConnectionId, DetailsOf(nodes[i], details), ResumeKey(nodes[i]));
if (runs.Count > 0 && runs[^1].Key == key) runs[^1].Indices.Add(i);
else runs.Add((key, [i]));
}
foreach (var (key, list) in runs)
{
var indices = list.ToArray();
if (cancellationToken.IsCancellationRequested || Remaining() <= TimeSpan.Zero) { FailAll(indices, BadTimeout); continue; }
if (received >= budget) { FailAll(indices, BadTooManyOperations); continue; }
await ReadGroupAsync(key, indices, cancellationToken).ConfigureAwait(false);
}
// 4. Charge the assembly budget in REQUEST order (H3 review D7): the first node that does not fit, and every later
// node with data, is BadTooManyOperations; its next origin cursor is released.
var left = budget;
var exhausted = false;
for (var i = 0; i < nodes.Count; i++)
{
if (assemblyRefused[i]) { exhausted = true; continue; }
if (outcomes[i] is not { } outcome || assembled[i] == 0 && !exhausted) continue;
if (exhausted || assembled[i] > left)
{
remaining = deadline - _clock.GetElapsedTime(started);
if (remaining <= TimeSpan.Zero) { FailAll(indices, BadTimeout); continue; }
exhausted = true;
(outcome.Continuation as RemoteCursor)?.ReleaseOrigin();
outcomes[i] = Fail(BadTooManyOperations);
continue;
}
else remaining = TimeSpan.FromHours(1); // unbounded locally: the connection's HistoryTimeout still caps each call
if (budget <= 0) { FailAll(indices, BadTooManyOperations); continue; }
await ReadGroupAsync(group.Key, indices, remaining, cancellationToken).ConfigureAwait(false);
left -= assembled[i];
}
return outcomes.Select(o => o ?? Fail(BadNoCommunication)).ToArray();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// Last resort (H3 review D1): whatever escaped, fail per node — a timeout when the deadline fired — and release every
// origin cursor this request still owns. Nothing escapes to the SDK override.
var timedOut = cancellationToken.IsCancellationRequested || Remaining() <= TimeSpan.Zero || ex is OperationCanceledException;
for (var i = 0; i < nodes.Count; i++)
{
if (outcomes[i] is not null) continue;
nodes[i].Resume?.ReleaseEvenIfClaimed();
outcomes[i] = Fail(timedOut ? BadTimeout : BadNoCommunication);
}
return outcomes.Select(o => o!).ToArray();
}
finally
{
foreach (var demand in demands) demand?.Dispose();
}
async Task ReadGroupAsync(GroupKey key, int[] indices, TimeSpan remaining, CancellationToken ct)
TimeSpan Remaining() => deadline > TimeSpan.Zero
? deadline - _clock.GetElapsedTime(started)
: TimeSpan.FromHours(1); // unbounded locally: the connection's HistoryTimeout still caps each call
async Task ReadGroupAsync(GroupKey key, int[] indices, CancellationToken ct)
{
IGrpcDataAdapterConnectionLease? lease = null;
try
{
var remaining = Remaining();
using var timeout = new CancellationTokenSource(remaining, _clock);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, timeout.Token);
lease = await _connections.AcquireAsync(key.ConnectionId, linked.Token).ConfigureAwait(false);
@@ -191,109 +233,106 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl
}
var route = lease.RouteIdentity;
var items = new List<DataHistoryReadItem>(indices.Length);
var sent = new List<int>(indices.Length);
var sendable = new List<int>(indices.Length);
foreach (var i in indices)
{
if (nodes[i].Resume is RemoteCursor cursor)
// The connection lease moved (expiry, redeployment, credential change): its tokens are gone.
if (nodes[i].Resume is RemoteCursor cursor && !Equals(cursor.RouteIdentity, route))
{
// The connection lease moved (expiry, redeployment, credential change): its tokens are gone.
if (!Equals(cursor.RouteIdentity, route))
{
cursor.ReleaseOrigin();
outcomes[i] = Fail(BadContinuationPointInvalid);
continue;
}
items.Add(new DataHistoryReadItem(sent.Count.ToString(System.Globalization.CultureInfo.InvariantCulture),
targets[i]!.OriginMetadata.View, cursor.AggregateId, cursor.Token));
}
else
{
items.Add(new DataHistoryReadItem(sent.Count.ToString(System.Globalization.CultureInfo.InvariantCulture),
targets[i]!.OriginMetadata.View, nodes[i].AggregateId));
cursor.ReleaseOrigin();
outcomes[i] = Fail(BadContinuationPointInvalid);
continue;
}
sent.Add(i);
sendable.Add(i);
}
if (items.Count == 0) return;
IReadOnlyList<DataHistoryReadResult> answers;
try
if (sendable.Count == 0) return;
var batch = await BatchSizeAsync(lease.Connection, sendable.Count, remaining, linked.Token).ConfigureAwait(false);
for (var offset = 0; offset < sendable.Count;)
{
answers = await history.ReadAsync(new DataHistoryReadRequest(key.Details, items,
new DataBudget(remaining, items.Count, (int)Math.Min(int.MaxValue, budget))), linked.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Our deadline or the SDK request ending: a timeout, never an origin fault (the connection records none).
foreach (var i in sent) outcomes[i] = Fail(BadTimeout);
return;
}
try
{
if (answers.Count != items.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);
if (fitting <= 0) { FailAll(sendable.Skip(offset).ToArray(), BadTooManyOperations); return; }
var from = offset;
var chunk = sendable.Skip(from).Take(Math.Min(batch, fitting)).ToArray();
offset += chunk.Length;
var items = chunk.Select((i, k) => new DataHistoryReadItem(k.ToString(System.Globalization.CultureInfo.InvariantCulture),
targets[i]!.OriginMetadata.View,
nodes[i].Resume is RemoteCursor c ? c.AggregateId : nodes[i].AggregateId,
(nodes[i].Resume as RemoteCursor)?.Token)).ToArray();
IReadOnlyList<DataHistoryReadResult> answers;
try
{
foreach (var i in sent) outcomes[i] = Fail(BadNoCommunication);
answers = await history.ReadAsync(new DataHistoryReadRequest(key.Details, items,
new DataBudget(now, items.Length, budget - received)), linked.Token).ConfigureAwait(false);
}
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);
return;
}
for (var k = 0; k < answers.Count; k++)
try
{
var i = sent[k];
var answer = answers[k];
if (answer.CorrelationId != items[k].CorrelationId)
if (answers.Count != items.Length)
{
outcomes[i] = Fail(BadNoCommunication);
FailAll(chunk, BadNoCommunication);
continue;
}
// The per-request assembly budget, in request order across the whole batch: once a node does not fit,
// it and every later node is BadTooManyOperations (never a partial answer; its origin cursor released).
long nodeBytes = 0;
foreach (var sample in answer.Samples) nodeBytes += sample.Value.EstimatedRetainedBytes;
if (nodeBytes > budget)
for (var k = 0; k < answers.Count; k++)
{
budget = 0;
if (answer.Continuation is { } dropped) EnqueueRelease(key.ConnectionId, dropped);
outcomes[i] = Fail(BadTooManyOperations);
continue;
var i = chunk[k];
var answer = answers[k];
if (answer.CorrelationId != items[k].CorrelationId)
{
if (answer.Continuation is { } stray) EnqueueRelease(key.ConnectionId, stray);
outcomes[i] = Fail(BadNoCommunication);
continue;
}
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
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);
}
budget -= 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);
}
finally
{
foreach (var answer in answers) answer.Dispose();
}
}
finally
{
foreach (var answer in answers) answer.Dispose();
}
}
catch (OperationCanceledException)
{
foreach (var i in indices)
{
if (outcomes[i] is not null) continue;
if (nodes[i].Resume is RemoteCursor c) c.ReleaseOrigin();
outcomes[i] = Fail(BadTimeout);
}
return;
FailAll(indices.Where(i => outcomes[i] is null).ToArray(), BadTimeout);
}
catch (Exception ex) when (ex is InvalidOperationException or UnauthorizedAccessException or ArgumentException or ObjectDisposedException)
catch (Exception ex) when (ex is not OutOfMemoryException)
{
foreach (var i in indices) outcomes[i] ??= Fail(nodes[i].Resume is null ? BadNoCommunication : BadContinuationPointInvalid);
return;
// An unexpected fault (an escaping RpcException, a malformed answer): per node, never out of the batch.
var timedOut = ct.IsCancellationRequested || Remaining() <= TimeSpan.Zero;
foreach (var i in indices.Where(i => outcomes[i] is null).ToArray())
{
if (nodes[i].Resume is RemoteCursor c) c.ReleaseOrigin();
outcomes[i] = Fail(timedOut ? BadTimeout : nodes[i].Resume is null ? BadNoCommunication : BadContinuationPointInvalid);
}
}
finally
{
@@ -311,6 +350,32 @@ 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).
/// </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);
}
/// <summary>The sub-batch size when the connection is not a deployment lease (tests, direct facades).</summary>
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;
private static ProjectedHistoryOutcome Fail(uint status) => new(status, []);
private static DataHistoryDetails DetailsOf(ProjectedHistoryNode node, DataHistoryDetails request) =>
@@ -358,6 +423,9 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl
return converted;
}
/// <summary>Queues a release directly (tests: the flush's wake-up under concurrent enqueues).</summary>
internal void EnqueueReleaseForTests(string connectionId, byte[] token) => EnqueueRelease(connectionId, token);
/// <summary>Queues an origin token for a coalesced best-effort release on its connection.</summary>
private void EnqueueRelease(string connectionId, byte[] token)
{
@@ -366,7 +434,10 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl
{
if (!_pendingReleases.TryGetValue(connectionId, out var list)) _pendingReleases[connectionId] = list = [];
list.Add(token);
if (!_releaseFlush.IsCompleted) return;
// H3 review D6: a flag under the gate, not Task.IsCompleted — a flush past its last check but not yet completed
// would otherwise swallow this token (a lost wakeup). The flush clears the flag under the same gate.
if (_flushScheduled) return;
_flushScheduled = true;
_releaseFlush = Task.Run(FlushReleasesAsync);
}
}
@@ -374,7 +445,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl
private async Task FlushReleasesAsync()
{
try { await Task.Delay(ReleaseCoalesce, _stop.Token).ConfigureAwait(false); }
catch (OperationCanceledException) { return; }
catch (OperationCanceledException) { lock (_releaseGate) _flushScheduled = false; return; }
Dictionary<string, List<byte[]>> batch;
lock (_releaseGate)
{
@@ -402,15 +473,19 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl
}
lock (_releaseGate)
{
if (_pendingReleases.Count > 0 && Volatile.Read(ref _disposed) == 0) _releaseFlush = Task.Run(FlushReleasesAsync);
else _flushScheduled = false;
}
}
/// <inheritdoc />
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
// Cancel only: a flush still running reads _stop.Token, so it is never disposed under it (H3 review D6). The source
// has no timer, so leaving it to the GC releases nothing.
_stop.Cancel();
_stop.Dispose();
}
/// <summary>