fix(grpc-data): move the in-stream root re-resolve off the condition frame loop (#934)
RetryDueAsync awaited the root metadata request (10 s budget) inside the frame loop, stalling every mapping's frames on that connection while the origin's metadata was slow. The request now runs as a task (FetchRootsAsync reads only the immutable root views); the task joins the loop's wake set beside the retry timer, and its answer is applied on the loop (ApplyResolvedAsync: RootView or MarkRefused, then the re-add). All runner state stays loop-owned. While resolving the mapping is Unavailable (unknown, T2) and is not re-scheduled. Test: a hung second metadata call no longer blocks another mapping's delta; releasing it re-adds the item exactly once.
This commit is contained in:
+89
-28
@@ -199,6 +199,8 @@ public sealed partial class ProjectedConditionAccess
|
||||
public DateTimeOffset? RetryDue { get; set; }
|
||||
/// <summary>#930: a re-added item awaits its ack / snapshot.</summary>
|
||||
public bool Retrying { get; set; }
|
||||
/// <summary>#934: an in-stream root re-resolve (metadata) is in flight off the loop; the mapping stays Unavailable.</summary>
|
||||
public bool Resolving { get; set; }
|
||||
/// <summary>#930: consecutive in-stream retries (reset by a completed snapshot); drives the backoff.</summary>
|
||||
public int Retries { get; set; }
|
||||
/// <summary>A4 diagnostics: the last count the origin reported or listed (a snapshot total, or the committed set).</summary>
|
||||
@@ -502,7 +504,7 @@ public sealed partial class ProjectedConditionAccess
|
||||
// The remote root's origin subject: placement addresses are made relative to it (SourceName, folder subject).
|
||||
// S6: a root whose metadata fails is Unavailable (its item is not opened — a root item without the origin's own
|
||||
// view is refused, and placements made relative to a missing root subject would be wrong).
|
||||
await ResolveRootsAsync(connection, states, token).ConfigureAwait(false);
|
||||
ApplyRoots(states, await FetchRootsAsync(connection, states, token).ConfigureAwait(false));
|
||||
var open = states.Where(x => !x.Refused).ToArray();
|
||||
if (open.Length == 0) throw new InvalidOperationException("No condition-bearing mapping root resolved.");
|
||||
|
||||
@@ -552,6 +554,8 @@ public sealed partial class ProjectedConditionAccess
|
||||
// #930 (N2/N3): an Unavailable or over-capacity mapping is retried ON THIS STREAM (its item re-added) on
|
||||
// its own backoff — the stream is no longer ended for it, so the healthy mappings are not re-snapshotted
|
||||
// and clients are not sent RefreshRequired every cycle.
|
||||
// #934: root re-resolves run off the loop; their results are applied (and the items re-added) HERE.
|
||||
await ApplyResolvedAsync(context, snapshotTimeout).ConfigureAwait(false);
|
||||
if (retry.Task.IsCompleted)
|
||||
{
|
||||
retry = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
@@ -560,7 +564,7 @@ public sealed partial class ProjectedConditionAccess
|
||||
ExpireHeld(states);
|
||||
}
|
||||
foreach (var s in states)
|
||||
if (s.RetryDue is null && s.Status is ProjectedConditionMappingStatus.Unavailable or ProjectedConditionMappingStatus.ConditionCapacity)
|
||||
if (s.RetryDue is null && !s.Resolving && s.Status is ProjectedConditionMappingStatus.Unavailable or ProjectedConditionMappingStatus.ConditionCapacity)
|
||||
ScheduleRetry(s, snapshotTimeout);
|
||||
// #933: the earliest held-key expiry shares the retry timer (the loop re-checks both when it fires).
|
||||
DateTimeOffset? wanted = states.Where(x => x.RetryDue is not null).Select(x => (DateTimeOffset?)x.RetryDue!.Value)
|
||||
@@ -582,7 +586,9 @@ public sealed partial class ProjectedConditionAccess
|
||||
next ??= frames.MoveNextAsync().AsTask();
|
||||
if (!next.IsCompleted)
|
||||
{
|
||||
var wake = barrierPassed ? retry.Task : timeout.Task;
|
||||
var wake = !barrierPassed ? timeout.Task
|
||||
: context.Resolves.Count == 0 ? retry.Task
|
||||
: Task.WhenAny(context.Resolves.Select(x => (Task)x.Fetch).Append(retry.Task));
|
||||
if (await Task.WhenAny(next, wake).ConfigureAwait(false) != next) continue;
|
||||
}
|
||||
if (!await next.ConfigureAwait(false)) return;
|
||||
@@ -611,34 +617,71 @@ public sealed partial class ProjectedConditionAccess
|
||||
new(state.MappingId, state.RootView ?? state.Root, new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null),
|
||||
new DataConditionScope(IncludeInfo: true));
|
||||
|
||||
/// <summary>Resolves the roots of <paramref name="targets"/> (metadata); a root that fails is refused (Unavailable).</summary>
|
||||
private async Task ResolveRootsAsync(IDataConnection connection, MappingState[] targets, CancellationToken token)
|
||||
/// <summary>The origin's answer to a root metadata request: the results, or the failure (never thrown, except cancellation).</summary>
|
||||
private sealed record RootFetch(IReadOnlyList<DataItemResult<DataMetadata>>? Metadata, Exception? Error);
|
||||
|
||||
/// <summary>#934: a root re-resolve in flight off the loop (its targets are <see cref="MappingState.Resolving"/>).</summary>
|
||||
private sealed record PendingRoots(MappingState[] Targets, Task<RootFetch> Fetch);
|
||||
|
||||
/// <summary>
|
||||
/// The metadata request for the roots of <paramref name="targets"/>. It reads only the targets' immutable
|
||||
/// <see cref="MappingState.Root"/> views, so it may run off the loop (#934); <see cref="ApplyRoots"/> applies the answer
|
||||
/// on the loop.
|
||||
/// </summary>
|
||||
private static async Task<RootFetch> FetchRootsAsync(IDataConnection connection, MappingState[] targets, CancellationToken token)
|
||||
{
|
||||
if (targets.Length == 0) return;
|
||||
if (targets.Length == 0) return new RootFetch([], null);
|
||||
try
|
||||
{
|
||||
var budget = new DataBudget(TimeSpan.FromSeconds(10), Math.Max(1, targets.Length), 1024 * 1024);
|
||||
var metadata = await connection.GetMetadataAsync(new MetadataRequest(targets.Select(x => x.Root).ToArray(), budget), token)
|
||||
.ConfigureAwait(false);
|
||||
for (var i = 0; i < targets.Length; i++)
|
||||
{
|
||||
if (i < metadata.Count && metadata[i] is { Status: DataItemStatus.Good, Value: { } root })
|
||||
{
|
||||
targets[i].RootSubject = root.View.Subject;
|
||||
targets[i].RootView = root.View;
|
||||
continue;
|
||||
}
|
||||
var status = i < metadata.Count ? metadata[i].Status : DataItemStatus.Unavailable;
|
||||
MarkRefused(targets[i], status);
|
||||
_owner._log.LogWarning("Imported conditions: mapping {Mapping} root metadata unavailable ({Status}) — Unavailable, retried in-stream",
|
||||
targets[i].MappingId, status);
|
||||
}
|
||||
return new RootFetch(await connection.GetMetadataAsync(new MetadataRequest(targets.Select(x => x.Root).ToArray(), budget), token)
|
||||
.ConfigureAwait(false), null);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
catch (Exception ex) when (ex is not OperationCanceledException) { return new RootFetch(null, ex); }
|
||||
}
|
||||
|
||||
/// <summary>On the loop: a resolved root sets the view; a root that failed is refused (Unavailable).</summary>
|
||||
private void ApplyRoots(MappingState[] targets, RootFetch fetched)
|
||||
{
|
||||
if (targets.Length == 0) return;
|
||||
if (fetched.Metadata is not { } metadata)
|
||||
{
|
||||
foreach (var state in targets) MarkRefused(state, DataItemStatus.Unavailable);
|
||||
_owner._log.LogWarning(ex, "Imported conditions: connection {Connection} root metadata failed — {Count} mapping(s) Unavailable",
|
||||
_owner._log.LogWarning(fetched.Error, "Imported conditions: connection {Connection} root metadata failed — {Count} mapping(s) Unavailable",
|
||||
ConnectionId, targets.Length);
|
||||
return;
|
||||
}
|
||||
for (var i = 0; i < targets.Length; i++)
|
||||
{
|
||||
if (i < metadata.Count && metadata[i] is { Status: DataItemStatus.Good, Value: { } root })
|
||||
{
|
||||
targets[i].RootSubject = root.View.Subject;
|
||||
targets[i].RootView = root.View;
|
||||
continue;
|
||||
}
|
||||
var status = i < metadata.Count ? metadata[i].Status : DataItemStatus.Unavailable;
|
||||
MarkRefused(targets[i], status);
|
||||
_owner._log.LogWarning("Imported conditions: mapping {Mapping} root metadata unavailable ({Status}) — Unavailable, retried in-stream",
|
||||
targets[i].MappingId, status);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #934 (on the loop): applies every finished root re-resolve and re-adds the mappings whose root resolved. A root
|
||||
/// that failed again is refused and re-scheduled on its backoff by the loop.
|
||||
/// </summary>
|
||||
private async Task ApplyResolvedAsync(StreamContext context, TimeSpan snapshotTimeout)
|
||||
{
|
||||
for (var i = 0; i < context.Resolves.Count;)
|
||||
{
|
||||
var pending = context.Resolves[i];
|
||||
if (!pending.Fetch.IsCompleted) { i++; continue; }
|
||||
context.Resolves.RemoveAt(i);
|
||||
var fetched = pending.Fetch.IsCompletedSuccessfully ? pending.Fetch.Result
|
||||
: new RootFetch(null, pending.Fetch.Exception?.GetBaseException() ?? new OperationCanceledException());
|
||||
foreach (var state in pending.Targets) state.Resolving = false;
|
||||
ApplyRoots(pending.Targets, fetched);
|
||||
await ReAddAsync(pending.Targets.Where(x => x.RootView is not null).ToArray(), context, snapshotTimeout).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -661,8 +704,8 @@ public sealed partial class ProjectedConditionAccess
|
||||
/// #930: runs the in-stream retries that are due. A retry whose snapshot has not completed by its deadline becomes
|
||||
/// Unavailable again; its buffer and claim are kept, so a late completion of that item is still taken (review r1 S1)
|
||||
/// until the next retry removes the item. A due Unavailable or
|
||||
/// ConditionCapacity mapping has its root re-resolved when it never resolved, any still-open item removed, and its item
|
||||
/// re-added with a fresh command id. While a retry runs the mapping is Pending — unknown, so nothing it might list is
|
||||
/// ConditionCapacity mapping has its root re-resolved when it never resolved (#934: off the loop — it is re-added when
|
||||
/// the answer is applied on the loop), any still-open item removed, and its item re-added with a fresh command id. While a retry runs the mapping is Pending — unknown, so nothing it might list is
|
||||
/// removed or marked known-inactive meanwhile (§5.1 T2).
|
||||
/// </summary>
|
||||
private async Task RetryDueAsync(IDataConnection connection, MappingState[] states, StreamContext context, TimeSpan snapshotTimeout)
|
||||
@@ -690,8 +733,22 @@ public sealed partial class ProjectedConditionAccess
|
||||
}
|
||||
if (due.Count == 0) return;
|
||||
foreach (var state in due) state.Retries++;
|
||||
await ResolveRootsAsync(connection, due.Where(x => x.RootView is null).ToArray(), context.Token).ConfigureAwait(false);
|
||||
var ready = due.Where(x => x.RootView is not null).ToArray();
|
||||
// #934: a root that never resolved is re-resolved OFF the loop (metadata has a 10 s budget; frames for every other
|
||||
// mapping keep flowing meanwhile). The mapping stays Unavailable — unknown, so nothing it might list is removed or
|
||||
// marked known-inactive (§5.1 T2) — and is re-added when the answer is applied on the loop (ApplyResolvedAsync).
|
||||
var unresolved = due.Where(x => x.RootView is null).ToArray();
|
||||
if (unresolved.Length > 0)
|
||||
{
|
||||
foreach (var state in unresolved) state.Resolving = true;
|
||||
context.Resolves.Add(new PendingRoots(unresolved, FetchRootsAsync(connection, unresolved, context.Token)));
|
||||
}
|
||||
await ReAddAsync(due.Where(x => x.RootView is not null).ToArray(), context, snapshotTimeout).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>#930: removes a still-open item of each of <paramref name="ready"/> and re-adds it with a fresh command id.</summary>
|
||||
private async Task ReAddAsync(MappingState[] ready, StreamContext context, TimeSpan snapshotTimeout)
|
||||
{
|
||||
if (ready.Length == 0) return;
|
||||
// An Unavailable mapping whose snapshot timed out still has its item open: remove it before re-adding (one per root).
|
||||
var stillOpen = ready.Where(x => x.ItemHandle is not null).ToArray();
|
||||
foreach (var state in stillOpen) CountItem(state, open: false);
|
||||
@@ -753,7 +810,11 @@ public sealed partial class ProjectedConditionAccess
|
||||
_owner._sink()?.RequireRefresh(ConnectionId);
|
||||
}
|
||||
|
||||
private sealed record StreamContext(IDataSubscription Subscription, string SubscriptionId, long Epoch, CancellationToken Token);
|
||||
private sealed record StreamContext(IDataSubscription Subscription, string SubscriptionId, long Epoch, CancellationToken Token)
|
||||
{
|
||||
/// <summary>#934: root re-resolves in flight (loop-owned list; each fetch completes off the loop).</summary>
|
||||
public List<PendingRoots> Resolves { get; } = [];
|
||||
}
|
||||
|
||||
private sealed record FrameOutcome(HashSet<string> Changed, bool Reconcile, bool Refresh);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user