1523a97708
Release, 10k cohort, 5 runs each: 2.21-2.31 KB -> 1.68-1.72 KB per delivered value, process-wide. - A live value takes over its hub read's sample lease and charge (CachedSourceRead.TryTransferSample: same amount, same budget; the read keeps its source guard until disposed) instead of retaining a second copy and reserving a second charge. Re-stamped with the item's serving only when it differs. - ValueLease holds a reference on the item's SharedSessionLease directly (no Hold per value); the release order (charge, item, snapshot) and once-only guard are unchanged. - The latest-sample cache keeps the published update itself for a scalar payload (arrays still copied). - The cohort's frame window is a FrameSlotWindow (SemaphoreSlim semantics: over-release throws, a cancelled wait takes no slot) on one reused SlotWaiter and one registration per attempt; the pump waited for nearly every frame, each wait allocating a task, state machine and registration. - SlotWaiter (moved out of the session) now makes a re-arm wait out a signaller still inside SetResult, so the old signal cannot complete the next wait; it is hot now (one wait per frame under load). - Indexed loops for the pump's frame sizing and DataSubscriptionValues.Dispose (no boxed enumerators). - ClientFilterState keeps its baseline's compared fields and value lease, not a re-wrapped sample. Pooling ValueLease/ValueDelivery (~150 B) is declined: the lease escapes as the public DataSubscriptionValues.ResourceLease and a delivery's Gate is handed to the gRPC sink as a publication guard, so a recycled object could release or authorize for another value. Tests (GrpcData1098OwnershipTests) fail on a read releasing a transferred sample, a lease not holding its item, a frame-window double release / lost wakeup, and a re-arm racing a completing signal.
329 lines
18 KiB
C#
329 lines
18 KiB
C#
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
|
|
|
/// <summary>
|
|
/// #1098: the publish path's ownership changes. A live value now takes over its hub read's sample lease and charge instead
|
|
/// of copying them; a value's lease holds a reference on its item's reservation instead of a separate hold; the cohort's
|
|
/// frame window is a reused waiter instead of a semaphore. Each test fails if an owner releases what another still holds
|
|
/// (a use-after-release or a double release), and each carries a positive control that the path under test ran.
|
|
/// </summary>
|
|
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Issue", "1098")]
|
|
public sealed class GrpcData1098OwnershipTests
|
|
{
|
|
// ---- CachedSourceRead.TryTransferSample ----
|
|
|
|
[Fact]
|
|
public void A_transferred_read_keeps_its_guard_but_leaves_the_sample_and_charge_to_the_new_owner()
|
|
{
|
|
using var hub = HubTest.Create(partitions: 1, bytes: 100_000);
|
|
var ticket = HubTest.Ticket("driver", "a");
|
|
HubTest.BindAndPublish(hub, ticket, 1, 7);
|
|
hub.ProcessPending();
|
|
var before = hub.Resources.RetainedBytes;
|
|
var read = hub.Read(ticket);
|
|
var sample = read.Sample.ShouldNotBeNull();
|
|
var charge = hub.Resources.RetainedBytes - before;
|
|
charge.ShouldBeGreaterThan(0, "positive control: a read holds a charge");
|
|
|
|
read.TryTransferSample(hub.Resources, charge, out var transferred).ShouldBeTrue();
|
|
transferred.ShouldBeSameAs(sample);
|
|
read.TryTransferSample(hub.Resources, charge, out _).ShouldBeFalse("a sample transfers once");
|
|
read.IsValid.ShouldBeTrue("the read's guard is the read's until it is disposed");
|
|
|
|
read.Dispose();
|
|
// The new owner's sample is still live and its charge still held: the read released neither.
|
|
transferred!.Value.GetScalar().ShouldBe(7);
|
|
hub.Resources.RetainedBytes.ShouldBe(before + charge);
|
|
read.Dispose();
|
|
hub.Resources.RetainedBytes.ShouldBe(before + charge, "a second dispose releases nothing");
|
|
|
|
transferred.Dispose(); hub.Resources.Release(charge);
|
|
hub.Resources.RetainedBytes.ShouldBe(before);
|
|
Should.Throw<ObjectDisposedException>(() => transferred.Value.GetScalar());
|
|
}
|
|
|
|
[Fact]
|
|
public void A_read_that_did_not_transfer_still_releases_its_sample_and_charge()
|
|
{
|
|
using var hub = HubTest.Create(partitions: 1, bytes: 100_000);
|
|
var ticket = HubTest.Ticket("driver", "a");
|
|
HubTest.BindAndPublish(hub, ticket, 1, 7);
|
|
hub.ProcessPending();
|
|
var before = hub.Resources.RetainedBytes;
|
|
var read = hub.Read(ticket);
|
|
var sample = read.Sample!;
|
|
var charge = hub.Resources.RetainedBytes - before;
|
|
// Refused: another budget, another charge. Neither transfers anything.
|
|
using var otherHub = HubTest.Create(partitions: 1, bytes: 100_000);
|
|
read.TryTransferSample(otherHub.Resources, charge, out var refused).ShouldBeFalse();
|
|
refused.ShouldBeNull();
|
|
read.TryTransferSample(hub.Resources, charge + 1, out _).ShouldBeFalse();
|
|
read.Dispose();
|
|
hub.Resources.RetainedBytes.ShouldBe(before);
|
|
Should.Throw<ObjectDisposedException>(() => sample.Value.GetScalar());
|
|
read.TryTransferSample(hub.Resources, charge, out _).ShouldBeFalse("nothing transfers after dispose");
|
|
}
|
|
|
|
// ---- the session: a live value owns the read's sample; its lease holds the item ----
|
|
|
|
[Fact(Timeout = 30000)]
|
|
public async Task A_live_value_that_took_over_its_read_is_still_owned_by_its_frame_after_the_read_is_gone()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
using var stream = await OneItemStream.OpenAsync(ct);
|
|
var (fixture, session) = (stream.Fixture, stream.Session);
|
|
var differing = fixture.Serving with { CatalogEpoch = 0, AuthorityEpoch = 0 };
|
|
foreach (var (version, value, serving) in new[] { (2L, 21, fixture.Serving), (3L, 31, differing) })
|
|
{
|
|
// The tick that queues the value also disposes the hub read it came from; only then is the frame taken.
|
|
await stream.PublishAndWaitForQueuedTickAsync(version, value, serving, ct);
|
|
var values = await stream.NextValuesAsync(ct);
|
|
var delivered = values.Items.ShouldHaveSingleItem().Sample;
|
|
delivered.Version.ShouldBe(version);
|
|
delivered.Value.GetScalar().ShouldBe(value, "the frame's sample must not have been released with the read");
|
|
delivered.Serving.ShouldBe(stream.ItemServing!, "a value carries the item's serving whatever the hub sample carried");
|
|
values.Dispose();
|
|
Should.Throw<ObjectDisposedException>(() => delivered.Value.GetScalar(), "positive control: the frame owns and releases it");
|
|
}
|
|
stream.ItemServing.ShouldBe(fixture.Serving, "positive control: the first value kept the read's own sample (no re-stamp)");
|
|
stream.ItemServing.ShouldNotBe(differing, "positive control: the second value took the re-stamp branch");
|
|
session.SampleTransfersForTests.ShouldBe(2, "positive control: both live values took over their reads");
|
|
await stream.DisposeAsync();
|
|
stream.AssertReleased();
|
|
}
|
|
|
|
[Fact(Timeout = 30000)]
|
|
public async Task A_held_value_frame_keeps_its_removed_items_reservation_until_the_frame_is_disposed_once()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
using var stream = await OneItemStream.OpenAsync(ct);
|
|
stream.Capacity.InterestsForTests.ShouldBe(1, "positive control: the open item holds a reservation");
|
|
await stream.PublishAndWaitForQueuedTickAsync(2, 21, stream.Fixture.Serving, ct);
|
|
var held = await stream.NextValuesAsync(ct);
|
|
await stream.Subscription.SendAsync(new RemoveSubscriptionItems("s", 1, "remove", TimeSpan.FromSeconds(5), [stream.Handle!]), ct);
|
|
(await stream.NextAsync<DataSubscriptionAck>(ct)).CommandId.ShouldBe("remove");
|
|
// The item is gone from the stream, but the frame's lease still holds a reference on its reservation.
|
|
stream.Capacity.InterestsForTests.ShouldBe(1, "a removed item's reservation outlives it while one of its frames is held");
|
|
held.Items[0].Sample.Value.GetScalar().ShouldBe(21);
|
|
held.Dispose();
|
|
stream.Capacity.InterestsForTests.ShouldBe(0, "the frame held the last reference");
|
|
held.Dispose();
|
|
stream.Capacity.InterestsForTests.ShouldBe(0);
|
|
await stream.DisposeAsync();
|
|
stream.AssertReleased();
|
|
}
|
|
|
|
// ---- FrameSlotWindow ----
|
|
|
|
[Fact(Timeout = 10000)]
|
|
public async Task The_frame_window_takes_a_slot_waits_for_a_release_and_refuses_a_double_release()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
var window = new FrameSlotWindow(2);
|
|
window.WaitAsync(ct).IsCompletedSuccessfully.ShouldBeTrue();
|
|
window.WaitAsync(ct).IsCompletedSuccessfully.ShouldBeTrue();
|
|
window.AvailableForTests.ShouldBe(0);
|
|
var waiting = window.WaitAsync(ct).AsTask();
|
|
await Task.Delay(50, ct);
|
|
waiting.IsCompleted.ShouldBeFalse("a full window waits");
|
|
window.Release();
|
|
await waiting.WaitAsync(TimeSpan.FromSeconds(5), ct);
|
|
window.AvailableForTests.ShouldBe(0, "the woken wait took the released slot");
|
|
window.Release(); window.Release();
|
|
window.AvailableForTests.ShouldBe(2);
|
|
Should.Throw<SemaphoreFullException>(() => window.Release(), "a release past the capacity is a double release");
|
|
window.AvailableForTests.ShouldBe(2);
|
|
}
|
|
|
|
[Fact(Timeout = 10000)]
|
|
public async Task A_cancelled_frame_window_wait_takes_no_slot()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
var window = new FrameSlotWindow(1);
|
|
await window.WaitAsync(ct);
|
|
using var stop = new CancellationTokenSource();
|
|
var waiting = window.WaitAsync(stop.Token).AsTask();
|
|
await Task.Delay(20, ct);
|
|
waiting.IsCompleted.ShouldBeFalse();
|
|
await stop.CancelAsync();
|
|
await Should.ThrowAsync<OperationCanceledException>(() => waiting.WaitAsync(TimeSpan.FromSeconds(5), ct));
|
|
// Already cancelled: refused at once, even with a slot free.
|
|
window.Release();
|
|
await Should.ThrowAsync<OperationCanceledException>(() => window.WaitAsync(stop.Token).AsTask());
|
|
window.AvailableForTests.ShouldBe(1, "neither cancelled wait took a slot");
|
|
// A later attempt's token registers afresh and still waits correctly.
|
|
await window.WaitAsync(ct);
|
|
var next = window.WaitAsync(ct).AsTask();
|
|
window.Release();
|
|
await next.WaitAsync(TimeSpan.FromSeconds(5), ct);
|
|
}
|
|
|
|
[Fact(Timeout = 60000)]
|
|
public async Task The_frame_window_never_admits_more_than_its_capacity_and_loses_no_wakeup()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
const int capacity = 3, frames = 200_000;
|
|
var window = new FrameSlotWindow(capacity);
|
|
var inFlight = 0; var maximum = 0;
|
|
var queue = new System.Collections.Concurrent.BlockingCollection<int>();
|
|
var consumer = Task.Run(() =>
|
|
{
|
|
foreach (var _ in queue.GetConsumingEnumerable(ct))
|
|
{
|
|
Interlocked.Decrement(ref inFlight);
|
|
window.Release();
|
|
}
|
|
}, ct);
|
|
for (var i = 0; i < frames; i++)
|
|
{
|
|
await window.WaitAsync(ct);
|
|
var now = Interlocked.Increment(ref inFlight);
|
|
if (now > maximum) maximum = now;
|
|
queue.Add(i, ct);
|
|
}
|
|
queue.CompleteAdding();
|
|
await consumer.WaitAsync(TimeSpan.FromSeconds(30), ct);
|
|
maximum.ShouldBeLessThanOrEqualTo(capacity);
|
|
maximum.ShouldBe(capacity, "positive control: the producer did fill the window");
|
|
window.AvailableForTests.ShouldBe(capacity);
|
|
}
|
|
|
|
[Fact(Timeout = 10000)]
|
|
public async Task Re_arming_the_slot_waiter_waits_out_a_signaller_still_completing_the_previous_wait()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
var waiter = new SlotWaiter();
|
|
var wait = waiter.Arm();
|
|
using var inside = new ManualResetEventSlim();
|
|
using var resume = new ManualResetEventSlim();
|
|
waiter.AfterSetResultForTests = () => { inside.Set(); resume.Wait(ct); };
|
|
var signaller = Task.Run(waiter.Signal, ct);
|
|
inside.Wait(TimeSpan.FromSeconds(5), ct).ShouldBeTrue();
|
|
// The waiter sees its wait complete while the signaller has not left Signal yet...
|
|
wait.IsCompleted.ShouldBeTrue();
|
|
await wait;
|
|
waiter.AfterSetResultForTests = null;
|
|
// ...so a re-arm must not reset the source under it.
|
|
var rearm = Task.Run(waiter.Arm, ct);
|
|
await Task.Delay(100, ct);
|
|
rearm.IsCompleted.ShouldBeFalse("a re-arm waits for the signaller to finish completing the previous wait");
|
|
resume.Set();
|
|
var next = await rearm.WaitAsync(TimeSpan.FromSeconds(5), ct);
|
|
await signaller.WaitAsync(TimeSpan.FromSeconds(5), ct);
|
|
next.IsCompleted.ShouldBeFalse("the previous signal must not complete the new wait");
|
|
waiter.Signal();
|
|
next.IsCompleted.ShouldBeTrue();
|
|
await next;
|
|
}
|
|
|
|
/// <summary>A real origin session with one subscribed item whose snapshot has been read.</summary>
|
|
private sealed class OneItemStream : IDisposable, IAsyncDisposable
|
|
{
|
|
private LocalDataFixture? _fixture;
|
|
private long _baselineBytes;
|
|
private int _queued;
|
|
private readonly SemaphoreSlim _queuedTicks = new(0);
|
|
private IAsyncEnumerator<DataSubscriptionFrame>? _reader;
|
|
private bool _disposed;
|
|
internal LocalDataFixture Fixture => _fixture!;
|
|
internal SubscriptionTransportCapacity Capacity { get; } = new(64, 16, 256L * 1024 * 1024);
|
|
internal IDataSubscription Subscription { get; private set; } = null!;
|
|
internal DataSubscriptionSession Session { get; private set; } = null!;
|
|
internal DataItemHandle? Handle { get; private set; }
|
|
internal ServingIdentity? ItemServing { get; private set; }
|
|
private IDataConnection? _connection;
|
|
|
|
internal static async Task<OneItemStream> OpenAsync(CancellationToken ct)
|
|
{
|
|
var stream = new OneItemStream();
|
|
var demand = new DeferredSubscriptionDemand(); demand.Accept();
|
|
var limits = new SubscriptionSessionLimits(16, 8, 100_000, TimeSpan.FromMinutes(1));
|
|
stream._fixture = new LocalDataFixture(maxMonitoredItems: 16, hubBytes: 64L * 1024 * 1024,
|
|
targetSubscriptions: (context, target) => new LocalSubscriptionService(stream._fixture!.Services, context, target, demand, limits, stream.Capacity));
|
|
stream._fixture.Publish(10);
|
|
stream._baselineBytes = stream._fixture.Hub.Resources.RetainedBytes;
|
|
stream._connection = stream._fixture.Connection();
|
|
stream.Subscription = await stream._connection.SubscribeAsync(ct);
|
|
stream.Session = stream.Subscription.ShouldBeOfType<DataSubscriptionSession>();
|
|
stream.Session.OnCandidateQueuedForTests = (_, _) => Interlocked.Exchange(ref stream._queued, 1);
|
|
stream.Session.AfterTickForTests = () => { if (Interlocked.Exchange(ref stream._queued, 0) == 1) stream._queuedTicks.Release(); };
|
|
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
|
|
await stream.Subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5),
|
|
[new DataSubscriptionItem("item", stream._fixture.Raw, settings)], false, TimeSpan.FromSeconds(30),
|
|
LocalDataFixture.Budget with { MaxItems = 1 }), ct);
|
|
stream._reader = stream.Subscription.ReadAllAsync(ct).GetAsyncEnumerator(ct);
|
|
var ack = await stream.NextAsync<DataSubscriptionAck>(ct);
|
|
stream.Handle = ack.Items.ShouldHaveSingleItem().Handle.ShouldNotBeNull();
|
|
var baseline = await stream.NextValuesAsync(ct);
|
|
baseline.IsSnapshot.ShouldBeTrue();
|
|
stream.ItemServing = baseline.Items[0].Sample.Serving;
|
|
baseline.Dispose();
|
|
(await stream.NextAsync<DataSubscriptionControl>(ct, x => x.Kind == DataStreamControlKind.SnapshotEnd)).ShouldNotBeNull();
|
|
return stream;
|
|
}
|
|
|
|
internal async Task PublishAndWaitForQueuedTickAsync(long version, int value, ServingIdentity serving, CancellationToken ct)
|
|
{
|
|
using (var owned = DataValue.FromScalar(DataValueKind.Int32, value))
|
|
{
|
|
Fixture.Hub.TryReserveIngress(Fixture.Ticket, owned.EstimatedRetainedBytes, out var reservation).ShouldBeTrue();
|
|
using (reservation!)
|
|
{
|
|
var sample = new DataSample(owned.Retain(), 0, null, Fixture.Clock.GetUtcNow(), serving, version);
|
|
if (!reservation!.TryCommit(sample, version)) { sample.Dispose(); throw new InvalidOperationException("Commit rejected."); }
|
|
}
|
|
}
|
|
Fixture.Hub.ProcessPending();
|
|
// A change that lands before the snapshot's completion is processed is picked up by a later tick (the session's
|
|
// 100 ms timer on this frozen clock), so step the clock while waiting.
|
|
var deadline = DateTime.UtcNow.AddSeconds(10);
|
|
while (!await _queuedTicks.WaitAsync(TimeSpan.FromMilliseconds(50), ct))
|
|
{
|
|
if (DateTime.UtcNow > deadline) throw new ShouldAssertException("no tick queued the value");
|
|
Fixture.Clock.Advance(TimeSpan.FromMilliseconds(100));
|
|
}
|
|
}
|
|
|
|
internal async Task<DataSubscriptionValues> NextValuesAsync(CancellationToken ct) => await NextAsync<DataSubscriptionValues>(ct);
|
|
|
|
internal async Task<T> NextAsync<T>(CancellationToken ct, Func<T, bool>? match = null) where T : DataSubscriptionFrame
|
|
{
|
|
while (true)
|
|
{
|
|
(await _reader!.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct)).ShouldBeTrue("the stream must stay open");
|
|
var frame = _reader.Current;
|
|
if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Reset } reset)
|
|
throw new ShouldAssertException("stream reset: " + reset.Diagnostic);
|
|
if (frame is T typed && (match is null || match(typed))) return typed;
|
|
(frame as IDisposable)?.Dispose();
|
|
}
|
|
}
|
|
|
|
/// <summary>Everything the stream charged is back: no leak, and (the equality) no double release.</summary>
|
|
internal void AssertReleased()
|
|
{
|
|
var deadline = DateTime.UtcNow.AddSeconds(10);
|
|
while ((Fixture.Hub.Resources.RetainedBytes != _baselineBytes || Capacity.InterestsForTests != 0) && DateTime.UtcNow < deadline)
|
|
Thread.Sleep(20);
|
|
Fixture.Hub.Resources.RetainedBytes.ShouldBe(_baselineBytes);
|
|
Capacity.InterestsForTests.ShouldBe(0);
|
|
}
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
if (_disposed) return;
|
|
_disposed = true;
|
|
if (_reader is not null) await _reader.DisposeAsync();
|
|
await Subscription.DisposeAsync();
|
|
await Session.Completion.WaitAsync(TimeSpan.FromSeconds(10));
|
|
if (_connection is not null) await _connection.DisposeAsync();
|
|
}
|
|
|
|
public void Dispose() { DisposeAsync().AsTask().GetAwaiter().GetResult(); _fixture?.Dispose(); _queuedTicks.Dispose(); }
|
|
}
|
|
}
|