fix(grpc-data): follow-ups review r1 — the unknown-mapping hold spares a transient mapping's own keys and pauses with no live stream (#933); cancel abandoned root fetches (#934)
S1: a held key that a transiently unknown mapping listed itself (_lastListed) is held without a bound; only a definitive refusal of that mapping (Denied / NotFound / Unsupported / ConditionCapacity, remembered across retries and stream ends) starts its MaxUnknownHold clock. Consistent with a never-opening stream. S2: the hold clock runs only while a stream is past its barrier (paused at the stream end, shifted at the next barrier). N1: in-stream root re-resolves run under a per-stream source cancelled when the stream ends. N2: no held-expiry timer without a sink (spin). N3: MaxUnknownHold must be positive. N5: #933 test lower bound taken before the hold starts; tests for S1, S2, N1, N2, N3 and a second failed re-resolve — each red on revert.
This commit is contained in:
+90
-5
@@ -259,6 +259,16 @@ public sealed partial class ProjectedConditionAccess
|
||||
/// <summary>#933: materialised keys no known mapping lists, held stale while another mapping is unknown → since when
|
||||
/// (kept across stream ends and hand-overs, so a flapping stream cannot restart the bound). Owned by the loop.</summary>
|
||||
private Dictionary<string, DateTimeOffset> _heldSince = new(StringComparer.Ordinal);
|
||||
/// <summary>#933 review r1 S2: the hold clock runs only while a stream is past its barrier — set when such a stream ends
|
||||
/// (the clock pauses), cleared at the next barrier, which shifts every <see cref="_heldSince"/> by the paused time. So a
|
||||
/// connection outage never counts toward <c>MaxUnknownHold</c>. Owned by the loop; handed over.</summary>
|
||||
private DateTimeOffset? _heldPausedAt;
|
||||
/// <summary>#933 review r1 S1: mappings whose latest refusal was DEFINITIVE (Denied / NotFound / Unsupported /
|
||||
/// ConditionCapacity), kept across in-stream retries and stream ends until the mapping completes a snapshot. Only a
|
||||
/// definitively refused mapping's own last-listed keys are subject to <c>MaxUnknownHold</c>. Owned by the loop; handed over.</summary>
|
||||
private HashSet<string> _definitiveRefused = new(StringComparer.OrdinalIgnoreCase);
|
||||
/// <summary>#933 review r1 S1: the transiently-unknown mappings the held keys were last decided against (loop-owned).</summary>
|
||||
private readonly HashSet<string> _transientSeen = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// A4 review r2 S3: this runner took over a set HELD across an undecided deploy. During the hold nothing imported was
|
||||
@@ -348,6 +358,10 @@ public sealed partial class ProjectedConditionAccess
|
||||
_heldSince = previous._heldSince;
|
||||
previous._heldSince = new Dictionary<string, DateTimeOffset>(StringComparer.Ordinal);
|
||||
foreach (var key in _heldSince.Keys.Where(k => !_materialised.Contains(k)).ToArray()) _heldSince.Remove(key);
|
||||
_heldPausedAt = previous._heldPausedAt;
|
||||
previous._heldPausedAt = null;
|
||||
_definitiveRefused = previous._definitiveRefused;
|
||||
previous._definitiveRefused = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
Volatile.Write(ref _materialisedCount, _materialised.Count);
|
||||
Volatile.Write(ref _unknownCount, _unknownKeys.Count);
|
||||
_predecessor = null;
|
||||
@@ -424,6 +438,8 @@ public sealed partial class ProjectedConditionAccess
|
||||
_lastListed.Clear();
|
||||
_sourceNames.Clear();
|
||||
_heldSince.Clear();
|
||||
_heldPausedAt = null;
|
||||
_definitiveRefused.Clear();
|
||||
Volatile.Write(ref _materialisedCount, 0);
|
||||
Volatile.Write(ref _unknownCount, 0);
|
||||
_owner._ledger.ResetClaims(ConnectionId);
|
||||
@@ -530,7 +546,10 @@ public sealed partial class ProjectedConditionAccess
|
||||
var retry = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
ITimer? retryTimer = null;
|
||||
DateTimeOffset? retryArmedFor = null;
|
||||
var context = new StreamContext(subscription, subscriptionId, epoch, token);
|
||||
// #934 review r1 N1: root re-resolves run under their own source, CANCELLED (not just disposed) when the stream ends
|
||||
// however it ends — an abandoned fetch must not run on to its 10 s budget against a released lease.
|
||||
using var fetches = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
var context = new StreamContext(subscription, subscriptionId, epoch, token, fetches.Token);
|
||||
try
|
||||
{
|
||||
await subscription.SendAsync(new OpenSubscription(subscriptionId, epoch, "open", TimeSpan.FromSeconds(30), items, false,
|
||||
@@ -566,9 +585,12 @@ public sealed partial class ProjectedConditionAccess
|
||||
foreach (var s in states)
|
||||
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).
|
||||
// #933 review r1 S1: a mapping became (or stopped being) transiently unknown — re-decide the held keys.
|
||||
if (TransientChanged(states)) ReconcileUnlisted(states);
|
||||
// #933: the earliest held-key expiry shares the retry timer (the loop re-checks both when it fires). Review
|
||||
// r1 N2: with no sink nothing can expire (Reconcile returns early), so an expiry is not armed — it would spin.
|
||||
DateTimeOffset? wanted = states.Where(x => x.RetryDue is not null).Select(x => (DateTimeOffset?)x.RetryDue!.Value)
|
||||
.Append(HeldExpiry()).Where(x => x is not null).Min();
|
||||
.Append(_owner._sink() is null ? null : HeldExpiry()).Where(x => x is not null).Min();
|
||||
if (wanted != retryArmedFor)
|
||||
{
|
||||
retryTimer?.Dispose(); retryTimer = null;
|
||||
@@ -605,6 +627,9 @@ public sealed partial class ProjectedConditionAccess
|
||||
finally
|
||||
{
|
||||
retryTimer?.Dispose();
|
||||
fetches.Cancel();
|
||||
// #933 review r1 S2: the hold clock pauses while no stream is past its barrier.
|
||||
if (barrierPassed && _heldPausedAt is null) _heldPausedAt = _owner._clock.GetUtcNow();
|
||||
foreach (var s in states)
|
||||
{
|
||||
CountItem(s, open: false);
|
||||
@@ -740,7 +765,7 @@ public sealed partial class ProjectedConditionAccess
|
||||
if (unresolved.Length > 0)
|
||||
{
|
||||
foreach (var state in unresolved) state.Resolving = true;
|
||||
context.Resolves.Add(new PendingRoots(unresolved, FetchRootsAsync(connection, unresolved, context.Token)));
|
||||
context.Resolves.Add(new PendingRoots(unresolved, FetchRootsAsync(connection, unresolved, context.FetchToken)));
|
||||
}
|
||||
await ReAddAsync(due.Where(x => x.RootView is not null).ToArray(), context, snapshotTimeout).ConfigureAwait(false);
|
||||
}
|
||||
@@ -797,6 +822,50 @@ public sealed partial class ProjectedConditionAccess
|
||||
if (keys.Count > 0) Reconcile(states, keys, full: false);
|
||||
}
|
||||
|
||||
/// <summary>#933 review r1 S1: unknown, and not definitively refused (a pending first snapshot, Unavailable, retrying).</summary>
|
||||
private bool Transient(MappingState state) => !state.Known && !_definitiveRefused.Contains(state.MappingId);
|
||||
|
||||
/// <summary>
|
||||
/// #933 review r1 S1: the held keys a transiently unknown mapping listed itself when last known (its re-listing will
|
||||
/// decide them); null when there are none. Only these escape <c>MaxUnknownHold</c> — a key held because ANOTHER
|
||||
/// mapping is unknown, or whose own mapping is definitively refused, is bounded.
|
||||
/// </summary>
|
||||
private HashSet<string>? TransientOwnedKeys(MappingState[] states)
|
||||
{
|
||||
HashSet<string>? exempt = null;
|
||||
foreach (var state in states)
|
||||
if (Transient(state) && _lastListed.TryGetValue(state.MappingId, out var listed) && listed.Count > 0)
|
||||
(exempt ??= new HashSet<string>(StringComparer.Ordinal)).UnionWith(listed);
|
||||
return exempt;
|
||||
}
|
||||
|
||||
/// <summary>#933 review r1 S1: whether the set of transiently unknown mappings changed since last decided (and records it).</summary>
|
||||
private bool TransientChanged(MappingState[] states)
|
||||
{
|
||||
var count = 0;
|
||||
var changed = false;
|
||||
foreach (var state in states)
|
||||
{
|
||||
if (!Transient(state)) continue;
|
||||
count++;
|
||||
if (!_transientSeen.Contains(state.MappingId)) changed = true;
|
||||
}
|
||||
if (!changed && count == _transientSeen.Count) return false;
|
||||
_transientSeen.Clear();
|
||||
foreach (var state in states) if (Transient(state)) _transientSeen.Add(state.MappingId);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>#933 review r1 S1: re-decides every held (materialised, unlisted) key — exempt keys drop their clock, the
|
||||
/// others start it (or are removed when every mapping is known).</summary>
|
||||
private void ReconcileUnlisted(MappingState[] states)
|
||||
{
|
||||
var keys = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var key in _materialised)
|
||||
if (!states.Any(x => x.Contributes && x.Live!.Records.ContainsKey(key))) keys.Add(key);
|
||||
if (keys.Count > 0) Reconcile(states, keys, full: false);
|
||||
}
|
||||
|
||||
private void CountItem(MappingState state, bool open)
|
||||
{
|
||||
if (state.ItemCounted == open) return;
|
||||
@@ -810,7 +879,8 @@ 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,
|
||||
CancellationToken FetchToken)
|
||||
{
|
||||
/// <summary>#934: root re-resolves in flight (loop-owned list; each fetch completes off the loop).</summary>
|
||||
public List<PendingRoots> Resolves { get; } = [];
|
||||
@@ -826,6 +896,7 @@ public sealed partial class ProjectedConditionAccess
|
||||
state.Refusal = status;
|
||||
if (state.Status != ProjectedConditionMappingStatus.ConditionCapacity) state.Status = ProjectedConditionMappingStatus.Unavailable;
|
||||
}
|
||||
if (Definitive(state)) _definitiveRefused.Add(state.MappingId); else _definitiveRefused.Remove(state.MappingId);
|
||||
state.Retrying = false;
|
||||
state.RetryDue = null; // re-scheduled (with its backoff) once past the barrier
|
||||
CountItem(state, open: false);
|
||||
@@ -839,6 +910,14 @@ public sealed partial class ProjectedConditionAccess
|
||||
Interlocked.Exchange(ref _snapshotAtTicks, _owner._clock.GetUtcNow().UtcTicks);
|
||||
_barrierThisStream = true;
|
||||
DisarmStale();
|
||||
// #933 review r1 S2: the hold clock resumes — the time no stream was past its barrier does not count.
|
||||
if (_heldPausedAt is { } paused)
|
||||
{
|
||||
var gap = _owner._clock.GetUtcNow() - paused;
|
||||
if (gap > TimeSpan.Zero) foreach (var key in _heldSince.Keys.ToArray()) _heldSince[key] += gap;
|
||||
_heldPausedAt = null;
|
||||
}
|
||||
TransientChanged(states); // S1: the full re-diff below decides against this set
|
||||
var incompleteSet = states.Where(x => !x.Known).Select(x => x.MappingId).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var incomplete = incompleteSet.Count > 0;
|
||||
// #930 N2: the same incomplete set as the last barrier ⇒ the clients were already told; a permanently refused
|
||||
@@ -952,6 +1031,7 @@ public sealed partial class ProjectedConditionAccess
|
||||
mapping.Live = done;
|
||||
mapping.Buffer = null;
|
||||
_lastListed.Remove(mapping.MappingId);
|
||||
_definitiveRefused.Remove(mapping.MappingId);
|
||||
lock (_statusGate) mapping.Status = ProjectedConditionMappingStatus.Complete;
|
||||
_owner._ledger.Commit(ConnectionId, mapping.MappingId, done.Records.Count); // ≤ the admitted total
|
||||
// #930: a completed (re)snapshot ends any retry; the mapping is known again.
|
||||
@@ -1011,6 +1091,7 @@ public sealed partial class ProjectedConditionAccess
|
||||
mapping.Live = null;
|
||||
mapping.Buffer = null;
|
||||
mapping.Observed = observed;
|
||||
_definitiveRefused.Add(mapping.MappingId);
|
||||
// #930 N3: re-added in-stream on the long timer (ConditionCapacity is definitive), not left empty until the stream ends.
|
||||
mapping.Retrying = false;
|
||||
mapping.RetryDue = null;
|
||||
@@ -1048,6 +1129,7 @@ public sealed partial class ProjectedConditionAccess
|
||||
foreach (var key in _materialised) if (!listed.Contains(key)) keys.Add(key);
|
||||
}
|
||||
var unknown = states.Any(x => !x.Known);
|
||||
var exempt = unknown ? TransientOwnedKeys(states) : null;
|
||||
var now = _owner._clock.GetUtcNow();
|
||||
var updates = new List<ImportedConditionUpdate>();
|
||||
var removals = new List<string>();
|
||||
@@ -1065,6 +1147,9 @@ public sealed partial class ProjectedConditionAccess
|
||||
if (!_materialised.Contains(key)) continue;
|
||||
if (unknown)
|
||||
{
|
||||
// #933 review r1 S1: a key a TRANSIENTLY unknown mapping listed itself is held without a bound — its origin
|
||||
// may well still list it (T2); only a definitive refusal of that mapping starts its clock.
|
||||
if (exempt is not null && exempt.Contains(key)) { _heldSince.Remove(key); stale.Add(key); continue; }
|
||||
// #933: the hold is bounded per key (MaxUnknownHold) — a durably Unavailable / Denied mapping no longer
|
||||
// keeps a retired condition forever. Past the bound it is removed (+ RefreshRequired), never known-inactive.
|
||||
if (!_heldSince.TryGetValue(key, out var since)) _heldSince[key] = since = now;
|
||||
|
||||
@@ -205,6 +205,9 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
|
||||
_sink = sink ?? (() => Sink);
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_options = options ?? ProjectedConditionOptions.Default;
|
||||
// #933 review r1 N3: zero or negative would remove every held key at once — the bound must be a real duration.
|
||||
if (_options.MaxUnknownHold <= TimeSpan.Zero)
|
||||
throw new ArgumentOutOfRangeException(nameof(options), _options.MaxUnknownHold, "MaxUnknownHold must be positive.");
|
||||
_log = logger ?? NullLogger.Instance;
|
||||
_ledger = new ConditionLedger(_options);
|
||||
_mappings.Changed += OnMappingsChanged;
|
||||
|
||||
+169
-6
@@ -1115,15 +1115,16 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
stream.Complete("map-a");
|
||||
await f.WaitAsync(() => f.Sink.Live.Contains(Key("x")));
|
||||
|
||||
// map-a retires x; map-b is unknown, so x is held stale (T2) — the stale mark is the must-arrive control.
|
||||
// map-a retires x; map-b is unknown, so x is held stale (T2) — the stale mark is the must-arrive control. Review r1 N5:
|
||||
// the runner's hold clock starts after this instant, so it is a true lower bound (no tolerance for a slow poll).
|
||||
var beforeHeld = DateTime.UtcNow;
|
||||
stream.Records("map-a", Record(Key("x"), 4, removed: true));
|
||||
await f.WaitAsync(() => f.Sink.StaleKeys.Contains(Key("x")));
|
||||
var heldAt = DateTime.UtcNow;
|
||||
f.Sink.Removed.ShouldBeEmpty("within the bound an unknown mapping still holds the key");
|
||||
|
||||
// …and past the bound it is removed (+ RefreshRequired at the sink), on the open stream, with no frame to prompt it.
|
||||
await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x")));
|
||||
(DateTime.UtcNow - heldAt).ShouldBeGreaterThan(hold - TimeSpan.FromMilliseconds(200), "not before MaxUnknownHold");
|
||||
(DateTime.UtcNow - beforeHeld).ShouldBeGreaterThanOrEqualTo(hold, "not before MaxUnknownHold");
|
||||
f.Sink.Removed.Count(k => k == Key("x")).ShouldBe(1);
|
||||
f.Sink.Live.ShouldNotContain(Key("x"));
|
||||
f.Access.MappingStatuses(Connection)!["map-b"].ShouldBe(ProjectedConditionMappingStatus.Unavailable, "still unknown");
|
||||
@@ -1171,6 +1172,158 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
Volatile.Read(ref f.Connections.MetadataCalls).ShouldBe(2);
|
||||
}
|
||||
|
||||
private static Fixture HoldFixture(int timeoutMs, TimeSpan hold, params (string Id, DataRealm Realm, int MaxConditions)[] mappings)
|
||||
{
|
||||
var f = new Fixture(Fixture.DefaultOptions with { LongRetryDelay = TimeSpan.FromMinutes(5), MaxUnknownHold = hold }, mappings);
|
||||
foreach (var m in f.Mappings.Current) m.Mapping.ConditionSnapshotTimeoutMilliseconds = timeoutMs;
|
||||
return f;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Issue933_r1_S1_a_key_its_own_transiently_unknown_mapping_listed_is_held_past_the_bound_until_that_mapping_is_definitively_refused()
|
||||
{
|
||||
var hold = TimeSpan.FromSeconds(1);
|
||||
await using var f = HoldFixture(300, hold, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
|
||||
using var demand = f.Access.AcquireEventDemand(null);
|
||||
var first = await f.NextStreamAsync();
|
||||
first.Ack();
|
||||
first.Begin("map-a", total: 0);
|
||||
first.Complete("map-a");
|
||||
first.Begin("map-b", total: 1);
|
||||
first.SnapshotRecords("map-b", Record(Key("x"), 3));
|
||||
first.Complete("map-b");
|
||||
await f.WaitAsync(() => f.Sink.Live.Contains(Key("x")));
|
||||
|
||||
// map-b listed x; on the next stream its item is refused TRANSIENTLY (Unavailable) and its retries keep timing out.
|
||||
first.End();
|
||||
var second = await f.NextStreamAsync();
|
||||
second.Ack(DataItemStatus.Unavailable, "map-b");
|
||||
second.Begin("map-a", total: 0);
|
||||
second.Complete("map-a");
|
||||
await f.WaitAsync(() => f.Sink.StaleKeys.Contains(Key("x")));
|
||||
await Task.Delay(hold * 2.5, TestContext.Current.CancellationToken);
|
||||
f.Sink.Removed.ShouldNotContain(Key("x"), "map-b's own key: its origin may still list it (T2) — no bound while map-b is transient");
|
||||
f.Sink.Live.ShouldContain(Key("x"));
|
||||
|
||||
// Positive control: map-b's retry is refused DEFINITIVELY — now the bound runs, from then.
|
||||
// Ack a FRESH re-add at once (its command stays current until the next re-add, ≥ 600 ms later on the backoff).
|
||||
var adds = second.AddsOf("map-b");
|
||||
await f.WaitAsync(() => second.AddsOf("map-b") > adds);
|
||||
var beforeDefinitive = DateTime.UtcNow;
|
||||
second.AckAdd("map-b", DataItemStatus.Denied);
|
||||
await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x")));
|
||||
(DateTime.UtcNow - beforeDefinitive).ShouldBeGreaterThanOrEqualTo(hold, "the clock starts at the definitive refusal");
|
||||
f.Access.MappingStatuses(Connection)!["map-b"].ShouldBe(ProjectedConditionMappingStatus.Unavailable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Issue933_r1_S2_time_with_no_stream_past_its_barrier_does_not_count_toward_MaxUnknownHold()
|
||||
{
|
||||
var hold = TimeSpan.FromSeconds(1.5);
|
||||
await using var f = new Fixture(Fixture.DefaultOptions with { LongRetryDelay = TimeSpan.FromMinutes(5), MaxUnknownHold = hold },
|
||||
("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-b"); // definitive: map-a's retired key is bounded
|
||||
first.Begin("map-a", total: 1);
|
||||
first.Records("map-a", Record(Key("x"), 3));
|
||||
first.Complete("map-a");
|
||||
await f.WaitAsync(() => f.Sink.Live.Contains(Key("x")));
|
||||
first.Records("map-a", Record(Key("x"), 4, removed: true));
|
||||
await f.WaitAsync(() => f.Sink.StaleKeys.Contains(Key("x")));
|
||||
|
||||
// The stream ends and the next one sits before its barrier (snapshot slow) for longer than the whole bound.
|
||||
first.End();
|
||||
var second = await f.NextStreamAsync();
|
||||
await Task.Delay(hold * 2, TestContext.Current.CancellationToken);
|
||||
f.Sink.Removed.ShouldBeEmpty("nothing is decided before a barrier");
|
||||
second.Ack(DataItemStatus.Denied, "map-b");
|
||||
second.Begin("map-a", total: 0);
|
||||
second.Complete("map-a");
|
||||
await f.WaitAsync(() => f.Access.MappingStatuses(Connection)!["map-a"] == ProjectedConditionMappingStatus.Complete);
|
||||
await Task.Delay(300, TestContext.Current.CancellationToken);
|
||||
f.Sink.Removed.ShouldBeEmpty("the outage did not count: x has been held well under the bound while a stream was live");
|
||||
|
||||
// Positive control: the remaining bound runs out on the live stream.
|
||||
await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x")));
|
||||
(await f.TryNextStreamAsync(TimeSpan.FromMilliseconds(100))).ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Issue933_r1_N2_with_no_sink_an_expired_hold_does_not_spin_the_loop()
|
||||
{
|
||||
var hold = TimeSpan.FromMilliseconds(300);
|
||||
await using var f = new Fixture(Fixture.DefaultOptions with { LongRetryDelay = TimeSpan.FromMinutes(5), MaxUnknownHold = hold },
|
||||
("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-b");
|
||||
stream.Begin("map-a", total: 1);
|
||||
stream.Records("map-a", Record(Key("x"), 3));
|
||||
stream.Complete("map-a");
|
||||
await f.WaitAsync(() => f.Sink.Live.Contains(Key("x")));
|
||||
stream.Records("map-a", Record(Key("x"), 4, removed: true));
|
||||
await f.WaitAsync(() => f.Sink.StaleKeys.Contains(Key("x")));
|
||||
f.SinkDetached = true;
|
||||
stream.Records("map-a", Record(Key("y"), 1)); // one frame so the loop re-arms its timer without a sink
|
||||
await Task.Delay(hold * 2, TestContext.Current.CancellationToken);
|
||||
var before = Volatile.Read(ref f.SinkLookups);
|
||||
await Task.Delay(500, TestContext.Current.CancellationToken);
|
||||
(Volatile.Read(ref f.SinkLookups) - before).ShouldBeLessThan(50, "an expiry that cannot be applied must not re-arm the timer at zero");
|
||||
f.SinkDetached = false;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Issue934_r1_N1_a_root_re_resolve_in_flight_is_cancelled_when_the_stream_ends()
|
||||
{
|
||||
await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
|
||||
f.Connections.MetadataFails.Add(0);
|
||||
f.Connections.MetadataBlockCall = 2;
|
||||
using var demand = f.Access.AcquireEventDemand(null);
|
||||
var stream = await f.NextStreamAsync();
|
||||
stream.Ack();
|
||||
stream.Begin("map-b", total: 0);
|
||||
stream.Complete("map-b");
|
||||
await f.WaitAsync(() => Volatile.Read(ref f.Connections.MetadataCalls) == 2); // the re-resolve is in flight
|
||||
f.Connections.MetadataCancelled.ShouldBe(0);
|
||||
|
||||
stream.End(); // a natural end (no consumer cancellation)
|
||||
await f.WaitAsync(() => Volatile.Read(ref f.Connections.MetadataCancelled) == 1);
|
||||
f.Connections.MetadataFails.Clear();
|
||||
var next = await f.NextStreamAsync(); // positive control: the next stream resolves map-a at its open
|
||||
next.Mappings.ShouldBe(["map-a", "map-b"]);
|
||||
stream.AddsOf("map-a").ShouldBe(0, "the abandoned answer was never applied");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Issue934_r1_a_second_failed_in_stream_re_resolve_is_rescheduled_and_a_later_success_re_adds_once()
|
||||
{
|
||||
await using var f = TimedFixture(200, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
|
||||
f.Connections.MetadataFails.Add(0); // map-a's root keeps failing: at the open, and on the first two re-resolves
|
||||
using var demand = f.Access.AcquireEventDemand(null);
|
||||
var stream = await f.NextStreamAsync();
|
||||
stream.Ack();
|
||||
stream.Begin("map-b", total: 0);
|
||||
stream.Complete("map-b");
|
||||
await f.WaitAsync(() => Volatile.Read(ref f.Connections.MetadataCalls) >= 3);
|
||||
stream.AddsOf("map-a").ShouldBe(0);
|
||||
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable);
|
||||
f.Connections.MetadataFails.Clear();
|
||||
await f.WaitAsync(() => stream.AddsOf("map-a") == 1);
|
||||
stream.AckAdd("map-a");
|
||||
stream.Begin("map-a", total: 0);
|
||||
stream.Complete("map-a");
|
||||
await f.WaitAsync(() => f.Access.MappingStatuses(Connection)!["map-a"] == ProjectedConditionMappingStatus.Complete);
|
||||
stream.AddsOf("map-a").ShouldBe(1);
|
||||
(await f.TryNextStreamAsync(TimeSpan.FromMilliseconds(100))).ShouldBeNull("handled in-stream");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Issue933_r1_N3_a_non_positive_MaxUnknownHold_is_refused()
|
||||
{
|
||||
Should.Throw<ArgumentOutOfRangeException>(() => new Fixture(Fixture.DefaultOptions with { MaxUnknownHold = TimeSpan.Zero }, ("map-a", DataRealm.Raw, 10)));
|
||||
}
|
||||
|
||||
private sealed class Fixture : IAsyncDisposable
|
||||
{
|
||||
internal static readonly DataView DefaultRawPlacement =
|
||||
@@ -1185,6 +1338,11 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
public FakeSink Sink { get; } = new();
|
||||
public FakeConnections Connections { get; } = new();
|
||||
public ProjectedConditionAccess Access { get; }
|
||||
/// <summary>#933 review r1 N2: when set, the sink is gone (the access sees null).</summary>
|
||||
public volatile bool SinkDetached;
|
||||
/// <summary>#933 review r1 N2: how often the access asked for the sink (a spinning loop asks continuously).</summary>
|
||||
public int SinkLookups;
|
||||
private IProjectedConditionSink? CurrentSink() { Interlocked.Increment(ref SinkLookups); return SinkDetached ? null : Sink; }
|
||||
|
||||
public Fixture(params (string Id, DataRealm Realm, int MaxConditions)[] mappings)
|
||||
: this(DefaultOptions, mappings) { }
|
||||
@@ -1200,7 +1358,7 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
Grant(NodePermissions.Browse | NodePermissions.Subscribe);
|
||||
Mappings = new FakeMappings(mappings.Select(m => Placement(m.Id, m.Realm, m.MaxConditions, m.Connection)).ToList());
|
||||
var policy = new DataOperationPolicy(_state, new TriePermissionEvaluator(_state.Tries, TimeProvider.System), TimeProvider.System);
|
||||
Access = new ProjectedConditionAccess(Mappings, Connections, policy, () => Sink, TimeProvider.System, options, NullLogger.Instance);
|
||||
Access = new ProjectedConditionAccess(Mappings, Connections, policy, CurrentSink, TimeProvider.System, options, NullLogger.Instance);
|
||||
}
|
||||
|
||||
/// <summary>A4 review r2: over a real mapping source (e.g. <see cref="DeployedConditionMappings"/>); <see cref="Mappings"/> is unset.</summary>
|
||||
@@ -1209,7 +1367,7 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
Grant(NodePermissions.Browse | NodePermissions.Subscribe);
|
||||
Mappings = null!;
|
||||
var policy = new DataOperationPolicy(_state, new TriePermissionEvaluator(_state.Tries, TimeProvider.System), TimeProvider.System);
|
||||
Access = new ProjectedConditionAccess(mappings, Connections, policy, () => Sink, TimeProvider.System, options ?? DefaultOptions, NullLogger.Instance);
|
||||
Access = new ProjectedConditionAccess(mappings, Connections, policy, CurrentSink, TimeProvider.System, options ?? DefaultOptions, NullLogger.Instance);
|
||||
}
|
||||
|
||||
public void Grant(NodePermissions permissions) =>
|
||||
@@ -1321,6 +1479,8 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
/// <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>#934 review r1 N1: blocked metadata calls whose token was cancelled.</summary>
|
||||
public int MetadataCancelled;
|
||||
/// <summary>The serving roles of the next streams (Primary when empty).</summary>
|
||||
public Queue<string> Roles { get; } = new();
|
||||
public int PrimarySubscribes;
|
||||
@@ -1350,7 +1510,10 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
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
|
||||
{
|
||||
try { await owner.MetadataRelease.Task.WaitAsync(cancellationToken); } // #934: a slow origin metadata answer
|
||||
catch (OperationCanceledException) { Interlocked.Increment(ref owner.MetadataCancelled); throw; }
|
||||
}
|
||||
return Answer(request);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user