fix(grpc-data): size projected unary reservations from the node's shape (#960); per-item status for projected items refused at create (#961)

#960: a projected read reserves 16 KiB for a fixed-size scalar (16 KiB + 256 B/element for a
fixed-length fixed-size array) instead of the whole MaxPendingBytes, so the default 1 MiB admits
64 concurrent scalar reads; String/Bytes/variable arrays keep the whole cap, and a waiting
whole-cap read holds back smaller ones for 100 ms (anti-starvation). Writes reserve
16 KiB + identifiers + 3 x the value bound (what the origin's DataWriteExecutor admits the batch
against). Monitored-item renewals reserve 256 KiB. Measured: 4 x 250 ms maxAge=0 reads 1016 ms /
1 in flight -> 285 ms / 4 in flight.

#961: TryAcquireProjectedItem reports BadResourceUnavailable for a stream-capacity refusal; the
node manager's CreateMonitoredItem override turns the item manager's ServiceResultException into
that item's status (was a whole-request fault), and an authority race is re-classified outside
Lock like the per-item probe.
This commit is contained in:
Joseph Doherty
2026-12-01 20:34:35 -05:00
parent 92da56c071
commit 75e6ff9af8
14 changed files with 644 additions and 48 deletions
@@ -169,7 +169,10 @@ public sealed partial class OtOpcUaNodeManager : IReadAsyncNodeManager, ICreateM
}
}
/// <summary>The per-read byte reservation of an awaited origin read (as a scheduled read; narrowed to the adapter's limit).</summary>
/// <summary>
/// The per-read byte cap of an awaited origin read (as a scheduled read). An upper bound: the access narrows it to the
/// adapter's limit and (#960) to what the node's declared shape can answer, so scalar reads run concurrently.
/// </summary>
private const long ProjectedOriginReadBytes = 4 * 1024 * 1024;
private static bool TryAcquireProjectedRead(IProjectedDataAccess access, NodeId nodeId, RoleCarryingUserIdentity identity,
@@ -4626,18 +4626,30 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
lock (Lock) return !_disposing && _projectedDefinitions.TryGetValue(nodeId, out var current) &&
ReferenceEquals(current.Lifetime, definition.Lifetime) && current.Lifetime.IsActive && current.AuthorityIsCurrent();
}
/// <summary>#961 test seam: runs as the create of a projected item starts (under <c>Lock</c>, after the per-item probe).</summary>
internal Action<NodeId>? BeforeProjectedItemAcquireForTests { get; set; }
/// <param name="refusal">
/// #961: why it was refused — <c>BadUserAccessDenied</c> when the node's authority did not admit the caller (re-classified
/// per item outside <c>Lock</c> by <see cref="CreateMonitoredItems"/>), <c>BadResourceUnavailable</c> when the authority
/// did but no origin stream could take the item (stream capacity, a closing cohort).
/// </param>
internal bool TryAcquireProjectedItem(ServerSystemContext context, NodeId nodeId, double publishingInterval,
out IProjectedDemandLease? demand, out ProjectedValueWrite? sample, out ProjectedVariableDefinition? definition)
out IProjectedDemandLease? demand, out ProjectedValueWrite? sample, out ProjectedVariableDefinition? definition, out StatusCode refusal)
{
demand = null; sample = null; definition = null;
demand = null; sample = null; definition = null; refusal = StatusCodes.BadUserAccessDenied;
BeforeProjectedItemAcquireForTests?.Invoke(nodeId);
var identity = IdentityOf(context);
var access = ProjectedDataAccess;
var accepted = false;
try
{
if (identity is null || access is null || !TryResolve(nodeId, out definition) || definition is null ||
!access.TryAcquire(nodeId, identity, DataOperations.Subscribe, out demand) || demand is null || !demand.IsValid ||
!access.StartSubscription(demand, TimeSpan.FromMilliseconds(Math.Max(0, publishingInterval)))) return false;
!access.TryAcquire(nodeId, identity, DataOperations.Subscribe, out demand) || demand is null || !demand.IsValid) return false;
if (!access.StartSubscription(demand, TimeSpan.FromMilliseconds(Math.Max(0, publishingInterval))))
{
if (demand.IsValid) refusal = StatusCodes.BadResourceUnavailable;
return false;
}
lock (Lock) _projectedSamples.TryGetValue(nodeId, out sample);
if (!demand.IsValid || !IsProjectedDefinitionCurrent(nodeId, definition)) return false;
accepted = true;
@@ -6558,9 +6570,11 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
bool createDurable,
MonitoredItemIdFactory monitoredItemIdFactory)
{
RoleCarryingUserIdentity? identity = null;
List<int>? projectedAdmitted = null;
if (SecurityFilteringActive)
{
var identity = IdentityOf(context);
identity = IdentityOf(context);
var denied = 0;
for (var ii = 0; ii < itemsToCreate.Count; ii++)
@@ -6580,6 +6594,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
errors[ii] = refusal;
if (refusal.Code == StatusCodes.BadUserAccessDenied.Code) denied++;
}
else (projectedAdmitted ??= []).Add(ii);
continue;
}
if (Permits(identity, OpcUaOperation.CreateMonitoredItems, target!.Value)) continue;
@@ -6595,6 +6610,47 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
base.CreateMonitoredItems(
context, subscriptionId, publishingInterval, timestampsToReturn, itemsToCreate, errors,
filterErrors, monitoredItems, createDurable, monitoredItemIdFactory);
// #961: an item the probe above admitted but whose create then found the authority changed (answered per item by
// CreateMonitoredItem, under Lock, as a provisional BadUserAccessDenied) is classified here, outside Lock, exactly like the
// probe: a lapse the caller is granted is retryable, a real refusal stays BadUserAccessDenied, and an authority that admits
// the caller again by now was a transient race — retryable too.
if (projectedAdmitted is not null && identity is not null && ProjectedDataAccess is { } classify)
{
foreach (var ii in projectedAdmitted)
{
if (monitoredItems[ii] is not null || errors[ii] is not { } error ||
error.StatusCode.Code != StatusCodes.BadUserAccessDenied.Code) continue;
errors[ii] = ProjectedSubscribeRefusal(classify, itemsToCreate[ii].ItemToMonitor.NodeId, identity)
?? StatusCodes.BadResourceUnavailable;
}
}
}
/// <inheritdoc />
/// <remarks>
/// #961: the SDK's <c>CreateMonitoredItems</c> calls this per item under <c>Lock</c> with no catch, so a
/// <see cref="ServiceResultException"/> thrown by the item manager (a projected item refused at create: the authority
/// changed after the per-item probe, or no origin stream could take it) faulted the WHOLE request, failing every other item
/// in the batch. It is this item's status instead. Nothing leaks: the item manager releases what it reserved before it
/// throws, and the base deletes an item it already created before rethrowing.
/// </remarks>
protected override ServiceResult CreateMonitoredItem(ServerSystemContext context, NodeHandle handle, uint subscriptionId,
double publishingInterval, DiagnosticsMasks diagnosticsMasks, TimestampsToReturn timestampsToReturn,
MonitoredItemCreateRequest itemToCreate, bool createDurable, MonitoredItemIdFactory monitoredItemId,
out MonitoringFilterResult filterResult, out IMonitoredItem? monitoredItem)
{
try
{
return base.CreateMonitoredItem(context, handle, subscriptionId, publishingInterval, diagnosticsMasks, timestampsToReturn,
itemToCreate, createDurable, monitoredItemId, out filterResult, out monitoredItem);
}
catch (ServiceResultException ex)
{
filterResult = null!;
monitoredItem = null;
return StatusCode.IsBad(ex.StatusCode) ? ex.StatusCode : StatusCodes.BadInternalError;
}
}
// Event subscriptions are gated on the notifier they attach to. This is the alarm-delivery path:
@@ -347,10 +347,12 @@ internal sealed class OrdinaryTagItemManager(IAsyncNodeManager nodeManager, ISer
IProjectedDemandLease? demand = null;
ProjectedValueWrite? initialSample = null;
ProjectedVariableDefinition? definition = null;
if (projected && !owner.TryAcquireProjectedItem(context, handle.NodeId, publishingInterval, out demand, out initialSample, out definition))
if (projected && !owner.TryAcquireProjectedItem(context, handle.NodeId, publishingInterval, out demand, out initialSample, out definition, out var refusal))
// #940: refusals known before the create are answered per item by OtOpcUaNodeManager.CreateMonitoredItems (lapse ⇒
// retryable); this is the race-only remainder (the authority changed in between).
throw new ServiceResultException(StatusCodes.BadUserAccessDenied);
// retryable); this is the remainder (the authority changed in between, or no origin stream could take the item).
// #961: OtOpcUaNodeManager.CreateMonitoredItem turns it into THIS item's status — thrown out of the SDK's create loop
// (under Lock, no catch) it faulted the whole request.
throw new ServiceResultException(refusal);
uint? reservedId = null;
ISampledDataChangeMonitoredItem? constructed = null;
@@ -70,38 +70,79 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
// Check the borrowed input without boxing or copying it. Array encoding temporarily owns
// two reference arrays, boxed elements and scalar wrappers as well as the eventual value;
// charge a conservative per-element bound before any of those allocations occur.
private static bool FitsWriteBudget(DataMetadata metadata, object? value, long maximumBytes)
// #960: returns that conservative bound (what the write reserves, plus the envelope allowance), or -1 when the value cannot
// fit maximumBytes or has an incompatible shape.
private static long WriteValueBytes(DataMetadata metadata, object? value, long maximumBytes)
{
const long scalarOverhead = 288;
if (maximumBytes < scalarOverhead) return false;
if (value is null) return true;
if (maximumBytes < scalarOverhead) return -1;
if (value is null) return scalarOverhead;
if (metadata.ValueKind == DataValueKind.Array)
{
if (metadata.ValueRank != 1 || metadata.Dimensions.Count != 1 || metadata.ArrayElementKind is not { } kind ||
!ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.IsSupportedArrayElementKind(kind) ||
value is not Array array || array.Rank != 1 || array.GetLowerBound(0) != 0 ||
(metadata.Dimensions[0] != 0 && metadata.Dimensions[0] != array.Length)) return false;
(metadata.Dimensions[0] != 0 && metadata.Dimensions[0] != array.Length)) return -1;
const long overhead = 512, perElement = 128;
if (maximumBytes < overhead || array.LongLength > (maximumBytes - overhead) / perElement) return false;
if (maximumBytes < overhead || array.LongLength > (maximumBytes - overhead) / perElement) return -1;
var used = overhead + perElement * array.LongLength;
if (kind == DataValueKind.String)
{
// Both typed string arrays and the object arrays accepted by EncodeValue are
// indexable without creating an iterator or boxing individual elements.
if (array is not object[] strings) return false;
if (array is not object[] strings) return -1;
for (var i = 0; i < strings.Length; i++)
{
if (strings[i] is not string text || text.Length > (maximumBytes - used) / 2) return false;
if (strings[i] is not string text || text.Length > (maximumBytes - used) / 2) return -1;
used += 2L * text.Length;
}
}
return true;
return used;
}
if (metadata.ValueKind == DataValueKind.Bytes && value is byte[] bytes)
return bytes.LongLength <= maximumBytes - scalarOverhead;
return bytes.LongLength <= maximumBytes - scalarOverhead ? scalarOverhead + bytes.LongLength : -1;
if (metadata.ValueKind == DataValueKind.String && value is string textValue)
return textValue.Length <= (maximumBytes - scalarOverhead) / 2;
return true; // Exact scalar type checks remain in EncodeValue after admission.
return textValue.Length <= (maximumBytes - scalarOverhead) / 2 ? scalarOverhead + 2L * textValue.Length : -1;
return scalarOverhead; // Exact scalar type checks remain in EncodeValue after admission.
}
// #960: the identifier strings a projected write carries (view, serving incarnation, and its two 32-char correlation ids).
private static long WriteIdentifierChars(Demand demand)
{
var view = demand.OriginView;
return 64L + (view.Subject?.Length ?? 0) + (view.MappingId?.Length ?? 0) + (view.Address?.OriginClusterId?.Length ?? 0) +
(view.Address?.NamespaceUri?.Length ?? 0) + (view.Address?.IdentifierKind?.Length ?? 0) + (view.Address?.Identifier?.Length ?? 0) +
(demand.Serving.Incarnation?.Length ?? 0);
}
/// <summary>
/// #960: the fixed part of every projected unary reservation — the response envelope (serving identity, correlation,
/// status, timestamps, age bounds) and one fixed-size scalar value, with a wide margin (a scalar Int32 read answers in
/// well under 2 KiB, decoded). The default 1 MiB <c>DataConnections:MaxPendingBytes</c> holds 64 of them, the default
/// <c>MaxConcurrentCalls</c>.
/// </summary>
internal const long ProjectedEnvelopeBytes = 16 * 1024;
/// <summary>#960: the decoded bound of one fixed-size array element (a Guid element, the widest, decodes to ~240 B).</summary>
private const long ProjectedFixedElementBytes = 256;
private static bool IsFixedSizeKind(DataValueKind kind) => kind is DataValueKind.Null or DataValueKind.Boolean or DataValueKind.Int8 or
DataValueKind.Int16 or DataValueKind.Int32 or DataValueKind.Int64 or DataValueKind.UInt8 or DataValueKind.UInt16 or DataValueKind.UInt32 or
DataValueKind.UInt64 or DataValueKind.Float or DataValueKind.Double or DataValueKind.Timestamp or DataValueKind.Guid;
/// <summary>
/// #960: what one projected read of a node with this origin metadata reserves against the unary byte budget, at most
/// <paramref name="ceiling"/>. A fixed-size scalar, or a fixed-length array of fixed-size elements, is bounded by its
/// shape; a String / Bytes value or a variable-length array has no declared bound, so it keeps the whole per-read cap.
/// The reservation is also the read's decode limit: an origin answering more than its node's declared shape allows is
/// refused at decode, so the memory bound holds whatever the origin sends.
/// </summary>
internal static long ReadReservationBytes(DataMetadata metadata, long ceiling)
{
long? bound = metadata.ValueKind switch
{
DataValueKind.Array when metadata.ValueRank == 1 && metadata.Dimensions.Count == 1 && metadata.Dimensions[0] > 0 &&
metadata.ArrayElementKind is { } element && IsFixedSizeKind(element) =>
ProjectedEnvelopeBytes + ProjectedFixedElementBytes * metadata.Dimensions[0],
var kind when IsFixedSizeKind(kind) => ProjectedEnvelopeBytes,
_ => null,
};
return bound is { } bytes && bytes < ceiling ? bytes : ceiling;
}
private static ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue EncodeValue(DataMetadata metadata, object? value, long maximumBytes)
{
@@ -860,7 +901,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
}
public bool ScheduleRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp)
{
if (!TryAdmitRead(demand, budget, requestStartedTimestamp, out var item, out var boundedBudget)) return false;
if (!TryAdmitRead(demand, budget, requestStartedTimestamp, waiting: false, out var item, out var boundedBudget)) return false;
_ = Task.Run(() => ReadCoreAsync(item!, boundedBudget!, requestStartedTimestamp, CancellationToken.None, ownsDemand: true)); return true;
}
/// <inheritdoc />
@@ -871,7 +912,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
// ScheduleRead — but the caller awaits it and is served what it read. The caller keeps the demand. Admission is decided
// here, synchronously, so NotAdmitted is an already-completed task.
if (cancellationToken.IsCancellationRequested) return Task.FromResult(ProjectedOriginRead.NoValue);
if (!TryAdmitRead(demand, budget, requestStartedTimestamp, out var item, out var boundedBudget))
if (!TryAdmitRead(demand, budget, requestStartedTimestamp, waiting: true, out var item, out var boundedBudget))
return Task.FromResult(demand is Demand { IsValid: true } ? ProjectedOriginRead.NotAdmitted : ProjectedOriginRead.NoValue);
return Task.Run(async () =>
{
@@ -879,7 +920,15 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
return value is null ? ProjectedOriginRead.NoValue : new ProjectedOriginRead(ProjectedOriginReadStatus.Served, value);
}, CancellationToken.None);
}
private bool TryAdmitRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp, out Demand? item, out DataBudget? boundedBudget)
/// <summary>
/// #960: how long a read refused for bytes by a caller that waits for capacity (<see cref="ReadNowAsync"/>) holds back
/// smaller reads, so a whole-cap (String / Bytes / variable-array) read is not starved by a steady stream of scalar reads
/// that each fit. Re-armed by every refused retry; cleared when a read at least that large is admitted.
/// </summary>
internal static readonly TimeSpan ReadDrainWindow = TimeSpan.FromMilliseconds(100);
private long _drainUntil;
private long _drainBytes;
private bool TryAdmitRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp, bool waiting, out Demand? item, out DataBudget? boundedBudget)
{
item = null; boundedBudget = null;
if (demand is not Demand candidate || candidate.RequestedOperation != DataOperations.Read || !candidate.IsValid || budget is null) return false;
@@ -887,12 +936,30 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
var elapsed = Clock.GetElapsedTime(requestStartedTimestamp, Clock.GetTimestamp());
if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout) return false;
// The request's byte budget is an upper bound. Narrow it to this adapter's
// configured physical limit before admission and before remote dispatch.
var bounded = budget with { MaxBytes = Math.Min(budget.MaxBytes, _limits.MaxUnaryBytes) };
// configured physical limit before admission and before remote dispatch, and (#960) to what the node's declared shape
// can answer: a scalar read no longer reserves the whole budget, so concurrent reads proceed.
var bounded = budget with { MaxBytes = ReadReservationBytes(candidate.Proof.OriginMetadata, Math.Min(budget.MaxBytes, _limits.MaxUnaryBytes)) };
lock (_sync)
{
if (_disposed || _unaryCount >= _limits.MaxUnaryOperations || bounded.MaxBytes > _limits.MaxUnaryBytes - _unaryBytes || !candidate.TryHold()) return false;
if (_disposed) return false;
var now = Clock.GetTimestamp();
var draining = _drainBytes > 0 && now < _drainUntil;
if (!draining) _drainBytes = 0;
var free = _limits.MaxUnaryBytes - _unaryBytes;
if (bounded.MaxBytes > free)
{
if (waiting)
{
_drainBytes = draining ? Math.Max(_drainBytes, bounded.MaxBytes) : bounded.MaxBytes;
_drainUntil = now + Math.Max(1, (long)(ReadDrainWindow.TotalSeconds * Clock.TimestampFrequency));
}
return false;
}
// A smaller read may still go ahead while one waits, but only into room the waiting read does not need.
if (draining && bounded.MaxBytes < _drainBytes && bounded.MaxBytes > free - _drainBytes) return false;
if (_unaryCount >= _limits.MaxUnaryOperations || !candidate.TryHold()) return false;
_unaryCount++; _unaryBytes += bounded.MaxBytes;
if (draining && bounded.MaxBytes >= _drainBytes) _drainBytes = 0;
}
item = candidate; boundedBudget = bounded;
return true;
@@ -966,7 +1033,12 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
// The SDK's request cap is an upper bound, not a minimum required reservation.
// Use the adapter's configured ceiling for payload checks and physical work.
budget = budget with { MaxBytes = Math.Min(budget.MaxBytes, _limits.MaxUnaryBytes) };
if (!FitsWriteBudget(item.Proof.OriginMetadata, value, budget.MaxBytes)) return rejected;
var valueBytes = WriteValueBytes(item.Proof.OriginMetadata, value, budget.MaxBytes);
if (valueBytes < 0) return rejected;
// #960: reserve what this write needs, not the whole cap, so concurrent writes and reads proceed. The reservation is
// also the batch budget the ORIGIN admits the write against (DataWriteExecutor: 3 × the value's retained estimate +
// 512 + 2 × its identifier strings), which valueBytes bounds from above.
budget = budget with { MaxBytes = Math.Min(budget.MaxBytes, ProjectedEnvelopeBytes + 2L * WriteIdentifierChars(item) + 3L * valueBytes) };
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or OverflowException) { return rejected; }
var elapsed = Clock.GetElapsedTime(requestStartedTimestamp, Clock.GetTimestamp());
@@ -1365,7 +1437,9 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
if (remaining <= TimeSpan.FromMilliseconds(1)) return false;
timeout = TimeSpan.FromTicks(Math.Min(timeout.Ticks, remaining.Ticks - remaining.Ticks / 4));
}
var budget = new DataBudget(timeout, 1, _owner._limits.MaxUnaryBytes);
// #960: one metadata item and its capability probe (as an on-demand lapse renewal), never the whole unary budget —
// which needed every other projected read/write to be idle, and so starved behind concurrent reads.
var budget = new DataBudget(timeout, 1, Math.Min(LapseRenewalBytes, _owner._limits.MaxUnaryBytes));
lock (_owner._sync)
{
if (_owner._disposed || demand.Disposed || _owner._unaryCount >= _owner._limits.MaxUnaryOperations ||