fix(grpc-data): A4 #930/#931 — in-stream condition retries (no refresh storm), ConditionCapacity recovery, reconnect backoff, ledger, single RefreshRequired, parked-runner release; condition diagnostics core

#930 N2: an Unavailable mapping (refused item, failed root, snapshot timeout) is retried on the OPEN stream by
re-adding its item (AddSubscriptionItems) on its own backoff — definitive refusals (Denied/NotFound/Unsupported)
on LongRetryDelay (5 min, doubling to 4x), transient ones on the snapshot timeout x 2^n (<= 8x) — so healthy
mappings are never re-snapshotted for it; an incomplete barrier whose incomplete set equals the previous barrier's
sends no RefreshRequired. N3: ConditionCapacity is retried in-stream on the long timer and recovers.
#931 N4 exponential reconnect backoff (MaxReconnectDelay 60 s); N5 held-but-unlisted keys charged beside known
claims (overlapping unknown ones) + SetMaterialised cap report; N6 method calls read Serving without _gate;
N7 a capacity reset that removed conditions sends no second RefreshRequired; N8 a parked runner is released once
its removal finished.
A4 diagnostics core: DataConnectionConditionDiagnostics (side-labelled items/resyncs/capacity/method metrics, new
refresh_required counter, consumer + origin evidence), Commons contracts, DI + deployment-runtime + driver-host wiring.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-11-24 23:03:53 -05:00
parent 9143804987
commit 78eb98ea13
15 changed files with 920 additions and 105 deletions
@@ -253,7 +253,9 @@ public sealed class GrpcDataProjectedConditionAccessTests
f.Sink.Removed.Single().ShouldBe(Key("x"), "y is still listed by map-b");
f.Sink.Live.ShouldBe([Key("y")]);
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity);
f.Sink.RefreshRequired.ShouldBeGreaterThan(refreshes, "clients are told the removal happened (§5.2)");
// #931 N7: the removal itself carries RefreshRequired to the holders (the sink's §5.2 "removal + RefreshRequired"), so
// the reset does not ask a second time.
f.Sink.RefreshRequired.ShouldBe(refreshes, "one RefreshRequired per capacity reset: the removal's");
}
private static Fixture TimedFixture(int timeoutMs, params (string Id, DataRealm Realm, int MaxConditions)[] mappings)
@@ -316,7 +318,17 @@ public sealed class GrpcDataProjectedConditionAccessTests
stream.Complete("map-b");
await f.WaitAsync(() => f.Sink.Applied.Count == 1);
f.Sink.RefreshRequired.ShouldBe(1, "S7: an incomplete barrier from a non-Good ack also requires refresh");
(await f.TryNextStreamAsync(TimeSpan.FromSeconds(5))).ShouldNotBeNull("B2: an Unavailable mapping ends the stream; a new one retries it");
// #930 N2: the retry is IN-STREAM (the item re-added after the bounded wait) — the stream is not ended for it.
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);
(await f.TryNextStreamAsync(TimeSpan.FromMilliseconds(300))).ShouldBeNull("no new stream: map-b is never re-snapshotted for map-a");
f.Sink.Applied.Count(u => u.State.ConditionKey == Key("x")).ShouldBe(1, "the healthy mapping's condition is not re-applied");
f.Sink.RefreshRequired.ShouldBe(1, "a recovered mapping needs no second RefreshRequired");
}
[Fact]
@@ -503,6 +515,162 @@ public sealed class GrpcDataProjectedConditionAccessTests
DateTimeOffset.UtcNow, true, new DataActivationMarker("inc", 1));
}
// ---------------------------------------------------------------------------------------------------------------------
// #930 (N2/N3) and #931 (N4/N5/N7/N8) — A4
// ---------------------------------------------------------------------------------------------------------------------
private static Fixture LongRetryFixture(TimeSpan longRetry, int timeoutMs, params (string Id, DataRealm Realm, int MaxConditions)[] mappings)
{
var f = new Fixture(Fixture.DefaultOptions with { LongRetryDelay = longRetry }, mappings);
foreach (var m in f.Mappings.Current) m.Mapping.ConditionSnapshotTimeoutMilliseconds = timeoutMs;
return f;
}
[Fact]
public async Task N2_a_definitive_refusal_waits_the_long_backoff_on_the_open_stream_never_storming_the_healthy_mapping()
{
await using var f = LongRetryFixture(TimeSpan.FromSeconds(30), 300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.NextStreamAsync();
stream.Ack(DataItemStatus.Denied, "map-a");
stream.Begin("map-b", total: 1);
stream.Records("map-b", Record(Key("x"), 3));
stream.Complete("map-b");
await f.WaitAsync(() => f.Sink.Applied.Count == 1);
// A transient refusal would be retried after the 300 ms snapshot timeout (and, before #930, the stream ended for it).
(await f.TryNextStreamAsync(TimeSpan.FromSeconds(1.5))).ShouldBeNull("the stream is kept");
stream.AddsOf("map-a").ShouldBe(0, "Denied is definitive: the long backoff, not the snapshot timeout");
f.Sink.Applied.Count.ShouldBe(1, "map-b is not re-snapshotted");
f.Sink.RefreshRequired.ShouldBe(1);
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable);
}
[Fact]
public async Task N2_an_unchanged_incomplete_set_on_a_new_stream_sends_no_second_RefreshRequired_a_changed_one_does()
{
await using var f = LongRetryFixture(TimeSpan.FromSeconds(30), 300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
var first = await f.NextStreamAsync();
first.Ack(DataItemStatus.Denied, "map-a");
first.Begin("map-b", total: 1);
first.Records("map-b", Record(Key("x"), 3));
first.Complete("map-b");
await f.WaitAsync(() => f.Access.BarriersCompleted(Connection) == 1);
f.Sink.RefreshRequired.ShouldBe(1);
first.End();
var second = await f.NextStreamAsync();
second.Ack(DataItemStatus.Denied, "map-a"); // still refused: the same incomplete set
second.Begin("map-b", total: 1);
second.SnapshotRecords("map-b", Record(Key("x"), 4));
second.Complete("map-b");
await f.WaitAsync(() => f.Access.BarriersCompleted(Connection) == 2);
f.Sink.RefreshRequired.ShouldBe(1, "the clients were already told about map-a");
second.End();
var third = await f.NextStreamAsync();
third.Ack(DataItemStatus.Denied, "map-a", "map-b"); // a changed incomplete set ⇒ told again (positive control)
await f.WaitAsync(() => f.Access.BarriersCompleted(Connection) == 3);
f.Sink.RefreshRequired.ShouldBe(2);
}
[Fact]
public async Task N3_a_ConditionCapacity_mapping_is_re_added_in_stream_on_the_long_timer_and_recovers_when_under_its_limit()
{
await using var f = LongRetryFixture(TimeSpan.FromMilliseconds(400), 30_000, ("map-a", DataRealm.Raw, 2), ("map-b", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.NextStreamAsync();
stream.Ack();
stream.Begin("map-a", total: 3); // over its MaxConditions
stream.Begin("map-b", total: 1);
stream.SnapshotRecords("map-b", Record(Key("x"), 3));
stream.Complete("map-b");
await f.WaitAsync(() => f.Sink.Live.Contains(Key("x")));
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity);
await f.WaitAsync(() => stream.AddsOf("map-a") == 1);
stream.AckAdd("map-a");
stream.Begin("map-a", total: 2); // the origin dropped back under the limit
stream.SnapshotRecords("map-a", Record(Key("y"), 3), Record(Key("z"), 3));
stream.Complete("map-a");
await f.WaitAsync(() => f.Sink.Live.Contains(Key("y")) && f.Sink.Live.Contains(Key("z")));
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Complete);
(await f.TryNextStreamAsync(TimeSpan.FromMilliseconds(300))).ShouldBeNull("recovered on the open stream");
}
[Fact]
public async Task N3_a_retry_still_over_capacity_stays_ConditionCapacity_and_is_retried_again_never_removing_what_another_mapping_lists()
{
await using var f = LongRetryFixture(TimeSpan.FromMilliseconds(300), 30_000, ("map-a", DataRealm.Raw, 1), ("map-b", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.NextStreamAsync();
stream.Ack();
stream.Begin("map-a", total: 2);
stream.Begin("map-b", total: 1);
stream.SnapshotRecords("map-b", Record(Key("x"), 3));
stream.Complete("map-b");
await f.WaitAsync(() => stream.AddsOf("map-a") == 1);
stream.AckAdd("map-a");
stream.Begin("map-a", total: 2);
await f.WaitAsync(() => stream.AddsOf("map-a") == 2); // backoff doubled, still in-stream
f.Sink.Removed.ShouldBeEmpty("map-b's key is never removed by map-a's retries (T2)");
f.Sink.Live.ShouldBe([Key("x")]);
}
[Fact]
public async Task N4_streams_that_never_reach_a_barrier_back_off_exponentially()
{
var options = Fixture.DefaultOptions with { MaxReconnectDelay = TimeSpan.FromMilliseconds(400) };
await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10));
f.Connections.MetadataFails.Add(0); // every mapping's root fails ⇒ every stream ends before a barrier
using var demand = f.Access.AcquireEventDemand(null);
await Task.Delay(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken);
var calls = Volatile.Read(ref f.Connections.MetadataCalls);
calls.ShouldBeGreaterThan(2, "it keeps retrying");
// Fixed 50 ms reconnects would make ~40 attempts in 2 s; 50, 100, 200, 400, 400… makes ≤ ~8.
calls.ShouldBeLessThan(12);
}
[Fact]
public async Task N5_held_stale_keys_are_charged_beside_a_known_mappings_new_claim_but_overlap_an_unknown_mappings()
{
var options = Fixture.DefaultOptions with { MaxImportedConditionNodes = 3 * 49 }; // 3 conditions on the node
await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
foreach (var m in f.Mappings.Current) m.Mapping.ConditionSnapshotTimeoutMilliseconds = 300;
f.Mappings.Current[0].Mapping.ConditionStaleTimeoutMilliseconds = 60_000;
f.Mappings.Current[1].Mapping.ConditionStaleTimeoutMilliseconds = 60_000;
using var demand = f.Access.AcquireEventDemand(null);
var first = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3), Record(Key("y"), 3)]), ("map-b", [Record(Key("z"), 3)]));
await f.WaitAsync(() => f.Sink.Live.Count == 3);
first.End();
var second = await f.NextStreamAsync();
second.Ack();
second.Begin("map-b", total: 1);
second.SnapshotRecords("map-b", Record(Key("z"), 4));
second.Complete("map-b"); // map-a never answers: x, y held stale (unlisted)
await f.WaitAsync(() => f.Sink.StaleKeys.Contains(Key("x")));
// map-b (known) now re-lists z plus a new w: 4 conditions would be held — over the 3-condition cap.
second.Begin("map-b", total: 2);
await f.WaitAsync(() => f.Access.MappingStatuses(Connection)!["map-b"] == ProjectedConditionMappingStatus.ConditionCapacity);
f.Sink.Live.ShouldNotContain(Key("w"));
f.Sink.Removed.ShouldBeEmpty("map-a is unknown: nothing is removed (T2)");
}
[Fact]
public async Task N8_a_stopped_runner_is_not_kept_parked_after_its_removal_finished()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 10));
var demand = f.Access.AcquireEventDemand(null)!;
var stream = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)]));
await f.WaitAsync(() => f.Sink.Live.Count == 1);
demand.Dispose();
await f.WaitAsync(() => !f.Access.IsRunning(Connection) && f.Sink.Removed.Count == 1);
await f.WaitAsync(() => !f.Access.IsParked(Connection));
f.Access.RunnerReference(Connection).ShouldBeNull("a connection that never returns pins no runner");
stream.Disposed.ShouldBeTrue();
}
private sealed class Fixture : IAsyncDisposable
{
internal static readonly DataView DefaultRawPlacement =
@@ -637,6 +805,8 @@ public sealed class GrpcDataProjectedConditionAccessTests
public Channel<FakeStream> Streams { get; } = Channel.CreateUnbounded<FakeStream>();
/// <summary>Metadata answers Bad for these root indexes (deployed order).</summary>
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>The serving roles of the next streams (Primary when empty).</summary>
public Queue<string> Roles { get; } = new();
public int PrimarySubscribes;
@@ -664,7 +834,7 @@ public sealed class GrpcDataProjectedConditionAccessTests
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) =>
Task.FromResult<IReadOnlyList<DataItemResult<DataMetadata>>>(request.Views.Select((v, i) => owner.MetadataFails.Contains(i)
Interlocked.Increment(ref owner.MetadataCalls) < 0 ? throw new InvalidOperationException() : Task.FromResult<IReadOnlyList<DataItemResult<DataMetadata>>>(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());
@@ -691,14 +861,37 @@ public sealed class GrpcDataProjectedConditionAccessTests
private readonly TaskCompletionSource<OpenSubscription> _open = new(TaskCreationOptions.RunContinuationsAsynchronously);
private long _sequence;
public List<DataItemHandle> Removed { get; } = [];
/// <summary>#930: in-stream item re-adds (retries), in order.</summary>
public List<AddSubscriptionItems> Adds { get; } = [];
private readonly Dictionary<string, DataItemHandle> _current = new(StringComparer.Ordinal);
private ulong _nextHandle = 100;
public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken)
{
if (command is OpenSubscription open) _open.TrySetResult(open);
if (command is RemoveSubscriptionItems remove) lock (Removed) Removed.AddRange(remove.Items);
if (command is AddSubscriptionItems add) lock (Adds) Adds.Add(add);
return Task.CompletedTask;
}
/// <summary>How many re-adds named <paramref name="mapping"/>.</summary>
public int AddsOf(string mapping) { lock (Adds) return Adds.Count(a => a.Items.Any(i => i.ClientItemId == mapping)); }
/// <summary>Acks the latest re-add of <paramref name="mapping"/> (Good ⇒ a fresh handle that later frames use).</summary>
public void AckAdd(string mapping, DataItemStatus status = DataItemStatus.Good)
{
AddSubscriptionItems add;
lock (Adds) add = Adds.Last(a => a.Items.Any(i => i.ClientItemId == mapping));
DataItemHandle? handle = null;
if (status == DataItemStatus.Good)
{
handle = new DataItemHandle(Open.SubscriptionId, Open.StreamEpoch, ++_nextHandle, 1);
lock (_current) _current[mapping] = handle;
}
_frames.Writer.TryWrite(new DataSubscriptionAck(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, add.CommandId,
[new DataSubscriptionItemAck(mapping, status, handle, null, status == DataItemStatus.Good ? null : "refused")]));
}
public IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync(CancellationToken cancellationToken) => _frames.Reader.ReadAllAsync(cancellationToken);
public ValueTask DisposeAsync() { Disposed = true; _frames.Writer.TryComplete(); return ValueTask.CompletedTask; }
@@ -706,13 +899,16 @@ public sealed class GrpcDataProjectedConditionAccessTests
public DataItemHandle HandleOf(string mapping)
{
lock (_current) if (_current.TryGetValue(mapping, out var current)) return current;
var index = Open.Items.Select((x, i) => (x, i)).Single(x => x.x.ClientItemId == mapping).i;
return new DataItemHandle(Open.SubscriptionId, Open.StreamEpoch, (ulong)(index + 1), 1);
}
public void Ack(params string[] refused) => _frames.Writer.TryWrite(new DataSubscriptionAck(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, "open",
public void Ack(params string[] refused) => Ack(DataItemStatus.Unavailable, refused);
public void Ack(DataItemStatus refusal, params string[] refused) => _frames.Writer.TryWrite(new DataSubscriptionAck(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, "open",
Open.Items.Select(x => refused.Contains(x.ClientItemId)
? new DataSubscriptionItemAck(x.ClientItemId, DataItemStatus.Unavailable, null, x.Settings, "secondary")
? new DataSubscriptionItemAck(x.ClientItemId, refusal, null, x.Settings, "refused")
: new DataSubscriptionItemAck(x.ClientItemId, DataItemStatus.Good, HandleOf(x.ClientItemId), x.Settings, null)).ToArray()));
/// <summary>Snapshot record frames exactly as the A2 origin frames them (is_snapshot, no total).</summary>