fix(grpc-data): H2 review 2/3/4/9 - readiness is Ready()'s job; client faults never escape

Origin advertises history whenever it has a historian, so a not-ready/demoted endpoint answers HistoryRead
Unavailable (ungranted: PermissionDenied) and the consumer fails over like v1 Read instead of 'unsupported'.
Client: malformed/undecodable answers are endpoint failures (fresh read moves on); a resumed item is
ContinuationPointInvalid while a fresh item of the same batch is BadNoCommunication; a fresh read tries the next
endpoint when one lacks history; discovery backoff honoured; origin Cancelled without a caller cancel is BadTimeout
(no RecordFailure); caller cancel throws. The deployment lease maps inner/scope faults to BadNoCommunication.
The UnaryTimeout cap is documented next to the AdminUI field and in DataConnections.md.
This commit is contained in:
Joseph Doherty
2026-11-23 22:04:23 -05:00
parent 53e3970f27
commit 3c5cbea931
10 changed files with 195 additions and 29 deletions
@@ -73,7 +73,7 @@ else
<label class="form-label" for="secret-ref">Secret reference</label><input id="secret-ref" class="form-control mb-2" placeholder="secret:data/…" @bind="c.SecretReference" /><div class="form-text">Reference only; never enter a key or secret value.</div>
<fieldset><legend class="fs-6">Consumer nodes</legend>@foreach (var n in Nodes) { <label class="me-3"><input type="checkbox" checked="@c.ConsumerNodeIds.Contains(n.NodeId)" @onchange="e => Toggle(c.ConsumerNodeIds, n.NodeId, (bool)e.Value!)" /> @n.NodeId</label> }</fieldset>
@Operations(c.AllowedOperations, v => c.AllowedOperations = v)
<label class="form-label" for="history-timeout">History call timeout (ms)</label><input id="history-timeout" type="number" min="1" max="@DataConnectionValidator.MaxHistoryTimeoutMilliseconds" class="form-control mb-2" @bind="c.HistoryTimeoutMilliseconds" /><div class="form-text">Each remote HistoryRead call is bounded by the caller's remaining deadline and this.</div>
<label class="form-label" for="history-timeout">History call timeout (ms)</label><input id="history-timeout" type="number" min="1" max="@DataConnectionValidator.MaxHistoryTimeoutMilliseconds" class="form-control mb-2" @bind="c.HistoryTimeoutMilliseconds" /><div class="form-text">Each remote HistoryRead call is bounded by the caller's remaining deadline and this, and in addition by the origin's <span class="mono">DataConnections:UnaryTimeout</span> (30 s by default): a larger value has no effect past it.</div>
<label><input type="checkbox" @bind="c.Enabled" /> Enabled in next deployment</label>
@Actions(c, c.DataConnectionRowId != Guid.Empty)
</div></section>
@@ -527,12 +527,28 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistor
// The deadline is the connection's HistoryTimeout (applied per call by GrpcDataConnection), not the unary timeout,
// and MaxBytes is the caller's chunk-assembly budget, so only the item count is clamped here.
request.Budget.Validate();
var value = await history.ReadAsync(request with { Budget = request.Budget with { MaxItems = Math.Min(request.Budget.MaxItems, _batch) } },
cancellationToken).ConfigureAwait(false);
IReadOnlyList<DataHistoryReadResult> value;
try
{
value = await history.ReadAsync(request with { Budget = request.Budget with { MaxItems = Math.Min(request.Budget.MaxItems, _batch) } },
cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (!cancellationToken.IsCancellationRequested && ex is InvalidOperationException or UnauthorizedAccessException)
{
return Unavailable(request); // connection or scope trouble is a per-item communication failure, never an escape
}
try { Check(DataOperations.HistoryRead); return value; }
catch { foreach (var item in value) item.Dispose(); throw; }
catch (Exception ex) when (ex is InvalidOperationException or UnauthorizedAccessException or OperationCanceledException
&& !cancellationToken.IsCancellationRequested)
{
foreach (var item in value) item.Dispose();
return Unavailable(request); // the scope moved while the answer was in flight
}
}
private static DataHistoryReadResult[] Unavailable(DataHistoryReadRequest request) => request.Items
.Select(x => new DataHistoryReadResult(x.CorrelationId, GrpcDataConnection.BadNoCommunication, [], null)).ToArray();
Task<IReadOnlyList<DataHistoryReadResult>> IDataHistoryService.ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) =>
ReadHistoryAsync(request, cancellationToken);
Task IDataHistoryService.ReleaseAsync(IReadOnlyList<byte[]> continuations, CancellationToken cancellationToken) =>
@@ -73,37 +73,55 @@ public sealed partial class GrpcDataConnection : IDataHistoryService
}
var pending = Enumerable.Range(0, items.Length).Where(i => results[i] is null).ToArray();
if (pending.Length == 0) return results.Select(x => x!).ToArray();
bool Resumed(int i) => request.Items[i].Continuation is not null;
DataHistoryReadResult[] Finish(Func<int, uint> status)
{
foreach (var i in pending) results[i] ??= new(request.Items[i].CorrelationId, status(i), [], null);
return results.Select(x => x!).ToArray();
}
// A fresh read honours discovery backoff like every v1 call; a resumed one goes to its issuing endpoint regardless.
if (pinned is null && !ProbeAllowed()) return Finish(_ => BadNoCommunication);
var candidates = pinned is { } fixedIndex ? [fixedIndex] : Enumerable.Range(0, _endpoints.Length).ToArray();
Exception? failure = null;
var unsupported = false;
foreach (var index in candidates)
{
Check();
cancellationToken.ThrowIfCancellationRequested();
Selected selected;
try { selected = await SelectAsync(_endpoints[index], start, request.Budget, false, cancellationToken).ConfigureAwait(false); ProbeSucceeded(); }
catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException or TimeoutException)
catch (Exception ex) when (!cancellationToken.IsCancellationRequested
&& ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException or TimeoutException or ArgumentException)
{ failure = ex; RecordFailure(ex); continue; }
if (pinnedServing is not null && pinnedServing != selected.Capabilities.Serving.Incarnation)
{
// The issuing endpoint restarted or failed over: its tokens are gone; never resume elsewhere.
foreach (var i in pending.Where(i => request.Items[i].Continuation is not null))
results[i] = new(request.Items[i].CorrelationId, BadContinuationPointInvalid, [], null);
foreach (var i in pending.Where(Resumed)) results[i] = new(request.Items[i].CorrelationId, BadContinuationPointInvalid, [], null);
pending = pending.Where(i => results[i] is null).ToArray();
if (pending.Length == 0) return results.Select(x => x!).ToArray();
}
if (RequestedFeatures(selected.Capabilities) == DataFeatures.None || !selected.Capabilities.Operations.HasFlag(DataOperations.HistoryRead))
{
foreach (var i in pending) results[i] = new(request.Items[i].CorrelationId, BadHistoryOperationUnsupported, [], null);
return results.Select(x => x!).ToArray();
// A fresh read tries the other endpoints; a pinned one cannot move.
unsupported = true;
if (pinned is not null) break;
continue;
}
var served = await ServeAsync(selected, index, request, items, pending, start, cancellationToken).ConfigureAwait(false);
if (served is null) { failure ??= new InvalidOperationException("History endpoint unavailable."); if (pinned is null) continue; break; }
DataHistoryReadResult[]? served;
try { served = await ServeAsync(selected, index, request, items, pending, start, cancellationToken).ConfigureAwait(false); }
catch (Exception ex) when (!cancellationToken.IsCancellationRequested
&& ex is InvalidOperationException or ArgumentException or RpcException or HttpRequestException)
{
// A malformed answer (unexpected items / serving identity, undecodable) is an endpoint failure.
failure = ex; RecordFailure(ex); served = null;
}
if (served is null) { failure ??= new InvalidOperationException("History endpoint unavailable."); if (pinned is not null) break; continue; }
for (var k = 0; k < pending.Length; k++) results[pending[k]] = served[k];
return results.Select(x => x!).ToArray();
}
if (failure is not null && pinned is null) ProbeFailed();
foreach (var i in pending) results[i] = new(request.Items[i].CorrelationId,
pinned is null ? BadNoCommunication : BadContinuationPointInvalid, [], null);
return results.Select(x => x!).ToArray();
if (failure is not null && pinned is null && !unsupported) ProbeFailed();
// Resumed items cannot move; fresh items of the same batch are a communication failure, never an invalid token.
return Finish(i => Resumed(i) ? BadContinuationPointInvalid : unsupported ? BadHistoryOperationUnsupported : BadNoCommunication);
}
finally { if (admitted) _unaryCapacity.Release(); ExitWork(); }
}
@@ -145,8 +163,10 @@ public sealed partial class GrpcDataConnection : IDataHistoryService
foreach (var k in map) final[k] ??= new(batch[k].CorrelationId, BadHistoryOperationUnsupported, [], null);
break;
}
catch (RpcException ex) when (ex.StatusCode == StatusCode.DeadlineExceeded && !cancellationToken.IsCancellationRequested)
catch (RpcException ex) when (ex.StatusCode is StatusCode.DeadlineExceeded or StatusCode.Cancelled && !cancellationToken.IsCancellationRequested)
{
// The call's own deadline, or the origin cancelling it at ITS unary timeout (the effective ceiling is
// min(HistoryTimeout, origin DataConnections:UnaryTimeout)): a timeout, never an endpoint failure.
foreach (var k in map) final[k] ??= new(batch[k].CorrelationId, BadTimeout, [], null);
break;
}
@@ -54,10 +54,16 @@ public sealed partial class LocalDataServices
node.Metadata.View.Realm == DataRealm.Raw ? AddressSpaceRealm.Raw : AddressSpaceRealm.Uns;
/// <summary>The caller's history capabilities, when HistoryRead is among its operations.</summary>
internal DataHistoryCapabilities? HistoryCapabilitiesFor(LocalExportCatalog? catalog, DataAuthenticatedContext context, DataOperations operations)
/// <remarks>
/// Present whenever this origin HAS a historian (H2 review): negotiation is header ∩ supported ∩ origin-has-historian,
/// and readiness / grants are answered by the RPC's <c>Ready(…, HistoryRead)</c> (Unavailable / PermissionDenied), so a
/// not-ready or demoted endpoint makes the consumer fail over exactly like a v1 Read, instead of "unsupported".
/// The limits are the principal's export limits, or the schema defaults when no export grants it history.
/// </remarks>
internal DataHistoryCapabilities? HistoryCapabilitiesFor(LocalExportCatalog? catalog, DataAuthenticatedContext context)
{
if ((operations & DataOperations.HistoryRead) == 0 || catalog?.HistoryLimitsFor(context.PrincipalId) is not { } limits
|| HistoryServing is not { } serving) return null;
if (HistoryServing is not { } serving) return null;
var limits = catalog?.HistoryLimitsFor(context.PrincipalId) ?? (4, 10_000, 4 * 1024 * 1024);
return new DataHistoryCapabilities(true, serving.Aggregates.Count > 0, true, serving.Aggregates, serving.TimestampResolutionTicks,
limits.ValuesPerPage, limits.ConcurrentReads, PeerHistoryIdle);
}
@@ -233,7 +233,7 @@ public sealed partial class LocalDataServices : IDataConnectionFactory
if (catalog is null || !Ready(catalog) || context.AuthorityEpoch != catalog.AuthorityEpoch || !RoleAllows(target, catalog.Serving))
capabilities = capabilities with { Readiness = DataReadiness.Unavailable, Operations = DataOperations.None };
// H2: the transport strips History (and the bit) from a call that did not negotiate history.
capabilities = capabilities with { History = HistoryCapabilitiesFor(catalog, context, capabilities.Operations) };
capabilities = capabilities with { History = HistoryCapabilitiesFor(catalog, context) };
return Task.FromResult(capabilities with { WriteServingGenerationEnforced = true, SubscriptionAgeReadiness = true,
ResponseServingIdentity = true, SubscriptionFreshnessChallenges = _subscriptionFreshnessChallenges,
MetadataItemLeases = true, ProtocolMinor = Math.Max(5, capabilities.ProtocolMinor) });