Merge gRPC data follow-ups (#1080): allocation-light projected publish (one ValueDelivery per value, synchronous enqueue when a slot is free, reused window waiter; ~20% fewer bytes/value), held connection's stale mark timed from the hold start
This commit is contained in:
+23
-1
@@ -293,6 +293,25 @@ Follow-ups (#1057):
|
||||
session tick reuses its working lists. Measured with the perf harness (10k-item cohort, 100 versions at 1k/s): about
|
||||
5.3 KB to about 4.3 KB allocated per delivered value. That figure includes the harness's own per-value copies.
|
||||
|
||||
Follow-ups (#1080):
|
||||
|
||||
- **A queued value is one object with fields.** Each value used to be a pending delivery built from a closure and seven
|
||||
delegates, plus three lease objects. It is now one `ValueDelivery` and one `ValueLease`. Controls, acknowledgements and
|
||||
condition frames are rare and keep the delegate form.
|
||||
- **A free window slot enqueues synchronously.** `EnqueueAsync` returns a `ValueTask` that completes without an async
|
||||
state machine when the write succeeds. A full window still waits for the reader, as the #994 fix requires; a command
|
||||
acknowledgement never resets the stream for a full window. The wait now uses the session's reused waiter, which every
|
||||
dequeue and `Stop` signal, instead of the channel's `WriteAsync`. That allocated a writer operation and a cancellation
|
||||
registration per wait. The waiting methods use pooled state machines.
|
||||
- **A consideration that cannot deliver does not copy the sample.** The tick first checks the source's version (a peek):
|
||||
an item already considered at that version, or not yet due at its publishing interval, stops there. Only an item that
|
||||
can deliver takes a full cache read.
|
||||
- Measured with the same harness (`GrpcDataWave3PerfTests`, 10k-item cohort, 100 versions at 1k/s), before and after on
|
||||
the same machine and session. Release: about 2.85–3.0 KB to about 2.2–2.5 KB per delivered value. Debug: about 4.5 KB to
|
||||
about 3.85 KB. The figure is a process-wide count: it includes the consumer cohort and the harness's own copies and
|
||||
polling. The remaining per-value cost is mostly sample and value copies along the path (the cache read, the frame's
|
||||
owned copy, the consumer's update).
|
||||
|
||||
### Mixed versions (X0 rollout)
|
||||
|
||||
The remote history and alarm work (`docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md`)
|
||||
@@ -610,7 +629,10 @@ An origin streams its alarm condition state to a peer that negotiated `condition
|
||||
empty and the held conditions are removed. (Browse anchors still stay retained until a successful activation.)
|
||||
- An attempt that never completes is bounded. The held conditions go `BadNoCommunication` on the connection's stale
|
||||
timeout, as for any stream gap, and are removed past `ProjectedConditionOptions.MaxHold` (5 min, 2.5× the deploy apply
|
||||
deadline). Until then they stay charged to the host caps and diagnostics show the connection as `held`.
|
||||
deadline). Until then they stay charged to the host caps and diagnostics show the connection as `held`. Both clocks
|
||||
run from the start of the hold (#1080). The stale mark still waits for the held runner's loop to unwind, so no late
|
||||
Good from that loop can follow it. A mark that falls due before the unwind lands at the unwind. It used to be armed
|
||||
only at the unwind, so under load it came late, or the MaxHold release ended the hold first and it never came.
|
||||
- The runner that takes a held set over sends **RefreshRequired once** at its first barrier. While the set was held
|
||||
nothing imported was visible, so an event queued then was dropped and a ConditionRefresh replayed nothing. RefreshRequired
|
||||
is a Server-object event, not a condition event: EventIds are kept and no condition event is added.
|
||||
|
||||
+7
-6
@@ -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.
|
||||
/// </summary>
|
||||
[System.Runtime.CompilerServices.AsyncMethodBuilder(typeof(System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder<>))] // #1080
|
||||
private async ValueTask<PendingDelivery?> NextPendingAsync(CancellationToken token)
|
||||
{
|
||||
while (true)
|
||||
@@ -257,20 +258,20 @@ internal sealed partial class DataSubscriptionSession
|
||||
|
||||
/// <summary>Test seam: queues an empty value frame on the v1 queue.</summary>
|
||||
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();
|
||||
|
||||
/// <summary>Test seam: queues a heartbeat control on the v1 queue.</summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>Test seam: queues an empty condition frame for <paramref name="handle"/>; false when the queue is full.</summary>
|
||||
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));
|
||||
|
||||
/// <summary>Called from the worker's teardown: completes and drains the condition queue, releases condition items.</summary>
|
||||
|
||||
+210
@@ -0,0 +1,210 @@
|
||||
using System.Threading.Tasks.Sources;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
/// <summary>
|
||||
/// #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.
|
||||
/// </summary>
|
||||
internal sealed partial class DataSubscriptionSession
|
||||
{
|
||||
/// <summary>
|
||||
/// One queued frame. <see cref="Take"/> transfers ownership of what it carries to the built frame; <see cref="Dispose"/>
|
||||
/// before that drops it. <see cref="Commit"/> or <see cref="Fail"/> settles it exactly once (a dispose settles as failed).
|
||||
/// </summary>
|
||||
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;
|
||||
/// <summary>Builds the frame; the frame owns what this delivery carried.</summary>
|
||||
protected abstract DataSubscriptionFrame Create(long sequence);
|
||||
protected virtual bool OnCommit() => true;
|
||||
/// <summary>Releases what this delivery carries when no frame took it.</summary>
|
||||
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); }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Controls, acknowledgements, condition frames and test probes: low-volume, so their hooks stay delegates.</summary>
|
||||
private sealed class DelegateDelivery(Func<long, DataSubscriptionFrame> create, Func<bool> gate,
|
||||
Func<bool>? commit = null, Action? drop = null, bool isValue = false, Func<bool>? obsolete = null,
|
||||
Action? settle = null, Action? failed = null, Func<bool>? 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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #1080: one item value (live or snapshot). It used to be a <see cref="DelegateDelivery"/> built from a closure and seven
|
||||
/// delegates per value; the same checks are methods over fields here.
|
||||
/// </summary>
|
||||
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)
|
||||
{
|
||||
/// <summary>The cheap identity fences: the item, its source ticket, the snapshot (for a snapshot value) and the stream.</summary>
|
||||
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(); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #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.
|
||||
/// </summary>
|
||||
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(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #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). <see cref="Arm"/> before re-trying the write, <see cref="Signal"/> 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.
|
||||
/// </summary>
|
||||
private sealed class SlotWaiter : IValueTaskSource
|
||||
{
|
||||
private ManualResetValueTaskSourceCore<bool> _core = new() { RunContinuationsAsynchronously = true };
|
||||
private int _armed;
|
||||
|
||||
/// <summary>Arms the waiter. The caller re-tries its write after this, so a slot freed in between is not missed.</summary>
|
||||
public ValueTask Arm()
|
||||
{
|
||||
_core.Reset();
|
||||
Interlocked.Exchange(ref _armed, 1);
|
||||
return new ValueTask(this, _core.Version);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="Arm"/> never resets a source being completed.
|
||||
/// </summary>
|
||||
public bool TryDisarm() => Interlocked.Exchange(ref _armed, 0) == 1;
|
||||
|
||||
/// <summary>Completes an armed wait. A full fence (the CAS) after the caller's dequeue pairs with the one in <see cref="Arm"/>.</summary>
|
||||
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<object?> continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) =>
|
||||
_core.OnCompleted(continuation, state, token, flags);
|
||||
}
|
||||
}
|
||||
@@ -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<Work> _deferred = new();
|
||||
private readonly Channel<PendingDelivery> _outbound;
|
||||
private readonly CancellationTokenSource _stop = new();
|
||||
private readonly SlotWaiter _slotWaiter = new();
|
||||
private readonly object _gate = new();
|
||||
private readonly Dictionary<ulong, Item> _items = new();
|
||||
private readonly Dictionary<string, Item> _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);
|
||||
/// <summary>#1080: the tick signal carries no command and no charge, so one immutable instance serves every tick.</summary>
|
||||
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<long, DataSubscriptionFrame> create, Func<bool> gate,
|
||||
Func<bool>? commit = null, Action? drop = null, bool isValue = false, Func<bool>? obsolete = null,
|
||||
Func<bool>? eligible = null, Func<long, (bool Accepted, TimeSpan Retry)>? consumeSnapshot = null,
|
||||
long directSnapshotBytes = 0, Action? settle = null, Action? failed = null,
|
||||
Func<bool>? 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #1080: the full-window path. It waits on the session's reused <see cref="SlotWaiter"/> (signalled by every dequeue and
|
||||
/// by <see cref="Stop"/>) 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.
|
||||
/// </summary>
|
||||
[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<bool> 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); }
|
||||
|
||||
+21
-16
@@ -395,27 +395,32 @@ public sealed partial class ProjectedConditionAccess
|
||||
|
||||
/// <summary>
|
||||
/// A4 review r2 S2 (under the owner's _gate, right after <see cref="Stop"/> without removal): the hold is bounded.
|
||||
/// <paramref name="release"/> fires at <c>MaxHold</c> (the owner releases); after the loop has stopped, the held
|
||||
/// conditions go <c>BadNoCommunication</c> on the connection's stale timeout — a hold is a stream gap (§5.1 T2: unknown,
|
||||
/// never known-inactive). <see cref="EndHold"/> (takeover / release) disarms both.
|
||||
/// <paramref name="release"/> fires at <c>MaxHold</c> (the owner releases); the held conditions go
|
||||
/// <c>BadNoCommunication</c> on the connection's stale timeout — a hold is a stream gap (§5.1 T2: unknown, never
|
||||
/// known-inactive). <see cref="EndHold"/> (takeover / release) disarms both.
|
||||
/// <para>
|
||||
/// #1080: the stale timeout runs from the hold's START, as MaxHold does. It used to be armed only once the loop had
|
||||
/// unwound, so under load (a slow unwind) the mark came late, or the MaxHold release ended the hold first and the
|
||||
/// mark never came. The mark still never lands before the unwind (a late Good from that loop could follow it): one
|
||||
/// due earlier waits for the unwind and lands then.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public void Hold(ITimer release)
|
||||
{
|
||||
lock (_staleGate) { _holding = true; _holdRelease = release; }
|
||||
_ = _stopped.ContinueWith(_ =>
|
||||
var stopped = _stopped;
|
||||
var timeout = TimeSpan.FromMilliseconds(Math.Max(1, _mappings.Min(x => x.Mapping.ConditionStaleTimeoutMilliseconds)));
|
||||
lock (_staleGate)
|
||||
{
|
||||
lock (_staleGate)
|
||||
_holding = true; _holdRelease = release;
|
||||
_holdStale = _owner._clock.CreateTimer(_ => _ = stopped.ContinueWith(_ =>
|
||||
{
|
||||
if (!_holding || _materialised.Count == 0) return;
|
||||
var timeout = TimeSpan.FromMilliseconds(Math.Max(1, _mappings.Min(x => x.Mapping.ConditionStaleTimeoutMilliseconds)));
|
||||
_holdStale = _owner._clock.CreateTimer(_ =>
|
||||
{
|
||||
// Under the same gate EndHold takes before any takeover, so a mark never lands after the successor began.
|
||||
lock (_staleGate)
|
||||
if (_holding) _owner._sink()?.MarkConnectionStale(ConnectionId);
|
||||
}, null, timeout, Timeout.InfiniteTimeSpan);
|
||||
}
|
||||
}, TaskScheduler.Default);
|
||||
// Under the same gate EndHold takes before any takeover, so a mark never lands after the successor began.
|
||||
// The loop has unwound here, so its materialised set is settled; nothing held ⇒ nothing to mark.
|
||||
lock (_staleGate)
|
||||
if (_holding && _materialised.Count > 0) _owner._sink()?.MarkConnectionStale(ConnectionId);
|
||||
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default),
|
||||
null, timeout, Timeout.InfiniteTimeSpan);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A4 review r2 S2: the hold ended (taken over, released, disposed) — no stale mark or release fires after this.</summary>
|
||||
|
||||
+45
@@ -79,4 +79,49 @@ public sealed class GrpcDataDeliveryWindowTests
|
||||
acks.ShouldBe(Enumerable.Range(0, commands).Select(i => "cmd-" + i), ignoreOrder: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #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.
|
||||
/// </summary>
|
||||
[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<DataSubscriptionSession>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+75
-4
@@ -1039,6 +1039,8 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
// (as in a full parallel Runtime.Tests run): the stale mark landed ~1.9 s after the hold while the release fired at
|
||||
// ~0.9 s — the release ends the hold first, so the stale mark is skipped (or the test's later check sees the removal).
|
||||
// Production keeps minutes of margin (MaxHold 5 min). 5 s keeps the ordering under that load (~3 s of margin).
|
||||
// #1080: the stale timeout now runs from the hold's start (a mark due before the unwind lands at the unwind), so only
|
||||
// an unwind slower than MaxHold could still reorder them; the fake-clock Issue1080_* tests pin that timing exactly.
|
||||
await using var f = new Fixture(Fixture.DefaultOptions with { MaxHold = TimeSpan.FromSeconds(5) }, ("map-a", DataRealm.Raw, 10));
|
||||
using var demand = f.Access.AcquireEventDemand(null);
|
||||
await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)]));
|
||||
@@ -1059,6 +1061,66 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
f.Access.Diagnostics.CaptureConsumer(Connection).ShouldBeNull();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #1080: the held set's stale mark is timed from the HOLD's start, as MaxHold is — not from the loop's unwind. Here the
|
||||
/// held runner's loop cannot unwind (its connection lease release is gated) until fake time is 50 ms short of MaxHold.
|
||||
/// The mark waits for the unwind (no late Good from that loop can follow it), then lands at once. It used to be armed
|
||||
/// only at the unwind, a further stale timeout later — past MaxHold here, so the release ended the hold first and the
|
||||
/// held conditions never went stale.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Issue1080_a_held_sets_stale_mark_is_timed_from_the_hold_not_from_the_loop_unwind()
|
||||
{
|
||||
var clock = new Harness.ManualTimeProvider();
|
||||
var maxHold = TimeSpan.FromSeconds(1);
|
||||
await using var f = new Fixture(clock, Fixture.DefaultOptions with { MaxHold = maxHold }, ("map-a", DataRealm.Raw, 10));
|
||||
using var demand = f.Access.AcquireEventDemand(null);
|
||||
await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)]));
|
||||
await f.WaitAsync(() => f.Sink.Live.Count == 1);
|
||||
|
||||
var unwind = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
f.Connections.LeaseReleaseGate = unwind;
|
||||
((List<ProjectedMappingPlacement>)f.Mappings.Current).Clear(); f.Mappings.Suspended = true; f.Mappings.Raise();
|
||||
await f.WaitAsync(() => f.Access.Diagnostics.CaptureConsumer(Connection)?.StreamState == "held");
|
||||
|
||||
// Past the stale timeout (100 ms), loop still unwinding: no mark yet — it must not precede the unwind.
|
||||
clock.Advance(maxHold - TimeSpan.FromMilliseconds(50));
|
||||
await Task.Delay(200, TestContext.Current.CancellationToken);
|
||||
f.Sink.Stale.ShouldBeEmpty("a stale mark must not land before the held runner's loop has unwound");
|
||||
|
||||
// The unwind completes: the mark, due since the hold's start + 100 ms, lands now — the clock does not move.
|
||||
unwind.SetResult();
|
||||
await f.WaitAsync(() => f.Sink.Stale.Contains(Connection));
|
||||
f.Sink.Removed.ShouldBeEmpty("stale, not removed, before MaxHold");
|
||||
|
||||
// MaxHold (from the hold's start) still releases the set.
|
||||
clock.Advance(TimeSpan.FromMilliseconds(50));
|
||||
await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x")));
|
||||
f.Sink.Live.ShouldBeEmpty();
|
||||
f.Sink.Stale.Count(x => x == Connection).ShouldBe(1);
|
||||
}
|
||||
|
||||
/// <summary>#1080: with a prompt unwind the stale mark lands exactly at hold start + the stale timeout (fake clock).</summary>
|
||||
[Fact]
|
||||
public async Task Issue1080_a_held_sets_stale_mark_lands_at_the_stale_timeout_after_the_hold()
|
||||
{
|
||||
var clock = new Harness.ManualTimeProvider();
|
||||
await using var f = new Fixture(clock, Fixture.DefaultOptions with { MaxHold = TimeSpan.FromSeconds(1) }, ("map-a", DataRealm.Raw, 10));
|
||||
using var demand = f.Access.AcquireEventDemand(null);
|
||||
await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)]));
|
||||
await f.WaitAsync(() => f.Sink.Live.Count == 1);
|
||||
|
||||
((List<ProjectedMappingPlacement>)f.Mappings.Current).Clear(); f.Mappings.Suspended = true; f.Mappings.Raise();
|
||||
await f.WaitAsync(() => f.Access.Diagnostics.CaptureConsumer(Connection)?.StreamState == "held");
|
||||
|
||||
clock.Advance(TimeSpan.FromMilliseconds(99));
|
||||
await Task.Delay(100, TestContext.Current.CancellationToken);
|
||||
f.Sink.Stale.ShouldBeEmpty("not before the stale timeout");
|
||||
clock.Advance(TimeSpan.FromMilliseconds(1));
|
||||
await f.WaitAsync(() => f.Sink.Stale.Contains(Connection)); // must-arrive: the timeout from the hold's start
|
||||
f.Sink.Removed.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
/// <summary>S3: the takeover's RefreshRequired is sent once — a later stream end with a complete re-snapshot sends none.</summary>
|
||||
[Fact]
|
||||
public async Task R2_S3_a_runner_taking_over_a_held_set_sends_RefreshRequired_once_at_its_first_barrier()
|
||||
@@ -1363,11 +1425,18 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
: this(options, mappings.Select(m => (m.Id, m.Realm, m.MaxConditions, Connection)).ToArray()) { }
|
||||
|
||||
public Fixture(ProjectedConditionOptions options, params (string Id, DataRealm Realm, int MaxConditions, string Connection)[] mappings)
|
||||
: this(TimeProvider.System, options, mappings) { }
|
||||
|
||||
/// <summary>#1080: the access runs on <paramref name="clock"/> (its timers: hold, stale, linger, snapshot, reconnect).</summary>
|
||||
public Fixture(TimeProvider clock, ProjectedConditionOptions options, params (string Id, DataRealm Realm, int MaxConditions)[] mappings)
|
||||
: this(clock, options, mappings.Select(m => (m.Id, m.Realm, m.MaxConditions, Connection)).ToArray()) { }
|
||||
|
||||
private Fixture(TimeProvider clock, ProjectedConditionOptions options, (string Id, DataRealm Realm, int MaxConditions, string Connection)[] mappings)
|
||||
{
|
||||
Grant(NodePermissions.Browse | NodePermissions.Subscribe);
|
||||
Mappings = new FakeMappings(mappings.Select(m => Placement(m.Id, m.Realm, m.MaxConditions, m.Connection)).ToList());
|
||||
var policy = new DataOperationPolicy(_state, new TriePermissionEvaluator(_state.Tries, TimeProvider.System), TimeProvider.System);
|
||||
Access = new ProjectedConditionAccess(Mappings, Connections, policy, CurrentSink, TimeProvider.System, options, NullLogger.Instance);
|
||||
Access = new ProjectedConditionAccess(Mappings, Connections, policy, CurrentSink, clock, options, NullLogger.Instance);
|
||||
}
|
||||
|
||||
/// <summary>A4 review r2: over a real mapping source (e.g. <see cref="DeployedConditionMappings"/>); <see cref="Mappings"/> is unset.</summary>
|
||||
@@ -1493,14 +1562,16 @@ public sealed class GrpcDataProjectedConditionAccessTests
|
||||
/// <summary>The serving roles of the next streams (Primary when empty).</summary>
|
||||
public Queue<string> Roles { get; } = new();
|
||||
public int PrimarySubscribes;
|
||||
/// <summary>#1080: when set, a runner's connection lease is released only once this completes (a slow loop unwind).</summary>
|
||||
public volatile TaskCompletionSource? LeaseReleaseGate;
|
||||
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken) =>
|
||||
ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(new Lease(new FakeConnection(this)));
|
||||
ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(new Lease(this, new FakeConnection(this)));
|
||||
|
||||
private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease
|
||||
private sealed class Lease(FakeConnections owner, IDataConnection connection) : IGrpcDataAdapterConnectionLease
|
||||
{
|
||||
public IDataConnection Connection => connection;
|
||||
public CancellationToken CancellationToken => CancellationToken.None;
|
||||
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
||||
public ValueTask DisposeAsync() => owner.LeaseReleaseGate is { } gate ? new ValueTask(gate.Task) : ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user