perf(grpc-data): #1057 trim the projected publish path's per-value allocation; allocation-free catalog/subject resolve
Measured with GrpcDataWave3PerfTests (10k-item cohort, 100 source versions at 1k/s; numbers in the issue report).
- Core: MappedSubjectResolver.Resolve returns shared immutable resolutions (built once per subject) and compares
scope/ancestry by index (no MappedSubjectResolution + 2 enumerators per call, several calls per value);
DataOperationPolicy checks segments by index and builds its local scope key with one exact-length string.Create.
- Origin: LocalExportCatalog.TryResolve compares the view field by field instead of building 'view with { Address }'
(and LocalAddress no longer copies an exactly-spelled address); the frame Eligible check peeks the latest READY
version (PartitionedSampleHub.TryPeekReadyVersion) instead of retaining a second sample per value; TickAsync reuses
worker-owned lists (interest groups, changes via SourceInterestLease.TryReadChanges(into), delivery slice via
DeliveryScheduler.TakeSlice(into), due items) and the delivery index reuses one ready-list node per source.
- Consumer: PublishPacedAsync is a ValueTask; the cohort and RemoteSubscription walk frame items by index; renewal
prunes expired witnesses in place.
This commit is contained in:
@@ -33,6 +33,11 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
|
||||
private readonly SortedSet<(long Due, ulong Handle)> _due = new();
|
||||
private readonly LinkedList<ulong> _waiting = new();
|
||||
private readonly LinkedList<SnapshotJob> _snapshotJobs = new();
|
||||
// #1057: TickAsync's working lists; only the command worker touches them, and one tick never overlaps another.
|
||||
private readonly List<InterestGroup> _tickInterests = [];
|
||||
private readonly List<SourceInterestChange> _tickChanges = [];
|
||||
private readonly List<ScheduledInterest> _tickSlice = [];
|
||||
private readonly List<Item> _tickDue = [];
|
||||
private readonly ConcurrentQueue<SnapshotJob> _committedSnapshots = new();
|
||||
private readonly HashSet<StagedChange> _pendingChanges = new();
|
||||
private readonly SortedSet<(long Deadline, long Id)> _ackDeadlines = new();
|
||||
@@ -895,7 +900,8 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
|
||||
{ waiting.Ticket = null; waiting.WaitingNode = _waiting.AddLast(waiting.Handle.Handle); }
|
||||
}
|
||||
}
|
||||
List<InterestGroup> interests = [];
|
||||
// #1057: the tick's working lists are worker-owned and reused (a tick runs per dequeued frame under load).
|
||||
var interests = _tickInterests; interests.Clear();
|
||||
lock (_gate)
|
||||
{
|
||||
_interestCursor ??= _interests.First;
|
||||
@@ -913,9 +919,11 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
|
||||
// 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;
|
||||
var changes = _tickChanges;
|
||||
foreach (var group in interests)
|
||||
{
|
||||
if (!group.Lease.TryReadChanges(256, 4096, out var changes, out var more))
|
||||
changes.Clear();
|
||||
if (!group.Lease.TryReadChanges(256, 4096, 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
|
||||
@@ -931,14 +939,18 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
|
||||
if (behind) QueueTick();
|
||||
var availableValues = AvailableValueSlots();
|
||||
if (availableValues > 0)
|
||||
foreach (var scheduled in _scheduler.TakeSlice(Math.Min(32, availableValues)))
|
||||
{
|
||||
var slice = _tickSlice; slice.Clear();
|
||||
_scheduler.TakeSlice(Math.Min(32, availableValues), slice);
|
||||
foreach (var scheduled in slice)
|
||||
{
|
||||
Item? item;
|
||||
lock (_gate) _items.TryGetValue((ulong)scheduled.InterestId, out item);
|
||||
if (item is not null) await ConsiderAsync(item).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
var now = _services.Clock.GetTimestamp();
|
||||
var dueItems = new List<Item>();
|
||||
var dueItems = _tickDue; dueItems.Clear();
|
||||
lock (_gate)
|
||||
{
|
||||
availableValues = AvailableValueSlots();
|
||||
@@ -951,7 +963,7 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
|
||||
}
|
||||
foreach (var item in dueItems) await ConsiderAsync(item).ConfigureAwait(false);
|
||||
}
|
||||
finally { AfterTickForTests?.Invoke(); }
|
||||
finally { _tickInterests.Clear(); _tickChanges.Clear(); _tickSlice.Clear(); _tickDue.Clear(); AfterTickForTests?.Invoke(); }
|
||||
}
|
||||
|
||||
private async Task<bool> RecoverWaitingAsync(Item item, SourceTicket ticket)
|
||||
@@ -1148,9 +1160,9 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
|
||||
{
|
||||
if (snapshot) return true;
|
||||
if (item.Ticket is not { } ticket) return false;
|
||||
using var latest = _services.SubscriptionHub.Read(ticket);
|
||||
if (latest.Readiness != DataReadiness.Ready || latest.Sample is null) { CloseWithReset("Source became unavailable."); return false; }
|
||||
if (latest.Sample.Version > owned.Version)
|
||||
// #1057: only the latest version matters here — peek it instead of retaining a second copy of the sample per value.
|
||||
if (!_services.SubscriptionHub.TryPeekReadyVersion(ticket, out var latestVersion)) { CloseWithReset("Source became unavailable."); return false; }
|
||||
if (latestVersion > owned.Version)
|
||||
{
|
||||
Interlocked.Exchange(ref _coalesced, 1);
|
||||
MarkDirty(item.View.Source); QueueTick(); return false;
|
||||
|
||||
@@ -15,7 +15,7 @@ internal sealed class DeliveryScheduler
|
||||
internal readonly LinkedList<Interest> Interests = new();
|
||||
internal readonly Dictionary<long, LinkedListNode<Interest>> Index = new();
|
||||
internal LinkedListNode<Interest>? Cursor;
|
||||
internal LinkedListNode<BackingSourceKey>? ReadyNode;
|
||||
internal LinkedListNode<BackingSourceKey>? ReadyNode, Node;
|
||||
internal long ActiveGeneration, PendingGeneration;
|
||||
internal int Remaining;
|
||||
}
|
||||
@@ -71,11 +71,21 @@ internal sealed class DeliveryScheduler
|
||||
}
|
||||
}
|
||||
internal IReadOnlyList<ScheduledInterest> TakeSlice(int maximum)
|
||||
{
|
||||
var result = new List<ScheduledInterest>();
|
||||
TakeSlice(maximum, result);
|
||||
return result;
|
||||
}
|
||||
/// <summary>#1057: appends the slice into the caller's (reused) list; the origin session takes one per tick.</summary>
|
||||
internal void TakeSlice(int maximum, List<ScheduledInterest> into)
|
||||
{
|
||||
if (maximum <= 0) throw new ArgumentOutOfRangeException(nameof(maximum));
|
||||
ArgumentNullException.ThrowIfNull(into);
|
||||
lock (_gate)
|
||||
{
|
||||
var result = new List<ScheduledInterest>(Math.Min(maximum, _interests));
|
||||
var result = into;
|
||||
maximum = checked(maximum + into.Count);
|
||||
// The popped node (a bucket's own, see Queue) may be queued again below.
|
||||
while (result.Count < maximum && _ready.First is { } ready)
|
||||
{
|
||||
var source = ready.Value; _ready.RemoveFirst();
|
||||
@@ -94,12 +104,14 @@ internal sealed class DeliveryScheduler
|
||||
}
|
||||
if (b.Remaining > 0 || b.PendingGeneration > b.ActiveGeneration) Queue(source, b);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
private void Queue(BackingSourceKey source, Bucket bucket)
|
||||
{
|
||||
if (bucket.ReadyNode is null && (bucket.Remaining > 0 || bucket.PendingGeneration > bucket.ActiveGeneration))
|
||||
bucket.ReadyNode = _ready.AddLast(source);
|
||||
if (bucket.ReadyNode is not null || bucket.Remaining <= 0 && bucket.PendingGeneration <= bucket.ActiveGeneration) return;
|
||||
// #1057: a bucket is on the ready list at most once, so it reuses one node instead of allocating one per queueing.
|
||||
bucket.Node ??= new LinkedListNode<BackingSourceKey>(source);
|
||||
_ready.AddLast(bucket.Node);
|
||||
bucket.ReadyNode = bucket.Node;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -960,21 +960,25 @@ public sealed partial class GrpcDataConnection : IDataConnection, IDataPrimarySu
|
||||
// #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)
|
||||
// #1057: indexed loops — a foreach over the IReadOnlyList boxed an enumerator per pass per frame.
|
||||
var items = values.Items;
|
||||
for (var index = 0; index < items.Count; index++)
|
||||
{
|
||||
var item = items[index];
|
||||
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.");
|
||||
}
|
||||
Verify(wire.Serving, selected); linked.Token.ThrowIfCancellationRequested();
|
||||
foreach (var item in values.Items) _versions[item.Handle.Handle] = item.Sample.Version;
|
||||
for (var index = 0; index < items.Count; index++) _versions[items[index].Handle.Handle] = items[index].Sample.Version;
|
||||
if (SupportsFreshnessChallenges)
|
||||
{
|
||||
var bounded = new List<DataSubscriptionValue>(values.Items.Count);
|
||||
var bounded = new List<DataSubscriptionValue>(items.Count);
|
||||
try
|
||||
{
|
||||
foreach (var item in values.Items)
|
||||
for (var index = 0; index < items.Count; index++)
|
||||
{
|
||||
var item = items[index];
|
||||
long start;
|
||||
lock (_pending) start = item.FreshnessChallengeId is { } nonce && _freshnessStarts.TryGetValue(nonce, out var known) ? known : -1;
|
||||
var bounds = item.AgeBounds;
|
||||
|
||||
@@ -139,14 +139,21 @@ public sealed partial class LocalExportCatalog
|
||||
public bool TryResolve(DataView view, out LocalDataNode node)
|
||||
{
|
||||
var address = LocalAddress(view.Address);
|
||||
if (_nodes.TryGetValue((address, view.Realm), out var found)
|
||||
&& found.Metadata.View == (view with { Address = address }))
|
||||
if (_nodes.TryGetValue((address, view.Realm), out var found) && SameView(found.Metadata.View, view, address))
|
||||
{ node = found; return true; }
|
||||
node = null!;
|
||||
return false;
|
||||
}
|
||||
private DataAddress LocalAddress(DataAddress address) => string.Equals(address.OriginClusterId, ClusterId, StringComparison.OrdinalIgnoreCase)
|
||||
? address with { OriginClusterId = ClusterId } : address;
|
||||
// #1057: `found == (view with { Address = address })` without building the copy — the origin's publish verdict resolves
|
||||
// every subscribed item about once a second. Field for field what DataView's record equality compares.
|
||||
private static bool SameView(DataView found, DataView view, DataAddress address) =>
|
||||
found.Address == address && found.Realm == view.Realm && string.Equals(found.MappingId, view.MappingId, StringComparison.Ordinal) &&
|
||||
found.MappingRevision == view.MappingRevision && string.Equals(found.Subject, view.Subject, StringComparison.Ordinal);
|
||||
// #1057: an address already naming this cluster with its exact spelling is returned as is (no copy).
|
||||
private DataAddress LocalAddress(DataAddress address) =>
|
||||
string.Equals(address.OriginClusterId, ClusterId, StringComparison.Ordinal) ? address
|
||||
: string.Equals(address.OriginClusterId, ClusterId, StringComparison.OrdinalIgnoreCase)
|
||||
? address with { OriginClusterId = ClusterId } : address;
|
||||
/// <summary>
|
||||
/// #943: whether a per-item refusal for <paramref name="view"/> may say "exists": the node at the view's address (in
|
||||
/// its realm, whatever the view's other fields claim) is inside the principal's grant — some export rule of the
|
||||
|
||||
@@ -228,6 +228,17 @@ public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable
|
||||
BeforeReadForTests?.Invoke(ticket);
|
||||
return IsDisposed || !ValidKey(ticket.Key) ? EmptyRead(DataItemStatus.Unavailable, DataReadiness.Unavailable, 0) : Partition(ticket.Key).Read(ticket);
|
||||
}
|
||||
/// <summary>
|
||||
/// #1057: the version of the source's current READY sample, without retaining it (no read lease, sample copy or charge).
|
||||
/// False exactly where <see cref="Read"/> would not return a Ready sample for a lack of one (not current, not ready,
|
||||
/// invalidation not yet applied). For a caller that only asks "is there a newer value?".
|
||||
/// </summary>
|
||||
internal bool TryPeekReadyVersion(SourceTicket ticket, out long version)
|
||||
{
|
||||
BeforeReadForTests?.Invoke(ticket);
|
||||
version = 0;
|
||||
return !IsDisposed && ValidKey(ticket.Key) && Partition(ticket.Key).TryPeekReadyVersion(ticket, out version);
|
||||
}
|
||||
internal CachedSourceRead EmptyRead(DataItemStatus status, DataReadiness readiness, long epoch) => new(Resources, status, readiness, null, 0, epoch, 0, 0);
|
||||
internal void ProcessPending() { foreach (var partition in Volatile.Read(ref _partitions)) partition.DrainForTests(); }
|
||||
internal void DrainOneSliceForTests(BackingSourceKey key) => Partition(key).Drain();
|
||||
|
||||
@@ -1678,7 +1678,8 @@ 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,
|
||||
// #1057: a ValueTask — almost every publication completes without its capacity retry, so no Task per value.
|
||||
async ValueTask<(bool Accepted, bool Validated)> PublishPacedAsync(Registration registration, ProjectedValueUpdate update, long version,
|
||||
CancellationToken token)
|
||||
{
|
||||
for (var attempt = 0; ; attempt++)
|
||||
@@ -1890,7 +1891,9 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
registration.RenewalPredecessor is not { IsValid: true }))
|
||||
throw new InvalidDataException("The predecessor expired before its successor baseline completed.");
|
||||
foreach (var witnesses in evidence.Values)
|
||||
foreach (var expired in witnesses.Where(proof => !proof.LeaseValid).ToArray()) { expired.Close(); witnesses.Remove(expired); }
|
||||
// #1057: in place — a LINQ copy per source per renewal tick was O(sources) allocations.
|
||||
for (var i = witnesses.Count - 1; i >= 0; i--)
|
||||
if (!witnesses[i].LeaseValid) { witnesses[i].Close(); witnesses.RemoveAt(i); }
|
||||
foreach (var registration in _registrations.Values.ToArray())
|
||||
{
|
||||
var demand = registration.Demand;
|
||||
@@ -2044,8 +2047,11 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
}
|
||||
else if (frame is DataSubscriptionValues values)
|
||||
{
|
||||
foreach (var item in values.Items)
|
||||
// #1057: indexed — a foreach over the IReadOnlyList boxed an enumerator per frame.
|
||||
var valueItems = values.Items;
|
||||
for (var valueIndex = 0; valueIndex < valueItems.Count; valueIndex++)
|
||||
{
|
||||
var item = valueItems[valueIndex];
|
||||
ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.Value);
|
||||
if (!_byHandle.TryGetValue(item.Handle, out var registration)) throw new InvalidDataException("Unknown item handle.");
|
||||
// Frames queued before a remove barrier may arrive while withdrawal is pending.
|
||||
|
||||
@@ -539,6 +539,18 @@ internal sealed class SamplePartition : IDisposable
|
||||
this, state, gate, Volatile.Read(ref state.InvalidationVersion), signal, _routingEpoch);
|
||||
}
|
||||
}
|
||||
/// <summary>#1057: <see cref="Read(SourceTicket, out long)"/>'s readiness checks, returning only the sample's version.</summary>
|
||||
internal bool TryPeekReadyVersion(SourceTicket ticket, out long version)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
version = 0;
|
||||
if (_disposed || !Current(ticket, out var state) || state.Readiness != DataReadiness.Ready || state.Sample is null) return false;
|
||||
if (Volatile.Read(ref Volatile.Read(ref state.Gate).Invalidated) != state.AppliedInvalidations) return false;
|
||||
version = state.Sample.Version;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
internal void ReleaseRead(object source)
|
||||
{
|
||||
var state = (SourceState)source;
|
||||
|
||||
@@ -93,25 +93,41 @@ public sealed class SourceInterestLease : IDisposable
|
||||
/// (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)
|
||||
{
|
||||
var result = new List<SourceInterestChange>();
|
||||
changes = result;
|
||||
return TryReadChanges(maximumMatches, maximumScanned, result, out more);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #1057: as above, appending into the caller's (reused) list — the origin session reads every group on every tick, and a
|
||||
/// list per read per tick was a measurable share of the per-value allocation. On failure nothing is left appended.
|
||||
/// </summary>
|
||||
internal bool TryReadChanges(int maximumMatches, int maximumScanned, List<SourceInterestChange> into, out bool more)
|
||||
{
|
||||
if (maximumMatches <= 0 || maximumScanned <= 0) throw new ArgumentOutOfRangeException(nameof(maximumMatches));
|
||||
ArgumentNullException.ThrowIfNull(into);
|
||||
more = false;
|
||||
lock (_gate)
|
||||
{
|
||||
var result = new List<SourceInterestChange>();
|
||||
changes = result;
|
||||
var start = into.Count;
|
||||
if (IsResetLocked()) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestReset); Release(); return false; }
|
||||
var scanned = 0;
|
||||
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; }
|
||||
var matched = into.Count - start;
|
||||
if (scanned >= maximumScanned || matched >= maximumMatches) { more = true; break; }
|
||||
if (!cursor.Partition.ReadInterestChanges(cursor.Epoch, ref cursor.Position, cursor.Tickets,
|
||||
maximumMatches - result.Count, maximumScanned - scanned, result, out var used, out var behind))
|
||||
{ Release(); result.Clear(); return false; }
|
||||
maximumMatches - matched, maximumScanned - scanned, into, out var used, out var behind))
|
||||
{ Release(); into.RemoveRange(start, into.Count - start); return false; }
|
||||
scanned += used; more |= behind;
|
||||
}
|
||||
if (IsResetLocked()) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestReset); Release(); result.Clear(); return false; }
|
||||
if (IsResetLocked())
|
||||
{
|
||||
SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestReset); Release();
|
||||
into.RemoveRange(start, into.Count - start); return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user