Merge gRPC data perf harness (#1094 test item): per-thread publish-path allocation sections, counter-based wait instead of copying polls

This commit is contained in:
Joseph Doherty
2026-12-04 14:38:16 -05:00
5 changed files with 116 additions and 7 deletions
+8
View File
@@ -311,6 +311,14 @@ Follow-ups (#1080):
about 3.85 KB. The figure is a process-wide count: it includes the consumer cohort and the harness's own copies and
polling. The remaining per-value cost is mostly sample and value copies along the path (the cache read, the frame's
owned copy, the consumer's update).
- **The harness measures the publish path per thread (#1094).** The process-wide figure above carried the harness's own polling
(`Latest.Values` copied a 10k array every 10 ms, which also slowed delivery: ~530 ms and ~12k values per run against ~185 ms and
exactly 10k once the poll reads a counter). The harness now polls a sink-maintained counter and prints per-thread sections from
`GC.GetAllocatedBytesForCurrentThread` (`PublishAllocations`, `DataSubscriptionSession.BeforeTickForTests`): session tick, the
session's read side, the consumer's frame handling and the sink. Release, 10k cohort: tick about 616 B/value (Hub read 256; the
owned sample copy 136; the value lease 80; `ValueDelivery` 96; the rest about 48), read side about 495-530 B, consumer frame 392 B,
sink 32 B, all stable to the byte except the read side (about 6%). Process-wide stays about 2.2-2.3 KB (5 runs 2.20-2.29 KB; the old
harness gave 2.41-2.55 KB, 6 runs).
### Mixed versions (X0 rollout)
@@ -58,6 +58,8 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
internal Action? SnapshotEndCommittedForTests { get; set; }
internal Action<int, int, int>? BeforeDirtyTickForTests { get; set; }
internal Action? AfterTickForTests { get; set; }
/// <summary>#1094: runs on the worker as a tick starts, so a harness can attribute the thread's allocations to the tick.</summary>
internal Action? BeforeTickForTests { get; set; }
/// <summary>Test seam: a frame met a full delivery window (the worker is about to wait for the reader).</summary>
internal Action? OutboundFullForTests { get; set; }
internal Action<DataItemHandle, long>? OnCandidateQueuedForTests { get; set; }
@@ -811,6 +813,7 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
[AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))]
private async ValueTask TickAsync()
{
BeforeTickForTests?.Invoke();
try
{
lock (_gate)
@@ -29,6 +29,12 @@ internal sealed class CohortScaleFixture : IFederatedProjectionCatalog, IProject
internal readonly ConcurrentDictionary<string, int> Baselines = new(StringComparer.Ordinal);
internal readonly ConcurrentDictionary<string, long> Latest = new(StringComparer.Ordinal);
internal int Retired, Publishes, Opens;
/// <summary>#1094: per-thread allocation attribution for the publish path. Off unless a harness sets it before the stream opens.</summary>
internal bool MeasureAllocations;
internal readonly PublishAllocations Allocations = new();
/// <summary>#1094: when non-zero, the sink counts items whose latest delivered version reaches it (a poll reads a counter, not a copy).</summary>
internal long TargetVersion;
internal int AtTargetVersion;
/// <summary>When set, TryPublish answers false (a capacity-refusing sink).</summary>
#pragma warning disable CS0649 // set by individual tests
internal volatile bool RefusePublish;
@@ -170,12 +176,22 @@ internal sealed class CohortScaleFixture : IFederatedProjectionCatalog, IProject
public bool TryPublish(IReadOnlyList<ProjectedValueUpdate> updates)
{
if (RefusePublish) return false;
var allocatedBefore = MeasureAllocations ? GC.GetAllocatedBytesForCurrentThread() : 0;
try { return PublishAll(updates); }
finally { if (MeasureAllocations) Allocations.AddSink(GC.GetAllocatedBytesForCurrentThread() - allocatedBefore, updates.Count); }
}
private bool PublishAll(IReadOnlyList<ProjectedValueUpdate> updates)
{
foreach (var update in updates)
{
if (PublishGate is { } gate && !gate(update)) return false;
Interlocked.Increment(ref Publishes);
if (update.IsCompleteSnapshot) Baselines.AddOrUpdate(update.Route.LocalIdentifier, 1, (_, count) => count + 1);
Latest[update.Route.LocalIdentifier] = update.SourceVersion ?? 0;
var version = update.SourceVersion ?? 0;
var target = Volatile.Read(ref TargetVersion);
if (target != 0 && version == target && (!Latest.TryGetValue(update.Route.LocalIdentifier, out var previous) || previous != target))
Interlocked.Increment(ref AtTargetVersion);
Latest[update.Route.LocalIdentifier] = version;
}
return true;
}
@@ -195,7 +211,11 @@ internal sealed class CohortScaleFixture : IFederatedProjectionCatalog, IProject
{
var stream = await inner.SubscribeAsync(cancellationToken);
Interlocked.Increment(ref owner.Opens);
if (stream is DataSubscriptionSession session) Volatile.Write(ref owner._session, session);
if (stream is DataSubscriptionSession session)
{
Volatile.Write(ref owner._session, session);
if (owner.MeasureAllocations) owner.Allocations.Attach(session);
}
var wrapped = new Recording(owner, stream);
owner._streams.Enqueue(wrapped);
return wrapped;
@@ -221,9 +241,22 @@ internal sealed class CohortScaleFixture : IFederatedProjectionCatalog, IProject
public async IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync(
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken)
{
await foreach (var frame in inner.ReadAllAsync(cancellationToken))
await using var frames = inner.ReadAllAsync(cancellationToken).GetAsyncEnumerator(cancellationToken);
while (true)
{
// #1094: a frame that is already waiting completes on this thread, so its read cost is attributable per thread.
var readStart = owner.MeasureAllocations ? GC.GetAllocatedBytesForCurrentThread() : 0;
var next = frames.MoveNextAsync();
if (next.IsCompleted)
{
var readBytes = owner.MeasureAllocations ? GC.GetAllocatedBytesForCurrentThread() - readStart : 0;
if (!next.GetAwaiter().GetResult()) yield break;
if (frames.Current is DataSubscriptionValues counted && owner.MeasureAllocations) owner.Allocations.AddRead(readBytes, counted.Items.Count);
}
else if (!await next.ConfigureAwait(false)) yield break;
var frame = frames.Current;
if (frame is not DataSubscriptionValues values) { yield return frame; continue; }
var bodyStart = owner.MeasureAllocations ? GC.GetAllocatedBytesForCurrentThread() : 0;
var bounded = new List<DataSubscriptionValue>(values.Items.Count);
foreach (var item in values.Items)
{
@@ -236,7 +269,9 @@ internal sealed class CohortScaleFixture : IFederatedProjectionCatalog, IProject
bounded.Add(item with { Sample = item.Sample with { Value = item.Sample.Value.Retain() }, AgeBounds = bounds,
FreshnessObservedTimestamp = observed });
}
yield return new DataSubscriptionValues(values.SubscriptionId, values.StreamEpoch, values.Sequence, values.IsSnapshot, bounded, values);
var result = new DataSubscriptionValues(values.SubscriptionId, values.StreamEpoch, values.Sequence, values.IsSnapshot, bounded, values);
if (owner.MeasureAllocations) owner.Allocations.AddConsumer(GC.GetAllocatedBytesForCurrentThread() - bodyStart, bounded.Count);
yield return result;
}
}
public ValueTask DisposeAsync() => inner.DisposeAsync();
@@ -21,7 +21,7 @@ public sealed class GrpcDataWave3PerfTests(ITestOutputHelper output)
{
Assert.SkipUnless(Enabled, "set OTOPCUA_GRPCDATA_PERF=1");
const int items = 10_000;
using var fixture = new CohortScaleFixture(items, maxBatchItems: 1000);
using var fixture = new CohortScaleFixture(items, maxBatchItems: 1000) { MeasureAllocations = true };
using var access = fixture.Create(items + 16);
var demands = fixture.AcquireAll(access);
try
@@ -42,10 +42,14 @@ public sealed class GrpcDataWave3PerfTests(ITestOutputHelper output)
// 1k values/s: 100 source versions 1 ms apart on the fixture clock (1,000 changes/s). The fixture's items share one
// origin source, so each change fans out to every item at its 100 ms publishing interval; count delivered item values.
// #1094: the wait below polls a counter the sink maintains (the old poll copied the 10k-entry Latest.Values every 10 ms), and
// the per-value figures come from per-thread counters on the publish path, so neither the poll nor the clock pump is in them.
var before = Volatile.Read(ref fixture.Publishes);
const int versions = 100;
Volatile.Write(ref fixture.TargetVersion, 1 + versions);
fixture.Allocations.Reset();
allocated = GC.GetTotalAllocatedBytes(precise: true);
watch.Restart();
const int versions = 100;
for (var version = 2; version < 2 + versions; version++)
{
fixture.PublishVersion(version, version);
@@ -53,12 +57,16 @@ public sealed class GrpcDataWave3PerfTests(ITestOutputHelper output)
await Task.Delay(1, TestContext.Current.CancellationToken);
}
await using (fixture.PumpClock())
await fixture.WaitForAsync(() => fixture.Latest.Values.All(v => v == 1 + versions), TimeSpan.FromSeconds(60), "final version everywhere");
await fixture.WaitForAsync(() => Volatile.Read(ref fixture.AtTargetVersion) >= items, TimeSpan.FromSeconds(60), "final version everywhere");
var publish = watch.Elapsed;
var delivered = Volatile.Read(ref fixture.Publishes) - before;
var publishAllocated = GC.GetTotalAllocatedBytes(precise: true) - allocated;
output.WriteLine($"publish: {versions} source versions -> {delivered} item values delivered in {publish.TotalMilliseconds:F0} ms " +
$"({delivered / Math.Max(0.001, publish.TotalSeconds):F0} values/s), {publishAllocated / Math.Max(1, delivered)} B allocated per value");
output.WriteLine("publish path (per-thread, #1094): " + fixture.Allocations);
var perValue = fixture.Allocations.PerValue();
perValue.Session.ShouldBeGreaterThan(0, "the tick seam must see the publish");
perValue.Consumer.ShouldBeGreaterThan(0, "the consumer seam must see frames");
fixture.Opens.ShouldBeLessThanOrEqualTo(3);
}
finally { foreach (var demand in demands) demand.Dispose(); }
@@ -0,0 +1,55 @@
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
/// <summary>
/// #1094: attributes allocations to the gRPC data publish path with <see cref="GC.GetAllocatedBytesForCurrentThread"/>, so the
/// harness's own polling and clock pump (other threads) no longer count. Four sections, each summed on the thread that ran it:
/// the session's tick (consider + build + enqueue), the session's read side (take + commit, only when the frame was already
/// waiting), the consumer's frame handling, and the consumer's sink. A section that crossed a thread (an async hop) is dropped
/// and counted, so the coverage is visible instead of silently wrong.
/// </summary>
internal sealed class PublishAllocations
{
[ThreadStatic] private static long _tickStart;
[ThreadStatic] private static bool _inTick;
private long _tickBytes, _tickValues, _tickCount, _tickDropped, _queued;
private long _readBytes, _readValues, _consumerBytes, _consumerValues, _sinkBytes, _sinkValues;
internal void Attach(DataSubscriptionSession session)
{
session.BeforeTickForTests = () => { _tickStart = GC.GetAllocatedBytesForCurrentThread(); _inTick = true; };
session.OnCandidateQueuedForTests = (_, _) => Interlocked.Increment(ref _queued);
session.AfterTickForTests = () =>
{
if (!_inTick) { Interlocked.Increment(ref _tickDropped); return; } // finished on a different thread than it started
_inTick = false;
var bytes = GC.GetAllocatedBytesForCurrentThread() - _tickStart;
var values = Interlocked.Exchange(ref _queued, 0);
if (values == 0) return; // an idle tick (heartbeat, empty slice) carries no value
Interlocked.Add(ref _tickBytes, bytes); Interlocked.Add(ref _tickValues, values); Interlocked.Increment(ref _tickCount);
};
}
internal void AddRead(long bytes, int values) { Interlocked.Add(ref _readBytes, bytes); Interlocked.Add(ref _readValues, values); }
internal void AddConsumer(long bytes, int values) { Interlocked.Add(ref _consumerBytes, bytes); Interlocked.Add(ref _consumerValues, values); }
internal void AddSink(long bytes, int values) { Interlocked.Add(ref _sinkBytes, bytes); Interlocked.Add(ref _sinkValues, values); }
internal void Reset()
{
foreach (var f in new[] { nameof(_tickBytes), nameof(_tickValues), nameof(_tickCount), nameof(_tickDropped), nameof(_queued),
nameof(_readBytes), nameof(_readValues), nameof(_consumerBytes), nameof(_consumerValues), nameof(_sinkBytes), nameof(_sinkValues) })
typeof(PublishAllocations).GetField(f, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.SetValue(this, 0L);
}
private static string Per(long bytes, long values) => values == 0 ? "n/a" : (bytes / values).ToString();
internal (double Session, double Read, double Consumer, double Sink) PerValue() => (
_tickValues == 0 ? 0 : (double)_tickBytes / _tickValues, _readValues == 0 ? 0 : (double)_readBytes / _readValues,
_consumerValues == 0 ? 0 : (double)_consumerBytes / _consumerValues, _sinkValues == 0 ? 0 : (double)_sinkBytes / _sinkValues);
public override string ToString() =>
$"tick(consider+enqueue) {Per(_tickBytes, _tickValues)} B/value over {_tickValues} values/{_tickCount} ticks ({_tickDropped} dropped), " +
$"read(take+commit, sync-completed) {Per(_readBytes, _readValues)} B/value over {_readValues} values, " +
$"consumer frame {Per(_consumerBytes, _consumerValues)} B/value over {_consumerValues}, sink {Per(_sinkBytes, _sinkValues)} B/value over {_sinkValues}";
}