fix(grpc-data): #994 projected cohorts batch, pace and scale past one item; busy origins no longer reset quiet streams

Wave 3 of the 2026-12-02 review (docs/reviews/2026-12-02/01-runtime.md R-2/3/7/8/9/10/12/13/21/22/23/24,
02-opcuaserver.md U-10/11/12/13).

Consumer (ProjectedDataAccess cohort):
- R-2: a cohort's OpenSubscription declared a snapshot budget of 1 item, which the origin uses to size the stream's
  handle table, so the 2nd item was refused LimitExceeded and the cohort re-opened in a loop (two projected items of
  one interval broke each other). Opens/adds/removes are now batched (IDataSubscriptionCommandLimits, <=256 items,
  bounded by estimated snapshot bytes) and paced (32 burst, 32/s, <=4 commands or snapshots outstanding).
- R-7: control events no longer share the bounded frame queue; a failed Remove can no longer Stop() the cohort.
- R-10: a local capacity refusal (TryPublishOrBackpressure -> CapacityExhausted) is retried for up to 2 s instead of
  invalidating healthy evidence and retiring the route.
- R-13: RemoteSubscription mutates its handle/version tables in place; the cohort caches the source per binding and
  drops the per-sample LINQ in EvidenceFor.
- R-8: only an unselectable endpoint arms the discovery backoff; a caller cancel is OperationCanceledException.
- R-24: the condition stream cancels and observes a pending frame read before disposing the enumerator.

Origin (DataSubscriptionSession / SamplePartition / SourceInterestLease):
- R-2 (found by the perf harness): the delivery index was sized MaxPendingFrames x 16 = 1024, so the 1025th item of a
  stream stopped the session after its ack; it now covers MaxMonitoredItems.
- R-3: interest reads count only own-ticket matches (scan budget separate), re-queue a lagging tick, and catch up from
  per-source last-change versions when the bounded history rolled off - no more "Source change history expired".
- R-9: a partition quiet bump resets a lease only when one of ITS sources was invalidated (per-source quiet version)
  or its binding retired; partition-wide invalidation still resets all.
- R-12: the per-item publish verdict is memoised per (catalog instance, authority generation) for <=1 s; Commit
  under the session lock re-checks identity only.
- R-21/R-22/R-23: registry prune is interval/capacity driven; a cleared history session refuses chunks; the snapshot
  barrier is decided and armed under the same gate its release is decided under.

Node manager: U-10 projected live items indexed by node; U-11 anchor removal / root-leaf swap tombstone the anchor's
own monitored node; U-12 per-parent child count; U-13 per-condition verdict index.

Also: Issue934_r1_N1 test clears its metadata failure before ending the stream (test-only sequencing race,
reproduced with a 200 ms delay; production behaviour correct).

Perf (Category=Perf, OTOPCUA_GRPCDATA_PERF=1): 10k-item cohort opens in 3.3 s / 80 commands / 1 stream (before: never
opens); 100 source versions at 1k/s -> 11,036 item values in 569 ms.
This commit is contained in:
Joseph Doherty
2026-12-03 11:59:26 -05:00
parent b9955f6946
commit 5cccfd75ce
30 changed files with 1697 additions and 189 deletions
@@ -787,7 +787,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
Volatile.Read(ref _refreshesInFlight));
Volatile.Read(ref _dataPlaneAuthority).Changed -= OnAuthorityChanged;
foreach (var item in _liveItems.Keys.OfType<ProjectedMonitoredItem>()) item.Retire();
_liveItems.Clear();
LiveClear();
_eventItems.Clear();
_allEventsItems.Clear();
lock (Lock) _allEventsMonitoredConditions.Clear();
@@ -4436,6 +4436,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
}
}
OnProjectedFolderRemoving(nodeId);
// #994 (U-11): the anchor's OWN monitored node too, not only its descendants'. The SDK keys MonitoredNodes by NodeId
// and reuses an entry, so an event/attribute item left on the dead folder would capture every later item on the
// re-created anchor (delivery requires ReferenceEquals(monitored.Node, node)).
TombstoneMonitoredNode(nodeId, UtcNow);
_projectedAnchors.TryRemove(nodeId, out _);
_projectedRootLeaves.TryRemove(nodeId, out _);
RetireProjectedCharge(nodeId, anchor.Definition.Lifetime);
@@ -4558,7 +4562,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
foreach (var pair in _projectedDefinitions.ToArray())
{
if (_projectedRootLeaves.ContainsKey(pair.Key) || pair.Value.AuthorityIsCurrent() || IsPinnedEventFolder(pair.Key) ||
_projectedVariables.Values.Any(child => child.Parent == pair.Key) || !pair.Value.Lifetime.TryRetire()) continue;
_projectedVariables.HasChildren(pair.Key) || !pair.Value.Lifetime.TryRetire()) continue;
if (!_projectedVariables.Remove(pair.Key, out var entry)) continue;
OnProjectedFolderRemoving(pair.Key);
_projectedDefinitions.Remove(pair.Key); RemoveProjectedSample(pair.Key);
@@ -4570,7 +4574,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
foreach (var pair in _projectedAnchors.ToArray())
{
if (pair.Value.Definition.AuthorityIsCurrent() || IsPinnedEventFolder(pair.Key) ||
_projectedVariables.Values.Any(node => node.Parent == pair.Key) || !pair.Value.Definition.Lifetime.TryRetire()) continue;
_projectedVariables.HasChildren(pair.Key) || !pair.Value.Definition.Lifetime.TryRetire()) continue;
if (!_projectedAnchors.TryRemove(pair.Key, out var anchor)) continue;
OnProjectedFolderRemoving(pair.Key);
if (_projectedRootLeaves.TryRemove(pair.Key, out _))
@@ -4797,8 +4801,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
{
var source = target.Value.Snapshot.Value;
var detached = target.Value with { Snapshot = target.Value.Snapshot with { Value = source is Array array ? array.Clone() : source } };
foreach (var item in _liveItems.Keys.OfType<ProjectedMonitoredItem>())
if (item.ProjectedNodeId == target.Id && item.ObserveSample(detached)) snapshotRequests.Add(item);
// #994 (U-10): only this node's projected items — not a snapshot + type test of every live item
// on every namespace, per published value, under Lock.
foreach (var item in ProjectedLiveItemsFor(target.Id))
if (item.ObserveSample(detached)) snapshotRequests.Add(item);
target.Node.Value = SdkValueBoundary.FromClr(detached.Snapshot.Value,
target.Metadata.ValueKind == DataValueKind.Array && target.Metadata.ArrayElementKind == DataValueKind.UInt8);
target.Node.StatusCode = detached.Snapshot.StatusCode;
@@ -4851,7 +4857,48 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
DataValueKind.Timestamp => value is DateTime or DateTimeOffset, _ => false
};
private readonly Dictionary<NodeId, (NodeId Parent, long Generation, DataMetadata Metadata, BaseInstanceState Node, Func<bool> Guard)> _projectedVariables = new();
private readonly ProjectedVariableTable _projectedVariables = new();
/// <summary>
/// #994 (U-12): the projected-variable map plus a per-parent child count kept in step on every write, so "does this node
/// still have projected children" is one lookup — the eviction loop and the page-sink remove used to answer it with a
/// full <c>Values.Any(child => child.Parent == id)</c> scan per candidate (O(N²) per reservation at the node cap).
/// Writers hold Lock (as for the plain dictionary it replaces).
/// </summary>
private sealed class ProjectedVariableTable
{
private readonly Dictionary<NodeId, (NodeId Parent, long Generation, DataMetadata Metadata, BaseInstanceState Node, Func<bool> Guard)> _entries = new();
private readonly Dictionary<NodeId, int> _children = new();
internal int Count => _entries.Count;
internal Dictionary<NodeId, (NodeId Parent, long Generation, DataMetadata Metadata, BaseInstanceState Node, Func<bool> Guard)>.KeyCollection Keys => _entries.Keys;
internal bool HasChildren(NodeId parent) => _children.ContainsKey(parent);
internal bool TryGetValue(NodeId id, out (NodeId Parent, long Generation, DataMetadata Metadata, BaseInstanceState Node, Func<bool> Guard) entry) =>
_entries.TryGetValue(id, out entry);
internal (NodeId Parent, long Generation, DataMetadata Metadata, BaseInstanceState Node, Func<bool> Guard) this[NodeId id]
{
get => _entries[id];
set
{
if (_entries.TryGetValue(id, out var previous)) Release(previous.Parent);
_entries[id] = value; Retain(value.Parent);
}
}
internal void Add(NodeId id, (NodeId Parent, long Generation, DataMetadata Metadata, BaseInstanceState Node, Func<bool> Guard) entry)
{ _entries.Add(id, entry); Retain(entry.Parent); }
internal bool Remove(NodeId id) => Remove(id, out _);
internal bool Remove(NodeId id, out (NodeId Parent, long Generation, DataMetadata Metadata, BaseInstanceState Node, Func<bool> Guard) entry)
{
if (!_entries.Remove(id, out entry)) return false;
Release(entry.Parent); return true;
}
internal void Clear() { _entries.Clear(); _children.Clear(); }
private void Retain(NodeId parent) { _children.TryGetValue(parent, out var count); _children[parent] = count + 1; }
private void Release(NodeId parent)
{
if (!_children.TryGetValue(parent, out var count)) return;
if (count <= 1) _children.Remove(parent); else _children[parent] = count - 1;
}
}
bool IProjectedNamespacePageSink.TryRenewExact(NodeId nodeId, ProjectedVariableDefinition expected,
ProjectedVariableDefinition replacement, Func<bool> commit)
@@ -5048,7 +5095,13 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
_projectedNodeCharges[anchorId] = anchorCharge + charge; _projectedNodeBytes += charge; charged = true;
if (!installed.AuthorityIsCurrent() || !commit() || !installed.AuthorityIsCurrent()) return false;
CommitProjectedDefinition(anchorId, installed);
accepted = true; return true;
accepted = true;
// #994 (U-11): the folder this NodeId named is gone (swapped for the leaf variable): unwire it and tombstone its
// monitored node so no item keeps pointing at the dead folder. Only once the swap is accepted — a refused swap
// restores the folder untouched.
OnProjectedFolderRemoving(anchorId);
TombstoneMonitoredNode(anchorId, UtcNow);
return true;
}
finally
{
@@ -5070,7 +5123,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
{
if (_disposing || _projectedRootLeaves.ContainsKey(nodeId) || !_projectedDefinitions.TryGetValue(nodeId, out var current) || !ReferenceEquals(current, expected) ||
IsPinnedEventFolder(nodeId) || // A3 N7: a folder holding an admitted event item is not retired
_projectedVariables.Values.Any(child => child.Parent == nodeId) || !_projectedVariables.Remove(nodeId, out var entry)) return false;
_projectedVariables.HasChildren(nodeId) || !_projectedVariables.Remove(nodeId, out var entry)) return false;
OnProjectedFolderRemoving(nodeId);
_projectedDefinitions.Remove(nodeId); RemoveProjectedSample(nodeId); RetireProjectedCharge(nodeId, current.Lifetime);
TombstoneMonitoredNode(nodeId, UtcNow);
@@ -6836,7 +6889,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
/// </remarks>
internal void TrackLiveMonitoredItem(NodeHandle handle, ISampledDataChangeMonitoredItem monitoredItem)
{
if (OwnsNamespace(handle.NodeId)) _liveItems[monitoredItem] = new LiveItem(handle);
if (OwnsNamespace(handle.NodeId)) LiveTrack(monitoredItem, new LiveItem(handle));
if (monitoredItem is ProjectedMonitoredItem projected) TrackProjectedHealth(projected);
}
@@ -6845,7 +6898,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
ServerSystemContext context, NodeHandle handle, ISampledDataChangeMonitoredItem monitoredItem)
{
if (monitoredItem is ProjectedMonitoredItem projected) { ForgetProjectedHealth(projected); projected.Retire(); }
if (_liveItems.TryRemove(monitoredItem, out var tracked) && tracked.Suppressed) Interlocked.Decrement(ref _suppressedItems);
if (LiveUntrack(monitoredItem, out var tracked) && tracked!.Suppressed) Interlocked.Decrement(ref _suppressedItems);
base.OnMonitoredItemDeleted(context, handle, monitoredItem);
}
@@ -6931,7 +6984,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
{
if (item is ProjectedMonitoredItem projected) projected.Retire();
TellNodeRemoved(item, now);
if (item is ISampledDataChangeMonitoredItem sampled) _liveItems.TryRemove(sampled, out _);
if (item is ISampledDataChangeMonitoredItem sampled) LiveUntrack(sampled, out _);
ReleaseComponentCacheReference(item);
}
}
@@ -6988,7 +7041,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
foreach (var (item, tracked) in _liveItems)
{
if (!tracked.Suppressed || (nodeId is not null && tracked.Handle.NodeId != nodeId.Value)) continue;
if (!_liveItems.TryRemove(item, out _)) continue;
if (!LiveUntrack(item, out _)) continue;
Interlocked.Decrement(ref _suppressedItems);
if (item is ProjectedMonitoredItem projected) projected.Retire();
TellNodeRemoved(item, now);
@@ -7151,6 +7204,49 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
/// for every create and delete including subscription teardown, so the map cannot outlive the items.
/// </remarks>
private readonly ConcurrentDictionary<ISampledDataChangeMonitoredItem, LiveItem> _liveItems = new();
// #994 (U-10): the projected members of _liveItems indexed by their node, kept in step by the three helpers below (the ONLY
// writers of _liveItems). Guarded by its own small gate, never held while calling out, so TryPublish (under Lock) and the
// SDK create/delete paths (not under Lock) can both use it without a lock-order edge.
private readonly object _projectedLiveGate = new();
private readonly Dictionary<NodeId, HashSet<ProjectedMonitoredItem>> _projectedLiveByNode = new();
private static readonly ProjectedMonitoredItem[] NoProjectedItems = [];
private void LiveTrack(ISampledDataChangeMonitoredItem item, LiveItem live)
{
_liveItems[item] = live;
if (item is not ProjectedMonitoredItem projected) return;
lock (_projectedLiveGate)
{
if (!_projectedLiveByNode.TryGetValue(projected.ProjectedNodeId, out var set))
_projectedLiveByNode.Add(projected.ProjectedNodeId, set = []);
set.Add(projected);
}
}
private bool LiveUntrack(ISampledDataChangeMonitoredItem item, out LiveItem? tracked)
{
if (!_liveItems.TryRemove(item, out tracked)) return false;
if (item is ProjectedMonitoredItem projected)
lock (_projectedLiveGate)
if (_projectedLiveByNode.TryGetValue(projected.ProjectedNodeId, out var set) && set.Remove(projected) && set.Count == 0)
_projectedLiveByNode.Remove(projected.ProjectedNodeId);
return true;
}
private void LiveClear()
{
_liveItems.Clear();
lock (_projectedLiveGate) _projectedLiveByNode.Clear();
}
private ProjectedMonitoredItem[] ProjectedLiveItemsFor(NodeId nodeId)
{
lock (_projectedLiveGate)
return _projectedLiveByNode.TryGetValue(nodeId, out var set) && set.Count != 0 ? [.. set] : NoProjectedItems;
}
internal int ProjectedLiveIndexCountForTests { get { lock (_projectedLiveGate) return _projectedLiveByNode.Sum(x => x.Value.Count); } }
private readonly object _projectedHealthGate = new();
private readonly LinkedList<ProjectedMonitoredItem> _projectedHealthItems = new();
private readonly Dictionary<ProjectedMonitoredItem, LinkedListNode<ProjectedMonitoredItem>> _projectedHealthIndex = new();
@@ -8737,7 +8833,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
}
else
{
_liveItems.TryRemove(item, out _); current.Suppressed = false;
LiveUntrack(item, out _); current.Suppressed = false;
Interlocked.Decrement(ref _suppressedItems); removed = true;
}
}
@@ -8808,7 +8904,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
: ResolveNodeState(MapKey(nodeId))) is { } liveNode
&& ReferenceEquals(liveNode, tracked.Handle.Node);
if (reattached) tracked.Handle.MonitoredNode?.Add(item);
else _liveItems.TryRemove(item, out _);
else LiveUntrack(item, out _);
}
Interlocked.Decrement(ref _suppressedItems);
@@ -140,6 +140,10 @@ internal sealed class ProjectedConditionRegistry
internal static readonly TimeSpan PositiveVerdictTtl = TimeSpan.FromSeconds(5);
private readonly object _verdictGate = new();
private readonly Dictionary<(object Identity, NodeId Condition), (long Generation, long PlacementVersion, bool Allowed, DateTimeOffset ValidUntil)> _verdicts = new();
/// <summary>#994 (U-13): condition → the identities holding a cached verdict for it, so a removal purges exactly its own
/// entries instead of scanning every cached verdict (up to 65,536) under the manager Lock.</summary>
private readonly Dictionary<NodeId, HashSet<object>> _verdictIdentities = new();
internal int VerdictCountForTests { get { lock (_verdictGate) return _verdicts.Count; } }
public int Count => _byNode.Count;
public IEnumerable<ImportedCondition> All => _byNode.Values;
@@ -163,7 +167,8 @@ internal sealed class ProjectedConditionRegistry
foreach (var key in condition.Placements.Select(FolderKey).Distinct())
if (ByFolderKey.TryGetValue(key, out var set) && set.Remove(condition.Alarm.NodeId) && set.Count == 0) ByFolderKey.Remove(key);
lock (_verdictGate)
foreach (var stale in _verdicts.Keys.Where(k => k.Condition == condition.Alarm.NodeId).ToList()) _verdicts.Remove(stale);
if (_verdictIdentities.Remove(condition.Alarm.NodeId, out var identities))
foreach (var identity in identities) _verdicts.Remove((identity, condition.Alarm.NodeId));
}
public static (string, string) FolderKey(ImportedConditionPlacement p) => (p.MappingId, p.FolderLocalSubject);
@@ -192,8 +197,10 @@ internal sealed class ProjectedConditionRegistry
// only while THIS instance is still the live one (Remove drops it from _byInstance before purging under this gate),
// so a same-NodeId re-creation never inherits a verdict computed for the removed instance.
if (!_byInstance.ContainsKey(condition.Alarm)) return allowed;
if (_verdicts.Count >= 65_536) _verdicts.Clear(); // bounded: a flood of identities only costs recomputation
if (_verdicts.Count >= 65_536) { _verdicts.Clear(); _verdictIdentities.Clear(); } // bounded: a flood of identities only costs recomputation
_verdicts[key] = (generation, condition.PlacementVersion, allowed, validUntil);
if (!_verdictIdentities.TryGetValue(key.NodeId, out var identities)) _verdictIdentities.Add(key.NodeId, identities = []);
identities.Add(identity);
}
return allowed;
}
@@ -190,10 +190,15 @@ public sealed class ActorProjectedValuePublisher : IProjectedValuePublisher, IDi
NotifyRetirements();
}
public bool TryPublish(IReadOnlyList<ProjectedValueUpdate> updates)
public bool TryPublish(IReadOnlyList<ProjectedValueUpdate> updates) => Publish(updates, backpressure: false) == ProjectedPublishOutcome.Accepted;
/// <inheritdoc />
public ProjectedPublishOutcome TryPublishOrBackpressure(IReadOnlyList<ProjectedValueUpdate> updates) => Publish(updates, backpressure: true);
private ProjectedPublishOutcome Publish(IReadOnlyList<ProjectedValueUpdate> updates, bool backpressure)
{
ArgumentNullException.ThrowIfNull(updates);
if (updates.Count == 0 || updates.Count > _maximumRoutes) { Invalidate(updates); return false; }
if (updates.Count == 0 || updates.Count > _maximumRoutes) { Invalidate(updates); return ProjectedPublishOutcome.Refused; }
var captured = updates.ToArray();
var bindings = new Binding[captured.Length];
long charge = 256;
@@ -209,6 +214,7 @@ public sealed class ActorProjectedValuePublisher : IProjectedValuePublisher, IDi
charge = checked(charge + 512 + OwnedDataSample.Estimate(update.Snapshot.Value));
}
var admitted = false;
var full = false;
lock (_sync)
{
if (!_disposed && charge <= _maximumBytes - _pendingBytes)
@@ -219,7 +225,10 @@ public sealed class ActorProjectedValuePublisher : IProjectedValuePublisher, IDi
{ admitted = false; break; }
if (admitted) _pendingBytes += charge;
}
else full = !_disposed && charge <= _maximumBytes;
}
// #994 (R-10): a full pending budget is local backpressure, not invalid evidence — the proof and the route stay.
if (!admitted && full && backpressure) return ProjectedPublishOutcome.CapacityExhausted;
if (!admitted) return Refused();
}
catch (Exception error) when (error is ArgumentException or OverflowException) { return Refused(); }
@@ -239,17 +248,17 @@ public sealed class ActorProjectedValuePublisher : IProjectedValuePublisher, IDi
batch.QueueSequence = checked(++_nextQueueSequence);
_pending.Add(batch);
}
if (!batch.IsValid || Host() is not { } host) { batch.AbortQueued(); return false; }
if (!batch.IsValid || Host() is not { } host) { batch.AbortQueued(); return ProjectedPublishOutcome.Refused; }
NotifyValues(host);
return true;
return ProjectedPublishOutcome.Accepted;
}
catch (Exception)
{
if (batch is not null) batch.AbortQueued();
else { lock (_sync) _pendingBytes -= charge; Invalidate(captured); }
return false;
return ProjectedPublishOutcome.Refused;
}
bool Refused() { Invalidate(captured); return false; }
ProjectedPublishOutcome Refused() { Invalidate(captured); return ProjectedPublishOutcome.Refused; }
void Complete(ProjectedPublicationBatch completed)
{ lock (_sync) { _pending.Remove(completed); _sdkPending.Remove(completed); _pendingBytes -= charge; } }
}
@@ -704,8 +704,12 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistor
{
public ServingIdentity Serving { get; } = serving;
}
private class ScopedSubscription(DataConnectionDeploymentLease owner, IDataSubscription inner) : IDataSubscription, IDataSubscriptionFreshnessSupport
private class ScopedSubscription(DataConnectionDeploymentLease owner, IDataSubscription inner) : IDataSubscription, IDataSubscriptionFreshnessSupport,
IDataSubscriptionCommandLimits
{
/// <summary>#994 (R-2): the peer's batch limit, within the connection row's batch and monitored-item caps.</summary>
public int MaxCommandItems => Math.Min(inner is IDataSubscriptionCommandLimits { MaxCommandItems: > 0 } limits ? limits.MaxCommandItems : owner._batch,
Math.Min(owner._batch, owner._monitored));
public bool SupportsFreshnessChallenges => inner is IDataSubscriptionFreshnessSupport { SupportsFreshnessChallenges: true };
public int FreshnessMaxItems => inner is IDataSubscriptionFreshnessSupport support && support.SupportsFreshnessChallenges
? Math.Min(support.FreshnessMaxItems, Math.Min(owner._batch, owner._monitored)) : 0;
@@ -5,8 +5,10 @@ using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>One caller-bound subscription with bounded commands and one ordered delivery mode.</summary>
internal sealed partial class DataSubscriptionSession : IDataSubscriptionTransport
internal sealed partial class DataSubscriptionSession : IDataSubscriptionTransport, IDataSubscriptionCommandLimits
{
/// <summary>#994 (R-2): one command may carry up to the origin's batch limit.</summary>
public int MaxCommandItems => _services.SubscriptionLimits.MaxBatchItems;
private readonly LocalDataServices _services;
private readonly DataAuthenticatedContext _context;
private readonly DataTarget _target;
@@ -206,7 +208,12 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
{ SingleReader = true, FullMode = BoundedChannelFullMode.Wait });
_outbound = Channel.CreateBounded<PendingDelivery>(new BoundedChannelOptions(limits.MaxPendingFrames)
{ SingleReader = true, SingleWriter = true, FullMode = BoundedChannelFullMode.Wait });
_scheduler = new DeliveryScheduler(limits.MaxPendingFrames * 16, limits.MaxPendingFrames * 16);
// #994 (R-2): the delivery index must hold every item (and every distinct source) the stream may admit. It was sized
// from the frame window alone (MaxPendingFrames × 16 = 1024 by default), so the 1025th item — inside the advertised
// MaxMonitoredItems — failed registration AFTER its acknowledgement and stopped the whole session.
var schedulerCapacity = checked(Math.Max(limits.MaxPendingFrames * 16, services.SubscriptionLimits.MaxMonitoredItems) +
limits.MaxPendingFrames * 16);
_scheduler = new DeliveryScheduler(schedulerCapacity, schedulerCapacity);
var preOpen = limits.PreOpenTimeout ?? TimeSpan.FromSeconds(10);
_preOpen = services.Clock.CreateTimer(static state => ((DataSubscriptionSession)state!).Stop(), this,
preOpen, Timeout.InfiniteTimeSpan);
@@ -343,9 +350,11 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
else
{
if (_handles is null || command.SubscriptionId != _subscriptionId || command.StreamEpoch != _epoch) { Stop(); break; }
if (command is ModifySubscriptionItems && HasIncompleteSnapshot() ||
command is ChallengeSubscriptionFreshness && HasOutstandingSnapshots())
{ _deferred.Enqueue(work); retained = true; Interlocked.CompareExchange(ref _barrier, 1, 0); continue; }
// #994 (R-23): decide AND arm under the gate the SnapshotEnd commit decides its release under. A check
// released before the CAS let that commit's ReleaseBarrier(1) find 0 and no-op, after which the CAS
// armed a barrier nothing would release: every later command deferred until its ack timeout.
if (TryArmSnapshotBarrier(command))
{ AfterSnapshotBarrierCheckForTests?.Invoke(); _deferred.Enqueue(work); retained = true; continue; }
switch (command)
{
case AddSubscriptionItems add: await AddAsync(add.Items, add.CommandId, work.Started, add.AcknowledgementTimeout).ConfigureAwait(false); break;
@@ -399,6 +408,20 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
lock (_gate) return _snapshots.Count != 0;
}
internal Action? AfterSnapshotBarrierCheckForTests { get; set; }
internal Action? SnapshotEndReleasedForTests { get; set; }
private bool TryArmSnapshotBarrier(DataSubscriptionCommand command)
{
lock (_gate)
{
var defer = command is ModifySubscriptionItems && _interests.Any(group => !group.SnapshotComplete) ||
command is ChallengeSubscriptionFreshness && _snapshots.Count != 0;
if (defer) Interlocked.CompareExchange(ref _barrier, 1, 0);
return defer;
}
}
private void ReleaseBarrier(int expected)
{
if (Interlocked.CompareExchange(ref _barrier, 0, expected) != expected) return;
@@ -874,9 +897,13 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
await PumpSnapshotsAsync().ConfigureAwait(false);
await PumpConditionsAsync().ConfigureAwait(false);
BeforeDirtyTickForTests?.Invoke(_outbound.Reader.Count, Volatile.Read(ref _queuedValues), interests.Count);
// #994 (R-3): each group drains up to 256 of ITS OWN changes per tick, walking at most 4096 partition entries (unrelated
// traffic no longer eats the budget); a group still behind re-queues a tick instead of waiting 100 ms, and a group that
// fell off the bounded history catches up from per-source versions rather than resetting the stream.
var behind = false;
foreach (var group in interests)
{
if (!group.Lease.TryReadChanges(32, out var changes))
if (!group.Lease.TryReadChanges(256, 4096, out var changes, out var more))
{
// #962: a modify's ack commit runs on the delivery side and can release a group this tick captured
// above (the replaced item's interest); its disposed lease then reads like a reset. That group is gone
@@ -887,7 +914,9 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
CloseWithReset("Source change history expired."); return;
}
foreach (var change in changes) MarkDirty(change.Ticket.Key);
behind |= more;
}
if (behind) QueueTick();
var availableValues = AvailableValueSlots();
if (availableValues > 0)
foreach (var scheduled in _scheduler.TakeSlice(Math.Min(32, availableValues)))
@@ -997,6 +1026,7 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
if (job.TemporaryInterest) FinishChallengeSnapshot(job);
QueueTick();
if (allComplete) ReleaseBarrier(1);
SnapshotEndReleasedForTests?.Invoke();
}, () =>
{
job.Snapshot.Dispose(); job.Admission.Dispose();
@@ -1080,15 +1110,18 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
if (snapshotHold is not null) lease = new CompositeLease(lease, snapshotHold);
}
catch { owned.Dispose(); snapshotHold?.Dispose(); _services.SubscriptionHub.Resources.Release(charge); return null; }
bool Gate() => item.Ticket is { } ticket &&
bool Identity() => item.Ticket is { } ticket &&
(snapshotLease is null || snapshotLease.IsItemCurrent(ticket) && snapshotPermit?.IsValid == true) &&
Volatile.Read(ref _closed) == 0 && Volatile.Read(ref _closing) == 0 && _handles!.IsCurrent(item.Handle) &&
_services.SubscriptionHub.IsTicketCurrentNonBlocking(ticket) && item.View.CanPublish();
_services.SubscriptionHub.IsTicketCurrentNonBlocking(ticket);
bool Gate() => Identity() && item.View.CanPublish();
bool Commit()
{
// #994 (R-12): the frame was authorized by Gate() right before the transport write it now commits; under the session
// lock only the cheap identity fences are re-checked (the authorization walk no longer runs while holding _gate).
lock (_gate)
{
if (!Gate() || !_items.TryGetValue(item.Handle.Handle, out var current) || !ReferenceEquals(current, item)) return false;
if (!Identity() || !_items.TryGetValue(item.Handle.Handle, out var current) || !ReferenceEquals(current, item)) return false;
if (!_services.SubscriptionHub.Resources.TryReserve(charge)) return false;
var next = new BudgetLease(_services.SubscriptionHub.Resources, charge);
item.Filter.Commit(owned); item.BaselineCharge?.Dispose(); item.BaselineCharge = next;
@@ -339,23 +339,35 @@ public sealed partial class GrpcDataConnection : IDataConnection, IDataPrimarySu
admitted = await _unaryCapacity.WaitAsync(0, admission.Token).ConfigureAwait(false);
if (!admitted) throw new InvalidOperationException("Unary capacity exhausted.");
if (!ProbeAllowed()) throw new InvalidOperationException("Data endpoint discovery is backing off.");
// #994 (R-8): only an endpoint that could not be SELECTED arms the connection-wide discovery backoff. A caller's
// cancel/deadline is the caller's cancellation (never an endpoint failure), and a per-call fault after a successful
// selection (a bad node id, a refused item, an oversized answer) fails this call alone — it used to refuse every
// other subscribe/write/read on the connection for the backoff window.
var selectedAny = false;
foreach (var endpoint in _endpoints)
{
Check();
Selected selected;
try { selected = await SelectAsync(endpoint, start, budget, false, ct).ConfigureAwait(false); }
catch (Exception ex) when (ct.IsCancellationRequested && ex is RpcException or OperationCanceledException)
{ throw new OperationCanceledException("Data request cancelled by the caller.", ex, ct); }
catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException)
{ failure = ex; RecordFailure(ex); continue; }
ProbeSucceeded(); selectedAny = true;
try
{
var selected = await SelectAsync(endpoint, start, budget, false, ct).ConfigureAwait(false);
ProbeSucceeded();
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, _scope.CancellationToken, selected.Channel.Retired.Token, _shutdown.Token);
var remaining = budget with { Timeout = Remaining(start, budget) };
var result = await call(selected, remaining, Options(selected, start, budget, linked.Token)).ConfigureAwait(false);
try { linked.Token.ThrowIfCancellationRequested(); return result; }
catch { if (result is IEnumerable<ReadResult> reads) foreach (var item in reads) item.Dispose(); throw; }
}
catch (Exception ex) when (ct.IsCancellationRequested && ex is RpcException or OperationCanceledException)
{ throw new OperationCanceledException("Data request cancelled by the caller.", ex, ct); }
catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException)
{ failure = ex; RecordFailure(ex); }
}
ProbeFailed();
if (!selectedAny) ProbeFailed();
throw new InvalidOperationException("No ready authenticated data endpoint.", failure);
}
finally { if (admitted) _unaryCapacity.Release(); ExitWork(); }
@@ -686,9 +698,12 @@ public sealed partial class GrpcDataConnection : IDataConnection, IDataPrimarySu
AsyncDuplexStreamingCall<W.SubscriptionCommand, W.SubscriptionFrame> call, Selected selected,
CancellationTokenSource lifetime, bool compactNegotiated, int maxBytes, int maxItems, int maxPendingCommands,
TimeSpan maxCommandTimeout, CommandStateBudget commandBudget, Func<string, long, bool> claimEpoch, Action<WeakReference>? observePending,
Func<Task>? afterTimerCancelled, Action release) : IDataSubscription, IDataSubscriptionProvenance, IDataSubscriptionFreshnessSupport
Func<Task>? afterTimerCancelled, Action release) : IDataSubscription, IDataSubscriptionProvenance, IDataSubscriptionFreshnessSupport,
IDataSubscriptionCommandLimits
{
public ServingIdentity Serving { get; } = selected.Capabilities.Serving;
/// <summary>#994 (R-2): the origin's advertised batch limit, within this stream's own item cap.</summary>
public int MaxCommandItems => Math.Min(selected.Capabilities.Limits.MaxBatchItems, maxItems);
public bool SupportsFreshnessChallenges => selected.Capabilities.SubscriptionFreshnessChallenges && selected.Capabilities.SubscriptionAgeReadiness;
public int FreshnessMaxItems => selected.Capabilities.Limits.MaxBatchItems;
private readonly Dictionary<string, long> _freshnessStarts = new(StringComparer.Ordinal);
@@ -878,10 +893,13 @@ public sealed partial class GrpcDataConnection : IDataConnection, IDataPrimarySu
}
var requested = pending.ClientIds ?? pending.Removed!.Select(_ => (string?)null).ToArray();
if (ack.Items.Count != requested.Length) throw new InvalidOperationException("Unexpected acknowledgement count.");
var next = new Dictionary<ulong, DataItemHandle>(_handles);
var nextClients = new Dictionary<string, ulong>(_clientHandles, StringComparer.Ordinal);
var nextUsed = new HashSet<ulong>(_usedHandles);
var nextVersions = new Dictionary<ulong, long>(_versions);
// #994 (R-13): the tables are mutated IN PLACE. Only this reader touches them, and any throw below ends the
// stream (the enumerator's finally disposes it), so the copy-then-commit this replaced bought nothing but
// four whole-table copies per acknowledgement (O(N²) across an N-item open).
var next = _handles;
var nextClients = _clientHandles;
var nextUsed = _usedHandles;
var nextVersions = _versions;
for (var i = 0; i < ack.Items.Count; i++)
{
var item = ack.Items[i];
@@ -931,7 +949,6 @@ public sealed partial class GrpcDataConnection : IDataConnection, IDataPrimarySu
if (!_pending.Remove(ack.CommandId)) throw new InvalidOperationException("Acknowledgement expired.");
_pendingBytes -= pending.Bytes; commandBudget.Release(pending.Bytes);
pending.Timer.Cancel(); pending.Timer.Dispose();
_handles = next; _clientHandles = nextClients; _usedHandles = nextUsed; _versions = nextVersions;
Volatile.Write(ref DiagnosticRegistrationCount, next.Count);
}
}
@@ -940,15 +957,17 @@ public sealed partial class GrpcDataConnection : IDataConnection, IDataPrimarySu
throw new InvalidOperationException("Condition frame for an unknown handle.");
if (frame is DataSubscriptionValues values)
{
var nextVersions = new Dictionary<ulong, long>(_versions);
var seen = new HashSet<ulong>();
// #994 (R-13): validate against the live table, then apply in place (a per-frame copy of the versions
// table was ~280 KB of LOH garbage per frame at 10k handles). A throw ends the stream either way.
HashSet<ulong>? seen = values.Items.Count > 1 ? new HashSet<ulong>(values.Items.Count) : null;
foreach (var item in values.Items)
{
if (!seen.Add(item.Handle.Handle) || nextVersions.TryGetValue(item.Handle.Handle, out var previous) && item.Sample.Version < previous)
if (seen is not null && !seen.Add(item.Handle.Handle) ||
_versions.TryGetValue(item.Handle.Handle, out var previous) && item.Sample.Version < previous)
throw new InvalidOperationException("Duplicate handle or sample version regression.");
nextVersions[item.Handle.Handle] = item.Sample.Version;
}
Verify(wire.Serving, selected); linked.Token.ThrowIfCancellationRequested(); _versions = nextVersions;
Verify(wire.Serving, selected); linked.Token.ThrowIfCancellationRequested();
foreach (var item in values.Items) _versions[item.Handle.Handle] = item.Sample.Version;
if (SupportsFreshnessChallenges)
{
var bounded = new List<DataSubscriptionValue>(values.Items.Count);
@@ -45,8 +45,18 @@ public interface IProjectedValuePublisher
bool TryBind(ProjectedValueRoute route);
bool TryPublish(IReadOnlyList<ProjectedValueUpdate> updates);
void Retire(ProjectedValueRoute route);
/// <summary>
/// #994 (R-10): like <see cref="TryPublish"/>, but a refusal for lack of local capacity (pending bytes) answers
/// <see cref="ProjectedPublishOutcome.CapacityExhausted"/> WITHOUT invalidating the proof or retiring the route — the
/// evidence is fine, only the sink is momentarily full, so the caller backs off and retries.
/// </summary>
ProjectedPublishOutcome TryPublishOrBackpressure(IReadOnlyList<ProjectedValueUpdate> updates) =>
TryPublish(updates) ? ProjectedPublishOutcome.Accepted : ProjectedPublishOutcome.Refused;
}
/// <summary>#994 (R-10): the outcome of a projected publication.</summary>
public enum ProjectedPublishOutcome { Accepted, Refused, CapacityExhausted }
/// <summary>A driver facade over a configured, scoped data connection.</summary>
public sealed class GrpcDataDriverAdapter : IDriver, IBatchSubscribable, IWriteOutcomeCapability
{
@@ -183,16 +183,37 @@ public sealed partial class LocalDataServices : IDataConnectionFactory
var serving = catalog.Serving;
var consistency = string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)
? DataConsistency.Primary : DataConsistency.ReadyReplica;
// #994 (R-12): the publish verdict is re-evaluated on every delivered frame (several times). The expensive half — the
// catalog resolve, export-rule ancestry walk and ACL evaluation — is memoised against the exact catalog instance and
// authority generation it was computed for, for at most PublishVerdictTtl; the cheap readiness/serving identity checks
// run every time. Any catalog swap or authority publish (ACL, key revocation) misses the memo; a credential's expiry is
// separately enforced by the session's expiry timer.
PublishVerdict? memo = null;
authorized = new(node.Metadata.View, source, serving, node.Metadata, context.PrincipalId,
catalog.SubscriptionExportScope(context.PrincipalId, node), target, consistency, () =>
{
var current = _catalog();
return current is not null && current.Serving == serving && current.TryResolve(view, out var now) &&
now.Source == source && Allowed(current, context, now, DataOperations.Subscribe);
if (current is null || current.Serving != serving || !Ready(current)) return false;
var epoch = _policy.AuthorityEpoch;
var now = Clock.GetTimestamp();
var cached = Volatile.Read(ref memo);
if (cached is not null && ReferenceEquals(cached.Catalog, current) && cached.AuthorityEpoch == epoch &&
Clock.GetElapsedTime(cached.At, now) < PublishVerdictTtl)
return cached.Allowed;
Interlocked.Increment(ref _publishVerdictEvaluations);
var allowed = current.TryResolve(view, out var resolved) && resolved.Source == source &&
Allowed(current, context, resolved, DataOperations.Subscribe);
Volatile.Write(ref memo, new PublishVerdict(current, epoch, now, allowed));
return allowed;
});
return DataItemStatus.Good;
}
/// <summary>#994 (R-12): how long a memoised per-item publish verdict may be reused for the same catalog + authority.</summary>
internal static readonly TimeSpan PublishVerdictTtl = TimeSpan.FromSeconds(1);
private sealed record PublishVerdict(LocalExportCatalog Catalog, long AuthorityEpoch, long At, bool Allowed);
private long _publishVerdictEvaluations;
internal long PublishVerdictEvaluationsForTests => Interlocked.Read(ref _publishVerdictEvaluations);
internal PartitionedSampleHub SubscriptionHub => _hub;
internal DataLimits SubscriptionLimits => _capabilities.Limits;
internal int SubscriptionItemLimit(DataAuthenticatedContext context)
@@ -17,6 +17,9 @@ internal sealed class OriginHistorySession
private readonly TimeProvider _clock;
private readonly OriginHistorySessions _owner;
private CancellationTokenRegistration _closed;
// #994 (R-22): set under _gate by Clear. A request that still holds this (now orphaned) session must not store a chunk in
// it — nothing would ever sweep it, and its bytes would stay charged to the principal for the life of the process.
private bool _cleared;
internal OriginHistorySession(OriginHistorySessions owner, string principal, string channelId, int capacity, TimeProvider clock)
{
@@ -84,7 +87,7 @@ internal sealed class OriginHistorySession
lock (_gate)
{
Sweep(_clock.GetTimestamp());
if (_chunks.Count >= Capacity)
if (_cleared || _chunks.Count >= Capacity)
{
_owner.ReleaseBytes(Principal, chunk.Bytes);
return null;
@@ -126,7 +129,7 @@ internal sealed class OriginHistorySession
_closed.Unregister();
Cursors.Clear();
Chunk[] dropped;
lock (_gate) { dropped = _chunks.Values.ToArray(); _chunks.Clear(); }
lock (_gate) { _cleared = true; dropped = _chunks.Values.ToArray(); _chunks.Clear(); }
foreach (var chunk in dropped) Drop(chunk);
}
@@ -294,6 +294,7 @@ public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable
var controls = new Dictionary<int, long>();
var quietControls = new Dictionary<int, long>();
var owners = new Dictionary<SourceTicket, (SamplePartition Partition, object Source)>();
var quietVersions = new Dictionary<SourceTicket, long>();
long snapshotCharge = 0, interestCharge = 0;
try
{
@@ -304,7 +305,7 @@ public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable
long watermark = 0, epoch = 0, control = 0, quietControl = 0;
var ok = !cancellationToken.IsCancellationRequested && routing == RoutingEpoch && partitions[group.Key].RoutingEpoch == routing && partitions[group.Key].Control.TryCapture(out control) &&
partitions[group.Key].Control.Quiet.TryCapture(out quietControl) &&
partitions[group.Key].CaptureAndRegister(group.ToArray(), items, captured, out watermark,
partitions[group.Key].CaptureAndRegister(group.ToArray(), items, captured, quietVersions, out watermark,
out epoch, ref snapshotCharge, ref interestCharge, Math.Min(budget.MaxBytes, _limits.MaxSnapshotBytes), admission);
foreach (var pair in captured) owners.Add(pair.Key, (partitions[group.Key], pair.Value));
if (!ok || !partitions[group.Key].Control.Matches(control) || !partitions[group.Key].Control.Quiet.Matches(quietControl)) return false;
@@ -316,7 +317,7 @@ public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable
snapshot = new SnapshotLease(this, items, watermarks, epochs, controls, partitions, routing, snapshotCharge, tickets.Count,
budget.Timeout < _limits.MaxSnapshotLifetime ? budget.Timeout : _limits.MaxSnapshotLifetime, cancellationToken);
snapshotCharge = 0; items = null!; _snapshots.TryAdd(snapshot, 0);
interest = new SourceInterestLease(this, owners, watermarks, epochs, quietControls, routing, interestCharge, cancellationToken);
interest = new SourceInterestLease(this, owners, watermarks, epochs, quietControls, quietVersions, routing, interestCharge, cancellationToken);
interestCharge = 0; owners = null!; _interests.TryAdd(interest, 0);
if (!snapshot.IsReset && !interest.IsReset) return true;
snapshot.Dispose(); ForgetSnapshot(snapshot); interest.Dispose(); snapshot = null; interest = null; return false;
@@ -550,13 +550,18 @@ public sealed partial class ProjectedConditionAccess
// 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);
// #994 (R-24): the frame read can be left pending across loop iterations; the teardown cancels it and observes it
// BEFORE disposing the enumerator (an async iterator disposed mid-MoveNextAsync throws NotSupportedException, which
// replaced the stream's real failure in the "stream ended" log and left `next` to fault unobserved).
using var frameStop = CancellationTokenSource.CreateLinkedTokenSource(token);
IAsyncEnumerator<DataSubscriptionFrame>? frames = null;
Task<bool>? next = null;
try
{
await subscription.SendAsync(new OpenSubscription(subscriptionId, epoch, "open", TimeSpan.FromSeconds(30), items, false,
TimeSpan.FromMinutes(60), new DataBudget(TimeSpan.FromSeconds(30), 1000, 4 * 1024 * 1024)), token).ConfigureAwait(false);
using var barrierTimer = _owner._clock.CreateTimer(_ => timeout.TrySetResult(), null, snapshotTimeout, Timeout.InfiniteTimeSpan);
await using var frames = subscription.ReadAllAsync(token).GetAsyncEnumerator(token);
Task<bool>? next = null;
frames = subscription.ReadAllAsync(frameStop.Token).GetAsyncEnumerator(frameStop.Token);
while (true)
{
if (!barrierPassed && timeout.Task.IsCompleted)
@@ -626,6 +631,7 @@ public sealed partial class ProjectedConditionAccess
}
finally
{
await ProjectedStreamTeardown.StopAsync(frameStop, next, frames).ConfigureAwait(false);
retryTimer?.Dispose();
fetches.Cancel();
// #933 review r1 S2: the hold clock pauses while no stream is past its barrier.
@@ -1226,3 +1232,17 @@ public sealed partial class ProjectedConditionAccess
}
}
}
/// <summary>
/// #994 (R-24): ends a frame loop that may have a <c>MoveNextAsync</c> still in flight — cancel it, observe it, then dispose
/// the enumerator. Never throws: the loop's own failure (if any) is the one the caller reports.
/// </summary>
internal static class ProjectedStreamTeardown
{
internal static async Task StopAsync<T>(CancellationTokenSource stop, Task<bool>? pending, IAsyncEnumerator<T>? enumerator)
{
try { await stop.CancelAsync().ConfigureAwait(false); } catch (Exception) { }
if (pending is not null) { try { await pending.ConfigureAwait(false); } catch (Exception) { } }
if (enumerator is not null) { try { await enumerator.DisposeAsync().ConfigureAwait(false); } catch (Exception) { } }
}
}
@@ -1248,21 +1248,55 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
private sealed record RenewalEvent : Event;
private sealed record RenewedEvent(Demand Demand, Demand.Binding Expected, bool Success) : Event;
private sealed record EndEvent : Event;
/// <summary>#994 (R-2): the command pacer has a slot again; flush the queued adds/removes/challenges.</summary>
private sealed record FlushEvent : Event;
private sealed class Registration(Demand demand, string id)
{
internal readonly Demand Demand = demand; internal readonly string Id = id;
internal DataItemHandle? Handle; internal bool Removed, Rebinding, Recovery, AwaitingCurrent, NeedsChallenge, HasBaseline, Renewal;
internal IDataAuthorizationLease? RenewalPredecessor;
// #994 (R-13): the source this registration last published through, for the binding it was resolved under — a
// sample re-resolves (global lock, key allocation, read-source sweep) only when the binding moved or the source
// was retired (an invalidated source answers IsValid = false).
internal SourceState? CachedSource; internal Demand.Binding? CachedBinding;
}
private readonly ProjectedDataAccess _owner;
private CohortKey _key;
private readonly string _connectionId;
// #994 (R-7): ONE unbounded event channel. Control events (add/remove/refresh/renewal/flush) are bounded by the demand
// set itself (one add and one remove per demand, a refresh deduplicated per demand, timer ticks deduplicated by flag), so
// enqueueing one can never fail — a failed Remove used to Stop() the whole cohort and dispose every sibling demand.
// Value frames keep their backpressure through _frameSlots (and the _frameBytes budget), so a slow consumer still
// stalls the pump rather than growing memory.
private readonly Channel<Event> _events;
private readonly SemaphoreSlim _frameSlots;
private readonly CancellationTokenSource _stop = new();
private readonly Dictionary<Demand, Registration> _registrations = new();
private readonly Dictionary<string, Registration> _byId = new(StringComparer.Ordinal);
private readonly Dictionary<DataItemHandle, Registration> _byHandle = new();
private readonly Dictionary<string, Registration> _removing = new(StringComparer.Ordinal);
private readonly Dictionary<string, List<Registration>> _removing = new(StringComparer.Ordinal);
// #994 (R-2): a per-cohort command pacer. The origin admits MaxCommandsPerSecond (default 128) commands per principal
// and STOPS the session past it; batching keeps a whole open to a handful of commands, and the pacer bounds a churn
// of single adds/removes (each lets the queue grow, so the next send carries more items). Kept across attempts.
internal const int CommandBurst = 32;
internal const double CommandsPerSecond = 32;
/// <summary>
/// The most commands this cohort leaves un-acknowledged at once. The origin reserves its session's MaxPendingBytes
/// from the node-wide hub budget for every queued command (64 MiB / 1 MiB by default, shared by every session), so
/// a cohort must not flood it — a refused reservation fails the command and the whole attempt.
/// </summary>
internal const int MaxOutstandingCommands = 4;
/// <summary>Items per command when the stream does not advertise its peer's batch limit.</summary>
internal const int DefaultCommandItems = 64;
private double _commandTokens;
private long _commandTokenStamp;
private int _flushQueued;
// #994 (R-10): a publication the local sink refused for capacity is retried after a short wait (backpressure on this
// loop, so the pump and the origin back up) instead of invalidating healthy evidence; only after the bound does it
// fall back to the fail-closed invalidation (which re-snapshots). Both fields belong to the attempt loop's thread.
internal const int CapacityRetries = 200;
internal static readonly TimeSpan CapacityRetryDelay = TimeSpan.FromMilliseconds(10);
private bool _capacityRetryAllowed, _capacityRefused;
// Guarded by the owner's lock; at most one queued or active refresh per demand.
private readonly HashSet<Demand> _refreshRequests = [];
private string _id = string.Empty;
@@ -1276,11 +1310,15 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
internal Cohort(ProjectedDataAccess owner, CohortKey key, string connectionId)
{
_owner = owner; _key = key; _connectionId = connectionId;
_events = Channel.CreateBounded<Event>(new BoundedChannelOptions(Math.Clamp(owner._limits.MaxDemands * 2, 4, 128))
{ SingleReader = true, FullMode = BoundedChannelFullMode.Wait });
_events = Channel.CreateUnbounded<Event>(new UnboundedChannelOptions { SingleReader = true });
var frames = Math.Clamp(owner._limits.MaxDemands * 2, 4, 128);
_frameSlots = new SemaphoreSlim(frames, frames);
_commandTokens = CommandBurst; _commandTokenStamp = owner.Clock.GetTimestamp();
}
internal bool Add(Demand demand) => _events.Writer.TryWrite(new AddEvent(demand));
internal void Remove(Demand demand) { if (!_events.Writer.TryWrite(new RemoveEvent(demand))) Stop(); }
// #994 (R-7): never tears the cohort down. The unbounded channel only refuses once completed (it never is); a disposed
// demand that is somehow not dequeued is reconciled by the next attempt's ReleaseDemand pass.
internal void Remove(Demand demand) => _events.Writer.TryWrite(new RemoveEvent(demand));
internal void Start() { if (Interlocked.Exchange(ref _started, 1) == 0) _ = Task.Run(RunAsync); }
internal void Stop() { if (Interlocked.Exchange(ref _closing, 1) == 0) _ = _stop.CancelAsync(); }
internal bool Refresh(Demand demand)
@@ -1305,12 +1343,71 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
checked(x.Sample.Value.EstimatedRetainedBytes + 2L * (x.FreshnessChallengeId?.Length ?? 0)))) : 512L;
if (bytes > _owner._limits.MaxUnaryBytes || Interlocked.Add(ref _frameBytes, bytes) > _owner._limits.MaxUnaryBytes)
{ Interlocked.Add(ref _frameBytes, -bytes); (frame as IDisposable)?.Dispose(); break; }
try { await _events.Writer.WriteAsync(new FrameEvent(frame, bytes, receivedTimestamp), attemptStop).ConfigureAwait(false); }
// #994 (R-7): frames wait for a slot; control events never do (they share the channel, not the bound).
try { await _frameSlots.WaitAsync(attemptStop).ConfigureAwait(false); }
catch { Interlocked.Add(ref _frameBytes, -bytes); (frame as IDisposable)?.Dispose(); throw; }
if (!_events.Writer.TryWrite(new FrameEvent(frame, bytes, receivedTimestamp)))
{ _frameSlots.Release(); Interlocked.Add(ref _frameBytes, -bytes); (frame as IDisposable)?.Dispose(); break; }
}
}
catch (Exception) { }
finally { try { await _events.Writer.WriteAsync(new EndEvent(), attemptStop).ConfigureAwait(false); } catch (OperationCanceledException) { } }
finally { _events.Writer.TryWrite(new EndEvent()); }
}
/// <summary>#994 (R-2): the hard ceiling of items per command — the origin acquires each item's demand inside the
/// command's acknowledgement deadline, so a command must stay small enough to be answered in time.</summary>
internal const int MaxCommandItemsCap = 256;
internal static int CommandItemsFor(IDataSubscription stream, int maxDemands)
{
var advertised = stream is IDataSubscriptionCommandLimits { MaxCommandItems: > 0 } limits ? limits.MaxCommandItems : DefaultCommandItems;
return Math.Max(1, Math.Min(Math.Min(advertised, MaxCommandItemsCap), Math.Max(1, maxDemands)));
}
/// <summary>
/// #994 (R-2): how many queued registrations fit one add command: at most <paramref name="commandItems"/>, and their
/// estimated command bytes and snapshot bytes (each answered item is one snapshot value, which the attempt holds
/// until the snapshot end and caps at <paramref name="maxBytes"/>) stay within half of <paramref name="maxBytes"/>.
/// </summary>
private static int AddBatchSize(List<Registration> queue, int commandItems, long maxBytes)
{
var budget = Math.Max(1, maxBytes / 2); long used = 0; var count = 0;
foreach (var registration in queue)
{
if (count >= commandItems) break;
var cost = ItemCostBytes(registration.Demand, registration.Id);
if (count > 0 && used + cost > budget) break;
used += cost; count++;
}
return Math.Max(1, count);
}
private static long ItemCostBytes(Demand demand, string clientItemId)
{
var view = demand.OriginView;
long wire = 512L + 2L * ((long)clientItemId.Length + (view.Subject?.Length ?? 0) + (view.MappingId?.Length ?? 0) +
(view.Address?.OriginClusterId?.Length ?? 0) + (view.Address?.NamespaceUri?.Length ?? 0) +
(view.Address?.IdentifierKind?.Length ?? 0) + (view.Address?.Identifier?.Length ?? 0));
var metadata = demand.Proof.OriginMetadata;
long value = metadata.ValueKind switch
{
DataValueKind.Array when metadata.ValueRank == 1 && metadata.Dimensions.Count == 1 && metadata.Dimensions[0] > 0 &&
metadata.ArrayElementKind is { } element && IsFixedSizeKind(element) => 512L + ProjectedFixedElementBytes * metadata.Dimensions[0],
var kind when IsFixedSizeKind(kind) => 1024L,
_ => ProjectedEnvelopeBytes,
};
return Math.Max(wire, value);
}
private bool TryTakeCommandToken()
{
var now = _owner.Clock.GetTimestamp();
var elapsed = Math.Max(0, _owner.Clock.GetElapsedTime(_commandTokenStamp, now).TotalSeconds);
_commandTokenStamp = now;
_commandTokens = Math.Min(CommandBurst, _commandTokens + elapsed * CommandsPerSecond);
if (_commandTokens < 1) return false;
_commandTokens -= 1; return true;
}
private void ArmFlush(ITimer? timer)
{
if (timer is null) return;
var wait = TimeSpan.FromSeconds(Math.Max(0, 1 - _commandTokens) / CommandsPerSecond) + TimeSpan.FromMilliseconds(1);
try { timer.Change(wait, Timeout.InfiniteTimeSpan); } catch (ObjectDisposedException) { }
}
private DataSubscriptionItem Item(Registration registration) => new(registration.Id, registration.Demand.OriginView,
new DataSubscriptionSettings(_key.Interval, _key.Interval, ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataChangeTrigger.StatusValueTimestamp, null));
@@ -1523,7 +1620,13 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
var demandSources = new Dictionary<Demand, SourceState>();
var renewals = new Dictionary<Demand, Task>();
var renewalQueued = 0;
var pendingCommands = new Dictionary<string, Registration>();
var pendingCommands = new Dictionary<string, List<Registration>>(StringComparer.Ordinal);
// #994 (R-2): registrations waiting for an add (open) command, and handles waiting for a remove command. Both are
// flushed in batches by FlushAsync — never one command per item.
var addQueue = new List<Registration>();
var removeQueue = new List<Registration>();
ITimer? flushTimer = null;
var commandItems = DefaultCommandItems;
var snapshotQueue = new Queue<HashSet<Registration>>();
HashSet<Registration>? snapshotOwners = null;
void EnqueueSnapshot(HashSet<Registration> owners)
@@ -1542,8 +1645,13 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
AttemptProof EvidenceFor(SourceState source, ProjectedNodeProof proof)
{
if (!evidence.TryGetValue(source, out var witnesses)) evidence[source] = witnesses = [];
foreach (var expired in witnesses.Where(witness => !witness.LeaseValid).ToArray()) { expired.Close(); witnesses.Remove(expired); }
var existing = witnesses.Find(witness => witness.Matches(proof));
AttemptProof? existing = null;
for (var i = witnesses.Count - 1; i >= 0; i--)
{
var witness = witnesses[i];
if (!witness.LeaseValid) { witness.Close(); witnesses.RemoveAt(i); }
else if (existing is null && witness.Matches(proof)) existing = witness;
}
if (existing is not null) return existing;
if (witnesses.Count >= 2) throw new InvalidDataException("Too many overlapping authority witnesses.");
var created = new AttemptProof(source, proof); witnesses.Add(created); return created;
@@ -1554,6 +1662,15 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
EvidenceFor(source, demand.Proof);
demandSources[demand] = source;
}
// #994 (R-2): a demand removed while its add was still queued (never sent) is dropped here, exactly as a removal
// acknowledgement would drop it.
void DropUnsent(Registration registration)
{
_registrations.Remove(registration.Demand); _byId.Remove(registration.Id);
UntrackSource(registration.Demand, registration.Renewal);
FinishRefresh(registration.Demand);
ReleaseDemand(registration.Demand);
}
void UntrackSource(Demand demand, bool preserve = false)
{
if (!demandSources.Remove(demand, out var source)) return;
@@ -1561,12 +1678,64 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
if (preserve) return;
if (evidence.Remove(source, out var witnesses)) foreach (var proof in witnesses) proof.Close();
}
async Task<(bool Accepted, bool Validated)> PublishPacedAsync(Registration registration, ProjectedValueUpdate update, long version,
CancellationToken token)
{
for (var attempt = 0; ; attempt++)
{
_capacityRetryAllowed = attempt < CapacityRetries; _capacityRefused = false;
var accepted = Publish(registration, update, version, out var validated);
if (!_capacityRefused) return (accepted, validated);
await Task.Delay(CapacityRetryDelay, token).ConfigureAwait(false);
}
}
// Commands not yet acknowledged AND snapshots not yet finished: the origin holds a snapshot admission per add and per
// challenge until its SnapshotEnd is delivered (MaxStreamsPerPrincipal per principal), and refusing one resets the stream.
int Outstanding() => pendingCommands.Count + _removing.Count + (challengeId is null ? 0 : 1) + snapshotQueue.Count + (inSnapshot ? 1 : 0);
bool TryTakeCommandSlot()
{
if (Outstanding() >= MaxOutstandingCommands) return false; // the next ack flushes again
if (TryTakeCommandToken()) return true;
ArmFlush(flushTimer);
return false;
}
async Task FlushAsync(CancellationToken token)
{
// Removes first: they free origin capacity the adds may need.
while (opened && removeQueue.Count > 0)
{
if (!TryTakeCommandSlot()) return;
var count = Math.Min(removeQueue.Count, commandItems);
var batch = removeQueue.GetRange(0, count); removeQueue.RemoveRange(0, count);
var commandId = Guid.NewGuid().ToString("N"); _removing[commandId] = batch;
await stream!.SendAsync(new RemoveSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5),
batch.Select(x => x.Handle!).ToArray()), token).ConfigureAwait(false);
}
while (addQueue.Count > 0)
{
if (!TryTakeCommandSlot()) return;
var count = AddBatchSize(addQueue, commandItems, _owner._limits.MaxUnaryBytes);
var batch = addQueue.GetRange(0, count); addQueue.RemoveRange(0, count);
var commandId = Guid.NewGuid().ToString("N"); pendingCommands.Add(commandId, batch);
var items = batch.Select(Item).ToArray();
// The open's snapshot budget also sizes the origin's handle table for the stream: it must cover every
// demand this cohort may carry (it used to be 1, so a second item was refused LimitExceeded forever).
DataSubscriptionCommand command = !opened
? new OpenSubscription(_id, _epoch, commandId, TimeSpan.FromSeconds(5), items, false, TimeSpan.FromMinutes(1),
new(TimeSpan.FromSeconds(5), Math.Max(1, _owner._limits.MaxDemands), _owner._limits.MaxUnaryBytes))
: new AddSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), items);
await stream!.SendAsync(command, token).ConfigureAwait(false); opened = true;
}
await ChallengeAsync(token).ConfigureAwait(false);
}
async Task ChallengeAsync(CancellationToken token)
{
if (challengeId is not null || stream is not IDataSubscriptionFreshnessSupport { SupportsFreshnessChallenges: true } support) return;
var chosen = _registrations.Values.Where(x => x.NeedsChallenge && !x.Removed && x.Demand.IsValid && x.Handle is not null)
.Take(Math.Min(128, support.FreshnessMaxItems)).ToArray();
var limit = Math.Min(commandItems, support.FreshnessMaxItems);
var chosen = _registrations.Values.Where(x => x.NeedsChallenge && !x.Removed && x.Handle is not null && x.Demand.IsValid)
.Take(Math.Max(1, limit)).ToArray();
if (chosen.Length == 0) return;
if (!TryTakeCommandSlot()) return;
foreach (var item in chosen) item.NeedsChallenge = false;
challengeId = "freshness-" + checked(++challengeSequence).ToString(System.Globalization.CultureInfo.InvariantCulture);
await stream.SendAsync(new ChallengeSubscriptionFreshness(_id, _epoch, challengeId, TimeSpan.FromSeconds(5),
@@ -1621,6 +1790,14 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
{ Interlocked.Decrement(ref _owner._renewalTicksQueued); Interlocked.Exchange(ref renewalQueued, 0); }
}
}, null, renewalInterval, renewalInterval);
commandItems = CommandItemsFor(stream, _owner._limits.MaxDemands);
flushTimer = _owner.Clock.CreateTimer(static state =>
{
var cohort = (Cohort)state!;
if (Interlocked.Exchange(ref cohort._flushQueued, 1) == 0 && !cohort._events.Writer.TryWrite(new FlushEvent()))
Interlocked.Exchange(ref cohort._flushQueued, 0);
}, this, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
Interlocked.Exchange(ref _flushQueued, 0);
pump = PumpAsync(stream, route.Token);
foreach (var demand in initial)
{
@@ -1629,17 +1806,25 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
TrackSource(demand);
var registration = new Registration(demand, Guid.NewGuid().ToString("N")) { Recovery = _epoch > 1 };
_registrations[demand] = registration; _byId[registration.Id] = registration;
var commandId = Guid.NewGuid().ToString("N"); pendingCommands.Add(commandId, registration);
DataSubscriptionCommand command = !opened
? new OpenSubscription(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [Item(registration)], false, TimeSpan.FromMinutes(1), new(TimeSpan.FromSeconds(5), 1, _owner._limits.MaxUnaryBytes))
: new AddSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [Item(registration)]);
await stream.SendAsync(command, route.Token).ConfigureAwait(false); opened = true;
addQueue.Add(registration);
}
// A temporarily unavailable proof must not leave an unopened stream parked
// forever. Retry the bounded attempt after backoff so renewal can make it usable.
if (!opened) return;
await foreach (var message in _events.Reader.ReadAllAsync(route.Token).ConfigureAwait(false))
if (addQueue.Count == 0) return;
await FlushAsync(route.Token).ConfigureAwait(false);
var sinceFlush = 0;
while (true)
{
// #994 (R-2): queued adds/removes go out whenever the event queue momentarily drains (or every 64 events
// under a sustained frame stream), so a burst of control events becomes a few batched commands.
if (!_events.Reader.TryRead(out var message))
{
sinceFlush = 0;
await FlushAsync(route.Token).ConfigureAwait(false);
message = await _events.Reader.ReadAsync(route.Token).ConfigureAwait(false);
}
else if (++sinceFlush >= 64) { sinceFlush = 0; await FlushAsync(route.Token).ConfigureAwait(false); }
if (message is FlushEvent) { Interlocked.Exchange(ref _flushQueued, 0); continue; }
if (message is AddEvent add)
{
lock (_owner._sync)
@@ -1656,11 +1841,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
Math.Min(TimeSpan.FromMilliseconds(250).Ticks, addedLease.UsableDuration.Ticks / 4)));
if (nextInterval < renewalInterval) { renewalInterval = nextInterval; renewalTimer.Change(nextInterval, nextInterval); }
}
var commandId = Guid.NewGuid().ToString("N"); pendingCommands.Add(commandId, registration);
DataSubscriptionCommand command = !opened
? new OpenSubscription(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [Item(registration)], false, TimeSpan.FromMinutes(1), new(TimeSpan.FromSeconds(5), 1, _owner._limits.MaxUnaryBytes))
: new AddSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [Item(registration)]);
await stream.SendAsync(command, route.Token).ConfigureAwait(false); opened = true;
addQueue.Add(registration);
}
else if (message is RefreshEvent refresh)
{
@@ -1674,11 +1855,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
continue;
}
registration.Removed = true; registration.Rebinding = true;
if (registration.Handle is { } handle)
{
var commandId = Guid.NewGuid().ToString("N"); _removing[commandId] = registration;
await stream.SendAsync(new RemoveSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [handle]), route.Token).ConfigureAwait(false);
}
if (registration.Handle is not null) removeQueue.Add(registration);
}
else if (message is RemoveEvent remove)
{
@@ -1689,11 +1866,9 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
if (!registration.Removed)
{
registration.Removed = true;
if (registration.Handle is { } handle)
{
var commandId = Guid.NewGuid().ToString("N"); _removing[commandId] = registration;
await stream.SendAsync(new RemoveSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [handle]), route.Token).ConfigureAwait(false);
}
if (registration.Handle is not null) removeQueue.Add(registration);
// Never acknowledged yet: its add may still be queued here — drop it rather than open it.
else if (addQueue.Remove(registration)) { DropUnsent(registration); }
}
}
else ReleaseDemand(remove.Demand);
@@ -1704,7 +1879,6 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
Interlocked.Exchange(ref _freshnessQueued, 0);
if (_registrations.Values.Any(x => !x.Removed && !x.Demand.IsValid)) break;
foreach (var registration in _registrations.Values) registration.NeedsChallenge = true;
await ChallengeAsync(route.Token).ConfigureAwait(false);
}
else if (message is RenewalEvent)
{
@@ -1746,11 +1920,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
renewed.Expected.NodePin.Dispose(); renewed.Expected.Pin.Dispose();
registration.Removed = true; registration.Rebinding = true; registration.Renewal = true;
registration.RenewalPredecessor = renewed.Expected.Proof.Lease;
if (registration.Handle is { } handle)
{
var commandId = Guid.NewGuid().ToString("N"); _removing[commandId] = registration;
await stream.SendAsync(new RemoveSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [handle]), route.Token).ConfigureAwait(false);
}
if (registration.Handle is not null) removeQueue.Add(registration);
}
else if (message is EndEvent) break;
else if (message is FrameEvent delivered)
@@ -1769,49 +1939,53 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
if (ack.Items.Any(x => x.Status != DataItemStatus.Good || x.Handle is null ||
!_byHandle.TryGetValue(x.Handle, out var current) || current.Id != x.ClientItemId)) throw new InvalidDataException("Invalid freshness acknowledgement.");
EnqueueSnapshot(ack.Items.Select(x => _byHandle[x.Handle!]).ToHashSet());
await ChallengeAsync(route.Token).ConfigureAwait(false);
}
else if (_removing.Remove(ack.CommandId, out var removed))
else if (_removing.Remove(ack.CommandId, out var removedBatch))
{
if (ack.Items.Count != 1 || ack.Items[0].Status != DataItemStatus.Good || ack.Items[0].Handle != removed.Handle || ack.Items[0].ClientItemId != removed.Id) throw new InvalidDataException("Invalid removal acknowledgement.");
_registrations.Remove(removed.Demand); _byId.Remove(removed.Id);
if (removed.Handle is { } removedHandle) _byHandle.Remove(removedHandle);
UntrackSource(removed.Demand, removed.Renewal);
if (removed.Rebinding && removed.Demand.IsValid)
if (ack.Items.Count != removedBatch.Count) throw new InvalidDataException("Invalid removal acknowledgement.");
for (var i = 0; i < removedBatch.Count; i++)
{
var replacement = new Registration(removed.Demand, Guid.NewGuid().ToString("N"))
{ Recovery = true, Renewal = removed.Renewal, RenewalPredecessor = removed.RenewalPredecessor };
_registrations[removed.Demand] = replacement; _byId[replacement.Id] = replacement;
TrackSource(removed.Demand);
var commandId = Guid.NewGuid().ToString("N"); pendingCommands.Add(commandId, replacement);
await stream.SendAsync(new AddSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [Item(replacement)]), route.Token).ConfigureAwait(false);
continue;
var removed = removedBatch[i]; var answer = ack.Items[i];
if (answer.Status != DataItemStatus.Good || answer.Handle != removed.Handle || answer.ClientItemId != removed.Id) throw new InvalidDataException("Invalid removal acknowledgement.");
_registrations.Remove(removed.Demand); _byId.Remove(removed.Id);
if (removed.Handle is { } removedHandle) _byHandle.Remove(removedHandle);
UntrackSource(removed.Demand, removed.Renewal);
if (removed.Rebinding && removed.Demand.IsValid)
{
var replacement = new Registration(removed.Demand, Guid.NewGuid().ToString("N"))
{ Recovery = true, Renewal = removed.Renewal, RenewalPredecessor = removed.RenewalPredecessor };
_registrations[removed.Demand] = replacement; _byId[replacement.Id] = replacement;
TrackSource(removed.Demand);
addQueue.Add(replacement);
continue;
}
FinishRefresh(removed.Demand);
ReleaseDemand(removed.Demand);
}
FinishRefresh(removed.Demand);
ReleaseDemand(removed.Demand);
}
else
{
if (!pendingCommands.Remove(ack.CommandId, out var expected) || ack.Items.Count != 1 ||
ack.Items[0].ClientItemId != expected.Id) throw new InvalidDataException("Unexpected snapshot acknowledgement.");
var response = ack.Items[0];
if (!_byId.TryGetValue(response.ClientItemId, out var registration) || response.Status != DataItemStatus.Good || response.Handle is null) throw new InvalidDataException("Invalid item acknowledgement.");
registration.Handle = response.Handle; _byHandle[response.Handle] = registration;
EnqueueSnapshot([registration]);
registration.NeedsChallenge = true;
if (!pendingCommands.Remove(ack.CommandId, out var expectedBatch) || ack.Items.Count != expectedBatch.Count)
throw new InvalidDataException("Unexpected snapshot acknowledgement.");
var owners = new HashSet<Registration>();
for (var i = 0; i < expectedBatch.Count; i++)
{
var response = ack.Items[i];
if (response.ClientItemId != expectedBatch[i].Id) throw new InvalidDataException("Unexpected snapshot acknowledgement.");
if (!_byId.TryGetValue(response.ClientItemId, out var registration) || response.Status != DataItemStatus.Good || response.Handle is null) throw new InvalidDataException("Invalid item acknowledgement.");
registration.Handle = response.Handle; _byHandle[response.Handle] = registration;
owners.Add(registration);
registration.NeedsChallenge = true;
if (registration.Removed) removeQueue.Add(registration);
}
EnqueueSnapshot(owners);
if (freshnessTimer is not null)
{
var milliseconds = Math.Clamp(_registrations.Values.Min(x => x.Demand.MaximumSampleAge.TotalMilliseconds) / 2, 50, 5000);
var interval = TimeSpan.FromMilliseconds(milliseconds);
freshnessTimer.Change(interval, interval);
}
if (registration.Removed)
{
var commandId = Guid.NewGuid().ToString("N"); _removing[commandId] = registration;
await stream.SendAsync(new RemoveSubscriptionItems(_id, _epoch, commandId, TimeSpan.FromSeconds(5), [response.Handle]), route.Token).ConfigureAwait(false);
}
}
await ChallengeAsync(route.Token).ConfigureAwait(false);
}
else if (frame is DataSubscriptionControl control)
{
@@ -1828,7 +2002,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
if (!inSnapshot) throw new InvalidDataException("Snapshot end without begin.");
foreach (var item in pending)
{
var accepted = Publish(item.Registration, item.Update with { IsCompleteSnapshot = true }, item.Version, out var validated);
var (accepted, validated) = await PublishPacedAsync(item.Registration, item.Update with { IsCompleteSnapshot = true }, item.Version, route.Token).ConfigureAwait(false);
if (!accepted && item.Registration.Recovery && item.Update.SourceProof is AttemptProof recoveryProof)
{
var recoverySource = recoveryProof.Source;
@@ -1883,7 +2057,15 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
if (!item.AgeBounds.Advance(_owner.Clock.GetElapsedTime(ageTimestamp, _owner.Clock.GetTimestamp())).IsFresh(registration.Demand.MaximumSampleAge))
{ ProjectedStreamDiagnostics.Count(item.AgeBounds.Upper is null ? ProjectedStreamDiagnostics.Event.UnknownAge : ProjectedStreamDiagnostics.Event.StaleAge); continue; }
ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.FreshAge);
var source = _owner.GetSource(registration.Demand, _connectionId); if (source is null) throw new InvalidDataException("Source unavailable.");
var binding = registration.Demand.CurrentBinding;
SourceState source;
if (registration.CachedSource is { } cachedSource && ReferenceEquals(registration.CachedBinding, binding) && cachedSource.IsValid)
source = cachedSource;
else
{
source = _owner.GetSource(registration.Demand, _connectionId) ?? throw new InvalidDataException("Source unavailable.");
registration.CachedSource = source; registration.CachedBinding = binding;
}
if (demandSources.TryGetValue(registration.Demand, out var priorSource) && !ReferenceEquals(priorSource, source))
UntrackSource(registration.Demand);
demandSources[registration.Demand] = source;
@@ -1906,14 +2088,14 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
// handle ready before its own snapshot barrier ends.
if (!registration.HasBaseline && !registration.AwaitingCurrent) continue;
var recovery = registration.Recovery && registration.AwaitingCurrent;
var accepted = Publish(registration, recovery ? update with { IsCompleteSnapshot = true } : update, sample.Version, out var validated);
var (accepted, validated) = await PublishPacedAsync(registration, recovery ? update with { IsCompleteSnapshot = true } : update, sample.Version, route.Token).ConfigureAwait(false);
if (recovery && (accepted || validated))
{ registration.HasBaseline = true; registration.Recovery = false; registration.AwaitingCurrent = false; FinishRefresh(registration.Demand); }
}
}
}
}
finally { Interlocked.Add(ref _frameBytes, -delivered.Bytes); (frame as IDisposable)?.Dispose(); }
finally { _frameSlots.Release(); Interlocked.Add(ref _frameBytes, -delivered.Bytes); (frame as IDisposable)?.Dispose(); }
}
}
}
@@ -1925,6 +2107,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
try { await attemptStop.CancelAsync().ConfigureAwait(false); } catch (Exception) { }
freshnessTimer?.Dispose();
renewalTimer?.Dispose();
flushTimer?.Dispose();
try { await Task.WhenAll(renewals.Values).ConfigureAwait(false); } catch (Exception) { }
try { if (stream is not null) await stream.DisposeAsync().ConfigureAwait(false); }
catch (Exception) { }
@@ -1936,7 +2119,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
while (_events.Reader.TryRead(out var remaining))
{
if (remaining is RenewalEvent) Interlocked.Increment(ref _owner._renewalTicksHandled);
else if (remaining is FrameEvent f) { Interlocked.Add(ref _frameBytes, -f.Bytes); (f.Frame as IDisposable)?.Dispose(); }
else if (remaining is FrameEvent f) { _frameSlots.Release(); Interlocked.Add(ref _frameBytes, -f.Bytes); (f.Frame as IDisposable)?.Dispose(); }
}
lock (_owner._sync) _refreshRequests.Clear();
}
@@ -1976,7 +2159,12 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
source.HasFreshCachedLocked(registration.Demand)) return false;
// A demand disposed since the check above publishes nothing (it is no longer anyone's subscription).
if (!registration.Demand.IsValid) { validated = false; ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishDemand); return false; }
if (_owner._publisher.TryPublish([update]))
var outcome = _owner._publisher.TryPublishOrBackpressure([update]);
if (outcome == ProjectedPublishOutcome.CapacityExhausted && _capacityRetryAllowed)
{ _capacityRefused = true; validated = false; ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishSink); return false; }
if (outcome == ProjectedPublishOutcome.CapacityExhausted)
try { update.SourceProof.Invalidate(); } catch (Exception) { } // the bound passed: fail closed as a refusal does
if (outcome == ProjectedPublishOutcome.Accepted)
{
if (successor is not null)
{
@@ -86,7 +86,7 @@ internal sealed class SamplePartition : IDisposable
Volatile.Write(ref state.Gate, new SourceGate(ticket.Generation, ticket.Binding));
state.AppliedInvalidations = 0;
state.LastApplied = 0; state.Barrier = 0; ReleaseCache(state);
RecordChange(ticket.Key); return true;
RecordChange(state); return true;
}
var charge = SourceCharge(ticket.Key);
if (!_hub.TryTrackSource()) { InvalidatePartition(); return false; }
@@ -151,6 +151,7 @@ internal sealed class SamplePartition : IDisposable
}
Interlocked.Increment(ref gate.Invalidated);
Interlocked.Increment(ref gate.ProducerStamp);
Interlocked.Increment(ref state.QuietVersion);
}
finally { Control.EndQuiet(); }
}
@@ -308,7 +309,7 @@ internal sealed class SamplePartition : IDisposable
private void InvalidateSource(SourceState state)
{
Control.BeginQuiet();
try { state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); ReleaseCache(state); }
try { state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); Interlocked.Increment(ref state.QuietVersion); ReleaseCache(state); }
finally { Control.EndQuiet(); }
}
@@ -343,7 +344,7 @@ internal sealed class SamplePartition : IDisposable
{
if (_queuedControls >= _hub.Limits.MaxControlItemsPerPartition || !_hub.Resources.TryReserve(ControlOverhead))
{ state.Removed = true; ticket.Binding!.Retire(); Interlocked.Exchange(ref state.Gate.Retired, 1); RequestReclaim(); InvalidatePartition(); return false; }
state.Removed = true; ticket.Binding!.Retire(); Interlocked.Exchange(ref state.Gate.Retired, 1); state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); Interlocked.Increment(ref state.Gate.ProducerStamp); ReleaseCache(state);
state.Removed = true; ticket.Binding!.Retire(); Interlocked.Exchange(ref state.Gate.Retired, 1); state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); Interlocked.Increment(ref state.Gate.ProducerStamp); Interlocked.Increment(ref state.QuietVersion); ReleaseCache(state);
}
finally { Control.EndQuiet(); }
RequestReclaim();
@@ -429,7 +430,7 @@ internal sealed class SamplePartition : IDisposable
else if (state.Sample is null) state.Readiness = DataReadiness.WaitingForInitialData;
_hub.Resources.Release(p.Charge);
}
RecordChange(p.Ticket.Key);
RecordChange(state);
}
if (!_disposed) ReclaimTombstones();
}
@@ -444,9 +445,11 @@ internal sealed class SamplePartition : IDisposable
lock (_gate) if (_queue.Count == 0 && _mailbox.IsEmpty && _dirty.IsEmpty) return;
}
}
private void RecordChange(BackingSourceKey key)
private void RecordChange(SourceState state)
{
var key = state.Ticket.Key;
_watermark++;
state.LastChange = _watermark;
if (_changes.Count == _hub.Limits.MaxSnapshotCatchUpItems)
{ _changeIndex.Remove(_changes.First!.Value.Version); _changes.RemoveFirst(); _hub.Resources.Release(ChangeOverhead); }
if (!_hub.Resources.TryReserve(ChangeOverhead)) { InvalidatePartition(); return; }
@@ -578,7 +581,7 @@ internal sealed class SamplePartition : IDisposable
}
}
internal bool CaptureAndRegister(IReadOnlyList<SourceTicket> tickets, Dictionary<SourceTicket, SnapshotItem> items,
Dictionary<SourceTicket, object> interests, out long watermark, out long epoch,
Dictionary<SourceTicket, object> interests, Dictionary<SourceTicket, long> quietVersions, out long watermark, out long epoch,
ref long snapshotCharge, ref long interestCharge, long limit, SnapshotAdmissionScheduler.Permit? admission)
{
lock (_gate)
@@ -592,31 +595,60 @@ internal sealed class SamplePartition : IDisposable
interestCharge += PartitionedSampleHub.ReferenceOverhead;
Interlocked.Increment(ref state.MetadataOwners);
interests.Add(ticket, state);
// Read inside the caller's quiet capture window (it re-checks the partition quiet stamp afterwards).
quietVersions[ticket] = Interlocked.Read(ref state.QuietVersion);
}
return true;
}
}
internal void ReleaseInterest(object source) => ReleaseMetadataOwner((SourceState)source);
/// <summary>#994 (R-9): the source's quiet version (see <see cref="SourceState.QuietVersion"/>); lock-free.</summary>
internal static long QuietVersionOf(object source) => Interlocked.Read(ref ((SourceState)source).QuietVersion);
internal bool ReadInterestChanges(long epoch, ref long position, IReadOnlyDictionary<BackingSourceKey, SourceTicket> tickets,
int maximum, List<SourceInterestChange> changes, out int scanned)
int maximum, List<SourceInterestChange> changes, out int scanned) =>
ReadInterestChanges(epoch, ref position, tickets, maximum, int.MaxValue, changes, out scanned, out _);
/// <summary>
/// #994 (R-3): reads this lease's changes since <paramref name="position"/>. At most <paramref name="maximumMatches"/>
/// changes of ITS OWN tickets are returned and at most <paramref name="maximumScanned"/> partition entries walked
/// (unrelated traffic no longer consumes the match budget); <paramref name="more"/> says the cursor is still behind.
/// When the bounded history no longer reaches the cursor (busy unrelated sources rolled it off) the lease catches
/// up from each own source's <see cref="SourceState.LastChange"/> — O(own tickets) — instead of resetting the stream.
/// </summary>
internal bool ReadInterestChanges(long epoch, ref long position, IReadOnlyDictionary<BackingSourceKey, SourceTicket> tickets,
int maximumMatches, int maximumScanned, List<SourceInterestChange> changes, out int scanned, out bool more)
{
scanned = 0;
scanned = 0; more = false;
lock (_gate)
{
if (_disposed || epoch != _epoch) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestEpoch); return false; }
if (position == _watermark) return true;
if (!_changeIndex.TryGetValue(position + 1, out var node)) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestHistoryGap); return false; }
while (node is not null && scanned < maximum)
if (!_changeIndex.TryGetValue(position + 1, out var node))
{
SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestHistoryGap);
foreach (var ticket in tickets.Values)
{
scanned++;
if (!_sources.TryGetValue(ticket.Key, out var state) || state.LastChange <= position) continue;
if (!Current(ticket, out _)) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestTicket); return false; }
changes.Add(new(ticket, state.LastChange));
}
position = _watermark;
return true;
}
var matched = 0;
while (node is not null && matched < maximumMatches && scanned < maximumScanned)
{
var change = node.Value; position = change.Version; scanned++;
if (tickets.TryGetValue(change.Key, out var ticket))
{
if (!Current(ticket, out _)) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestTicket); return false; }
changes.Add(new(ticket, change.Version));
changes.Add(new(ticket, change.Version)); matched++;
}
node = node.Next;
}
more = position != _watermark;
return true;
}
}
@@ -678,6 +710,13 @@ internal sealed class SamplePartition : IDisposable
public bool Removed; public DataReadiness Readiness = DataReadiness.WaitingForInitialData;
public DataSample? Sample; public long SampleCharge; public long Received;
public long LastApplied; public long Barrier; public long InvalidationVersion; public Pending? Dirty;
/// <summary>#994 (R-3): the partition watermark of this source's latest recorded change (under the partition gate).</summary>
public long LastChange;
/// <summary>
/// #994 (R-9): bumped INSIDE every quiet bracket that invalidates this source (Signal, InvalidateSource, TryRemove),
/// so an interest lease can tell its own sources' invalidation from a sibling's partition-wide quiet bump.
/// </summary>
public long QuietVersion;
}
private sealed class Pending
{
@@ -12,12 +12,14 @@ public sealed class SourceInterestLease : IDisposable
internal readonly SamplePartition Partition = partition;
internal long Position = position;
internal readonly long Epoch = epoch;
internal readonly long QuietControl = quietControl;
// #994 (R-9): advanced (under the lease gate) once a partition quiet bump is proven to concern only OTHER sources.
internal long QuietControl = quietControl;
internal readonly Dictionary<BackingSourceKey, SourceTicket> Tickets = tickets;
}
private readonly object _gate = new();
private readonly PartitionedSampleHub _hub;
private readonly Dictionary<SourceTicket, (SamplePartition Partition, object Source)> _owners;
private readonly Dictionary<SourceTicket, long> _quietVersions;
private Cursor[] _cursors;
private readonly long _routingEpoch;
private long _charge;
@@ -27,9 +29,9 @@ public sealed class SourceInterestLease : IDisposable
internal SourceInterestLease(PartitionedSampleHub hub,
Dictionary<SourceTicket, (SamplePartition Partition, object Source)> owners,
IReadOnlyDictionary<int, long> watermarks, IReadOnlyDictionary<int, long> epochs, IReadOnlyDictionary<int, long> quietControls,
long routingEpoch, long charge, CancellationToken cancellationToken)
Dictionary<SourceTicket, long> quietVersions, long routingEpoch, long charge, CancellationToken cancellationToken)
{
_hub = hub; _owners = owners; _routingEpoch = routingEpoch; _charge = charge;
_hub = hub; _owners = owners; _quietVersions = quietVersions; _routingEpoch = routingEpoch; _charge = charge;
_cursors = owners.GroupBy(x => x.Value.Partition.Id).Select(group => new Cursor(group.First().Value.Partition,
watermarks[group.Key], epochs[group.Key], quietControls[group.Key], group.ToDictionary(x => x.Key.Key, x => x.Key))).ToArray();
_cancellation = cancellationToken.Register(static state => ((SourceInterestLease)state!).Dispose(), this);
@@ -39,6 +41,7 @@ public sealed class SourceInterestLease : IDisposable
lock (_gate)
{
if (_released != 0 || !_owners.Remove(ticket, out var owner)) return false;
_quietVersions.Remove(ticket);
foreach (var cursor in _cursors) cursor.Tickets.Remove(ticket.Key);
_cursors = _cursors.Where(cursor => cursor.Tickets.Count != 0).ToArray();
if (_next >= _cursors.Length) _next = 0;
@@ -52,33 +55,63 @@ public sealed class SourceInterestLease : IDisposable
}
public bool IsReset
{
get
get { lock (_gate) return IsResetLocked(); }
}
/// <summary>
/// #994 (R-9): a partition's quiet stamp moves for ANY source's invalidation (including ordinary lock contention on a
/// sibling). It resets this lease only when one of its OWN sources was invalidated (its quiet version moved) or its
/// binding was retired; otherwise the cursor adopts the new stamp. An in-progress bracket is undecided, not a reset —
/// the next read decides it. Partition-wide invalidation still resets through the partition epoch.
/// </summary>
private bool IsResetLocked()
{
if (_released != 0 || _hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch) return true;
foreach (var cursor in _cursors)
{
if (Volatile.Read(ref _released) != 0 || _hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch) return true;
foreach (var cursor in Volatile.Read(ref _cursors))
if (!cursor.Partition.Control.Quiet.Matches(cursor.QuietControl)) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestQuiet); return true; }
return Volatile.Read(ref _released) != 0 || _hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch;
var quiet = cursor.Partition.Control.Quiet;
if (quiet.Matches(cursor.QuietControl)) continue;
if (!quiet.TryCapture(out var now)) continue;
foreach (var ticket in cursor.Tickets.Values)
{
if (!_owners.TryGetValue(ticket, out var owner) || !_quietVersions.TryGetValue(ticket, out var captured) ||
SamplePartition.QuietVersionOf(owner.Source) != captured || !cursor.Partition.IsTicketCurrentNonBlocking(ticket))
{ SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestQuiet); return true; }
}
cursor.QuietControl = now;
}
return _hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch;
}
/// <summary>Scans at most maximum retained partition changes, returning false on a gap or epoch reset.</summary>
public bool TryReadChanges(int maximum, out IReadOnlyList<SourceInterestChange> changes)
public bool TryReadChanges(int maximum, out IReadOnlyList<SourceInterestChange> changes) =>
TryReadChanges(maximum, maximum, out changes, out _);
/// <summary>
/// #994 (R-3): returns at most <paramref name="maximumMatches"/> changes of this lease's own sources, walking at most
/// <paramref name="maximumScanned"/> partition entries; <paramref name="more"/> is true when a cursor is still behind
/// (the caller re-queues instead of waiting for its next timer tick).
/// </summary>
public bool TryReadChanges(int maximumMatches, int maximumScanned, out IReadOnlyList<SourceInterestChange> changes, out bool more)
{
if (maximum <= 0) throw new ArgumentOutOfRangeException(nameof(maximum));
if (maximumMatches <= 0 || maximumScanned <= 0) throw new ArgumentOutOfRangeException(nameof(maximumMatches));
more = false;
lock (_gate)
{
var result = new List<SourceInterestChange>();
changes = result;
if (IsReset) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestReset); Release(); return false; }
if (IsResetLocked()) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestReset); Release(); return false; }
var scanned = 0;
for (var visited = 0; visited < _cursors.Length && scanned < maximum; visited++)
for (var visited = 0; visited < _cursors.Length; visited++)
{
var cursor = _cursors[_next]; _next = (_next + 1) % _cursors.Length;
if (scanned >= maximumScanned || result.Count >= maximumMatches) { more = true; break; }
if (!cursor.Partition.ReadInterestChanges(cursor.Epoch, ref cursor.Position, cursor.Tickets,
maximum - scanned, result, out var used)) { Release(); result.Clear(); return false; }
scanned += used;
maximumMatches - result.Count, maximumScanned - scanned, result, out var used, out var behind))
{ Release(); result.Clear(); return false; }
scanned += used; more |= behind;
}
if (IsReset) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestReset); Release(); result.Clear(); return false; }
if (IsResetLocked()) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestReset); Release(); result.Clear(); return false; }
return true;
}
}
@@ -89,7 +122,7 @@ public sealed class SourceInterestLease : IDisposable
_cancellation.Unregister();
var count = _owners.Count;
foreach (var owner in _owners.Values) owner.Partition.ReleaseInterest(owner.Source);
_owners.Clear(); _cursors = [];
_owners.Clear(); _quietVersions.Clear(); _cursors = [];
_hub.Resources.Release(_charge); _hub.UntrackInterestItems(count);
}
_hub.ForgetInterest(this);
@@ -20,6 +20,7 @@ public sealed class WriteOperationRegistry
private readonly TimeSpan _retention;
private readonly TimeProvider _clock;
private long _retainedBytes;
private long _lastPrune;
/// <param name="maxEntriesPerPrincipal">
/// A2b security review: the most entries one principal may hold at once (null ⇒ <paramref name="maxEntries"/>, i.e.
@@ -52,14 +53,28 @@ public sealed class WriteOperationRegistry
var bytes = 256L + 2L * principal.Length + 2L * operationId.Length + semanticHash.Length;
lock (_gate)
{
Prune();
// #994 (R-21): the full retirement sweep runs at most once per prune interval, or when the table would refuse —
// it used to copy and scan the whole table on every claim (~retention × writes/s entries, under this lock). An
// expired entry met by key is retired on the spot, so a reused operation id past retention is a fresh owner exactly
// as before, and capacity is never refused while a retirable entry remains.
var now = _clock.GetTimestamp();
if (_clock.GetElapsedTime(_lastPrune, now) >= PruneInterval) Prune(now);
var key = (principal, operationId);
if (_entries.TryGetValue(key, out var existing))
return existing.Hash.AsSpan().SequenceEqual(semanticHash.Span)
? new(WriteClaimKind.Existing, existing.Claim) : new(WriteClaimKind.Conflict);
{
if (!existing.Claim.CanRetire(now, _retention))
return existing.Hash.AsSpan().SequenceEqual(semanticHash.Span)
? new(WriteClaimKind.Existing, existing.Claim) : new(WriteClaimKind.Conflict);
Remove(key, existing);
}
_perPrincipal.TryGetValue(principal, out var held);
if (_entries.Count >= _maxEntries || held >= _maxEntriesPerPrincipal || bytes > _maxBytes - _retainedBytes)
return new(WriteClaimKind.Capacity);
{
Prune(now);
_perPrincipal.TryGetValue(principal, out held);
if (_entries.Count >= _maxEntries || held >= _maxEntriesPerPrincipal || bytes > _maxBytes - _retainedBytes)
return new(WriteClaimKind.Capacity);
}
var claim = new WriteClaim(_clock);
_entries.Add(key, new Entry(semanticHash.ToArray(), claim, bytes));
_perPrincipal[principal] = held + 1;
@@ -101,10 +116,13 @@ public sealed class WriteOperationRegistry
}
}
private void Prune()
private TimeSpan PruneInterval => _retention < TimeSpan.FromSeconds(4) ? _retention / 4 : TimeSpan.FromSeconds(1);
private void Prune(long now)
{
var now = _clock.GetTimestamp();
foreach (var pair in _entries.ToArray())
_lastPrune = now;
// Removing during enumeration is supported by Dictionary<,> (no copy of the table).
foreach (var pair in _entries)
{
if (!pair.Value.Claim.CanRetire(now, _retention)) continue;
Remove(pair.Key, pair.Value);