fix(grpc-data): A4 review r1 — B1 unique capacity-reset command id (fake now rejects reused ids); S1 retry timeout keeps buffer+claim; S2 late ack of a superseded re-add removes the orphan + InvalidArgument backstop; S3 overlap only for keys the mapping itself held; S4 SourceName independent of runtime status; NITs resyncs count opened streams, prune removed connections' counters
This commit is contained in:
+13
@@ -124,6 +124,19 @@ public sealed class DataConnectionConditionDiagnostics
|
||||
CountMethod(ConsumerSide, method, outcome);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Review r1 NIT: drops the counters of connections no deployed mapping references any more (a removed connection), so
|
||||
/// the per-connection map does not grow with every connection id ever deployed.
|
||||
/// </summary>
|
||||
internal void RetainConsumers(IReadOnlySet<string> connectionIds)
|
||||
{
|
||||
foreach (var id in _consumer.Keys)
|
||||
if (!connectionIds.Contains(id)) _consumer.TryRemove(id, out _);
|
||||
}
|
||||
|
||||
/// <summary>Test observation: whether counters are kept for the connection.</summary>
|
||||
internal bool HasConsumerCounters(string connectionId) => _consumer.ContainsKey(connectionId);
|
||||
|
||||
/// <summary>The consumer evidence of one connection; null when it carries no condition-bearing mapping.</summary>
|
||||
public ConsumerConditionDiagnostics? CaptureConsumer(string connectionId)
|
||||
{
|
||||
|
||||
+153
-25
@@ -29,18 +29,27 @@ public sealed partial class ProjectedConditionAccess
|
||||
public int Unlisted;
|
||||
public readonly Dictionary<string, int> Claims = new(StringComparer.OrdinalIgnoreCase);
|
||||
/// <summary>Claims of mappings with no committed set in this stream (first snapshot / retry): they may re-list the
|
||||
/// held-but-unlisted keys, so they overlap <see cref="Unlisted"/> instead of adding to it.</summary>
|
||||
/// held-but-unlisted keys, so they overlap <see cref="Unlisted"/> — but only by <see cref="Overlap"/>.</summary>
|
||||
public readonly HashSet<string> Unknown = new(StringComparer.OrdinalIgnoreCase);
|
||||
/// <summary>A4 review r1 S3: per unknown mapping, how many of the held-but-unlisted keys it listed itself the last time
|
||||
/// it was known on this runner — the most of its claim that can be a re-listing rather than new keys.</summary>
|
||||
public readonly Dictionary<string, int> Overlap = new(StringComparer.OrdinalIgnoreCase);
|
||||
// N5: max(Materialised, ΣClaims) under-counted while one mapping's stale keys were held and another (known) mapping
|
||||
// claimed new ones. The held-but-unlisted keys are charged beside the known mappings' claims; an unknown mapping's
|
||||
// claim may be those very keys, so it is charged as max(Unlisted, Σ unknown claims).
|
||||
// claimed new ones. The held-but-unlisted keys are charged beside every claim; an unknown mapping's claim is reduced
|
||||
// only by the held keys IT previously listed (review r1 S3: the old max(Unlisted, Σ unknown) let a mapping that never
|
||||
// held a key claim another mapping's stale keys as overlap, and the node exceed its caps after the swap).
|
||||
public long Charge
|
||||
{
|
||||
get
|
||||
{
|
||||
long known = 0, unknown = 0;
|
||||
foreach (var (mapping, count) in Claims) if (Unknown.Contains(mapping)) unknown += count; else known += count;
|
||||
return Math.Max(Materialised, known + Math.Max(Unlisted, unknown));
|
||||
long known = 0, unknown = 0, overlap = 0;
|
||||
foreach (var (mapping, count) in Claims)
|
||||
{
|
||||
if (!Unknown.Contains(mapping)) { known += count; continue; }
|
||||
unknown += count;
|
||||
overlap += Math.Min(count, Overlap.GetValueOrDefault(mapping));
|
||||
}
|
||||
return Math.Max(Materialised, known + Unlisted + unknown - Math.Min(Unlisted, overlap));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -61,19 +70,23 @@ public sealed partial class ProjectedConditionAccess
|
||||
|
||||
/// <summary>Sets a mapping's claim when the node total stays within both caps; otherwise leaves it unchanged.</summary>
|
||||
/// <param name="unknown">The mapping has no committed set in this stream yet (N5: its claim may overlap held keys).</param>
|
||||
public bool TryClaim(string connection, string mapping, int count, bool unknown, out long total)
|
||||
/// <param name="overlap">S3: for an unknown mapping, the held-but-unlisted keys it listed itself when last known.</param>
|
||||
public bool TryClaim(string connection, string mapping, int count, bool unknown, out long total, int overlap = 0)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_connections.TryGetValue(connection, out var entry)) _connections[connection] = entry = new Entry();
|
||||
var had = entry.Claims.TryGetValue(mapping, out var previous);
|
||||
var wasUnknown = entry.Unknown.Contains(mapping);
|
||||
var hadOverlap = entry.Overlap.TryGetValue(mapping, out var previousOverlap);
|
||||
entry.Claims[mapping] = count;
|
||||
if (unknown) entry.Unknown.Add(mapping); else entry.Unknown.Remove(mapping);
|
||||
if (unknown) { entry.Unknown.Add(mapping); entry.Overlap[mapping] = overlap; }
|
||||
else { entry.Unknown.Remove(mapping); entry.Overlap.Remove(mapping); }
|
||||
total = TotalLocked();
|
||||
if (!Over(total) || (count <= previous && unknown == wasUnknown)) return true;
|
||||
if (!Over(total) || (count <= previous && unknown == wasUnknown && (!unknown || overlap >= previousOverlap))) return true;
|
||||
if (had) entry.Claims[mapping] = previous; else entry.Claims.Remove(mapping);
|
||||
if (wasUnknown) entry.Unknown.Add(mapping); else entry.Unknown.Remove(mapping);
|
||||
if (hadOverlap) entry.Overlap[mapping] = previousOverlap; else entry.Overlap.Remove(mapping);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -86,17 +99,18 @@ public sealed partial class ProjectedConditionAccess
|
||||
if (!_connections.TryGetValue(connection, out var entry)) _connections[connection] = entry = new Entry();
|
||||
entry.Claims[mapping] = count;
|
||||
entry.Unknown.Remove(mapping);
|
||||
entry.Overlap.Remove(mapping);
|
||||
}
|
||||
}
|
||||
|
||||
public void Release(string connection, string mapping)
|
||||
{
|
||||
lock (_gate) if (_connections.TryGetValue(connection, out var entry)) { entry.Claims.Remove(mapping); entry.Unknown.Remove(mapping); }
|
||||
lock (_gate) if (_connections.TryGetValue(connection, out var entry)) { entry.Claims.Remove(mapping); entry.Unknown.Remove(mapping); entry.Overlap.Remove(mapping); }
|
||||
}
|
||||
|
||||
public void ResetClaims(string connection)
|
||||
{
|
||||
lock (_gate) if (_connections.TryGetValue(connection, out var entry)) { entry.Claims.Clear(); entry.Unknown.Clear(); }
|
||||
lock (_gate) if (_connections.TryGetValue(connection, out var entry)) { entry.Claims.Clear(); entry.Unknown.Clear(); entry.Overlap.Clear(); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -173,6 +187,14 @@ public sealed partial class ProjectedConditionAccess
|
||||
public DataItemStatus? Refusal { get; set; } // written under _statusGate (MarkRefused / retry), read there by Capture
|
||||
/// <summary>#930: the command whose ack belongs to the mapping's current item ("open", then "retry-…").</summary>
|
||||
public string CommandId { get; set; } = "open";
|
||||
/// <summary>A4 review r1 S2: the current command's ack arrived (Good or refused).</summary>
|
||||
public bool Acked { get; set; }
|
||||
/// <summary>A4 review r1 S2: earlier commands replaced before their ack arrived. A late Good ack of one of them means the
|
||||
/// origin holds an item nobody else would remove (later re-adds would be refused "duplicate client item id" forever),
|
||||
/// so it is removed on arrival. Bounded (oldest dropped).</summary>
|
||||
public List<string> Superseded { get; } = [];
|
||||
/// <summary>A4 review r1 S2: consecutive in-stream re-adds refused <c>InvalidArgument</c> (the backstop ends the stream).</summary>
|
||||
public int InvalidArgumentRefusals { get; set; }
|
||||
/// <summary>#930: when the next in-stream retry (or, while <see cref="Retrying"/>, the retry's snapshot deadline) is due.</summary>
|
||||
public DateTimeOffset? RetryDue { get; set; }
|
||||
/// <summary>#930: a re-added item awaits its ack / snapshot.</summary>
|
||||
@@ -194,6 +216,9 @@ public sealed partial class ProjectedConditionAccess
|
||||
public int Claim => Math.Max(Buffer?.Total ?? 0, Live?.Records.Count ?? 0);
|
||||
}
|
||||
|
||||
/// <summary>A4 review r1 S2: consecutive InvalidArgument refusals of a mapping's in-stream re-adds that end the stream.</summary>
|
||||
internal const int MaxInvalidArgumentRefusals = 3;
|
||||
|
||||
private sealed class ConnectionRunner
|
||||
{
|
||||
private readonly ProjectedConditionAccess _owner;
|
||||
@@ -221,7 +246,14 @@ public sealed partial class ProjectedConditionAccess
|
||||
private int _unknownCount;
|
||||
private long _snapshotAtTicks;
|
||||
private int _streamOpen;
|
||||
/// <summary>The current attempt's stream opened (loop-owned; counts a consumer resync when it ends).</summary>
|
||||
private bool _streamOpened;
|
||||
private int _unlisted;
|
||||
/// <summary>A4 review r1 S3: the keys a mapping listed when it was last known on this runner, kept only while it has no
|
||||
/// committed set (a stream end, a capacity reset); its re-listing can overlap only these held keys. Owned by the loop.</summary>
|
||||
private Dictionary<string, HashSet<string>> _lastListed = new(StringComparer.OrdinalIgnoreCase);
|
||||
/// <summary>A4 review r1 S4: per materialised key, the mapping that chose its SourceName and that name. Owned by the loop.</summary>
|
||||
private Dictionary<string, (string MappingId, string SourceName)> _sourceNames = new(StringComparer.Ordinal);
|
||||
|
||||
public ConnectionRunner(ProjectedConditionAccess owner, string connectionId, ProjectedMappingPlacement[] mappings, string signature,
|
||||
ConnectionRunner? predecessor)
|
||||
@@ -290,6 +322,11 @@ public sealed partial class ProjectedConditionAccess
|
||||
_unknownKeys.UnionWith(previous._unknownKeys);
|
||||
_unknownKeys.IntersectWith(_materialised);
|
||||
previous._unknownKeys.Clear();
|
||||
_lastListed = previous._lastListed;
|
||||
previous._lastListed = new Dictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase);
|
||||
_sourceNames = previous._sourceNames;
|
||||
previous._sourceNames = new Dictionary<string, (string, string)>(StringComparer.Ordinal);
|
||||
foreach (var key in _sourceNames.Keys.Where(k => !_materialised.Contains(k)).ToArray()) _sourceNames.Remove(key);
|
||||
Volatile.Write(ref _materialisedCount, _materialised.Count);
|
||||
Volatile.Write(ref _unknownCount, _unknownKeys.Count);
|
||||
_predecessor = null;
|
||||
@@ -309,6 +346,8 @@ public sealed partial class ProjectedConditionAccess
|
||||
if (keys.Length > 0 && _owner._sink() is { } sink) sink.RemoveConditions(ConnectionId, keys);
|
||||
_materialised.Clear();
|
||||
_unknownKeys.Clear();
|
||||
_lastListed.Clear();
|
||||
_sourceNames.Clear();
|
||||
Volatile.Write(ref _materialisedCount, 0);
|
||||
Volatile.Write(ref _unknownCount, 0);
|
||||
_owner._ledger.ResetClaims(ConnectionId);
|
||||
@@ -323,6 +362,7 @@ public sealed partial class ProjectedConditionAccess
|
||||
{
|
||||
epoch++;
|
||||
var barriers = Barriers;
|
||||
_streamOpened = false;
|
||||
try { await RunStreamAsync(epoch, ct).ConfigureAwait(false); }
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; }
|
||||
catch (Exception ex)
|
||||
@@ -333,7 +373,8 @@ public sealed partial class ProjectedConditionAccess
|
||||
finally { Volatile.Write(ref _serving, null); Volatile.Write(ref _streamOpen, 0); }
|
||||
// §5.5 lifetime rule: a stream end is "re-snapshot", never "conditions removed". Arm staleness instead.
|
||||
ArmStale();
|
||||
_owner.Diagnostics.ConsumerResync(ConnectionId);
|
||||
// Review r1 NIT: a resync is a stream that OPENED and ended — not every failed connect attempt.
|
||||
if (_streamOpened) _owner.Diagnostics.ConsumerResync(ConnectionId);
|
||||
// #931 N4: a stream that never reached its barrier (metadata failing for every mapping, no Primary during a
|
||||
// failover) backs off exponentially up to MaxReconnectDelay instead of looping at ReconnectDelay.
|
||||
_failedStreams = Barriers > barriers ? 0 : _failedStreams + 1;
|
||||
@@ -377,6 +418,9 @@ public sealed partial class ProjectedConditionAccess
|
||||
var states = _mappings.Select(x => new MappingState(x)).ToArray();
|
||||
lock (_statusGate) _states = states;
|
||||
_owner._ledger.ResetClaims(ConnectionId);
|
||||
// S3: no mapping has a committed set yet, so every held key is unlisted until the barrier's re-diff.
|
||||
_unlisted = _materialised.Count;
|
||||
_owner._ledger.SetMaterialised(ConnectionId, _materialised.Count, _unlisted);
|
||||
await using var lease = await _owner._connections.AcquireAsync(ConnectionId, ct).ConfigureAwait(false)
|
||||
?? throw new InvalidOperationException("Connection unavailable.");
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, lease.CancellationToken);
|
||||
@@ -399,6 +443,7 @@ public sealed partial class ProjectedConditionAccess
|
||||
Volatile.Write(ref _serving, serving);
|
||||
_barrierThisStream = false;
|
||||
Volatile.Write(ref _streamOpen, 1);
|
||||
_streamOpened = true;
|
||||
_owner._log.LogInformation("Imported conditions: stream {Epoch} for connection {Connection} opened ({Mappings} mapping(s), serving {Serving})",
|
||||
epoch, ConnectionId, open.Length, Serving?.NodeId ?? "(no provenance)");
|
||||
var subscriptionId = "conditions-" + Guid.NewGuid().ToString("N");
|
||||
@@ -479,7 +524,11 @@ public sealed partial class ProjectedConditionAccess
|
||||
finally
|
||||
{
|
||||
retryTimer?.Dispose();
|
||||
foreach (var s in states) CountItem(s, open: false);
|
||||
foreach (var s in states)
|
||||
{
|
||||
CountItem(s, open: false);
|
||||
if (s.Live is { } listed) Remember(s.MappingId, listed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -535,7 +584,8 @@ public sealed partial class ProjectedConditionAccess
|
||||
|
||||
/// <summary>
|
||||
/// #930: runs the in-stream retries that are due. A retry whose snapshot has not completed by its deadline becomes
|
||||
/// Unavailable again (its claim released; a late completion of that item is still taken). A due Unavailable or
|
||||
/// 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
|
||||
/// removed or marked known-inactive meanwhile (§5.1 T2).
|
||||
@@ -552,10 +602,12 @@ public sealed partial class ProjectedConditionAccess
|
||||
state.Retrying = false;
|
||||
if (state.Status is ProjectedConditionMappingStatus.Pending or ProjectedConditionMappingStatus.Snapshotting)
|
||||
{
|
||||
// A4 review r1 S1: exactly as the initial barrier's timeout — the buffer and its claim are KEPT, so the
|
||||
// item's still-streaming snapshot completes late and swaps in (it is dropped only when the next retry
|
||||
// removes the item). Releasing them here made a listing slower than the timeout never complete.
|
||||
lock (_statusGate) state.Status = ProjectedConditionMappingStatus.Unavailable;
|
||||
state.Buffer = null;
|
||||
_owner._ledger.Release(ConnectionId, state.MappingId);
|
||||
_owner._log.LogWarning("Imported conditions: mapping {Mapping} retry snapshot timed out — Unavailable", state.MappingId);
|
||||
_owner._log.LogWarning("Imported conditions: mapping {Mapping} retry snapshot timed out — Unavailable (a late completion is still taken)",
|
||||
state.MappingId);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -578,8 +630,17 @@ public sealed partial class ProjectedConditionAccess
|
||||
state.Status = ProjectedConditionMappingStatus.Pending;
|
||||
state.Refused = false; state.Refusal = null;
|
||||
state.Handle = null; state.ItemHandle = null;
|
||||
// S2: an un-acked command may still be acked late — remember it, so that item is removed when it is.
|
||||
if (!state.Acked)
|
||||
{
|
||||
state.Superseded.Add(state.CommandId);
|
||||
if (state.Superseded.Count > MaxSupersededCommands) state.Superseded.RemoveAt(0);
|
||||
}
|
||||
state.Acked = false;
|
||||
state.CommandId = "retry-" + state.MappingId + "-" + Guid.NewGuid().ToString("N");
|
||||
}
|
||||
// The previous item's buffered (late) snapshot is abandoned with it: its claim goes too (S1 kept it until now).
|
||||
if (state.Buffer is not null && state.Live is null) _owner._ledger.Release(ConnectionId, state.MappingId);
|
||||
state.Buffer = null;
|
||||
state.Retrying = true;
|
||||
state.RetryDue = _owner._clock.GetUtcNow() + snapshotTimeout;
|
||||
@@ -658,16 +719,30 @@ public sealed partial class ProjectedConditionAccess
|
||||
{
|
||||
// #930: an ack belongs to the mapping's CURRENT command (the open, or its latest in-stream retry).
|
||||
var state = states.FirstOrDefault(x => x.MappingId == itemAck.ClientItemId && x.CommandId == ack.CommandId);
|
||||
if (state is null) continue;
|
||||
if (state is null)
|
||||
{
|
||||
await RemoveLateItemAsync(states, ack.CommandId, itemAck, context).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
state.Acked = true;
|
||||
if (itemAck.Status == DataItemStatus.Good && itemAck.Handle is { } handle)
|
||||
{
|
||||
lock (_statusGate) { state.Handle = handle.Handle; state.ItemHandle = handle; }
|
||||
state.InvalidArgumentRefusals = 0;
|
||||
CountItem(state, open: true);
|
||||
continue;
|
||||
}
|
||||
MarkRefused(state, itemAck.Status);
|
||||
_owner._log.LogWarning("Imported conditions: mapping {Mapping} item refused by the origin ({Status}: {Diagnostic})",
|
||||
state.MappingId, itemAck.Status, itemAck.Diagnostic);
|
||||
// S2 backstop: an in-stream re-add the origin keeps refusing InvalidArgument ("duplicate client item id",
|
||||
// "already open for this root") means the origin holds an item of ours this runner lost track of — only a
|
||||
// new stream clears it.
|
||||
state.InvalidArgumentRefusals = itemAck.Status == DataItemStatus.InvalidArgument && ack.CommandId != "open"
|
||||
? state.InvalidArgumentRefusals + 1 : 0;
|
||||
if (state.InvalidArgumentRefusals >= MaxInvalidArgumentRefusals)
|
||||
throw new InvalidOperationException(
|
||||
$"Mapping {state.MappingId}: {state.InvalidArgumentRefusals} consecutive in-stream re-adds refused InvalidArgument; re-opening the stream.");
|
||||
}
|
||||
break;
|
||||
case DataSubscriptionConditions conditions:
|
||||
@@ -679,7 +754,7 @@ public sealed partial class ProjectedConditionAccess
|
||||
// A snapshot begin: decided before anything of it is materialised; buffered until snapshot_complete (B1),
|
||||
// so the committed set (and what is materialised) is untouched while it streams.
|
||||
if (total > limit || !_owner._ledger.TryClaim(ConnectionId, mapping.MappingId, Math.Max(total, mapping.Live?.Records.Count ?? 0),
|
||||
mapping.Live is null, out var after))
|
||||
mapping.Live is null, out var after, mapping.Live is null ? HeldOverlap(mapping, states) : 0))
|
||||
{
|
||||
await ResetToCapacityAsync(mapping, total, total > limit ? "over its MaxConditions" : "would cross the host condition caps",
|
||||
changed, context).ConfigureAwait(false);
|
||||
@@ -723,6 +798,7 @@ public sealed partial class ProjectedConditionAccess
|
||||
changed.UnionWith(done.Records.Keys);
|
||||
mapping.Live = done;
|
||||
mapping.Buffer = null;
|
||||
_lastListed.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.
|
||||
@@ -736,11 +812,49 @@ public sealed partial class ProjectedConditionAccess
|
||||
return new FrameOutcome(changed, reconcile, refresh);
|
||||
}
|
||||
|
||||
/// <summary>S3: records what a mapping listed as it loses its committed set.</summary>
|
||||
private void Remember(string mapping, ConditionSet listed) =>
|
||||
_lastListed[mapping] = new HashSet<string>(listed.Records.Keys, StringComparer.Ordinal);
|
||||
|
||||
/// <summary>
|
||||
/// A4 review r1 S3: how many held keys no contributing mapping lists that <paramref name="mapping"/> itself listed when it
|
||||
/// was last known here — the most of its new claim that can re-list held keys. A mapping that never held a key on this
|
||||
/// runner overlaps nothing, so another mapping's stale keys are charged beside its claim.
|
||||
/// </summary>
|
||||
private int HeldOverlap(MappingState mapping, MappingState[] states)
|
||||
{
|
||||
if (!_lastListed.TryGetValue(mapping.MappingId, out var previous)) return 0;
|
||||
var count = 0;
|
||||
foreach (var key in previous)
|
||||
if (_materialised.Contains(key) && !states.Any(x => x.Contributes && x.Live!.Records.ContainsKey(key))) count++;
|
||||
return count;
|
||||
}
|
||||
|
||||
/// <summary>A4 review r1 S2: how many superseded (never-acked) command ids a mapping remembers.</summary>
|
||||
private const int MaxSupersededCommands = 8;
|
||||
|
||||
/// <summary>
|
||||
/// A4 review r1 S2: an ack for a command the mapping already replaced (its retry was declared timed out before the ack
|
||||
/// came). A Good one means the origin opened an item this runner no longer tracks — removed now, or every later re-add
|
||||
/// would be refused as a duplicate.
|
||||
/// </summary>
|
||||
private async Task RemoveLateItemAsync(MappingState[] states, string commandId, DataSubscriptionItemAck itemAck, StreamContext context)
|
||||
{
|
||||
var state = states.FirstOrDefault(x => x.MappingId == itemAck.ClientItemId && x.Superseded.Contains(commandId));
|
||||
if (state is null) return;
|
||||
state.Superseded.Remove(commandId);
|
||||
if (itemAck.Status != DataItemStatus.Good || itemAck.Handle is not { } handle) return;
|
||||
_owner._log.LogWarning("Imported conditions: mapping {Mapping} late ack of a superseded command — removing the orphaned origin item",
|
||||
state.MappingId);
|
||||
await context.Subscription.SendAsync(new RemoveSubscriptionItems(context.SubscriptionId, context.Epoch, "remove-late-" + Guid.NewGuid().ToString("N"),
|
||||
TimeSpan.FromSeconds(30), [handle]), context.Token).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>§5.5 Unavailable(ConditionCapacity): the item is removed and the mapping contributes nothing (all-or-nothing).</summary>
|
||||
private async Task ResetToCapacityAsync(MappingState mapping, int observed, string reason, HashSet<string> changed, StreamContext context)
|
||||
{
|
||||
lock (_statusGate) mapping.Status = ProjectedConditionMappingStatus.ConditionCapacity;
|
||||
if (mapping.Live is { } live) changed.UnionWith(live.Records.Keys);
|
||||
if (mapping.Live is { } live) { changed.UnionWith(live.Records.Keys); Remember(mapping.MappingId, live); }
|
||||
mapping.Live = null;
|
||||
mapping.Buffer = null;
|
||||
mapping.Observed = observed;
|
||||
@@ -751,12 +865,14 @@ public sealed partial class ProjectedConditionAccess
|
||||
_owner.Diagnostics.ConsumerCapacityRejection(ConnectionId);
|
||||
_owner._log.LogWarning("Imported conditions: mapping {Mapping} ({Count} conditions) {Reason} (MaxConditions {Max}) — Unavailable(ConditionCapacity)",
|
||||
mapping.MappingId, observed, reason, mapping.Placement.Mapping.MaxConditions);
|
||||
// §5.5: the over-limit item is REMOVED (it costs an item slot and the origin's re-listing).
|
||||
// §5.5: the over-limit item is REMOVED (it costs an item slot and the origin's re-listing). A4 review r1 B1: every
|
||||
// command id is unique on the stream — the transport refuses a reused one and the stream would end (a second reset
|
||||
// of the same mapping, after an in-stream retry, reused "remove-{mapping}").
|
||||
if (mapping.ItemHandle is { } handle)
|
||||
{
|
||||
lock (_statusGate) { mapping.Handle = null; mapping.ItemHandle = null; }
|
||||
CountItem(mapping, open: false);
|
||||
await context.Subscription.SendAsync(new RemoveSubscriptionItems(context.SubscriptionId, context.Epoch, "remove-" + mapping.MappingId,
|
||||
await context.Subscription.SendAsync(new RemoveSubscriptionItems(context.SubscriptionId, context.Epoch, "remove-" + mapping.MappingId + "-" + Guid.NewGuid().ToString("N"),
|
||||
TimeSpan.FromSeconds(30), [handle]), context.Token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -792,7 +908,7 @@ public sealed partial class ProjectedConditionAccess
|
||||
}
|
||||
if (!_materialised.Contains(key)) continue;
|
||||
if (unknown) stale.Add(key);
|
||||
else { _materialised.Remove(key); _unknownKeys.Remove(key); removals.Add(key); }
|
||||
else { _materialised.Remove(key); _unknownKeys.Remove(key); _sourceNames.Remove(key); removals.Add(key); }
|
||||
}
|
||||
Volatile.Write(ref _unknownCount, _unknownKeys.Count);
|
||||
Volatile.Write(ref _materialisedCount, _materialised.Count);
|
||||
@@ -831,8 +947,20 @@ public sealed partial class ProjectedConditionAccess
|
||||
if (latest is null || placements.Count == 0) return null;
|
||||
var ordered = placements.OrderBy(x => x.Order).Select(x => x.Placement).ToArray();
|
||||
var primary = ordered[0];
|
||||
var anchor = states[placements.Min(x => x.Order)].Placement.Anchor.Subject;
|
||||
return new ImportedConditionUpdate(ConnectionId, latest, info, ordered, anchor + "/" + primary.RelativePath);
|
||||
var primaryOrder = placements.Min(x => x.Order);
|
||||
var sourceName = states[primaryOrder].Placement.Anchor.Subject + "/" + primary.RelativePath;
|
||||
// A4 review r1 S4: SourceName follows the deployed primary order and what the origin lists — never a mapping's
|
||||
// runtime status. A higher-priority mapping that chose this key's SourceName and is merely not contributing now
|
||||
// (Unavailable / retrying / Pending on a new stream / ConditionCapacity) keeps it: its listing is unknown, not
|
||||
// changed. It moves only when that mapping contributes again (and so re-decides), or is no longer deployed.
|
||||
var chosenBy = states[primaryOrder].MappingId;
|
||||
if (_sourceNames.TryGetValue(key, out var held))
|
||||
{
|
||||
var heldOrder = Array.FindIndex(states, x => string.Equals(x.MappingId, held.MappingId, StringComparison.OrdinalIgnoreCase));
|
||||
if (heldOrder >= 0 && heldOrder < primaryOrder && !states[heldOrder].Contributes) (chosenBy, sourceName) = held;
|
||||
}
|
||||
_sourceNames[key] = (chosenBy, sourceName);
|
||||
return new ImportedConditionUpdate(ConnectionId, latest, info, ordered, sourceName);
|
||||
}
|
||||
|
||||
private static ImportedConditionPlacement ToPlacement(MappingState state, DataView view)
|
||||
|
||||
@@ -264,6 +264,7 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
|
||||
private void OnMappingsChanged()
|
||||
{
|
||||
Interlocked.Increment(ref _mappingVersion);
|
||||
Diagnostics.RetainConsumers(_mappings.Current.Select(x => x.Mapping.DataConnectionId).ToHashSet(StringComparer.OrdinalIgnoreCase));
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
|
||||
+186
@@ -617,6 +617,10 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
stream.AckAdd("map-a");
|
||||
stream.Begin("map-a", total: 2);
|
||||
await f.WaitAsync(() => stream.AddsOf("map-a") == 2); // backoff doubled, still in-stream
|
||||
// A4 review r1 B1: the second capacity reset's remove used the first one's command id, which the transport refuses
|
||||
// (the FakeStream now does too), ending the stream.
|
||||
f.Connections.Streams.Reader.TryPeek(out _).ShouldBeFalse("both capacity resets stayed on the open stream");
|
||||
lock (stream.Removed) stream.Removed.Count.ShouldBe(2, "each reset removed its item");
|
||||
f.Sink.Removed.ShouldBeEmpty("map-b's key is never removed by map-a's retries (T2)");
|
||||
f.Sink.Live.ShouldBe([Key("x")]);
|
||||
}
|
||||
@@ -701,6 +705,169 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
live.HostConditionLimit.ShouldBe(122_500 / 49);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------------
|
||||
// A4 review round 1 (S1–S4, NITs). B1 is pinned by the FakeStream's command-id uniqueness rule (it made
|
||||
// N3_a_retry_still_over_capacity… red) plus the no-new-stream assertion there.
|
||||
// ---------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public async Task R1_S1_a_retry_snapshot_slower_than_the_timeout_still_completes_late_on_the_open_stream()
|
||||
{
|
||||
await using var f = LongRetryFixture(TimeSpan.FromSeconds(30), 500, ("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.Unavailable, "map-a"); // transient ⇒ retried after the snapshot timeout
|
||||
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);
|
||||
stream.SnapshotRecords("map-a", Record(Key("y"), 3));
|
||||
// The retry's deadline passes with the listing half delivered …
|
||||
await f.WaitAsync(() => f.Access.MappingStatuses(Connection)!["map-a"] == ProjectedConditionMappingStatus.Unavailable);
|
||||
// … and the rest arrives before the next retry (2× the timeout later): the late completion is taken.
|
||||
stream.SnapshotRecords("map-a", 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);
|
||||
stream.AddsOf("map-a").ShouldBe(1, "no restart was needed");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task R1_S2_a_late_ack_of_a_superseded_retry_removes_the_orphaned_origin_item_and_the_mapping_recovers()
|
||||
{
|
||||
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.Unavailable, "map-a");
|
||||
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); // retry #1: its ack is slow
|
||||
await f.WaitAsync(() => stream.AddsOf("map-a") == 2); // #1 declared timed out; retry #2 replaced its command
|
||||
var orphan = stream.AckAddAt("map-a", 0); // the origin did open #1 — acked late
|
||||
await f.WaitAsync(() => { lock (stream.Removed) return stream.Removed.Contains(orphan); });
|
||||
stream.AckAdd("map-a", DataItemStatus.InvalidArgument); // #2 reached the origin while #1 was open: duplicate
|
||||
await f.WaitAsync(() => stream.AddsOf("map-a") == 3); // the orphan is gone, so the next re-add is accepted
|
||||
stream.AckAdd("map-a");
|
||||
stream.Begin("map-a", total: 1);
|
||||
stream.SnapshotRecords("map-a", Record(Key("y"), 3));
|
||||
stream.Complete("map-a");
|
||||
await f.WaitAsync(() => f.Sink.Live.Contains(Key("y")));
|
||||
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Complete);
|
||||
f.Connections.Streams.Reader.TryPeek(out _).ShouldBeFalse("recovered on the open stream");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task R1_S2_consecutive_InvalidArgument_refusals_of_in_stream_re_adds_end_the_stream_as_a_backstop()
|
||||
{
|
||||
await using var f = LongRetryFixture(TimeSpan.FromSeconds(30), 200, ("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.Unavailable, "map-a");
|
||||
stream.Begin("map-b", total: 1);
|
||||
stream.SnapshotRecords("map-b", Record(Key("x"), 3));
|
||||
stream.Complete("map-b");
|
||||
for (var i = 1; i < ProjectedConditionAccess.MaxInvalidArgumentRefusals; i++)
|
||||
{
|
||||
await f.WaitAsync(() => stream.AddsOf("map-a") == i);
|
||||
stream.AckAdd("map-a", DataItemStatus.InvalidArgument);
|
||||
}
|
||||
await f.WaitAsync(() => stream.AddsOf("map-a") == ProjectedConditionAccess.MaxInvalidArgumentRefusals);
|
||||
f.Connections.Streams.Reader.TryPeek(out _).ShouldBeFalse("fewer refusals keep the stream");
|
||||
stream.AckAdd("map-a", DataItemStatus.InvalidArgument);
|
||||
(await f.TryNextStreamAsync(TimeSpan.FromSeconds(5))).ShouldNotBeNull("the origin holds an item we lost: only a new stream clears it");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task R1_S3_another_mappings_held_stale_keys_are_not_overlap_for_a_mapping_that_never_listed_them()
|
||||
{
|
||||
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-c", DataRealm.Raw, 10));
|
||||
foreach (var m in f.Mappings.Current) { m.Mapping.ConditionSnapshotTimeoutMilliseconds = 300; m.Mapping.ConditionStaleTimeoutMilliseconds = 60_000; }
|
||||
using var demand = f.Access.AcquireEventDemand(null);
|
||||
var first = await CompleteFirstAsync(f, ("map-a", []), ("map-c", [Record(Key("x"), 3), Record(Key("y"), 3)]));
|
||||
await f.WaitAsync(() => f.Sink.Live.Count == 2);
|
||||
first.End();
|
||||
|
||||
var second = await f.NextStreamAsync();
|
||||
second.Ack(DataItemStatus.Denied, "map-c"); // map-c's x, y are held stale (unknown ≠ gone)
|
||||
// map-a never listed x or y: its 2 new keys + the 2 held would be 4 on a 3-condition node.
|
||||
second.Begin("map-a", total: 2);
|
||||
await f.WaitAsync(() => f.Access.MappingStatuses(Connection)!["map-a"] == ProjectedConditionMappingStatus.ConditionCapacity);
|
||||
f.Sink.Live.Count.ShouldBe(2);
|
||||
f.Sink.Removed.ShouldBeEmpty("map-c is unknown: nothing is removed (T2)");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task R1_S4_SourceName_stays_on_the_deployed_primary_while_it_is_unavailable_and_moves_only_when_its_listing_changes()
|
||||
{
|
||||
await using var f = LongRetryFixture(TimeSpan.FromSeconds(30), 300, ("map-r", DataRealm.Raw, 10), ("map-u", DataRealm.Uns, 10));
|
||||
foreach (var m in f.Mappings.Current) m.Mapping.ConditionStaleTimeoutMilliseconds = 60_000;
|
||||
using var demand = f.Access.AcquireEventDemand(null);
|
||||
var first = await CompleteFirstAsync(f, ("map-r", [Record(Key("x"), 3)]), ("map-u", [Record(Key("x"), 3, placement: f.UnsPlacement)]));
|
||||
await f.WaitAsync(() => f.Sink.Applied.Count >= 1);
|
||||
var rawName = f.Sink.Applied.Last().SourceName;
|
||||
rawName.ShouldStartWith("Plant/map-r/");
|
||||
first.End();
|
||||
|
||||
var second = await f.NextStreamAsync();
|
||||
second.Ack(DataItemStatus.Denied, "map-r"); // a runtime refusal, not a deployed-config change
|
||||
second.Begin("map-u", total: 1);
|
||||
second.SnapshotRecords("map-u", Record(Key("x"), 4, placement: f.UnsPlacement));
|
||||
second.Complete("map-u");
|
||||
await f.WaitAsync(() => f.Sink.Applied.Any(u => u.State.Version == 4));
|
||||
var held = f.Sink.Applied.Last(u => u.State.Version == 4);
|
||||
held.Placements.Select(p => p.MappingId).ShouldBe(["map-u"], "only the contributing placement is materialised");
|
||||
held.SourceName.ShouldBe(rawName, "SourceName does not follow a runtime refusal");
|
||||
second.End();
|
||||
|
||||
// Positive control: once the Raw mapping is known again and no longer lists x, SourceName moves.
|
||||
var third = await f.NextStreamAsync();
|
||||
third.Ack();
|
||||
third.Begin("map-r", total: 0);
|
||||
third.Complete("map-r");
|
||||
third.Begin("map-u", total: 1);
|
||||
third.SnapshotRecords("map-u", Record(Key("x"), 5, placement: f.UnsPlacement));
|
||||
third.Complete("map-u");
|
||||
await f.WaitAsync(() => f.Sink.Applied.Any(u => u.State.Version == 5));
|
||||
f.Sink.Applied.Last(u => u.State.Version == 5).SourceName.ShouldStartWith("Plant/map-u/");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task R1_NIT_consumer_resyncs_count_streams_that_opened_not_failed_connect_attempts()
|
||||
{
|
||||
var options = Fixture.DefaultOptions with { MaxReconnectDelay = TimeSpan.FromMilliseconds(100) };
|
||||
await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10));
|
||||
f.Connections.MetadataFails.Add(0); // every attempt ends before a stream opens
|
||||
using (f.Access.AcquireEventDemand(null))
|
||||
{
|
||||
await f.WaitAsync(() => Volatile.Read(ref f.Connections.MetadataCalls) >= 4);
|
||||
f.Access.Diagnostics.CaptureConsumer(Connection)!.Resyncs.ShouldBe(0);
|
||||
}
|
||||
|
||||
await using var g = new Fixture(("map-a", DataRealm.Raw, 10)); // positive control: an opened stream that ends counts
|
||||
using var demand = g.Access.AcquireEventDemand(null);
|
||||
var stream = await CompleteFirstAsync(g, ("map-a", [Record(Key("x"), 3)]));
|
||||
stream.End();
|
||||
await g.WaitAsync(() => g.Access.Diagnostics.CaptureConsumer(Connection)!.Resyncs >= 1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task R1_NIT_consumer_counters_of_a_removed_connection_are_pruned()
|
||||
{
|
||||
await using var f = LongRetryFixture(TimeSpan.FromSeconds(30), 300, ("map-a", DataRealm.Raw, 10));
|
||||
using var demand = f.Access.AcquireEventDemand(null);
|
||||
var stream = await f.NextStreamAsync();
|
||||
stream.Ack(DataItemStatus.Denied, "map-a");
|
||||
await f.WaitAsync(() => f.Sink.RefreshRequired >= 1);
|
||||
f.Access.Diagnostics.HasConsumerCounters(Connection).ShouldBeTrue();
|
||||
((List<ProjectedMappingPlacement>)f.Mappings.Current).Clear();
|
||||
f.Mappings.Raise();
|
||||
f.Access.Diagnostics.HasConsumerCounters(Connection).ShouldBeFalse();
|
||||
}
|
||||
|
||||
private sealed class Fixture : IAsyncDisposable
|
||||
{
|
||||
internal static readonly DataView DefaultRawPlacement =
|
||||
@@ -896,8 +1063,16 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
private readonly Dictionary<string, DataItemHandle> _current = new(StringComparer.Ordinal);
|
||||
private ulong _nextHandle = 100;
|
||||
|
||||
/// <summary>Every command id this stream has accepted (A4 review r1 B1).</summary>
|
||||
private readonly HashSet<string> _commandIds = new(StringComparer.Ordinal);
|
||||
|
||||
public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
// A4 review r1 B1: the real transport refuses a command id already used on the stream (GrpcDataConnection
|
||||
// `_usedCommands`, "Command capacity or duplicate command"), and the origin one still pending
|
||||
// (DataSubscriptionSession); either ends the consumer's stream. The fake enforces the stricter (transport) rule.
|
||||
lock (_commandIds)
|
||||
if (!_commandIds.Add(command.CommandId)) throw new InvalidOperationException("Command capacity or duplicate command.");
|
||||
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);
|
||||
@@ -922,6 +1097,17 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
[new DataSubscriptionItemAck(mapping, status, handle, null, status == DataItemStatus.Good ? null : "refused")]));
|
||||
}
|
||||
|
||||
/// <summary>A4 review r1 S2: acks the <paramref name="index"/>-th re-add of <paramref name="mapping"/> (a late ack), Good.</summary>
|
||||
public DataItemHandle AckAddAt(string mapping, int index)
|
||||
{
|
||||
AddSubscriptionItems add;
|
||||
lock (Adds) add = Adds.Where(a => a.Items.Any(i => i.ClientItemId == mapping)).ElementAt(index);
|
||||
var handle = new DataItemHandle(Open.SubscriptionId, Open.StreamEpoch, ++_nextHandle, 1);
|
||||
_frames.Writer.TryWrite(new DataSubscriptionAck(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, add.CommandId,
|
||||
[new DataSubscriptionItemAck(mapping, DataItemStatus.Good, handle, null, null)]));
|
||||
return handle;
|
||||
}
|
||||
|
||||
public IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync(CancellationToken cancellationToken) => _frames.Reader.ReadAllAsync(cancellationToken);
|
||||
public ValueTask DisposeAsync() { Disposed = true; _frames.Writer.TryComplete(); return ValueTask.CompletedTask; }
|
||||
|
||||
|
||||
Reference in New Issue
Block a user