From bac7cfeaa94691774c99b151e70f593474afa740 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 16:47:48 -0500 Subject: [PATCH] perf(grpc-data): #1080 projected publish - per-value delivery without closures, sync enqueue, pooled full-window wait - PendingDelivery is an abstract base: ValueDelivery carries a value's state in fields (was a closure + seven delegates per value), DelegateDelivery keeps the delegate form for controls/acks/conditions. One ValueLease replaces BudgetLease + one or two CompositeLeases (same release order). - EnqueueAsync returns ValueTask and completes synchronously when a slot is free. A full window waits on the session's reused SlotWaiter (signalled by every dequeue and by Stop, which sets _closed first) instead of the channel's WriteAsync (a writer operation + cancellation registration per wait); the wait and TickAsync/PumpSnapshotsAsync/ConsiderAsync use PoolingAsyncValueTaskMethodBuilder, as do the reader's MoveNextAsync/NextPendingAsync. The #994 behaviour is unchanged: an ack meeting a full window waits for the reader and never resets the stream. - ConsiderAsync decides 'already considered / not yet due' on a version peek before taking a full cache read (CachedSourceRead + sample copy + value). - The tick signal is one shared immutable Work. New test: a worker waiting on a full window ends when the stream stops and releases what it held (fails if Stop does not wake the waiter). --- .../DataSubscriptionSession.Conditions.cs | 13 +- .../DataSubscriptionSession.Delivery.cs | 210 ++++++++++++++++++ .../DataSubscriptionSession.cs | 206 ++++++----------- .../GrpcDataDeliveryWindowTests.cs | 45 ++++ 4 files changed, 336 insertions(+), 138 deletions(-) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Delivery.cs diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Conditions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Conditions.cs index 3e3930ac3..de5f4ca64 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Conditions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Conditions.cs @@ -181,7 +181,7 @@ internal sealed partial class DataSubscriptionSession private PendingDelivery ConditionDelivery(ConditionItem item, ConditionChunk chunk) { var serving = _serving ?? throw new InvalidOperationException("Stream serving identity is unavailable."); - return new PendingDelivery(sequence => new DataSubscriptionConditions(_subscriptionId!, _epoch, sequence, item.Handle, + return new DelegateDelivery(sequence => new DataSubscriptionConditions(_subscriptionId!, _epoch, sequence, item.Handle, chunk.IsSnapshot, chunk.Total, chunk.Items, chunk.SnapshotComplete), () => Volatile.Read(ref _closed) == 0 && Volatile.Read(ref _closing) == 0 && _services.CanUseSubscription(_context, _target, serving) && IsConditionItemCurrent(item) && item.Authority.CanPublish(), @@ -200,6 +200,7 @@ internal sealed partial class DataSubscriptionSession /// on that). So conditions overtake queued values, and never a control or ack that is next. Null when the stream's /// queues are completed and drained. /// + [System.Runtime.CompilerServices.AsyncMethodBuilder(typeof(System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder<>))] // #1080 private async ValueTask NextPendingAsync(CancellationToken token) { while (true) @@ -257,20 +258,20 @@ internal sealed partial class DataSubscriptionSession /// Test seam: queues an empty value frame on the v1 queue. internal Task EnqueueValueProbeForTests() => - EnqueueAsync(new PendingDelivery(sequence => new DataSubscriptionValues(_subscriptionId!, _epoch, sequence, false, []), - () => true, isValue: true)); + EnqueueAsync(new DelegateDelivery(sequence => new DataSubscriptionValues(_subscriptionId!, _epoch, sequence, false, []), + () => true, isValue: true)).AsTask(); /// Test seam: queues a heartbeat control on the v1 queue. internal Task EnqueueHeartbeatProbeForTests() { var serving = _serving!; - return EnqueueAsync(new PendingDelivery(sequence => new DataSubscriptionControl(_subscriptionId!, _epoch, sequence, - DataStreamControlKind.Heartbeat, [], serving.CatalogEpoch, serving.AuthorityEpoch, null), () => true)); + return EnqueueAsync(new DelegateDelivery(sequence => new DataSubscriptionControl(_subscriptionId!, _epoch, sequence, + DataStreamControlKind.Heartbeat, [], serving.CatalogEpoch, serving.AuthorityEpoch, null), () => true)).AsTask(); } /// Test seam: queues an empty condition frame for ; false when the queue is full. internal bool TryEnqueueConditionProbeForTests(DataItemHandle handle) => - ConditionOutbound.Writer.TryWrite(new PendingDelivery(sequence => new DataSubscriptionConditions(_subscriptionId!, _epoch, + ConditionOutbound.Writer.TryWrite(new DelegateDelivery(sequence => new DataSubscriptionConditions(_subscriptionId!, _epoch, sequence, handle, false, null, [], false), () => true)); /// Called from the worker's teardown: completes and drains the condition queue, releases condition items. 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 new file mode 100644 index 000000000..7ab40beca --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.Delivery.cs @@ -0,0 +1,210 @@ +using System.Threading.Tasks.Sources; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// +/// #1080: the queued-frame types and the delivery-window waiter. A value is the hot path (one per delivered item value), so it +/// is its own type carrying its state in fields; controls and acknowledgements are rare and keep the delegate form. +/// +internal sealed partial class DataSubscriptionSession +{ + /// + /// One queued frame. transfers ownership of what it carries to the built frame; + /// before that drops it. or settles it exactly once (a dispose settles as failed). + /// + private abstract class PendingDelivery(bool isValue) : IDisposable + { + private int _transferred, _settled; + internal bool IsValue { get; } = isValue; + internal virtual bool IsObsolete() => false; + internal virtual bool IsEligible() => true; + internal virtual (bool Accepted, TimeSpan Retry) ConsumeSnapshot(long? bytes = null) => (true, TimeSpan.Zero); + internal abstract bool Gate(); + internal virtual bool FinalAuthority() => true; + /// Builds the frame; the frame owns what this delivery carried. + protected abstract DataSubscriptionFrame Create(long sequence); + protected virtual bool OnCommit() => true; + /// Releases what this delivery carries when no frame took it. + protected virtual void OnDrop() { } + protected virtual void OnFailed() { } + protected virtual void OnSettled() { } + internal bool Commit() + { + var success = false; + try { success = OnCommit(); return success; } + finally { Settle(success); } + } + internal void Fail() => Settle(false); + private void Settle(bool success) + { + if (Interlocked.Exchange(ref _settled, 1) != 0) return; + try { if (!success) OnFailed(); } + finally { OnSettled(); } + } + internal DataSubscriptionFrame Take(long sequence) + { + if (Interlocked.Exchange(ref _transferred, 1) != 0) throw new InvalidOperationException(); + try { return Create(sequence); } + catch { OnDrop(); Settle(false); throw; } + } + public void Dispose() + { + try { if (Interlocked.Exchange(ref _transferred, 1) == 0) OnDrop(); } + finally { Settle(false); } + } + } + + /// Controls, acknowledgements, condition frames and test probes: low-volume, so their hooks stay delegates. + private sealed class DelegateDelivery(Func create, Func gate, + Func? commit = null, Action? drop = null, bool isValue = false, Func? obsolete = null, + Action? settle = null, Action? failed = null, Func? finalAuthority = null) : PendingDelivery(isValue) + { + internal override bool IsObsolete() => obsolete?.Invoke() == true; + internal override bool Gate() => gate(); + internal override bool FinalAuthority() => finalAuthority?.Invoke() ?? true; + protected override DataSubscriptionFrame Create(long sequence) => create(sequence); + protected override bool OnCommit() => commit?.Invoke() ?? true; + protected override void OnDrop() => drop?.Invoke(); + protected override void OnFailed() => failed?.Invoke(); + protected override void OnSettled() => settle?.Invoke(); + } + + /// + /// #1080: one item value (live or snapshot). It used to be a built from a closure and seven + /// delegates per value; the same checks are methods over fields here. + /// + private sealed class ValueDelivery(DataSubscriptionSession session, Item item, DataSample owned, long received, long charge, + ValueLease lease, bool snapshot, SnapshotLease? snapshotLease, SnapshotAdmissionScheduler.Permit? snapshotPermit) + : PendingDelivery(isValue: true) + { + /// The cheap identity fences: the item, its source ticket, the snapshot (for a snapshot value) and the stream. + private bool Identity() => item.Ticket is { } ticket && + (snapshotLease is null || snapshotLease.IsItemCurrent(ticket) && snapshotPermit?.IsValid == true) && + Volatile.Read(ref session._closed) == 0 && Volatile.Read(ref session._closing) == 0 && session._handles!.IsCurrent(item.Handle) && + session._services.SubscriptionHub.IsTicketCurrentNonBlocking(ticket); + + internal override bool Gate() => Identity() && item.View.CanPublish(); + + internal override bool IsObsolete() => Volatile.Read(ref session._closing) != 0 || !session._handles!.IsCurrent(item.Handle); + + internal override bool IsEligible() + { + if (snapshot) return true; + if (item.Ticket is not { } ticket) return false; + // #1057: only the latest version matters here — peek it instead of retaining a second copy of the sample per value. + if (!session._services.SubscriptionHub.TryPeekReadyVersion(ticket, out var latestVersion)) + { session.CloseWithReset("Source became unavailable."); return false; } + if (latestVersion > owned.Version) + { + Interlocked.Exchange(ref session._coalesced, 1); + session.MarkDirty(item.View.Source); session.QueueTick(); return false; + } + lock (session._gate) + { + if (session._services.Clock.GetTimestamp() < item.NextDue) + { + if (item.LastConsidered == owned.Version) item.LastConsidered = item.LastPublished; + if (item.QueuedDue is null) { item.QueuedDue = item.NextDue; session._due.Add((item.NextDue, item.Handle.Handle)); } + return false; + } + return item.Filter.ShouldDeliver(owned, item.Settings); + } + } + + internal override (bool Accepted, TimeSpan Retry) ConsumeSnapshot(long? bytes = null) + { + if (!snapshot) return (true, TimeSpan.Zero); + if (snapshotPermit?.IsValid != true) return (false, TimeSpan.FromSeconds(1)); + var accepted = session._capacity.Snapshots.TryConsume(session._context.PrincipalId, bytes ?? charge, out var retry); + return (accepted, retry); + } + + protected override DataSubscriptionFrame Create(long sequence) + { + // Capture the admitted challenge before computing the age; queued/prepared frames retain this witness. + var freshnessChallengeId = Volatile.Read(ref session._freshnessChallengeId); + var age = session._services.Clock.GetElapsedTime(received); + if (age < TimeSpan.Zero) throw new InvalidOperationException("Invalid monotonic age."); + return new DataSubscriptionValues(session._subscriptionId!, session._epoch, sequence, snapshot, + [new(item.Handle, owned, new DataAgeBounds(age, null), DataReadiness.Ready, freshnessChallengeId)], lease); + } + + protected override bool OnCommit() + { + // #994 (R-12): the frame was authorized by Gate() right before the transport write it now commits; under the session + // lock only the cheap identity fences are re-checked (the authorization walk no longer runs while holding _gate). + lock (session._gate) + { + if (!Identity() || !session._items.TryGetValue(item.Handle.Handle, out var current) || !ReferenceEquals(current, item)) return false; + var resources = session._services.SubscriptionHub.Resources; + if (!resources.TryReserve(charge)) return false; + var next = new BudgetLease(resources, charge); + item.Filter.Commit(owned); item.BaselineCharge?.Dispose(); item.BaselineCharge = next; + item.LastPublished = owned.Version; + var now = session._services.Clock.GetTimestamp(); + item.LastDeliveryTimestamp = now; item.NextDue = session.DueFor(now, item.Settings); + return true; + } + } + + protected override void OnDrop() { owned.Dispose(); lease.Dispose(); } + } + + /// + /// #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. + /// + private sealed class ValueLease(DataResourceBudget budget, long charge, IDisposable itemHold, IDisposable? snapshotHold) : IDisposable + { + private int _disposed; + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + try { budget.Release(charge); } + finally + { + try { itemHold.Dispose(); } + finally { snapshotHold?.Dispose(); } + } + } + } + + /// + /// #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 4eba93987..40717f021 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs @@ -1,5 +1,6 @@ using System.Threading.Channels; using System.Collections.Concurrent; +using System.Runtime.CompilerServices; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; @@ -20,6 +21,7 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo private readonly Queue _deferred = new(); private readonly Channel _outbound; private readonly CancellationTokenSource _stop = new(); + private readonly SlotWaiter _slotWaiter = new(); private readonly object _gate = new(); private readonly Dictionary _items = new(); private readonly Dictionary _itemsByClient = new(StringComparer.Ordinal); @@ -85,6 +87,8 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo } private sealed record Work(DataSubscriptionCommand? Command, long Started, IDisposable? Charge = null); + /// #1080: the tick signal carries no command and no charge, so one immutable instance serves every tick. + private static readonly Work TickWork = new(null, 0); private sealed class Item(string clientItemId, DataItemHandle handle, SubscriptionAuthorizedView view, DataSubscriptionSettings settings, IDisposable demandLease, IDisposable itemReservation) : IDisposable { @@ -145,15 +149,6 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo private DataResourceBudget? _budget = budget; public void Dispose() => Interlocked.Exchange(ref _budget, null)?.Release(charge); } - private sealed class CompositeLease(IDisposable first, IDisposable second) : IDisposable - { - private IDisposable? _first = first, _second = second; - public void Dispose() - { - try { Interlocked.Exchange(ref _first, null)?.Dispose(); } - finally { Interlocked.Exchange(ref _second, null)?.Dispose(); } - } - } private sealed class SnapshotOwnership(SnapshotAdmissionScheduler.Permit permit, IDisposable hold) : IDisposable { internal readonly SnapshotAdmissionScheduler.Permit Permit = permit; @@ -164,46 +159,6 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo Interlocked.Exchange(ref _hold, null)?.Dispose(); } } - private sealed class PendingDelivery(Func create, Func gate, - Func? commit = null, Action? drop = null, bool isValue = false, Func? obsolete = null, - Func? eligible = null, Func? consumeSnapshot = null, - long directSnapshotBytes = 0, Action? settle = null, Action? failed = null, - Func? finalAuthority = null) : IDisposable - { - private int _transferred, _settled; - internal bool IsValue { get; } = isValue; - internal bool IsObsolete() => obsolete?.Invoke() == true; - internal bool IsEligible() => eligible?.Invoke() ?? true; - internal (bool Accepted, TimeSpan Retry) ConsumeSnapshot(long? bytes = null) => - consumeSnapshot?.Invoke(bytes ?? directSnapshotBytes) ?? (true, TimeSpan.Zero); - internal bool Gate() => gate(); - internal bool FinalAuthority() => finalAuthority?.Invoke() ?? true; - internal bool Commit() - { - var success = false; - try { success = commit?.Invoke() ?? true; return success; } - finally { Settle(success); } - } - internal void Fail() => Settle(false); - private void Settle(bool success) - { - if (Interlocked.Exchange(ref _settled, 1) != 0) return; - try { if (!success) failed?.Invoke(); } - finally { settle?.Invoke(); } - } - internal DataSubscriptionFrame Take(long sequence) - { - if (Interlocked.Exchange(ref _transferred, 1) != 0) throw new InvalidOperationException(); - try { return create(sequence); } - catch { drop?.Invoke(); Settle(false); throw; } - } - public void Dispose() - { - try { if (Interlocked.Exchange(ref _transferred, 1) == 0) drop?.Invoke(); } - finally { Settle(false); } - } - } - internal DataSubscriptionSession(LocalDataServices services, DataAuthenticatedContext context, DataTarget target, ISubscriptionDemandSource demand, SubscriptionSessionLimits limits, SubscriptionTransportCapacity capacity, IDisposable sessionReservation, CancellationToken lifetimeToken = default) @@ -433,7 +388,7 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo { if (Interlocked.CompareExchange(ref _barrier, 0, expected) != expected) return; // A full command queue already wakes the worker; otherwise this bounded signal does. - _commands.Writer.TryWrite(new(null, 0)); + _commands.Writer.TryWrite(TickWork); } private async Task OpenAsync(OpenSubscription open, long started) @@ -848,10 +803,13 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo private void QueueTick() { if (Interlocked.Exchange(ref _tickQueued, 1) != 0 || Volatile.Read(ref _closed) != 0) return; - if (!_commands.Writer.TryWrite(new(null, 0))) { Interlocked.Exchange(ref _tickQueued, 0); Stop(); } + if (!_commands.Writer.TryWrite(TickWork)) { Interlocked.Exchange(ref _tickQueued, 0); Stop(); } } - private async Task TickAsync() + // #1080: TickAsync, PumpSnapshotsAsync and ConsiderAsync box only when a frame meets a full window; the pooling builder + // reuses those boxes. A free slot completes them synchronously. + [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))] + private async ValueTask TickAsync() { try { @@ -872,7 +830,7 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo { _lastHeartbeat = _services.Clock.GetTimestamp(); var serving = _serving!; - await EnqueueAsync(new PendingDelivery(sequence => new DataSubscriptionControl(_subscriptionId!, _epoch, + await EnqueueAsync(new DelegateDelivery(sequence => new DataSubscriptionControl(_subscriptionId!, _epoch, sequence, DataStreamControlKind.Heartbeat, [], serving.CatalogEpoch, serving.AuthorityEpoch, null), () => Volatile.Read(ref _closed) == 0 && _services.CanUseSubscription(_context, _target, _serving))).ConfigureAwait(false); } @@ -996,7 +954,8 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo return true; } - private async Task PumpSnapshotsAsync() + [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))] + private async ValueTask PumpSnapshotsAsync() { var budget = Math.Min(32, _snapshotJobs.Count * 2); while (budget-- > 0 && _snapshotJobs.First is { } node && Volatile.Read(ref _closing) == 0) @@ -1084,7 +1043,8 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo job.Group.Lease.Dispose(); } - private async Task ConsiderAsync(Item item) + [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))] + private async ValueTask ConsiderAsync(Item item) { lock (_gate) { @@ -1097,10 +1057,23 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo if (item.Interest is { SnapshotComplete: false }) return; } if (item.Ticket is not { } ticket) return; + // #1080: most considerations end before a value is built (already considered, or not yet due at the publishing + // interval). Decide those on a version peek; only a consideration that can deliver retains a copy of the sample. + if (!_services.SubscriptionHub.TryPeekReadyVersion(ticket, out var peeked)) { CloseWithReset("Source became unavailable."); return; } + if (peeked <= item.LastConsidered) return; + var now = _services.Clock.GetTimestamp(); + lock (_gate) + { + if (!_items.TryGetValue(item.Handle.Handle, out var current) || !ReferenceEquals(current, item)) return; + if (now < item.NextDue) + { + if (item.QueuedDue is null) { item.QueuedDue = item.NextDue; _due.Add((item.NextDue, item.Handle.Handle)); } + return; + } + } using var read = _services.SubscriptionHub.Read(ticket); if (read.Readiness != DataReadiness.Ready || read.Sample is null) { CloseWithReset("Source became unavailable."); return; } if (read.Sample.Version <= item.LastConsidered) return; - var now = _services.Clock.GetTimestamp(); lock (_gate) { if (!_items.TryGetValue(item.Handle.Handle, out var current) || !ReferenceEquals(current, item)) return; @@ -1128,72 +1101,11 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo DataSample owned; try { owned = sample with { Value = sample.Value.Retain(), Serving = item.View.Serving }; } catch { snapshotHold?.Dispose(); _services.SubscriptionHub.Resources.Release(charge); throw; } - IDisposable lease; - try - { - lease = new CompositeLease(new BudgetLease(_services.SubscriptionHub.Resources, charge), item.Resources.Retain()); - if (snapshotHold is not null) lease = new CompositeLease(lease, snapshotHold); - } + 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; } - bool Identity() => item.Ticket is { } ticket && - (snapshotLease is null || snapshotLease.IsItemCurrent(ticket) && snapshotPermit?.IsValid == true) && - Volatile.Read(ref _closed) == 0 && Volatile.Read(ref _closing) == 0 && _handles!.IsCurrent(item.Handle) && - _services.SubscriptionHub.IsTicketCurrentNonBlocking(ticket); - bool Gate() => Identity() && item.View.CanPublish(); - bool Commit() - { - // #994 (R-12): the frame was authorized by Gate() right before the transport write it now commits; under the session - // lock only the cheap identity fences are re-checked (the authorization walk no longer runs while holding _gate). - lock (_gate) - { - if (!Identity() || !_items.TryGetValue(item.Handle.Handle, out var current) || !ReferenceEquals(current, item)) return false; - if (!_services.SubscriptionHub.Resources.TryReserve(charge)) return false; - var next = new BudgetLease(_services.SubscriptionHub.Resources, charge); - item.Filter.Commit(owned); item.BaselineCharge?.Dispose(); item.BaselineCharge = next; - item.LastPublished = owned.Version; - var now = _services.Clock.GetTimestamp(); - item.LastDeliveryTimestamp = now; item.NextDue = DueFor(now, item.Settings); - return true; - } - } - bool Eligible() - { - if (snapshot) return true; - if (item.Ticket is not { } ticket) return false; - // #1057: only the latest version matters here — peek it instead of retaining a second copy of the sample per value. - if (!_services.SubscriptionHub.TryPeekReadyVersion(ticket, out var latestVersion)) { CloseWithReset("Source became unavailable."); return false; } - if (latestVersion > owned.Version) - { - Interlocked.Exchange(ref _coalesced, 1); - MarkDirty(item.View.Source); QueueTick(); return false; - } - lock (_gate) - { - if (_services.Clock.GetTimestamp() < item.NextDue) - { - if (item.LastConsidered == owned.Version) item.LastConsidered = item.LastPublished; - if (item.QueuedDue is null) { item.QueuedDue = item.NextDue; _due.Add((item.NextDue, item.Handle.Handle)); } - return false; - } - return item.Filter.ShouldDeliver(owned, item.Settings); - } - } - return new PendingDelivery(sequence => - { - // Capture the admitted challenge before computing the age; queued/prepared frames retain this witness. - var freshnessChallengeId = Volatile.Read(ref _freshnessChallengeId); - var age = _services.Clock.GetElapsedTime(received); - if (age < TimeSpan.Zero) throw new InvalidOperationException("Invalid monotonic age."); - return new DataSubscriptionValues(_subscriptionId!, _epoch, sequence, snapshot, - [new(item.Handle, owned, new DataAgeBounds(age, null), DataReadiness.Ready, freshnessChallengeId)], lease); - }, Gate, Commit, () => { owned.Dispose(); lease.Dispose(); }, true, - () => Volatile.Read(ref _closing) != 0 || !_handles!.IsCurrent(item.Handle), Eligible, - snapshot ? bytes => - { - if (snapshotPermit?.IsValid != true) return (false, TimeSpan.FromSeconds(1)); - var accepted = _capacity.Snapshots.TryConsume(_context.PrincipalId, bytes, out var retry); - return (accepted, retry); - } : null, charge); + // #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); } private long DueFor(long? observedStart, DataSubscriptionSettings settings) @@ -1214,7 +1126,7 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo if (bytes > _limits.MaxPendingBytes || !_services.SubscriptionHub.Resources.TryReserve(bytes)) throw new InvalidOperationException("Acknowledgement memory capacity exhausted."); var charge = new BudgetLease(_services.SubscriptionHub.Resources, bytes); - return new PendingDelivery(sequence => new DataSubscriptionAck(_subscriptionId!, _epoch, sequence, command, acks), + return new DelegateDelivery(sequence => new DataSubscriptionAck(_subscriptionId!, _epoch, sequence, command, acks), () => (additionalGate?.Invoke() ?? true) && Volatile.Read(ref _closed) == 0 && _services.CanUseSubscription(_context, _target, _serving), () => CompleteAck(command) && (onDelivered?.Invoke() ?? true), settle: charge.Dispose, failed: onFailed, @@ -1224,7 +1136,7 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo SnapshotAdmissionScheduler.Permit permit, Action? delivered = null, Action? dropped = null) { var serving = _serving ?? throw new InvalidOperationException("Stream serving identity is unavailable."); - return new(sequence => new DataSubscriptionControl(_subscriptionId!, _epoch, sequence, kind, marks, + return new DelegateDelivery(sequence => new DataSubscriptionControl(_subscriptionId!, _epoch, sequence, kind, marks, serving.CatalogEpoch, serving.AuthorityEpoch, null), () => !snapshot.IsReset && permit.IsValid && Volatile.Read(ref _closed) == 0 && Volatile.Read(ref _closing) == 0 && _services.CanUseSubscription(_context, _target, _serving), @@ -1241,14 +1153,15 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo // Production callers all run on the command worker (commands, ticks, the snapshot pump), so waiting here backpressures // that worker — never the reader, which drains the window independently. - private async Task EnqueueAsync(PendingDelivery delivery) + private ValueTask EnqueueAsync(PendingDelivery delivery) { - if (Volatile.Read(ref _closed) != 0 || Volatile.Read(ref _closing) != 0) { delivery.Dispose(); return; } + if (Volatile.Read(ref _closed) != 0 || Volatile.Read(ref _closing) != 0) { delivery.Dispose(); return default; } if (delivery.IsValue && Interlocked.Increment(ref _queuedValues) > Math.Max(1, _limits.MaxPendingFrames - 2)) { - Interlocked.Decrement(ref _queuedValues); delivery.Dispose(); CloseWithReset("Pending value capacity exhausted."); return; + Interlocked.Decrement(ref _queuedValues); delivery.Dispose(); CloseWithReset("Pending value capacity exhausted."); return default; } - if (_outbound.Writer.TryWrite(delivery)) return; + // #1080: a free slot completes synchronously: no async state machine, no Task. + if (_outbound.Writer.TryWrite(delivery)) return default; // A full window is a reader a few frames behind, not a fault. The snapshot pump leaves only one slot for command // acknowledgements, but the peer may have up to MaxCommands commands in flight (a projected cohort keeps four), so a // second acknowledgement produced while a snapshot filled the window found it full and this used to reset the whole @@ -1256,19 +1169,45 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo // Wait for the reader instead: every dequeue frees a slot, and a reader that never drains is still bounded by the // acknowledgement deadline, the session lifetime and the command queue (each of which Stops the session). OutboundFullForTests?.Invoke(); - try { await _outbound.Writer.WriteAsync(delivery, _stop.Token).ConfigureAwait(false); } - catch (Exception ex) when (ex is OperationCanceledException or ChannelClosedException) - { Dequeued(delivery); delivery.Dispose(); } + return WaitForSlotAsync(delivery); + } + + /// + /// #1080: the full-window path. It waits on the session's reused (signalled by every dequeue and + /// by ) instead of the channel's WriteAsync, which allocated a writer operation and a cancellation + /// registration per wait; the pooling builder reuses this method's state-machine box. + /// + [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))] + private async ValueTask WaitForSlotAsync(PendingDelivery delivery) + { + while (true) + { + // Arm before re-trying: a dequeue (or a stop) landing between the failed write and the await is then never missed. + // Stop sets _closed before it signals, so a stop either is seen here or wakes the await below. + var slot = _slotWaiter.Arm(); + if (Volatile.Read(ref _closed) != 0) + { + if (!_slotWaiter.TryDisarm()) await slot.ConfigureAwait(false); + Dequeued(delivery); delivery.Dispose(); return; + } + if (_outbound.Writer.TryWrite(delivery)) + { + if (!_slotWaiter.TryDisarm()) await slot.ConfigureAwait(false); + return; + } + await slot.ConfigureAwait(false); + } } private void Dequeued(PendingDelivery delivery) { if (delivery.IsValue) Interlocked.Decrement(ref _queuedValues); + _slotWaiter.Signal(); QueueTick(); } private PendingDelivery CoalescedControl() { var serving = _serving ?? throw new InvalidOperationException("Stream serving identity is unavailable."); - return new PendingDelivery(sequence => new DataSubscriptionControl(_subscriptionId!, _epoch, sequence, + return new DelegateDelivery(sequence => new DataSubscriptionControl(_subscriptionId!, _epoch, sequence, DataStreamControlKind.Coalesced, [], serving.CatalogEpoch, serving.AuthorityEpoch, null), () => Volatile.Read(ref _closed) == 0 && Volatile.Read(ref _closing) == 0 && _services.CanUseSubscription(_context, _target, serving)); @@ -1278,7 +1217,7 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo if (Interlocked.Exchange(ref _closing, 1) != 0) return; _tick?.Dispose(); var serving = _serving; - if (serving is null || !_outbound.Writer.TryWrite(new PendingDelivery(sequence => + if (serving is null || !_outbound.Writer.TryWrite(new DelegateDelivery(sequence => new DataSubscriptionControl(_subscriptionId!, _epoch, sequence, DataStreamControlKind.Reset, [], serving.CatalogEpoch, serving.AuthorityEpoch, diagnostic), () => Volatile.Read(ref _closed) == 0 && _services.CanUseSubscription(_context, _target, serving), @@ -1296,6 +1235,8 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo if (Interlocked.CompareExchange(ref owner._mode, 1, 0) != 0) throw new InvalidOperationException("Delivery mode already selected."); _linked = CancellationTokenSource.CreateLinkedTokenSource(token, cancellationToken, owner._stop.Token); return this; } + // #1080: the reader waits on an empty window between frames; reuse that state-machine box. + [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))] public async ValueTask MoveNextAsync() { try @@ -1382,6 +1323,7 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo private void Stop() { if (Interlocked.Exchange(ref _closed, 1) != 0) return; + _slotWaiter.Signal(); // #1080: a worker waiting for a window slot sees _closed and gives the frame up _preOpen?.Dispose(); _expiry?.Dispose(); _tick?.Dispose(); _ackTimer?.Dispose(); _commands.Writer.TryComplete(); _stop.Cancel(); } public async ValueTask DisposeAsync() { Stop(); await _worker.ConfigureAwait(false); } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeliveryWindowTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeliveryWindowTests.cs index 8ab156f7d..72cd2e4f8 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeliveryWindowTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeliveryWindowTests.cs @@ -79,4 +79,49 @@ public sealed class GrpcDataDeliveryWindowTests acks.ShouldBe(Enumerable.Range(0, commands).Select(i => "cmd-" + i), ignoreOrder: true); } } + + /// + /// #1080: the full-window wait is the session's own reused waiter (signalled by dequeues and by stop), no longer the + /// channel's cancellable WriteAsync. A stream that stops while its worker waits on a full window must still end that + /// wait: the worker exits, and the waiting frame and everything queued are released. + /// + [Fact(Timeout = 30000)] + public async Task A_worker_waiting_on_a_full_window_ends_when_the_stream_stops_and_releases_what_it_held() + { + var ct = TestContext.Current.CancellationToken; + var demand = new DeferredSubscriptionDemand(); demand.Accept(); + var capacity = new SubscriptionTransportCapacity(64, 16, 256L * 1024 * 1024); + var limits = new SubscriptionSessionLimits(16, 8, 100_000, TimeSpan.FromMinutes(1)); + const int commands = 4, perCommand = 4; + LocalDataFixture? fixture = null; + using (fixture = new LocalDataFixture(additionalRawNodes: commands * perCommand, maxMonitoredItems: 64, hubBytes: 64L * 1024 * 1024, + targetSubscriptions: (context, target) => new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity))) + { + fixture.Publish(10); + var baseline = fixture.Hub.Resources.RetainedBytes; + await using var connection = fixture.Connection(); + var subscription = await connection.SubscribeAsync(ct); + var session = subscription.ShouldBeOfType(); + using var full = new ManualResetEventSlim(); + session.OutboundFullForTests = full.Set; + var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null); + DataSubscriptionItem[] Items(int command) => Enumerable.Range(command * perCommand, perCommand) + .Select(i => new DataSubscriptionItem("item-" + i, fixture.Raw with + { Address = fixture.Raw.Address with { Identifier = fixture.Raw.Address.Identifier + i }, Subject = fixture.Raw.Subject + i }, settings)) + .ToArray(); + await subscription.SendAsync(new OpenSubscription("s", 1, "cmd-0", TimeSpan.FromSeconds(5), Items(0), false, + TimeSpan.FromSeconds(30), LocalDataFixture.Budget with { MaxItems = commands * perCommand }), ct); + for (var command = 1; command < commands; command++) + await subscription.SendAsync(new AddSubscriptionItems("s", 1, "cmd-" + command, TimeSpan.FromSeconds(5), Items(command)), ct); + full.Wait(TimeSpan.FromSeconds(10), ct).ShouldBeTrue("positive control: the worker met a full delivery window"); + fixture.Hub.Resources.RetainedBytes.ShouldBeGreaterThan(baseline, "positive control: queued frames hold budget"); + + // Nothing was ever read: the stop alone must end the worker's wait. + await subscription.DisposeAsync(); + await session.Completion.WaitAsync(TimeSpan.FromSeconds(10), ct); + var deadline = DateTime.UtcNow.AddSeconds(10); + while (fixture.Hub.Resources.RetainedBytes != baseline && DateTime.UtcNow < deadline) await Task.Delay(20, ct); + fixture.Hub.Resources.RetainedBytes.ShouldBe(baseline); + } + } }