diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs
index bd13cfecc..11f3bab89 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs
@@ -12,11 +12,40 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// Finite ownership limits for mapped access and its physical work.
public sealed record ProjectedDataAccessLimits(int MaxDemands, int MaxUnaryOperations, long MaxUnaryBytes, int MaxStreams);
+/// #1098: the consumer-side sections of the projected publish path a test probe can attribute allocations to.
+internal enum ProjectedPublishSection
+{
+ /// The stream pump: a received frame sized and its wait for a frame slot begun (a Task only when none is free).
+ Pump,
+ /// The stream pump: the slotted frame queued on the cohort's event channel.
+ Queue,
+ /// The cohort loop between events: the drain check, the command flush it triggers, the event read.
+ Dispatch,
+ /// One value: its checks, source resolve, decode and the built from it.
+ Build,
+ /// One value's publication: the paced publish, the sink call (which a sink may measure itself) and the cache.
+ Publish,
+ /// A handled frame's release: its slot, its bytes and the frame (with what it owns) disposed.
+ Release,
+}
+
+///
+/// #1098: a test-only probe over the consumer side of the projected publish path. Every is paired with an
+/// on the same thread with no await in between, so a probe can attribute that thread's allocations.
+///
+internal interface IProjectedPublishProbe
+{
+ void Enter(ProjectedPublishSection section);
+ void Exit(ProjectedPublishSection section);
+}
+
/// Admission and asynchronous transport for projected SDK access.
public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
{
private readonly object _sync = new();
public TimeProvider Clock { get; }
+ /// #1098: allocation attribution for the perf harness; null (one field read per section) in production.
+ internal IProjectedPublishProbe? PublishProbeForTests { get; set; }
internal Func? 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);
+ }
}
}
}
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/CohortScaleFixture.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/CohortScaleFixture.cs
index bd018c9f8..5cab427f6 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/CohortScaleFixture.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/CohortScaleFixture.cs
@@ -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)
{
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataWave3PerfTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataWave3PerfTests.cs
index 1740a457a..9cd072c0d 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataWave3PerfTests.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataWave3PerfTests.cs
@@ -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");
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/PublishAllocations.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/PublishAllocations.cs
index 65ee67b31..d5f41b315 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/PublishAllocations.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/PublishAllocations.cs
@@ -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.
///
-internal sealed class PublishAllocations
+internal sealed class PublishAllocations : IProjectedPublishProbe
{
+ private static readonly int SectionCount = Enum.GetValues().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); }
+ }
+
+ /// #1098: a consumer section's bytes per delivered value (the sink's count), and how many times it ran.
+ 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]));
+ }
+
+ /// #1098: every per-thread section's bytes over the delivered values (the sink is nested inside Publish, so counted once).
+ 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().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();