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:
@@ -424,7 +424,9 @@ refresh, EventIds) is documented in [Alarm tracking § Imported conditions](Alar
|
||||
- A mapping that completes late is merged in.
|
||||
- An `Unavailable` mapping (item refused, root metadata failed, snapshot timed out) or a `ConditionCapacity` mapping is
|
||||
**retried on the open stream** (#930). Its root is re-resolved if it never resolved, any item it still holds is removed,
|
||||
and a new item is added. The stream is not ended for it, so the healthy mappings are never re-snapshotted and their
|
||||
and a new item is added. The root re-resolve (metadata, 10 s budget) runs off the stream's frame loop (#934): frames of
|
||||
the other mappings keep flowing meanwhile, the mapping stays `Unavailable` until the answer is applied on the loop, and
|
||||
its item is re-added then. The stream is not ended for it, so the healthy mappings are never re-snapshotted and their
|
||||
methods are never answered `BadNoCommunication` because of it.
|
||||
- Retry delay, per mapping. A **definitive** refusal (`Denied`, `NotFound` or `Unsupported`, for the item or the root
|
||||
metadata) or `ConditionCapacity` waits `LongRetryDelay` (5 min) × 2ⁿ, capped at 4× (20 min). Any other refusal or a
|
||||
|
||||
+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);
|
||||
|
||||
|
||||
+50
-3
@@ -1134,6 +1134,43 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
await f.WaitAsync(() => f.Sink.Live.Contains(Key("x")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Issue934_a_slow_in_stream_root_re_resolve_does_not_stall_frames_of_the_other_mappings()
|
||||
{
|
||||
await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
|
||||
f.Connections.MetadataFails.Add(0); // map-a's root fails at the open: Unavailable, its item is not opened
|
||||
f.Connections.MetadataBlockCall = 2; // …and its in-stream re-resolve (the 2nd metadata call) hangs until released
|
||||
using var demand = f.Access.AcquireEventDemand(null);
|
||||
var stream = await f.NextStreamAsync();
|
||||
stream.Mappings.ShouldBe(["map-b"]);
|
||||
stream.Ack();
|
||||
stream.Begin("map-b", total: 1);
|
||||
stream.Records("map-b", Record(Key("x"), 3));
|
||||
stream.Complete("map-b");
|
||||
await f.WaitAsync(() => f.Sink.Live.Contains(Key("x")));
|
||||
f.Connections.MetadataFails.Clear();
|
||||
await f.WaitAsync(() => Volatile.Read(ref f.Connections.MetadataCalls) == 2); // the re-resolve is in flight
|
||||
|
||||
// The frame loop is not blocked by it: map-b's delta is applied while the metadata call is still pending.
|
||||
stream.Records("map-b", Record(Key("y"), 3));
|
||||
await f.WaitAsync(() => f.Sink.Live.Contains(Key("y")));
|
||||
f.Connections.MetadataRelease.Task.IsCompleted.ShouldBeFalse();
|
||||
stream.AddsOf("map-a").ShouldBe(0, "not re-added before its root resolved");
|
||||
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable, "unknown while resolving (T2)");
|
||||
|
||||
// Positive control: once the answer arrives it is applied on the loop and the item is re-added — exactly once.
|
||||
f.Connections.MetadataRelease.SetResult();
|
||||
await f.WaitAsync(() => stream.AddsOf("map-a") == 1);
|
||||
stream.AckAdd("map-a");
|
||||
stream.Begin("map-a", total: 1);
|
||||
stream.SnapshotRecords("map-a", Record(Key("w"), 3));
|
||||
stream.Complete("map-a");
|
||||
await f.WaitAsync(() => f.Sink.Live.Contains(Key("w")));
|
||||
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Complete);
|
||||
stream.AddsOf("map-a").ShouldBe(1);
|
||||
Volatile.Read(ref f.Connections.MetadataCalls).ShouldBe(2);
|
||||
}
|
||||
|
||||
private sealed class Fixture : IAsyncDisposable
|
||||
{
|
||||
internal static readonly DataView DefaultRawPlacement =
|
||||
@@ -1281,6 +1318,9 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
public HashSet<int> MetadataFails { get; } = [];
|
||||
/// <summary>#931 N4: metadata requests made (one per stream attempt, plus in-stream root retries).</summary>
|
||||
public int MetadataCalls;
|
||||
/// <summary>#934: when set, the metadata call with this 1-based number waits for <see cref="MetadataRelease"/>.</summary>
|
||||
public int? MetadataBlockCall;
|
||||
public TaskCompletionSource MetadataRelease { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
/// <summary>The serving roles of the next streams (Primary when empty).</summary>
|
||||
public Queue<string> Roles { get; } = new();
|
||||
public int PrimarySubscribes;
|
||||
@@ -1307,11 +1347,18 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
public TimeProvider Clock => TimeProvider.System;
|
||||
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => throw new NotSupportedException();
|
||||
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
|
||||
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) =>
|
||||
Interlocked.Increment(ref owner.MetadataCalls) < 0 ? throw new InvalidOperationException() : Task.FromResult<IReadOnlyList<DataItemResult<DataMetadata>>>(request.Views.Select((v, i) => owner.MetadataFails.Contains(i)
|
||||
public async Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (Interlocked.Increment(ref owner.MetadataCalls) == owner.MetadataBlockCall)
|
||||
await owner.MetadataRelease.Task.WaitAsync(cancellationToken); // #934: a slow origin metadata answer
|
||||
return Answer(request);
|
||||
}
|
||||
|
||||
private IReadOnlyList<DataItemResult<DataMetadata>> Answer(MetadataRequest request) =>
|
||||
request.Views.Select((v, i) => owner.MetadataFails.Contains(i)
|
||||
? new DataItemResult<DataMetadata>("0", DataItemStatus.Unavailable, null, null)
|
||||
: new DataItemResult<DataMetadata>("0", DataItemStatus.Good, new DataMetadata(v with { Subject = v.Address.Identifier }, v.Address.Identifier, "Folder", DataValueKind.Null, -1, [], false,
|
||||
DataOperations.Browse, 1, null, null, false), null)).ToArray());
|
||||
DataOperations.Browse, 1, null, null, false), null)).ToArray();
|
||||
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
|
||||
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => throw new NotSupportedException();
|
||||
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken)
|
||||
|
||||
Reference in New Issue
Block a user