Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeliveryWindowTests.cs
T
Joseph Doherty bac7cfeaa9 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).
2026-12-03 16:47:48 -05:00

128 lines
8.6 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>
/// The origin session's bounded delivery window (MaxPendingFrames) is shared by values, snapshot controls and command
/// acknowledgements. The snapshot pump kept exactly ONE slot free "for command acknowledgements", but a peer may have
/// several commands in flight (a projected cohort keeps up to four), so a second acknowledgement produced while a
/// snapshot had filled the window behind a reader that was a few frames behind found it full — and the session reset
/// the whole stream ("Pending control capacity exhausted.") instead of waiting for the reader. This was the
/// ~1-in-20 second origin open behind <c>GrpcDataCohortScaleTests.R2_a_cohort_above_1024_items_opens_on_one_origin_stream</c>.
/// </summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData")]
public sealed class GrpcDataDeliveryWindowTests
{
[Fact(Timeout = 30000)]
public async Task An_acknowledgement_that_meets_a_full_delivery_window_waits_for_the_reader_instead_of_resetting_the_stream()
{
var ct = TestContext.Current.CancellationToken;
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(64, 16, 256L * 1024 * 1024);
// An 8-frame window: one open's acknowledgement, SnapshotBegin and a few values fill it.
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);
await using var connection = fixture.Connection();
await using 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();
// Nothing is read yet: the open's snapshot fills the window, and the later commands' acknowledgements meet it full
// (the clock is frozen, so only the worker's own pumping and a reader's dequeue move the window).
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: an acknowledgement met a full delivery window");
var acks = new HashSet<string>(StringComparer.Ordinal);
var baselines = new HashSet<long>();
var ends = 0;
var seen = new List<string>();
await using var reader = subscription.ReadAllAsync(ct).GetAsyncEnumerator(ct);
while (acks.Count < commands || ends < commands || baselines.Count < commands * perCommand)
{
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct))
.ShouldBeTrue("the stream must stay open: " + string.Join(" ", seen));
switch (reader.Current)
{
case DataSubscriptionAck ack:
seen.Add("ack:" + ack.CommandId);
ack.Items.ShouldAllBe(item => item.Handle != null);
acks.Add(ack.CommandId);
break;
case DataSubscriptionControl control:
seen.Add(control.Kind + (control.Diagnostic is { } diagnostic ? ":" + diagnostic : ""));
control.Kind.ShouldNotBe(DataStreamControlKind.Reset, "a reader a few frames behind is backpressure, not a fault: " + string.Join(" ", seen));
if (control.Kind == DataStreamControlKind.SnapshotEnd) ends++;
break;
case DataSubscriptionValues values:
seen.Add("values");
foreach (var item in values.Items) if (values.IsSnapshot) baselines.Add(checked((long)item.Handle.Handle));
values.Dispose();
break;
}
}
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);
}
}
}