fix(grpc-data): A2 review S2/S3/S4/S5/N1/N2/N4/N5/N6 — bounded, effective-named, fair condition streams

S2: one condition item per (stream, root) (InvalidArgument + diagnostic), SubscriptionSessionLimits
    .MaxConditionItems (32) per stream (LimitExceeded), each snapshot's estimated bytes charged against
    the principal's snapshot memory budget until its last chunk is delivered (refused ⇒ retried).
S3: a native condition in a UNS listing is named by its placement's browse name (effective name);
    a raw-derived message (raw name, raw leaf, RawPath) is replaced by it.
S4: the item limit rides ConditionItemScope and is re-read with every listing.
S5: chunk budget = min(256 KiB, MaxPendingBytes, MaxMessageBytes) − frame overhead; an oversized
    record's free text is truncated (no split surrogate); one that cannot fit resets with a diagnostic.
N1: one queued v1 frame after every 8 condition frames.  N2: removal/snapshot-begin bypass rule documented.
N4: min(limit, DefaultMaxConditionsPerHold) per Lock hold.  N5: losing channel waits are reused.
N6: ConditionTestAssertions deleted; probe seams reduced to three primitives; class doc moved back.
S1 (tests): the fixture 'deploy' test renamed to what it is (a listing swap without an attempt);
    a real LocalCatalogCoordinator republish ends the stream.
This commit is contained in:
Joseph Doherty
2026-11-24 14:56:49 -05:00
parent 7694eb67b2
commit 20bf937259
5 changed files with 556 additions and 90 deletions
@@ -7,20 +7,19 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>
/// A2: root-scoped condition items (plan §5.5). They share the stream, the handle table (one monitored item each) and the
/// principal's interest capacity with value items, but have their own non-coalescing bounded queue: the delivery loop
/// takes a queued control/ack first, then a condition frame, then a value (priority control &gt; condition &gt; value).
/// Production is pull-based (<see cref="ConditionItemStream"/>): an item produces only while the queue has room, so a slow
/// consumer back-pressures into the hub, whose eviction resets the item to a fresh snapshot.
/// takes a queued control/ack first, then a condition frame, then a value (priority control &gt; condition &gt; value,
/// with a fairness cap: after <see cref="ConditionFramesPerValueFrame"/> condition frames in a row a queued v1 frame goes
/// next). Production is pull-based (<see cref="ConditionItemStream"/>): an item produces only while the queue has room,
/// so a slow consumer back-pressures into the hub, whose eviction resets the item to a fresh snapshot.
/// </summary>
internal static class ConditionTestAssertions
{
internal static void ShouldBeTrueForTests(this bool value)
{
if (!value) throw new InvalidOperationException("Test probe could not be queued.");
}
}
internal sealed partial class DataSubscriptionSession
{
/// <summary>A2 review N1: after this many condition frames in a row, a queued value/heartbeat frame is delivered next.</summary>
internal const int ConditionFramesPerValueFrame = 8;
/// <summary>The frame bytes a condition chunk's records must leave free (the sink's frame charge plus wire fields).</summary>
private long ConditionFrameOverhead => 2048L + 4L * (_subscriptionId?.Length ?? 0) + 1024L;
private sealed class ConditionItem(string clientItemId, DataItemHandle handle, ConditionItemAuthority authority,
ConditionItemStream stream, IDisposable reservation) : IDisposable
{
@@ -34,6 +33,7 @@ internal sealed partial class DataSubscriptionSession
{
if (Interlocked.Exchange(ref _reservation, null) is { } r)
{
Stream.Dispose(); // releases the snapshot memory charge
r.Dispose();
OtOpcUaTelemetry.DataConnConditionItems.Add(-1);
}
@@ -44,6 +44,8 @@ internal sealed partial class DataSubscriptionSession
private readonly Dictionary<string, List<ConditionItem>> _conditionActivations = new(StringComparer.Ordinal);
private Channel<PendingDelivery>? _conditionOutboundChannel;
private int _conditionCursor;
private int _conditionStreak;
private Task<bool>? _valuesWait, _conditionsWait;
/// <summary>The bounded condition queue (created lazily on the first condition item; v1 streams never allocate it).</summary>
private Channel<PendingDelivery> ConditionOutbound
@@ -76,8 +78,23 @@ internal sealed partial class DataSubscriptionSession
if (status != DataItemStatus.Good || authority is null) return new(request.ClientItemId, status, null, null, null);
if (authority.Serving != _serving) return new(request.ClientItemId, DataItemStatus.Unavailable, null, null, null);
lock (_gate)
{
if (_conditionItems.Values.Any(x => x.ClientItemId == request.ClientItemId) || _itemsByClient.ContainsKey(request.ClientItemId))
return new(request.ClientItemId, DataItemStatus.InvalidArgument, null, null, "Duplicate client item id.");
// A2 review S2: one condition item per (stream, root) — a second would materialise the same listing again.
if (_conditionItems.Values.Any(x => x.Authority.Root.Address == authority.Root.Address && x.Authority.Root.Realm == authority.Root.Realm))
return new(request.ClientItemId, DataItemStatus.InvalidArgument, null, null, "A condition item for this root is already open on this stream.");
// …and at most MaxConditionItems per stream (SubscriptionSessionLimits.DefaultMaxConditionItems).
if (_conditionItems.Count >= _limits.MaxConditionItems)
return new(request.ClientItemId, DataItemStatus.LimitExceeded, null, null,
$"At most {_limits.MaxConditionItems} condition items per stream.");
}
// A2 review S5: a chunk fits both the session's pending bytes and the message limit, after the frame's own overhead.
var chunkBytes = Math.Min(ConditionItemStream.MaxChunkBytes,
Math.Min(_limits.MaxPendingBytes, services.SubscriptionLimits.MaxMessageBytes) - ConditionFrameOverhead);
if (chunkBytes < ConditionItemStream.MinRecordBytes)
return new(request.ClientItemId, DataItemStatus.LimitExceeded, null, null,
"The stream's message limits are too small for condition records.");
var fixedBytes = checked(4096L + 2L * (request.ClientItemId.Length + authority.Root.Subject.Length
+ authority.Root.Address.Identifier.Length + authority.Root.Address.NamespaceUri.Length));
var itemLimit = services.SubscriptionItemLimit(_context);
@@ -88,8 +105,10 @@ internal sealed partial class DataSubscriptionSession
catch (Exception ex) when (ex is InvalidOperationException or OverflowException)
{ reservation!.Dispose(); return new(request.ClientItemId, DataItemStatus.LimitExceeded, null, null, null); }
_ = ConditionOutbound; // exists before the ack is queued, so the delivery loop waits on it from then on
var stream = new ConditionItemStream(hub, source, authority.Scope, authority.Limit,
request.ConditionScope!.IncludeInfo, services.Clock);
var principal = _context.PrincipalId;
var snapshots = _capacity.Snapshots;
var stream = new ConditionItemStream(hub, source, authority.Scope, request.ConditionScope!.IncludeInfo, services.Clock,
reserveSnapshot: bytes => snapshots.TryAcquire(principal, bytes, out var lease) ? lease : null, chunkBytes: chunkBytes);
var item = new ConditionItem(request.ClientItemId, handle, authority, stream, reservation!);
OtOpcUaTelemetry.DataConnConditionItems.Add(1);
lock (_gate)
@@ -146,6 +165,7 @@ internal sealed partial class DataSubscriptionSession
if (!item.Authority.CanPublish()) { Stop(); break; }
var chunk = item.Stream.Next();
if (item.Stream.Overflowed) { CloseWithReset("Condition stream overflow; retry later."); break; }
if (item.Stream.Oversized) { CloseWithReset("A condition record exceeds the stream's message limits."); break; }
if (item.Stream.IsRevoked) { Stop(); break; }
if (chunk is null) { idle++; continue; }
idle = 0;
@@ -187,19 +207,26 @@ internal sealed partial class DataSubscriptionSession
if (_outbound.Reader.TryRead(out var control)) { Dequeued(control); return control; }
continue;
}
// A2 review N1: strict condition priority would starve values and heartbeats during a long snapshot.
if (_conditionStreak >= ConditionFramesPerValueFrame && _outbound.Reader.TryRead(out var fair))
{ _conditionStreak = 0; Dequeued(fair); return fair; }
if (_conditionOutboundChannel is { } conditions && conditions.Reader.TryRead(out var condition))
{
_conditionStreak++;
QueueTick();
return condition;
}
if (_outbound.Reader.TryRead(out var value)) { Dequeued(value); return value; }
if (_outbound.Reader.TryRead(out var value)) { _conditionStreak = 0; Dequeued(value); return value; }
if (_conditionOutboundChannel is null)
{
if (!await _outbound.Reader.WaitToReadAsync(token).ConfigureAwait(false)) return null;
continue;
}
var values = _outbound.Reader.WaitToReadAsync(token).AsTask();
var conditionsReady = _conditionOutboundChannel.Reader.WaitToReadAsync(token).AsTask();
// A2 review N5: a wait that lost the race stays pending on its channel; reuse it rather than registering a new
// waiter on every pass (values flowing while conditions idle would otherwise pile up condition waiters).
var values = _valuesWait is { IsCompleted: false } pendingValues ? pendingValues : _valuesWait = StartWait(_outbound.Reader, token);
var conditionsReady = _conditionsWait is { IsCompleted: false } pendingConditions
? pendingConditions : _conditionsWait = StartWait(_conditionOutboundChannel.Reader, token);
await Task.WhenAny(values, conditionsReady).ConfigureAwait(false);
token.ThrowIfCancellationRequested();
if (values.IsCompletedSuccessfully && !values.Result && (!conditionsReady.IsCompletedSuccessfully || !conditionsReady.Result)
@@ -208,26 +235,41 @@ internal sealed partial class DataSubscriptionSession
}
}
private Task<bool> StartWait(ChannelReader<PendingDelivery> reader, CancellationToken token)
{
Interlocked.Increment(ref _conditionWaitsStarted);
return reader.WaitToReadAsync(token).AsTask();
}
private int _conditionWaitsStarted;
/// <summary>Test seam (N5): how many channel waits the delivery loop has registered.</summary>
internal int ConditionWaitsStartedForTests => Volatile.Read(ref _conditionWaitsStarted);
/// <summary>Test seam: the stream has processed its Open.</summary>
internal bool IsOpenForTests => Volatile.Read(ref _handles) is not null;
/// <summary>
/// Test seam (stream priority): queues an empty value frame and a heartbeat control on the v1 queue (control first
/// when <paramref name="controlFirst"/>), then a condition frame.
/// </summary>
internal async Task EnqueuePriorityProbesForTests(DataItemHandle conditionHandle, bool controlFirst)
// Test seams (stream priority, fairness, waiters). Internal, reached only through InternalsVisibleTo: they queue empty
// frames directly, bypassing items, so the delivery order can be asserted without a producer.
/// <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));
/// <summary>Test seam: queues a heartbeat control on the v1 queue.</summary>
internal Task EnqueueHeartbeatProbeForTests()
{
var serving = _serving!;
PendingDelivery Value() => new(sequence => new DataSubscriptionValues(_subscriptionId!, _epoch, sequence, false, []),
() => true, isValue: true);
PendingDelivery Control() => new(sequence => new DataSubscriptionControl(_subscriptionId!, _epoch, sequence,
DataStreamControlKind.Heartbeat, [], serving.CatalogEpoch, serving.AuthorityEpoch, null), () => true);
await EnqueueAsync(controlFirst ? Control() : Value()).ConfigureAwait(false);
await EnqueueAsync(controlFirst ? Value() : Control()).ConfigureAwait(false);
ConditionOutbound.Writer.TryWrite(new PendingDelivery(sequence => new DataSubscriptionConditions(_subscriptionId!, _epoch,
sequence, conditionHandle, false, null, [], false), () => true)).ShouldBeTrueForTests();
return EnqueueAsync(new PendingDelivery(sequence => new DataSubscriptionControl(_subscriptionId!, _epoch, sequence,
DataStreamControlKind.Heartbeat, [], serving.CatalogEpoch, serving.AuthorityEpoch, null), () => true));
}
/// <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,
sequence, handle, false, null, [], false), () => true));
/// <summary>Called from the worker's teardown: completes and drains the condition queue, releases condition items.</summary>
private void TearDownConditions()
{