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:
Joseph Doherty
2026-12-03 15:31:31 -05:00
parent 3d73f4d7d5
commit a6e5ae8aa2
12 changed files with 323 additions and 47 deletions
@@ -122,7 +122,7 @@ public sealed class DataOperationPolicy
if (scope is null || caller is null || !snapshot.HasArtifact || string.IsNullOrWhiteSpace(snapshot.ClusterId)
|| !string.Equals(scope.ClusterId, snapshot.ClusterId, StringComparison.OrdinalIgnoreCase)
|| !Enum.IsDefined(operation) || (scope.Kind != NodeHierarchyKind.Raw && scope.Kind != NodeHierarchyKind.Uns)
|| scope.Segments is null || scope.Segments.Any(string.IsNullOrEmpty)
|| scope.Segments is null || HasEmptySegment(scope.Segments)
|| !CredentialUsable(snapshot, caller, allowLegacyUnversionedKey)) return false;
var key = new DataAuthorizationCacheKey(snapshot.GenerationId, caller, operation,
@@ -141,12 +141,46 @@ public sealed class DataOperationPolicy
return allowed && ReferenceEquals(snapshot, _authority.Current) && CredentialUsable(snapshot, caller, allowLegacyUnversionedKey);
}
private static string LocalScopeKey(NodeScope scope)
// #1057: indexed — Any() over an IReadOnlyList allocated an enumerator on every authorization (several per projected value).
private static bool HasEmptySegment(IReadOnlyList<string> segments)
{
var key = new StringBuilder().Append((int)scope.Kind).Append(':').Append(scope.ClusterId.Length)
.Append(':').Append(scope.ClusterId);
foreach (var segment in scope.Segments) key.Append(':').Append(segment.Length).Append(':').Append(segment);
return key.ToString();
for (var i = 0; i < segments.Count; i++)
if (string.IsNullOrEmpty(segments[i])) return true;
return false;
}
// "{kind}:{len}:{cluster}" then ":{len}:{segment}" per segment. #1057: built in one exact-length string (no StringBuilder and
// its buffers) — the origin's publish verdict asks for it per subscribed item about once a second.
internal static string LocalScopeKey(NodeScope scope)
{
var segments = scope.Segments;
var length = Digits((int)scope.Kind) + 1 + Digits(scope.ClusterId.Length) + 1 + scope.ClusterId.Length;
for (var i = 0; i < segments.Count; i++) length = checked(length + 2 + Digits(segments[i].Length) + segments[i].Length);
return string.Create(length, scope, static (span, scope) =>
{
var position = 0;
Write(span, ref position, (int)scope.Kind); span[position++] = ':';
Write(span, ref position, scope.ClusterId.Length); span[position++] = ':';
scope.ClusterId.CopyTo(span[position..]); position += scope.ClusterId.Length;
var segments = scope.Segments;
for (var i = 0; i < segments.Count; i++)
{
span[position++] = ':'; Write(span, ref position, segments[i].Length); span[position++] = ':';
segments[i].CopyTo(span[position..]); position += segments[i].Length;
}
});
static int Digits(int value)
{
if (value < 0) return value.ToString(System.Globalization.CultureInfo.InvariantCulture).Length;
var digits = 1;
while (value >= 10) { value /= 10; digits++; }
return digits;
}
static void Write(Span<char> span, ref int position, int value)
{
value.TryFormat(span[position..], out var written, default, System.Globalization.CultureInfo.InvariantCulture);
position += written;
}
}
private bool Walk(DataPlaneAuthoritySnapshot snapshot, DataCallerIdentity caller, OpcUaOperation operation, NodeScope scope)
@@ -5,8 +5,12 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Authorization;
/// <summary>Immutable, generation-bound projection of deployed mapped subjects.</summary>
public sealed class MappedSubjectResolver
{
private readonly Dictionary<DataView, MappedNamespaceSubject?> _subjects = new();
// #1057: each subject's Mapped resolution is built once here; Resolve runs per projected value (several times) and allocated
// a result record plus two sequence enumerators per call.
private readonly Dictionary<DataView, MappedSubjectResolution?> _subjects = new();
private readonly long _catalogEpoch;
private static readonly MappedSubjectResolution Deny = new(MappedSubjectResolutionKind.Deny);
private static readonly MappedSubjectResolution Local = new(MappedSubjectResolutionKind.Local);
/// <summary>The subjects must come from the trusted deployed catalog, never a request.</summary>
public MappedSubjectResolver(IEnumerable<MappedNamespaceSubject> authoritativeSubjects, long catalogEpoch,
@@ -18,30 +22,33 @@ public sealed class MappedSubjectResolver
foreach (var subject in authoritativeSubjects)
{
var copy = Copy(subject);
if (!_subjects.TryAdd(copy.View, copy)) _subjects[copy.View] = null;
if (!_subjects.TryAdd(copy.View, new(MappedSubjectResolutionKind.Mapped, copy))) _subjects[copy.View] = null;
}
}
/// <summary>The trusted local activation captured alongside this immutable projection.</summary>
public IDataMappedCatalogAuthority LocalAuthority { get; }
/// <summary>Compares request and live evidence before any cached grant or local fallback is used.</summary>
/// <summary>
/// Compares request and live evidence before any cached grant or local fallback is used. Allocation-free (#1057): the
/// returned resolutions are shared, immutable instances.
/// </summary>
public MappedSubjectResolution Resolve(DataView requested, MappedNamespaceSubject? live)
{
if (requested is null) return new(MappedSubjectResolutionKind.Deny);
if (requested is null) return Deny;
if (live is null)
return requested.MappingId is null ? new(MappedSubjectResolutionKind.Local) : new(MappedSubjectResolutionKind.Deny);
return requested.MappingId is null ? Local : Deny;
if (requested.MappingId is null || _catalogEpoch <= 0 || live.Serving.CatalogEpoch != _catalogEpoch
|| !LocalAuthority.IsActive || LocalAuthority.CatalogEpoch <= 0 || LocalAuthority.AuthorityEpoch <= 0)
return new(MappedSubjectResolutionKind.Deny);
return Deny;
if (!_subjects.TryGetValue(requested, out var found) || found is null
if (!_subjects.TryGetValue(requested, out var resolution) || resolution?.Subject is not { } found
|| found.Serving.CatalogEpoch != _catalogEpoch || !Matches(found, live)
|| found.View.MappingRevision <= 0 || string.IsNullOrWhiteSpace(found.View.MappingId)
|| string.IsNullOrWhiteSpace(found.View.Subject)
|| found.View.Realm != (found.Scope.Kind == NodeHierarchyKind.Raw ? DataRealm.Raw : DataRealm.Uns))
return new(MappedSubjectResolutionKind.Deny);
return new(MappedSubjectResolutionKind.Mapped, found);
return Deny;
return resolution;
}
private static bool Matches(MappedNamespaceSubject x, MappedNamespaceSubject y) =>
@@ -49,8 +56,18 @@ public sealed class MappedSubjectResolver
&& x.WriteThrough == y.WriteThrough
&& string.Equals(x.Scope.ClusterId, y.Scope.ClusterId, StringComparison.OrdinalIgnoreCase)
&& x.Scope.Kind == y.Scope.Kind
&& x.Scope.Segments.SequenceEqual(y.Scope.Segments, StringComparer.Ordinal)
&& x.LocalAncestry.SequenceEqual(y.LocalAncestry, StringComparer.OrdinalIgnoreCase);
&& SameSequence(x.Scope.Segments, y.Scope.Segments, StringComparer.Ordinal)
&& SameSequence(x.LocalAncestry, y.LocalAncestry, StringComparer.OrdinalIgnoreCase);
// Indexed: SequenceEqual over IReadOnlyList allocated an enumerator per side.
private static bool SameSequence(IReadOnlyList<string> x, IReadOnlyList<string> y, StringComparer comparer)
{
if (ReferenceEquals(x, y)) return true;
if (x is null || y is null || x.Count != y.Count) return false;
for (var i = 0; i < x.Count; i++)
if (!comparer.Equals(x[i], y[i])) return false;
return true;
}
private static MappedNamespaceSubject Copy(MappedNamespaceSubject subject) => subject with
{
@@ -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;
}
}
@@ -0,0 +1,65 @@
using System.Text;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
namespace ZB.MOM.WW.OtOpcUa.Core.Tests.Authorization;
/// <summary>#1057: the mapped-subject resolve and the policy's scope key run per projected value; they must not allocate.</summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Issue", "1057")]
public sealed class GrpcDataPolicyAllocationTests
{
[Fact]
public void Resolve_is_allocation_free_and_still_answers_every_kind()
{
var fixture = new GrpcDataPolicyTests.Fixture(NodeHierarchyKind.Raw);
var subject = fixture.Subject(DataRealm.Raw, NodeHierarchyKind.Raw, "mapping-a", "Plant/Mount/Speed");
var resolver = fixture.Resolver([subject]);
var moved = subject with { LocalAncestry = ["different-parent", "mapping-a"] };
var local = subject.View with { MappingId = null, MappingRevision = 0 };
resolver.Resolve(subject.View, subject).Kind.ShouldBe(MappedSubjectResolutionKind.Mapped);
resolver.Resolve(subject.View, subject).Subject.ShouldNotBeSameAs(subject, "the authoritative copy, never the live claim");
resolver.Resolve(subject.View, moved).Kind.ShouldBe(MappedSubjectResolutionKind.Deny);
resolver.Resolve(local, null).Kind.ShouldBe(MappedSubjectResolutionKind.Local);
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 1000; i++)
{
resolver.Resolve(subject.View, subject);
resolver.Resolve(subject.View, moved);
resolver.Resolve(local, null);
}
(GC.GetAllocatedBytesForCurrentThread() - before).ShouldBe(0);
}
[Fact]
public void A_case_mismatched_ancestry_still_matches_and_a_segment_mismatch_still_denies()
{
var fixture = new GrpcDataPolicyTests.Fixture(NodeHierarchyKind.Raw);
var subject = fixture.Subject(DataRealm.Raw, NodeHierarchyKind.Raw, "mapping-a", "Plant/Mount/Speed");
var resolver = fixture.Resolver([subject]);
resolver.Resolve(subject.View, subject with { LocalAncestry = ["LOCAL-PARENT", "MAPPING-A"] }).Kind
.ShouldBe(MappedSubjectResolutionKind.Mapped, "ancestry compares OrdinalIgnoreCase, as before");
resolver.Resolve(subject.View, subject with { Scope = subject.Scope with { Segments = ["Plant", "Mount", "SPEED"] } }).Kind
.ShouldBe(MappedSubjectResolutionKind.Deny, "segments compare Ordinal, as before");
resolver.Resolve(subject.View, subject with { Scope = subject.Scope with { Segments = ["Plant", "Mount"] } }).Kind
.ShouldBe(MappedSubjectResolutionKind.Deny);
}
[Theory]
[InlineData("c1")]
[InlineData("c1", "Plant")]
[InlineData("a-much-longer-cluster-id", "Plant", "0123456789", "a-segment-well-past-ten-characters", "Ünïcødé")]
public void The_scope_key_is_unchanged(string cluster, params string[] segments)
{
foreach (var kind in new[] { NodeHierarchyKind.Raw, NodeHierarchyKind.Uns })
{
var scope = new NodeScope { ClusterId = cluster, Kind = kind, Segments = segments };
var expected = new StringBuilder().Append((int)scope.Kind).Append(':').Append(scope.ClusterId.Length).Append(':').Append(scope.ClusterId);
foreach (var segment in segments) expected.Append(':').Append(segment.Length).Append(':').Append(segment);
DataOperationPolicy.LocalScopeKey(scope).ShouldBe(expected.ToString());
}
}
}
@@ -0,0 +1,80 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
/// <summary>
/// #1057: the per-value / per-tick pieces of the origin publish path that used to allocate. Each runs once warm, then a loop is
/// measured on this thread. (End-to-end numbers: <c>GrpcDataWave3PerfTests</c>, opt-in.)
/// </summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Issue", "1057")]
public sealed class GrpcData1057AllocationTests
{
private static long Measure(Action action, int iterations = 1000)
{
action();
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < iterations; i++) action();
return GC.GetAllocatedBytesForCurrentThread() - before;
}
[Fact]
public void The_delivery_index_slice_reuses_the_callers_list_and_its_ready_nodes()
{
var scheduler = new DeliveryScheduler(16, 16);
var source = HubTest.Ticket("driver", "a").Key;
scheduler.TryRegister(source, 1).ShouldBeTrue();
scheduler.TryRegister(source, 2).ShouldBeTrue();
var slice = new List<ScheduledInterest>(8);
long generation = 0;
var allocated = Measure(() =>
{
scheduler.TryMarkDirty(source, ++generation).ShouldBeTrue();
slice.Clear(); scheduler.TakeSlice(8, slice);
slice.Clear(); scheduler.TakeSlice(8, slice);
});
allocated.ShouldBe(0);
// Positive control: the slices still visit every interest of a dirty source.
scheduler.TryMarkDirty(source, ++generation);
var seen = new List<ScheduledInterest>();
for (var i = 0; i < 4; i++) scheduler.TakeSlice(8, seen);
seen.Select(x => x.InterestId).OrderBy(x => x).ShouldBe([1L, 2L]);
}
[Fact]
public void An_interest_lease_reads_into_the_callers_list_without_allocating()
{
using var hub = HubTest.Create(partitions: 1, bytes: 1_000_000, ingress: 100, dirty: 100);
var mine = HubTest.Ticket("driver", "mine");
HubTest.BindAndPublish(hub, mine, 1, 1);
hub.ProcessPending();
hub.TryCaptureInterestSnapshot([mine], HubTest.Budget, CancellationToken.None, out var snapshot, out var interest).ShouldBeTrue();
using (snapshot!) using (interest!)
{
var changes = new List<SourceInterestChange>(8);
Measure(() => { changes.Clear(); interest!.TryReadChanges(256, 4096, changes, out _).ShouldBeTrue(); }).ShouldBe(0);
HubTest.Publish(hub, mine, 2, 2); hub.ProcessPending();
changes.Clear();
interest!.TryReadChanges(256, 4096, changes, out _).ShouldBeTrue();
changes.ShouldHaveSingleItem().Ticket.ShouldBe(mine);
}
}
[Fact]
public void The_catalog_resolve_and_the_latest_version_peek_do_not_allocate()
{
using var fixture = new LocalDataFixture();
fixture.Publish(10);
fixture.Catalog.TryResolve(fixture.Raw, out var node).ShouldBeTrue();
node.Metadata.View.ShouldBe(fixture.Raw);
Measure(() => fixture.Catalog.TryResolve(fixture.Raw, out _)).ShouldBe(0);
fixture.Hub.TryPeekReadyVersion(fixture.Ticket, out var version).ShouldBeTrue();
version.ShouldBe(1);
Measure(() => fixture.Hub.TryPeekReadyVersion(fixture.Ticket, out _)).ShouldBe(0);
// The resolve still refuses a view whose other fields disagree with the node's.
fixture.Catalog.TryResolve(fixture.Raw with { Subject = "Plant/Other" }, out _).ShouldBeFalse();
// ...and still normalises a differently-cased origin cluster id.
fixture.Catalog.TryResolve(fixture.Raw with { Address = fixture.Raw.Address with { OriginClusterId = "CLUSTER" } }, out _).ShouldBeTrue();
}
}