fix(grpc-data): a command ack that meets a full delivery window waits for the reader instead of resetting the stream

Root cause of the ~1-in-20 flake in GrpcDataCohortScaleTests.R2_a_cohort_above_1024_items_opens_on_one_origin_stream
(Opens = 2): a production race in the origin DataSubscriptionSession, not a fixture artifact.

The session's bounded outbound window (MaxPendingFrames) is shared by values, snapshot controls and command acks. The
snapshot pump leaves exactly one slot "for command acknowledgements", but a peer may have up to MaxCommands commands
in flight (the #994 projected cohort keeps 4 outstanding). When the reader was a few frames behind, an open/add's
snapshot filled the window, the next add's ack took the reserved slot, and the following ack's TryWrite failed;
EnqueueAsync then CloseWithReset("Pending control capacity exhausted.") the whole stream, and the cohort re-opened
all 1100 items on a second origin stream. Instrumented repro: the failing run's trace shows exactly that reset on the
1100-item cohort's first stream, then a second COHORT OPEN with epoch=2; the reset never appeared in passing runs.

Fix: EnqueueAsync (production callers all on the command worker) now awaits the window when it is full instead of
resetting — backpressure on the worker, never on the reader. A reader that never drains is still bounded by the ack
deadline, the session lifetime and the bounded command queue. The values cap (MaxPendingFrames - 2) still resets.

Regression: GrpcDataDeliveryWindowTests drives an 8-frame window with an unread open + 3 adds on a frozen clock; the
OutboundFullForTests seam proves an ack met a full window. Before the fix the stream ended with that reset; after it
every ack, SnapshotEnd and baseline arrives with no Reset.

Verified: GrpcDataCohortScaleTests + GrpcDataDeliveryWindowTests 30/30 consecutive passes (plus 30/30 instrumented
with zero "Pending control capacity" resets); full Runtime.Tests (Category!=SlowUnit) 2283 passed / 0 failed.
This commit is contained in:
Joseph Doherty
2026-12-03 12:30:00 -05:00
parent a164c76086
commit ded28d9e47
2 changed files with 102 additions and 9 deletions
@@ -51,6 +51,8 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
internal Action? SnapshotEndCommittedForTests { get; set; }
internal Action<int, int, int>? BeforeDirtyTickForTests { get; set; }
internal Action? AfterTickForTests { get; set; }
/// <summary>Test seam: a frame met a full delivery window (the worker is about to wait for the reader).</summary>
internal Action? OutboundFullForTests { get; set; }
internal Action<DataItemHandle, long>? OnCandidateQueuedForTests { get; set; }
private sealed class SharedSessionLease(IDisposable lease) : IDisposable
@@ -982,7 +984,8 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
{ CloseWithReset("Snapshot catch-up expired; retry later."); return; }
if (!job.Started)
{
// Leave a control slot available for command acknowledgements. A dequeued
// Leave a control slot available for command acknowledgements (an optimisation: an acknowledgement that
// still finds the window full waits for the reader in EnqueueAsync). A dequeued
// frame queues another tick, so a blocked boundary remains resumable.
if (_outbound.Reader.Count >= Math.Max(1, _limits.MaxPendingFrames - 1)) return;
await EnqueueAsync(Control(DataStreamControlKind.SnapshotBegin, job.Watermarks, job.Snapshot,
@@ -1214,18 +1217,26 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo
return Math.Min(valueSlots, channelSlots);
}
private Task EnqueueAsync(PendingDelivery delivery)
// 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)
{
if (Volatile.Read(ref _closed) != 0 || Volatile.Read(ref _closing) != 0) { delivery.Dispose(); return Task.CompletedTask; }
if (Volatile.Read(ref _closed) != 0 || Volatile.Read(ref _closing) != 0) { delivery.Dispose(); return; }
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 Task.CompletedTask;
Interlocked.Decrement(ref _queuedValues); delivery.Dispose(); CloseWithReset("Pending value capacity exhausted."); return;
}
if (!_outbound.Writer.TryWrite(delivery))
{
Dequeued(delivery); delivery.Dispose(); CloseWithReset("Pending control capacity exhausted.");
}
return Task.CompletedTask;
if (_outbound.Writer.TryWrite(delivery)) return;
// 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
// stream ("Pending control capacity exhausted.") — the cohort then re-opened every item on a second origin stream.
// 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(); }
}
private void Dequeued(PendingDelivery delivery)
{
@@ -0,0 +1,82 @@
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);
}
}
}