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;
|
||||
|
||||
Reference in New Issue
Block a user