diff --git a/docs/DataConnections.md b/docs/DataConnections.md index 4c77a1ac0..5d9a76bbf 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -320,6 +320,39 @@ Follow-ups (#1080): 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). +Follow-ups (#1098): + +- **The consumer side is attributed too.** `ProjectedDataAccess` has a test-only probe (`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 what remains of the process-wide figure. The ~600-650 + B/value that #1094 left unattributed was: pump 84-209 B (a LINQ `Sum` boxing an enumerator per frame, and `SemaphoreSlim.WaitAsync` + allocating a waiter, a state machine and a cancellation registration for each wait; a fast origin keeps the frame window full, so + the pump waits for nearly every frame), frame queue 40 B, build 184 B, publication 208 B (the latest-sample cache re-wrapped each + update in two identical records), release 55-88 B (enumerators boxed by the frame disposes). 15-50 B stays unattributed. +- **What changed.** A live value takes over its hub read's sample lease and charge instead of retaining a second copy and reserving + a second charge. The charge is the same amount from the same budget, and the read keeps its source guard until it is disposed + (`CachedSourceRead.TryTransferSample`). The sample is re-stamped with the item's serving only when the hub sample carries a + different one. A value's lease takes a reference on its item's reservation directly, with no hold object. Release order is + unchanged: charge, item, snapshot. The latest-sample cache keeps the published update itself unless the payload is an array (an + array is still copied, because the sink may hold the published one). The frame window is a `FrameSlotWindow`: the semaphore's + semantics (a release past capacity throws, a cancelled wait takes no slot) on one reused waiter and one cancellation registration + per attempt. Since that waiter now runs once per frame under load, a re-arm also waits for a signaller that is still inside + `SetResult` for the previous wait (`SlotWaiter`, shared with the origin's delivery window from #1080). Before, a `Reset` landing + in that gap could let the old signal complete the new wait, which then threw. The pump sizes a frame with an indexed loop, and + `DataSubscriptionValues.Dispose` disposes its samples the same way. + A client filter keeps its baseline's compared fields and its own value lease instead of a re-wrapped sample. +- **Not done: pooling `ValueLease` / `ValueDelivery`.** The saving would be about 150 B per value. The risk is out of proportion + to it. The lease leaves the session as the frame's public `DataSubscriptionValues.ResourceLease`, which any consumer may dispose + itself, so a recycled lease could release another value's charge, item hold and snapshot hold. A queued delivery's `Gate` is + handed to the gRPC sink as its publication guard, so a recycled delivery could authorize a frame against another item's + identity. Both are returned on other threads at arbitrary times, so the pool would need its own synchronisation. +- Measured with the same harness (Release, 10k cohort, 100 versions at 1k/s, 5 runs each, same machine and session). Before: + 2.21-2.31 KB per value process-wide, 15-51 B of it unattributed. Tick 616 B, read side 495-520 B, consumer frame 392 B, pump 84-209 B, queue 40 B, dispatch + 2-5 B, build 184 B, publication 208 B (sink excluded), sink 32 B, release 55-88 B. After: 1.68-1.72 KB. Tick 560 B, read side + 402-424 B, consumer frame 392 B, pump 0 B, queue 40-42 B, dispatch 2-3 B, build 184 B, publication 24 B, sink 32 B, release 0 + B, 21-48 B unattributed. The harness's hub samples carry a different serving than the items, so its tick still pays the 96 B re-stamp. Where they + match, a value reuses the read's sample object outright. + ### Mixed versions (X0 rollout) The remote history and alarm work (`docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md`) diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs index afb6a491b..a52deda47 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs @@ -129,7 +129,8 @@ public sealed record DataSubscriptionValues(string SubscriptionId, long StreamEp public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) != 0) return; - try { foreach (var item in Items) item.Sample.Dispose(); } + // #1098: indexed — a foreach over the IReadOnlyList boxed an enumerator per frame (one frame per value on the hot path). + try { for (var i = 0; i < Items.Count; i++) Items[i].Sample.Dispose(); } finally { ResourceLease?.Dispose(); } } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ClientFilterState.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ClientFilterState.cs index f93f8a0ef..52585e10f 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ClientFilterState.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ClientFilterState.cs @@ -2,10 +2,31 @@ using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; -/// Per-registration baseline. Only a successful delivery may call Commit. +/// +/// Per-registration baseline. Only a successful delivery may call Commit. #1098: the baseline is the committed sample's +/// compared fields plus its own value lease, not a re-wrapped (a 96 B record per delivered value); +/// every call happens under the owning session's lock. +/// internal sealed class ClientFilterState : IDisposable { - private DataSample? _baseline; + private Baseline? _baseline; + + /// The committed sample's compared fields; owns (an independent lease). + private sealed class Baseline(DataSample sample) + { + internal DataValue Value = sample.Value.Retain(); + internal uint StatusCode = sample.StatusCode; + internal DateTimeOffset? SourceTimestampUtc = sample.SourceTimestampUtc, ServerTimestampUtc = sample.ServerTimestampUtc; + internal ServingIdentity Serving = sample.Serving; + internal void Set(DataSample sample) + { + var retained = sample.Value.Retain(); + var previous = Value; + Value = retained; StatusCode = sample.StatusCode; Serving = sample.Serving; + SourceTimestampUtc = sample.SourceTimestampUtc; ServerTimestampUtc = sample.ServerTimestampUtc; + previous.Dispose(); + } + } internal bool ShouldDeliver(DataSample sample, DataSubscriptionSettings settings) { @@ -37,10 +58,8 @@ internal sealed class ClientFilterState : IDisposable internal void Commit(DataSample sample) { ArgumentNullException.ThrowIfNull(sample); - var retained = sample with { Value = sample.Value.Retain() }; - var previous = _baseline; - _baseline = retained; - previous?.Dispose(); + if (_baseline is { } baseline) baseline.Set(sample); + else _baseline = new Baseline(sample); } private static bool Numeric(DataValue value, out double number) @@ -52,5 +71,5 @@ internal sealed class ClientFilterState : IDisposable number = 0; return false; } - public void Dispose() { _baseline?.Dispose(); _baseline = null; } + public void Dispose() { _baseline?.Value.Dispose(); _baseline = null; } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Delivery.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Delivery.cs index 7ab40beca..c02bcfed5 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Delivery.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Delivery.cs @@ -1,4 +1,3 @@ -using System.Threading.Tasks.Sources; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; @@ -155,8 +154,10 @@ internal sealed partial class DataSubscriptionSession /// #1080: what a queued value holds, released once by whoever ends up owning it (the frame, or the delivery when no frame /// took it): the value's budget charge, a hold on the item's reservation and, for a snapshot value, its snapshot hold. It /// replaces a BudgetLease inside one or two CompositeLeases. Release order is unchanged: charge, item, snapshot. + /// #1098: the item hold is a reference on the item's taken by the caller + /// (), released once here, instead of a separate hold object per value. /// - private sealed class ValueLease(DataResourceBudget budget, long charge, IDisposable itemHold, IDisposable? snapshotHold) : IDisposable + private sealed class ValueLease(DataResourceBudget budget, long charge, SharedSessionLease itemHold, IDisposable? snapshotHold) : IDisposable { private int _disposed; public void Dispose() @@ -170,41 +171,4 @@ internal sealed partial class DataSubscriptionSession } } } - - /// - /// #1080: the command worker's wait for a delivery-window slot, reused for every wait (at most one is ever pending: every - /// producer of the window runs on the worker). before re-trying the write, on every - /// dequeue and on stop; a signal that finds nothing armed is a no-op. It replaces the channel's per-wait writer operation - /// and its cancellation registration. - /// - private sealed class SlotWaiter : IValueTaskSource - { - private ManualResetValueTaskSourceCore _core = new() { RunContinuationsAsynchronously = true }; - private int _armed; - - /// Arms the waiter. The caller re-tries its write after this, so a slot freed in between is not missed. - public ValueTask Arm() - { - _core.Reset(); - Interlocked.Exchange(ref _armed, 1); - return new ValueTask(this, _core.Version); - } - - /// - /// Disarms a waiter whose re-tried write succeeded (or that will not wait). False when a signal already claimed it: the - /// caller must then still await the armed task, so the next never resets a source being completed. - /// - public bool TryDisarm() => Interlocked.Exchange(ref _armed, 0) == 1; - - /// Completes an armed wait. A full fence (the CAS) after the caller's dequeue pairs with the one in . - public void Signal() - { - if (Interlocked.CompareExchange(ref _armed, 0, 1) == 1) _core.SetResult(true); - } - - void IValueTaskSource.GetResult(short token) => _core.GetResult(token); - ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) => _core.GetStatus(token); - void IValueTaskSource.OnCompleted(Action continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) => - _core.OnCompleted(continuation, state, token, flags); - } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs index b685a5fd7..620ac6b51 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs @@ -63,6 +63,9 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo /// Test seam: a frame met a full delivery window (the worker is about to wait for the reader). internal Action? OutboundFullForTests { get; set; } internal Action? OnCandidateQueuedForTests { get; set; } + private int _sampleTransfers; + /// #1098: values that took over their hub read's sample and charge instead of copying them. + internal int SampleTransfersForTests => Volatile.Read(ref _sampleTransfers); private sealed class SharedSessionLease(IDisposable lease) : IDisposable { @@ -73,13 +76,18 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo private SharedSessionLease? _owner = owner; public void Dispose() => Interlocked.Exchange(ref _owner, null)?.Dispose(); } - internal IDisposable Retain() + internal IDisposable Retain() { AddReference(); return new Hold(this); } + /// + /// #1098: takes a reference without a ; the caller releases it with exactly one + /// (a , whose own once-only guard replaces the hold's). + /// + internal void AddReference() { while (true) { var current = Volatile.Read(ref _references); if (current <= 0) throw new ObjectDisposedException(nameof(SharedSessionLease)); - if (Interlocked.CompareExchange(ref _references, checked(current + 1), current) == current) return new Hold(this); + if (Interlocked.CompareExchange(ref _references, checked(current + 1), current) == current) return; } } public void Dispose() @@ -1088,25 +1096,42 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo item.LastConsidered = read.Sample.Version; if (!item.Filter.ShouldDeliver(read.Sample, item.Settings)) return; } - var delivery = MakeValue(item, read.Sample, read.ReceivedTimestamp, false, null); + var version = read.Sample.Version; + var delivery = MakeValue(item, read.Sample, read.ReceivedTimestamp, false, null, read: read); if (delivery is null) { if (!_handles!.IsCurrent(item.Handle)) return; CloseWithReset("Pending value memory exhausted."); return; } await EnqueueAsync(delivery).ConfigureAwait(false); - OnCandidateQueuedForTests?.Invoke(item.Handle, read.Sample.Version); + OnCandidateQueuedForTests?.Invoke(item.Handle, version); } + /// + /// Builds one queued value owning its own sample lease and budget charge. #1098: given the hub the + /// sample came from, it takes over that read's sample lease and charge (the same amount, from the same budget) instead + /// of retaining a second copy and reserving a second charge; the read keeps its source guard until it is disposed. + /// private PendingDelivery? MakeValue(Item item, DataSample sample, long received, bool snapshot, SnapshotLease? snapshotLease, - SnapshotAdmissionScheduler.Permit? snapshotPermit = null) + SnapshotAdmissionScheduler.Permit? snapshotPermit = null, CachedSourceRead? read = null) { + var budget = _services.SubscriptionHub.Resources; var charge = checked(sample.Value.EstimatedRetainedBytes + PartitionedSampleHub.ReferenceOverhead); IDisposable? snapshotHold = null; if (snapshotPermit is not null && !snapshotPermit.TryRetain(out snapshotHold)) return null; - if (!_services.SubscriptionHub.Resources.TryReserve(charge)) { snapshotHold?.Dispose(); return null; } DataSample owned; - try { owned = sample with { Value = sample.Value.Retain(), Serving = item.View.Serving }; } - catch { snapshotHold?.Dispose(); _services.SubscriptionHub.Resources.Release(charge); throw; } + if (read is not null && ReferenceEquals(read.Sample, sample) && read.TryTransferSample(budget, charge, out var transferred)) + { + // The read's own retained copy: re-stamped with the item's serving only when it differs (the value lease moves as is). + Interlocked.Increment(ref _sampleTransfers); + try { owned = transferred!.Serving == item.View.Serving ? transferred : transferred with { Serving = item.View.Serving }; } + catch { transferred!.Dispose(); snapshotHold?.Dispose(); budget.Release(charge); throw; } + } + else + { + if (!budget.TryReserve(charge)) { snapshotHold?.Dispose(); return null; } + try { owned = sample with { Value = sample.Value.Retain(), Serving = item.View.Serving }; } + catch { snapshotHold?.Dispose(); budget.Release(charge); throw; } + } ValueLease lease; - try { lease = new ValueLease(_services.SubscriptionHub.Resources, charge, item.Resources.Retain(), snapshotHold); } - catch { owned.Dispose(); snapshotHold?.Dispose(); _services.SubscriptionHub.Resources.Release(charge); return null; } + try { item.Resources.AddReference(); lease = new ValueLease(budget, charge, item.Resources, snapshotHold); } + catch { owned.Dispose(); snapshotHold?.Dispose(); budget.Release(charge); return null; } // #1080: the value's checks live on ValueDelivery (fields, not a closure and seven delegates per value). return new ValueDelivery(this, item, owned, received, charge, lease, snapshot, snapshotLease, snapshotPermit); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionedSampleHub.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionedSampleHub.cs index 0664bb79d..52b55cb46 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionedSampleHub.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionedSampleHub.cs @@ -127,9 +127,28 @@ public sealed class CachedSourceRead : IDisposable { var charge = Interlocked.Exchange(ref _charge, 0); if (charge == 0) return; - Sample?.Dispose(); _budget.Release(charge); + // #1098: a transferred sample (and its charge) belongs to its new owner; the read still releases its source guard here. + if (Interlocked.Exchange(ref _sampleTransferred, 1) == 0) { Sample?.Dispose(); _budget.Release(charge); } if (_guard is not null && _source is not null) _guard.ReleaseRead(_source); } + + private int _sampleTransferred; + + /// + /// #1098: hands this read's sample lease and its admission charge to the caller, which must release both exactly once + /// (the sample's , back to ). The read + /// keeps its source guard until , so its lifetime and are unchanged. False, + /// transferring nothing, once disposed or transferred, without a sample, or unless the read holds exactly + /// from . + /// + internal bool TryTransferSample(DataResourceBudget budget, long charge, out DataSample? sample) + { + sample = null; + if (charge <= 0 || Volatile.Read(ref _charge) != charge || Sample is null || !ReferenceEquals(budget, _budget) || + Interlocked.Exchange(ref _sampleTransferred, 1) != 0) return false; + sample = Sample; + return true; + } } /// 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..5caf9d4dd 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 @@ -763,7 +792,9 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable try { var owned = OwnedDataSample.CopyLegacy(update.Snapshot.Value); - _cachedSample = update with { Snapshot = update.Snapshot with { Value = owned } }; + // #1098: only an array payload is copied (the sink may hold the published one); a scalar comes back as itself, + // and re-wrapping it in two identical records cost ~184 B per value. The update is immutable, so cache it. + _cachedSample = ReferenceEquals(owned, update.Snapshot.Value) ? update : update with { Snapshot = update.Snapshot with { Value = owned } }; _cachedVersion = version; _cachedBytes = bytes; } catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or OverflowException) { } @@ -1267,9 +1298,10 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable // set itself (one add and one remove per demand, a refresh deduplicated per demand, timer ticks deduplicated by flag), so // enqueueing one can never fail — a failed Remove used to Stop() the whole cohort and dispose every sibling demand. // Value frames keep their backpressure through _frameSlots (and the _frameBytes budget), so a slow consumer still - // stalls the pump rather than growing memory. + // stalls the pump rather than growing memory. #1098: a FrameSlotWindow (the semaphore's semantics, without its per-wait + // allocations: a fast origin keeps the window full, so the pump waits for nearly every frame). private readonly Channel _events; - private readonly SemaphoreSlim _frameSlots; + private readonly FrameSlotWindow _frameSlots; private readonly CancellationTokenSource _stop = new(); private readonly Dictionary _registrations = new(); private readonly Dictionary _byId = new(StringComparer.Ordinal); @@ -1312,7 +1344,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable _owner = owner; _key = key; _connectionId = connectionId; _events = Channel.CreateUnbounded(new UnboundedChannelOptions { SingleReader = true }); var frames = Math.Clamp(owner._limits.MaxDemands * 2, 4, 128); - _frameSlots = new SemaphoreSlim(frames, frames); + _frameSlots = new FrameSlotWindow(frames); _commandTokens = CommandBurst; _commandTokenStamp = owner.Clock.GetTimestamp(); } internal bool Add(Demand demand) => _events.Writer.TryWrite(new AddEvent(demand)); @@ -1338,21 +1370,43 @@ 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; + var bytes = frame is DataSubscriptionValues values ? FrameBytes(values.Items) : 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; } } } catch (Exception) { } finally { _events.Writer.TryWrite(new EndEvent()); } } + /// #1098: a value frame's charge, indexed (the LINQ Sum boxed the list's enumerator once per frame). + private static long FrameBytes(IReadOnlyList items) + { + var bytes = 512L; + for (var i = 0; i < items.Count; i++) + { + var item = items[i]; + bytes = checked(bytes + checked(item.Sample.Value.EstimatedRetainedBytes + 2L * (item.FreshnessChallengeId?.Length ?? 0))); + } + return bytes; + } /// #994 (R-2): the hard ceiling of items per command — the origin acquires each item's demand inside the /// command's acknowledgement deadline, so a command must stay small enough to be answered in time. internal const int MaxCommandItemsCap = 256; @@ -1819,13 +1873,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 +2120,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 +2151,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 +2166,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/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SlotWaiter.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SlotWaiter.cs new file mode 100644 index 000000000..1e4a45adc --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SlotWaiter.cs @@ -0,0 +1,136 @@ +using System.Runtime.CompilerServices; +using System.Threading.Tasks.Sources; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// +/// #1080: the command worker's wait for a delivery-window slot, reused for every wait (at most one is ever pending: every +/// producer of the window runs on the worker). before re-trying the write, on every +/// dequeue and on stop; a signal that finds nothing armed is a no-op. It replaces the channel's per-wait writer operation +/// and its cancellation registration. (#1098: moved out of DataSubscriptionSession so +/// reuses it, and a re-arm now waits out a signaller still completing the previous wait.) +/// +internal sealed class SlotWaiter : IValueTaskSource +{ + private const int Idle = 0, Armed = 1, Completing = 2; + private ManualResetValueTaskSourceCore _core = new() { RunContinuationsAsynchronously = true }; + private int _armed; + /// #1098: runs in after the wait is completed, before the waiter may re-arm. + internal Action? AfterSetResultForTests { get; set; } + + /// Arms the waiter. The caller re-tries its write after this, so a slot freed in between is not missed. + public ValueTask Arm() + { + // #1098: a waiter that saw its last wait complete synchronously can come back here while the signaller that claimed that + // wait is still inside SetResult (it marks the source completed, then publishes its continuation sentinel). A Reset + // landing in between would let that sentinel complete the NEXT wait, which then throws from GetResult. Wait it out: + // SetResult with asynchronous continuations only queues work, so the signaller never waits on this thread. + SpinWait spin = default; + while (Volatile.Read(ref _armed) == Completing) spin.SpinOnce(); + _core.Reset(); + Interlocked.Exchange(ref _armed, Armed); + return new ValueTask(this, _core.Version); + } + + /// + /// Disarms a waiter whose re-tried write succeeded (or that will not wait). False when a signal already claimed it: the + /// caller must then still await the armed task, so the next never resets a source being completed. + /// + public bool TryDisarm() => Interlocked.CompareExchange(ref _armed, Idle, Armed) == Armed; + + /// Completes an armed wait. A full fence (the CAS) after the caller's dequeue pairs with the one in . + public void Signal() + { + if (Interlocked.CompareExchange(ref _armed, Completing, Armed) != Armed) return; + try { _core.SetResult(true); AfterSetResultForTests?.Invoke(); } + finally { Volatile.Write(ref _armed, Idle); } + } + + void IValueTaskSource.GetResult(short token) => _core.GetResult(token); + ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) => _core.GetStatus(token); + void IValueTaskSource.OnCompleted(Action continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) => + _core.OnCompleted(continuation, state, token, flags); +} + +/// +/// #1098: a projected cohort's frame window: how many frames its stream pump may hand to the cohort loop before one is +/// released. It replaces a whose WaitAsync(token) allocated a waiter task, an async +/// state machine and a cancellation registration for every wait, which is every frame while a fast origin keeps the window +/// full (~130-180 B per value in the perf harness). The semantics are the semaphore's: a wait takes one slot or waits for a +/// ; a release past the capacity throws ; a cancelled token fails +/// the wait () without taking a slot. +/// ONE waiter at a time (the attempt's pump; an attempt awaits its pump before the next attempt starts). Waits reuse one +/// and one cancellation registration per token, so a full window costs nothing per frame. +/// +internal sealed class FrameSlotWindow +{ + private readonly int _capacity; + private readonly SlotWaiter _waiter = new(); + private int _available; + private CancellationToken _registeredToken; + private CancellationTokenRegistration _registration; + + internal FrameSlotWindow(int capacity) + { + ArgumentOutOfRangeException.ThrowIfLessThan(capacity, 1); + _capacity = capacity; _available = capacity; + } + + internal int AvailableForTests => Volatile.Read(ref _available); + + /// Takes a slot, waiting for a release if none is free. One caller at a time. + internal ValueTask WaitAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) return ValueTask.FromCanceled(cancellationToken); + return TryTake() ? default : WaitSlowAsync(cancellationToken); + } + + /// Returns a slot and wakes the waiter. A release past the capacity (a double release) throws. + internal void Release() + { + if (Interlocked.Increment(ref _available) > _capacity) + { + Interlocked.Decrement(ref _available); + throw new SemaphoreFullException(); + } + _waiter.Signal(); + } + + private bool TryTake() + { + while (true) + { + var current = Volatile.Read(ref _available); + if (current <= 0) return false; + if (Interlocked.CompareExchange(ref _available, current - 1, current) == current) return true; + } + } + + [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))] + private async ValueTask WaitSlowAsync(CancellationToken cancellationToken) + { + if (cancellationToken.CanBeCanceled && cancellationToken != _registeredToken) + { + // One registration per token (one per attempt), not per wait. A cancel wakes the armed wait, which then throws. + _registration.Dispose(); + _registration = cancellationToken.UnsafeRegister(static state => ((SlotWaiter)state!).Signal(), _waiter); + _registeredToken = cancellationToken; + } + while (true) + { + // Arm before re-trying: a release (or a cancel) landing between the failed take and the await is never missed. + var wait = _waiter.Arm(); + if (TryTake()) + { + if (!_waiter.TryDisarm()) await wait.ConfigureAwait(false); + return; + } + if (cancellationToken.IsCancellationRequested) + { + if (!_waiter.TryDisarm()) await wait.ConfigureAwait(false); + cancellationToken.ThrowIfCancellationRequested(); + } + await wait.ConfigureAwait(false); + } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SubscriptionTransportCapacity.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SubscriptionTransportCapacity.cs index c76ebd277..1a79ab2c1 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SubscriptionTransportCapacity.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SubscriptionTransportCapacity.cs @@ -89,6 +89,8 @@ internal sealed class SubscriptionTransportCapacity maxSnapshotsPerPrincipal: checked(streamsPerPrincipal * SnapshotSlotsPerStream), maxSnapshotsPerSession: SnapshotSlotsPerStream); internal int ActiveOperations { get { lock (_gate) return _active; } } + /// #1098: item (interest) reservations currently held, node-wide. + internal int InterestsForTests { get { lock (_gate) return _interests; } } internal bool TryAdmitCommand(string principal) { ArgumentException.ThrowIfNullOrWhiteSpace(principal); 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/GrpcData1098OwnershipTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1098OwnershipTests.cs new file mode 100644 index 000000000..0e69e4d22 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1098OwnershipTests.cs @@ -0,0 +1,328 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// #1098: the publish path's ownership changes. A live value now takes over its hub read's sample lease and charge instead +/// of copying them; a value's lease holds a reference on its item's reservation instead of a separate hold; the cohort's +/// frame window is a reused waiter instead of a semaphore. Each test fails if an owner releases what another still holds +/// (a use-after-release or a double release), and each carries a positive control that the path under test ran. +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Issue", "1098")] +public sealed class GrpcData1098OwnershipTests +{ + // ---- CachedSourceRead.TryTransferSample ---- + + [Fact] + public void A_transferred_read_keeps_its_guard_but_leaves_the_sample_and_charge_to_the_new_owner() + { + using var hub = HubTest.Create(partitions: 1, bytes: 100_000); + var ticket = HubTest.Ticket("driver", "a"); + HubTest.BindAndPublish(hub, ticket, 1, 7); + hub.ProcessPending(); + var before = hub.Resources.RetainedBytes; + var read = hub.Read(ticket); + var sample = read.Sample.ShouldNotBeNull(); + var charge = hub.Resources.RetainedBytes - before; + charge.ShouldBeGreaterThan(0, "positive control: a read holds a charge"); + + read.TryTransferSample(hub.Resources, charge, out var transferred).ShouldBeTrue(); + transferred.ShouldBeSameAs(sample); + read.TryTransferSample(hub.Resources, charge, out _).ShouldBeFalse("a sample transfers once"); + read.IsValid.ShouldBeTrue("the read's guard is the read's until it is disposed"); + + read.Dispose(); + // The new owner's sample is still live and its charge still held: the read released neither. + transferred!.Value.GetScalar().ShouldBe(7); + hub.Resources.RetainedBytes.ShouldBe(before + charge); + read.Dispose(); + hub.Resources.RetainedBytes.ShouldBe(before + charge, "a second dispose releases nothing"); + + transferred.Dispose(); hub.Resources.Release(charge); + hub.Resources.RetainedBytes.ShouldBe(before); + Should.Throw(() => transferred.Value.GetScalar()); + } + + [Fact] + public void A_read_that_did_not_transfer_still_releases_its_sample_and_charge() + { + using var hub = HubTest.Create(partitions: 1, bytes: 100_000); + var ticket = HubTest.Ticket("driver", "a"); + HubTest.BindAndPublish(hub, ticket, 1, 7); + hub.ProcessPending(); + var before = hub.Resources.RetainedBytes; + var read = hub.Read(ticket); + var sample = read.Sample!; + var charge = hub.Resources.RetainedBytes - before; + // Refused: another budget, another charge. Neither transfers anything. + using var otherHub = HubTest.Create(partitions: 1, bytes: 100_000); + read.TryTransferSample(otherHub.Resources, charge, out var refused).ShouldBeFalse(); + refused.ShouldBeNull(); + read.TryTransferSample(hub.Resources, charge + 1, out _).ShouldBeFalse(); + read.Dispose(); + hub.Resources.RetainedBytes.ShouldBe(before); + Should.Throw(() => sample.Value.GetScalar()); + read.TryTransferSample(hub.Resources, charge, out _).ShouldBeFalse("nothing transfers after dispose"); + } + + // ---- the session: a live value owns the read's sample; its lease holds the item ---- + + [Fact(Timeout = 30000)] + public async Task A_live_value_that_took_over_its_read_is_still_owned_by_its_frame_after_the_read_is_gone() + { + var ct = TestContext.Current.CancellationToken; + using var stream = await OneItemStream.OpenAsync(ct); + var (fixture, session) = (stream.Fixture, stream.Session); + var differing = fixture.Serving with { CatalogEpoch = 0, AuthorityEpoch = 0 }; + foreach (var (version, value, serving) in new[] { (2L, 21, fixture.Serving), (3L, 31, differing) }) + { + // The tick that queues the value also disposes the hub read it came from; only then is the frame taken. + await stream.PublishAndWaitForQueuedTickAsync(version, value, serving, ct); + var values = await stream.NextValuesAsync(ct); + var delivered = values.Items.ShouldHaveSingleItem().Sample; + delivered.Version.ShouldBe(version); + delivered.Value.GetScalar().ShouldBe(value, "the frame's sample must not have been released with the read"); + delivered.Serving.ShouldBe(stream.ItemServing!, "a value carries the item's serving whatever the hub sample carried"); + values.Dispose(); + Should.Throw(() => delivered.Value.GetScalar(), "positive control: the frame owns and releases it"); + } + stream.ItemServing.ShouldBe(fixture.Serving, "positive control: the first value kept the read's own sample (no re-stamp)"); + stream.ItemServing.ShouldNotBe(differing, "positive control: the second value took the re-stamp branch"); + session.SampleTransfersForTests.ShouldBe(2, "positive control: both live values took over their reads"); + await stream.DisposeAsync(); + stream.AssertReleased(); + } + + [Fact(Timeout = 30000)] + public async Task A_held_value_frame_keeps_its_removed_items_reservation_until_the_frame_is_disposed_once() + { + var ct = TestContext.Current.CancellationToken; + using var stream = await OneItemStream.OpenAsync(ct); + stream.Capacity.InterestsForTests.ShouldBe(1, "positive control: the open item holds a reservation"); + await stream.PublishAndWaitForQueuedTickAsync(2, 21, stream.Fixture.Serving, ct); + var held = await stream.NextValuesAsync(ct); + await stream.Subscription.SendAsync(new RemoveSubscriptionItems("s", 1, "remove", TimeSpan.FromSeconds(5), [stream.Handle!]), ct); + (await stream.NextAsync(ct)).CommandId.ShouldBe("remove"); + // The item is gone from the stream, but the frame's lease still holds a reference on its reservation. + stream.Capacity.InterestsForTests.ShouldBe(1, "a removed item's reservation outlives it while one of its frames is held"); + held.Items[0].Sample.Value.GetScalar().ShouldBe(21); + held.Dispose(); + stream.Capacity.InterestsForTests.ShouldBe(0, "the frame held the last reference"); + held.Dispose(); + stream.Capacity.InterestsForTests.ShouldBe(0); + await stream.DisposeAsync(); + stream.AssertReleased(); + } + + // ---- FrameSlotWindow ---- + + [Fact(Timeout = 10000)] + public async Task The_frame_window_takes_a_slot_waits_for_a_release_and_refuses_a_double_release() + { + var ct = TestContext.Current.CancellationToken; + var window = new FrameSlotWindow(2); + window.WaitAsync(ct).IsCompletedSuccessfully.ShouldBeTrue(); + window.WaitAsync(ct).IsCompletedSuccessfully.ShouldBeTrue(); + window.AvailableForTests.ShouldBe(0); + var waiting = window.WaitAsync(ct).AsTask(); + await Task.Delay(50, ct); + waiting.IsCompleted.ShouldBeFalse("a full window waits"); + window.Release(); + await waiting.WaitAsync(TimeSpan.FromSeconds(5), ct); + window.AvailableForTests.ShouldBe(0, "the woken wait took the released slot"); + window.Release(); window.Release(); + window.AvailableForTests.ShouldBe(2); + Should.Throw(() => window.Release(), "a release past the capacity is a double release"); + window.AvailableForTests.ShouldBe(2); + } + + [Fact(Timeout = 10000)] + public async Task A_cancelled_frame_window_wait_takes_no_slot() + { + var ct = TestContext.Current.CancellationToken; + var window = new FrameSlotWindow(1); + await window.WaitAsync(ct); + using var stop = new CancellationTokenSource(); + var waiting = window.WaitAsync(stop.Token).AsTask(); + await Task.Delay(20, ct); + waiting.IsCompleted.ShouldBeFalse(); + await stop.CancelAsync(); + await Should.ThrowAsync(() => waiting.WaitAsync(TimeSpan.FromSeconds(5), ct)); + // Already cancelled: refused at once, even with a slot free. + window.Release(); + await Should.ThrowAsync(() => window.WaitAsync(stop.Token).AsTask()); + window.AvailableForTests.ShouldBe(1, "neither cancelled wait took a slot"); + // A later attempt's token registers afresh and still waits correctly. + await window.WaitAsync(ct); + var next = window.WaitAsync(ct).AsTask(); + window.Release(); + await next.WaitAsync(TimeSpan.FromSeconds(5), ct); + } + + [Fact(Timeout = 60000)] + public async Task The_frame_window_never_admits_more_than_its_capacity_and_loses_no_wakeup() + { + var ct = TestContext.Current.CancellationToken; + const int capacity = 3, frames = 200_000; + var window = new FrameSlotWindow(capacity); + var inFlight = 0; var maximum = 0; + var queue = new System.Collections.Concurrent.BlockingCollection(); + var consumer = Task.Run(() => + { + foreach (var _ in queue.GetConsumingEnumerable(ct)) + { + Interlocked.Decrement(ref inFlight); + window.Release(); + } + }, ct); + for (var i = 0; i < frames; i++) + { + await window.WaitAsync(ct); + var now = Interlocked.Increment(ref inFlight); + if (now > maximum) maximum = now; + queue.Add(i, ct); + } + queue.CompleteAdding(); + await consumer.WaitAsync(TimeSpan.FromSeconds(30), ct); + maximum.ShouldBeLessThanOrEqualTo(capacity); + maximum.ShouldBe(capacity, "positive control: the producer did fill the window"); + window.AvailableForTests.ShouldBe(capacity); + } + + [Fact(Timeout = 10000)] + public async Task Re_arming_the_slot_waiter_waits_out_a_signaller_still_completing_the_previous_wait() + { + var ct = TestContext.Current.CancellationToken; + var waiter = new SlotWaiter(); + var wait = waiter.Arm(); + using var inside = new ManualResetEventSlim(); + using var resume = new ManualResetEventSlim(); + waiter.AfterSetResultForTests = () => { inside.Set(); resume.Wait(ct); }; + var signaller = Task.Run(waiter.Signal, ct); + inside.Wait(TimeSpan.FromSeconds(5), ct).ShouldBeTrue(); + // The waiter sees its wait complete while the signaller has not left Signal yet... + wait.IsCompleted.ShouldBeTrue(); + await wait; + waiter.AfterSetResultForTests = null; + // ...so a re-arm must not reset the source under it. + var rearm = Task.Run(waiter.Arm, ct); + await Task.Delay(100, ct); + rearm.IsCompleted.ShouldBeFalse("a re-arm waits for the signaller to finish completing the previous wait"); + resume.Set(); + var next = await rearm.WaitAsync(TimeSpan.FromSeconds(5), ct); + await signaller.WaitAsync(TimeSpan.FromSeconds(5), ct); + next.IsCompleted.ShouldBeFalse("the previous signal must not complete the new wait"); + waiter.Signal(); + next.IsCompleted.ShouldBeTrue(); + await next; + } + + /// A real origin session with one subscribed item whose snapshot has been read. + private sealed class OneItemStream : IDisposable, IAsyncDisposable + { + private LocalDataFixture? _fixture; + private long _baselineBytes; + private int _queued; + private readonly SemaphoreSlim _queuedTicks = new(0); + private IAsyncEnumerator? _reader; + private bool _disposed; + internal LocalDataFixture Fixture => _fixture!; + internal SubscriptionTransportCapacity Capacity { get; } = new(64, 16, 256L * 1024 * 1024); + internal IDataSubscription Subscription { get; private set; } = null!; + internal DataSubscriptionSession Session { get; private set; } = null!; + internal DataItemHandle? Handle { get; private set; } + internal ServingIdentity? ItemServing { get; private set; } + private IDataConnection? _connection; + + internal static async Task OpenAsync(CancellationToken ct) + { + var stream = new OneItemStream(); + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var limits = new SubscriptionSessionLimits(16, 8, 100_000, TimeSpan.FromMinutes(1)); + stream._fixture = new LocalDataFixture(maxMonitoredItems: 16, hubBytes: 64L * 1024 * 1024, + targetSubscriptions: (context, target) => new LocalSubscriptionService(stream._fixture!.Services, context, target, demand, limits, stream.Capacity)); + stream._fixture.Publish(10); + stream._baselineBytes = stream._fixture.Hub.Resources.RetainedBytes; + stream._connection = stream._fixture.Connection(); + stream.Subscription = await stream._connection.SubscribeAsync(ct); + stream.Session = stream.Subscription.ShouldBeOfType(); + stream.Session.OnCandidateQueuedForTests = (_, _) => Interlocked.Exchange(ref stream._queued, 1); + stream.Session.AfterTickForTests = () => { if (Interlocked.Exchange(ref stream._queued, 0) == 1) stream._queuedTicks.Release(); }; + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); + await stream.Subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), + [new DataSubscriptionItem("item", stream._fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), + LocalDataFixture.Budget with { MaxItems = 1 }), ct); + stream._reader = stream.Subscription.ReadAllAsync(ct).GetAsyncEnumerator(ct); + var ack = await stream.NextAsync(ct); + stream.Handle = ack.Items.ShouldHaveSingleItem().Handle.ShouldNotBeNull(); + var baseline = await stream.NextValuesAsync(ct); + baseline.IsSnapshot.ShouldBeTrue(); + stream.ItemServing = baseline.Items[0].Sample.Serving; + baseline.Dispose(); + (await stream.NextAsync(ct, x => x.Kind == DataStreamControlKind.SnapshotEnd)).ShouldNotBeNull(); + return stream; + } + + internal async Task PublishAndWaitForQueuedTickAsync(long version, int value, ServingIdentity serving, CancellationToken ct) + { + using (var owned = DataValue.FromScalar(DataValueKind.Int32, value)) + { + Fixture.Hub.TryReserveIngress(Fixture.Ticket, owned.EstimatedRetainedBytes, out var reservation).ShouldBeTrue(); + using (reservation!) + { + var sample = new DataSample(owned.Retain(), 0, null, Fixture.Clock.GetUtcNow(), serving, version); + if (!reservation!.TryCommit(sample, version)) { sample.Dispose(); throw new InvalidOperationException("Commit rejected."); } + } + } + Fixture.Hub.ProcessPending(); + // A change that lands before the snapshot's completion is processed is picked up by a later tick (the session's + // 100 ms timer on this frozen clock), so step the clock while waiting. + var deadline = DateTime.UtcNow.AddSeconds(10); + while (!await _queuedTicks.WaitAsync(TimeSpan.FromMilliseconds(50), ct)) + { + if (DateTime.UtcNow > deadline) throw new ShouldAssertException("no tick queued the value"); + Fixture.Clock.Advance(TimeSpan.FromMilliseconds(100)); + } + } + + internal async Task NextValuesAsync(CancellationToken ct) => await NextAsync(ct); + + internal async Task NextAsync(CancellationToken ct, Func? match = null) where T : DataSubscriptionFrame + { + while (true) + { + (await _reader!.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct)).ShouldBeTrue("the stream must stay open"); + var frame = _reader.Current; + if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Reset } reset) + throw new ShouldAssertException("stream reset: " + reset.Diagnostic); + if (frame is T typed && (match is null || match(typed))) return typed; + (frame as IDisposable)?.Dispose(); + } + } + + /// Everything the stream charged is back: no leak, and (the equality) no double release. + internal void AssertReleased() + { + var deadline = DateTime.UtcNow.AddSeconds(10); + while ((Fixture.Hub.Resources.RetainedBytes != _baselineBytes || Capacity.InterestsForTests != 0) && DateTime.UtcNow < deadline) + Thread.Sleep(20); + Fixture.Hub.Resources.RetainedBytes.ShouldBe(_baselineBytes); + Capacity.InterestsForTests.ShouldBe(0); + } + + public async ValueTask DisposeAsync() + { + if (_disposed) return; + _disposed = true; + if (_reader is not null) await _reader.DisposeAsync(); + await Subscription.DisposeAsync(); + await Session.Completion.WaitAsync(TimeSpan.FromSeconds(10)); + if (_connection is not null) await _connection.DisposeAsync(); + } + + public void Dispose() { DisposeAsync().AsTask().GetAwaiter().GetResult(); _fixture?.Dispose(); _queuedTicks.Dispose(); } + } +} 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();