test(grpc-data): #1098 attribute the consumer side of the projected publish path per thread

ProjectedDataAccess gets a test-only IProjectedPublishProbe (null in production) over six synchronous
sections: the stream pump, the frame queue, the cohort loop's dispatch, a value's build, its publication
and the frame's release. The perf harness prints them and the remainder against the process-wide figure.
Release, 10k cohort, 5 runs: the ~600-650 B/value that #1094 left unattributed is Pump 84-209 (the LINQ
Sum's boxed enumerator plus SemaphoreSlim.WaitAsync under a full frame window), Queue 40 (FrameEvent),
Build 184 (DataValueSnapshot + ProjectedValueUpdate), Publish 208 (the latest-sample cache re-wrapping
the update in two identical records, plus the one-element list), Release 55-88 (enumerators boxed by
the frame disposes); 15-51 B/value stays unattributed (other threads).
This commit is contained in:
Joseph Doherty
2026-12-04 17:36:54 -05:00
parent 50a2acb2be
commit b9bd7960de
4 changed files with 133 additions and 11 deletions
@@ -12,11 +12,40 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Finite ownership limits for mapped access and its physical work.</summary>
public sealed record ProjectedDataAccessLimits(int MaxDemands, int MaxUnaryOperations, long MaxUnaryBytes, int MaxStreams);
/// <summary>#1098: the consumer-side sections of the projected publish path a test probe can attribute allocations to.</summary>
internal enum ProjectedPublishSection
{
/// <summary>The stream pump: a received frame sized and its wait for a frame slot begun (a Task only when none is free).</summary>
Pump,
/// <summary>The stream pump: the slotted frame queued on the cohort's event channel.</summary>
Queue,
/// <summary>The cohort loop between events: the drain check, the command flush it triggers, the event read.</summary>
Dispatch,
/// <summary>One value: its checks, source resolve, decode and the <see cref="ProjectedValueUpdate"/> built from it.</summary>
Build,
/// <summary>One value's publication: the paced publish, the sink call (which a sink may measure itself) and the cache.</summary>
Publish,
/// <summary>A handled frame's release: its slot, its bytes and the frame (with what it owns) disposed.</summary>
Release,
}
/// <summary>
/// #1098: a test-only probe over the consumer side of the projected publish path. Every <see cref="Enter"/> is paired with an
/// <see cref="Exit"/> on the same thread with no await in between, so a probe can attribute that thread's allocations.
/// </summary>
internal interface IProjectedPublishProbe
{
void Enter(ProjectedPublishSection section);
void Exit(ProjectedPublishSection section);
}
/// <summary>Admission and asynchronous transport for projected SDK access.</summary>
public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
{
private readonly object _sync = new();
public TimeProvider Clock { get; }
/// <summary>#1098: allocation attribution for the perf harness; null (one field read per section) in production.</summary>
internal IProjectedPublishProbe? PublishProbeForTests { get; set; }
internal Func<TimeSpan, TimeSpan>? RetryJitterForTests { get; set; }
internal Action? BeforeSuccessorAdoptionForTests { get; set; }
// #965: renewal ticks queued by cohort timers vs. ticks whose handler has finished. A test that steps a fake clock waits
@@ -1338,15 +1367,27 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
{
await foreach (var frame in stream.ReadAllAsync(attemptStop).ConfigureAwait(false))
{
var probe = _owner.PublishProbeForTests;
probe?.Enter(ProjectedPublishSection.Pump);
var receivedTimestamp = _owner.Clock.GetTimestamp();
var bytes = frame is DataSubscriptionValues values ? checked(512L + values.Items.Sum(x =>
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; }
{ probe?.Exit(ProjectedPublishSection.Pump); Interlocked.Add(ref _frameBytes, -bytes); (frame as IDisposable)?.Dispose(); break; }
// #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)))
try
{
// The wait's synchronous part (a Task only when no slot is free) belongs to the pump section.
var slot = _frameSlots.WaitAsync(attemptStop);
probe?.Exit(ProjectedPublishSection.Pump); probe = null;
await slot.ConfigureAwait(false);
}
catch { probe?.Exit(ProjectedPublishSection.Pump); Interlocked.Add(ref _frameBytes, -bytes); (frame as IDisposable)?.Dispose(); throw; }
probe = _owner.PublishProbeForTests;
probe?.Enter(ProjectedPublishSection.Queue);
var queued = _events.Writer.TryWrite(new FrameEvent(frame, bytes, receivedTimestamp));
probe?.Exit(ProjectedPublishSection.Queue);
if (!queued)
{ _frameSlots.Release(); Interlocked.Add(ref _frameBytes, -bytes); (frame as IDisposable)?.Dispose(); break; }
}
}
@@ -1819,13 +1860,28 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
{
// #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.
// #1098: the probe sees only the synchronous part of each call (no await inside a section).
var probe = _owner.PublishProbeForTests;
probe?.Enter(ProjectedPublishSection.Dispatch);
if (!_events.Reader.TryRead(out var message))
{
sinceFlush = 0;
await FlushAsync(route.Token).ConfigureAwait(false);
message = await _events.Reader.ReadAsync(route.Token).ConfigureAwait(false);
var flush = FlushAsync(route.Token);
probe?.Exit(ProjectedPublishSection.Dispatch);
await flush.ConfigureAwait(false);
probe?.Enter(ProjectedPublishSection.Dispatch);
var read = _events.Reader.ReadAsync(route.Token);
probe?.Exit(ProjectedPublishSection.Dispatch);
message = await read.ConfigureAwait(false);
}
else if (++sinceFlush >= 64) { sinceFlush = 0; await FlushAsync(route.Token).ConfigureAwait(false); }
else if (++sinceFlush >= 64)
{
sinceFlush = 0;
var flush = FlushAsync(route.Token);
probe?.Exit(ProjectedPublishSection.Dispatch);
await flush.ConfigureAwait(false);
}
else probe?.Exit(ProjectedPublishSection.Dispatch);
if (message is FlushEvent) { Interlocked.Exchange(ref _flushQueued, 0); continue; }
if (message is AddEvent add)
{
@@ -2051,6 +2107,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
var valueItems = values.Items;
for (var valueIndex = 0; valueIndex < valueItems.Count; valueIndex++)
{
probe?.Enter(ProjectedPublishSection.Build);
var item = valueItems[valueIndex];
ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.Value);
if (!_byHandle.TryGetValue(item.Handle, out var registration)) throw new InvalidDataException("Unknown item handle.");
@@ -2081,6 +2138,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
var payload = DecodeValue(sample.Value, registration.Demand.Proof.OriginMetadata);
var update = new ProjectedValueUpdate(source.Route, new DataValueSnapshot(payload, sample.StatusCode, sample.SourceTimestampUtc?.UtcDateTime, sample.ServerTimestampUtc?.UtcDateTime),
item.AgeBounds, ageTimestamp, attemptProof, false, registration.Demand.MaximumSampleAge, sample.Version);
probe?.Exit(ProjectedPublishSection.Build);
if (values.IsSnapshot)
{
if (!inSnapshot) throw new InvalidDataException("Snapshot value outside snapshot.");
@@ -2095,14 +2153,22 @@ 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, validated) = await PublishPacedAsync(registration, recovery ? update with { IsCompleteSnapshot = true } : update, sample.Version, route.Token).ConfigureAwait(false);
probe?.Enter(ProjectedPublishSection.Publish);
var publication = PublishPacedAsync(registration, recovery ? update with { IsCompleteSnapshot = true } : update, sample.Version, route.Token);
probe?.Exit(ProjectedPublishSection.Publish);
var (accepted, validated) = await publication.ConfigureAwait(false);
if (recovery && (accepted || validated))
{ registration.HasBaseline = true; registration.Recovery = false; registration.AwaitingCurrent = false; FinishRefresh(registration.Demand); }
}
}
}
}
finally { _frameSlots.Release(); Interlocked.Add(ref _frameBytes, -delivered.Bytes); (frame as IDisposable)?.Dispose(); }
finally
{
probe?.Enter(ProjectedPublishSection.Release);
_frameSlots.Release(); Interlocked.Add(ref _frameBytes, -delivered.Bytes); (frame as IDisposable)?.Dispose();
probe?.Exit(ProjectedPublishSection.Release);
}
}
}
}
@@ -84,7 +84,8 @@ internal sealed class CohortScaleFixture : IFederatedProjectionCatalog, IProject
}
internal ProjectedDataAccess Create(int maxDemands) =>
new(this, this, this, _ => "link", _policy, this, Origin.Clock, new(maxDemands, 8, 64L * 1024 * 1024, 4));
new(this, this, this, _ => "link", _policy, this, Origin.Clock, new(maxDemands, 8, 64L * 1024 * 1024, 4))
{ PublishProbeForTests = MeasureAllocations ? Allocations : null };
internal IProjectedDemandLease[] AcquireAll(ProjectedDataAccess access)
{
@@ -64,6 +64,10 @@ public sealed class GrpcDataWave3PerfTests(ITestOutputHelper output)
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 attributed = fixture.Allocations.AttributedPerValue();
output.WriteLine("consumer sections (per-thread, #1098): " + fixture.Allocations.Consumer());
output.WriteLine($"attributed {attributed:F0} B/value of {publishAllocated / Math.Max(1, delivered)} B/value process-wide; " +
$"unattributed {publishAllocated / (double)Math.Max(1, delivered) - attributed:F0} B/value");
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");
@@ -9,8 +9,29 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
/// 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
internal sealed class PublishAllocations : IProjectedPublishProbe
{
private static readonly int SectionCount = Enum.GetValues<ProjectedPublishSection>().Length;
// #1098: the consumer's sections (ProjectedDataAccess). A section is synchronous by contract, so a thread-static start is
// exact; an Enter without its Exit (an exception path) is simply overwritten by the next Enter.
[ThreadStatic] private static long[]? _sectionStarts;
private readonly long[] _sectionBytes = new long[SectionCount], _sectionCounts = new long[SectionCount];
public void Enter(ProjectedPublishSection section)
{
var starts = _sectionStarts ??= new long[SectionCount];
starts[(int)section] = GC.GetAllocatedBytesForCurrentThread();
}
public void Exit(ProjectedPublishSection section)
{
var end = GC.GetAllocatedBytesForCurrentThread();
if (_sectionStarts is not { } starts || starts[(int)section] == 0) return;
Interlocked.Add(ref _sectionBytes[(int)section], end - starts[(int)section]);
Interlocked.Increment(ref _sectionCounts[(int)section]);
starts[(int)section] = 0;
}
[ThreadStatic] private static long _tickStart;
[ThreadStatic] private static bool _inTick;
private long _tickBytes, _tickValues, _tickCount, _tickDropped, _queued;
@@ -40,6 +61,36 @@ internal sealed class PublishAllocations
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);
for (var i = 0; i < SectionCount; i++) { Interlocked.Exchange(ref _sectionBytes[i], 0); Interlocked.Exchange(ref _sectionCounts[i], 0); }
}
/// <summary>#1098: a consumer section's bytes per delivered value (the sink's count), and how many times it ran.</summary>
internal (double PerValue, long Runs) Section(ProjectedPublishSection section)
{
var values = Interlocked.Read(ref _sinkValues);
return (values == 0 ? 0 : (double)Interlocked.Read(ref _sectionBytes[(int)section]) / values, Interlocked.Read(ref _sectionCounts[(int)section]));
}
/// <summary>#1098: every per-thread section's bytes over the delivered values (the sink is nested inside Publish, so counted once).</summary>
internal double AttributedPerValue()
{
var values = Interlocked.Read(ref _sinkValues);
if (values == 0) return 0;
long bytes = Interlocked.Read(ref _tickBytes) + Interlocked.Read(ref _readBytes) + Interlocked.Read(ref _consumerBytes);
for (var i = 0; i < SectionCount; i++) bytes += Interlocked.Read(ref _sectionBytes[i]);
return (double)bytes / values;
}
internal string Consumer()
{
var sink = PerValue().Sink;
return string.Join(", ", Enum.GetValues<ProjectedPublishSection>().Select(s =>
{
var (perValue, runs) = Section(s);
return s == ProjectedPublishSection.Publish
? $"{s} {perValue - sink:F0} B/value excl. sink ({runs} runs)"
: $"{s} {perValue:F0} B/value ({runs} runs)";
}));
}
private static string Per(long bytes, long values) => values == 0 ? "n/a" : (bytes / values).ToString();