Merge #960/#961: projected reads reserve by declared type (16 KiB scalar) so up to 64 run concurrently, large-read anti-starvation, writes reserve 3x value bound; a refused projected item in CreateMonitoredItems is a per-item status
v2-ci / unit-tests (push) Failing after 10m20s

This commit is contained in:
Joseph Doherty
2026-12-01 20:41:43 -05:00
14 changed files with 644 additions and 48 deletions
+1 -1
View File
@@ -262,7 +262,7 @@ consumer scope, exports, mappings, credential provisioning and recovery.
| `MaxMessageBytes` / `MaxConcurrentCalls` | `1048576` / `64` | Message-size and concurrent unary-call admission. |
| `MaxStreams` / `MaxStreamsPerPrincipal` | `256` / `8` | Global and per-principal stream bounds. |
| `MaxMonitoredItems` | `10000` | Listener monitored-item bound. |
| `MaxTransportBytes` / `MaxPendingBytes` | `67108864` / `1048576` | Retained transport and pending-work byte bounds. |
| `MaxTransportBytes` / `MaxPendingBytes` | `67108864` / `1048576` | Retained transport and pending-work byte bounds. `MaxPendingBytes` is also the consumer's projected unary budget: since #960 a projected Read reserves 16 KiB for a fixed-size scalar (64 fit the default), a String / Bytes / variable-array read the whole `min(4 MiB, MaxPendingBytes)` — raise it for concurrent reads of those. |
| `MaxSessionLifetime` | `01:00:00` | Finite stream-session lifetime. |
| `UnaryTimeout` / `StreamCommandTimeout` | `00:00:30` / `00:00:05` | Finite ingress unary and stream-command deadlines. |
| `CredentialBundlePath` / `TrustBundlePath` | unset | Independent node-local credential and trust provisioning mounts. |
+7 -2
View File
@@ -101,7 +101,7 @@ a write also needs this node's local write role). A caller without the grant is
`GetMetadata` renewal as above, for the operation it is performing (its Read / HistoryRead / Write /
Subscribe bit), one per node and operation at a time, with a 250 ms back-off after a failure. On-demand
renewals never touch the unary budget (cold reads, writes) or the browse/subscription-renewal fetch
slots: they queue (at most 64) for their own pool of `max(1, maxConcurrentFetches / 2)` origin calls,
slots (an existing monitored item's renewal reserves 256 KiB of the unary budget since #960, not all of it): they queue (at most 64) for their own pool of `max(1, maxConcurrentFetches / 2)` origin calls,
reserve 256 KiB each, and have 3 s end to end, so a batch of N lapsed nodes renews all N:
- **Value Read** awaits the renewal within the request (#938; the async Read, no `Lock`, at most
@@ -116,7 +116,12 @@ reserve 256 KiB each, and have 3 s end to end, so a batch of N lapsed nodes rene
most 4 s, async, no `Lock`) and then creates them. An item still not acquirable is answered PER
ITEM — `BadResourceUnavailable` for a lapse the caller is granted, `BadUserAccessDenied` for a real
refusal. (Before, a refused projected item was thrown from the item manager and faulted the whole
CreateMonitoredItems request.)
CreateMonitoredItems request.) **Since #961** the remainder refused at the create itself (under the SDK's
`Lock`, after that per-item check) is per item too: the authority changing in between is re-classified
the same way once the create returns (granted lapse, or admitted again by then ⇒ `BadResourceUnavailable`;
real refusal ⇒ `BadUserAccessDenied`), and no origin stream able to take the item (the node's
`MaxStreams` streams — one per connection, serving identity and publishing interval — all in use, or a
closing one) is `BadResourceUnavailable`. The other items of the request are created normally.
- **HistoryRead** renews within the request and is then served. The wait (one per batch, at most 4 s
and never past `HistoryReadDeadline`, no node-manager `Lock` held, the request's cancellation
honoured) takes one of the non-local history batch slots first. A batch that finds none free does
+13 -3
View File
@@ -40,9 +40,19 @@ a missing sample or an unsuitable one — is served from a bounded origin read *
request**: the node manager's async Read (`IReadAsyncNodeManager`, no node-manager `Lock` held, no
request thread blocked) reads the origin, serves what it read and publishes it to the cache. The
wait is at most 5 s per request (`OtOpcUaNodeManager.ProjectedOriginReadWait`), less the request
deadline's margin; the reads are admitted against the same unary budget as before (the default
1 MiB `MaxPendingBytes` admits one 1 MiB read at a time) and a batch is pumped through it as reads
complete. A read that is not answered in time, or answers nothing servable (unreachable, not
deadline's margin; the reads are admitted against the same unary budget as before and a batch is
pumped through it as reads complete. **Since #960** each read reserves only what its node's declared
shape can answer — 16 KiB for a fixed-size scalar, 16 KiB + 256 B per element for a fixed-length
array of fixed-size elements — so the default 1 MiB `DataConnections:MaxPendingBytes` admits up to
`MaxConcurrentCalls` (64) scalar reads at once (measured: four 250 ms origin reads in one `maxAge=0`
request, 1016 ms / 1 in flight before, 285 ms / 4 in flight after). A String / Bytes value or a
variable-length array has no declared bound and still reserves the whole per-read cap
(`min(4 MiB, MaxPendingBytes)`), so such reads run one at a time at the default; a read of that kind
that is waiting for capacity holds back smaller reads for 100 ms (re-armed while it waits) so a steady
stream of scalar reads cannot starve it. The reservation is also the read's decode limit, so an
origin answering more than the node's shape allows is refused rather than exceeding the bound. A
projected Write likewise reserves what its value needs (16 KiB + identifiers + 3 × the value's
size bound — the budget the origin admits a write batch against), not the whole cap. A read that is not answered in time, or answers nothing servable (unreachable, not
ready, older than the mapping's stale timeout), returns `BadWaitingForInitialData` as before; a
read never admitted by the deadline is scheduled as before. A lapsed lease is renewed first, in the
same request (see [Data connections](DataConnections.md#subscription-freshness-and-exact-item-renewal)).
@@ -0,0 +1,88 @@
# #960 / #961 — projected unary reservation sizing, per-item create refusals
2026-12-01. Follow-ups of #938 and #940 (`938-939-940-948.md`). Consumer side of gRPC data connections.
## #960 — one projected origin read/write in flight per node
**Root cause.** `ProjectedDataAccess` admitted every projected read (`ScheduleRead` / `ReadNowAsync`) and write by reserving
`min(caller cap = 4 MiB, MaxUnaryBytes)` against `MaxUnaryBytes`, which production wires to `DataConnections:MaxPendingBytes`
(default **1 MiB**). Every operation reserved the whole budget, so one read or write excluded all others and
`MaxConcurrentCalls` (64) never applied. A `maxAge=0` batch of N nodes was N serial origin round trips; a concurrent write was
rejected outright (`WriteAsync` does not wait). An existing monitored item's metadata renewal (`RenewOwnedAsync`) also reserved
the whole budget, so it needed every other projected operation idle.
**Fix.** Size each reservation from what the operation can carry, keeping the sum bounded by `MaxPendingBytes`:
- **Read** — `ReadReservationBytes(originMetadata, cap)`: 16 KiB (`ProjectedEnvelopeBytes`) for a fixed-size scalar (Boolean,
integers, Float/Double, Timestamp, Guid, Null); 16 KiB + 256 B/element for a fixed-length array of fixed-size elements; the
whole cap for String / Bytes / variable-length or string arrays (no declared bound — unchanged). The reservation is also the
read's budget, i.e. the consumer's decode limit and the origin's response limit, so an origin answering more than the node's
shape allows is refused rather than exceeding the bound. `GrpcDataProjectedReadReservationTests` pins the constants against
the real wire codec (widest value of each bounded shape, 128-char serving identifiers, decoded at exactly the reservation).
- **Anti-starvation.** A whole-cap read refused for bytes by a caller that waits (`ReadNowAsync`, the #938 pump) holds back
smaller reads for 100 ms (`ReadDrainWindow`, re-armed by each refused retry, cleared when it is admitted), so scalar reads
that now share the budget cannot starve it. Fire-and-forget `ScheduleRead` does not arm it; writes neither arm nor honour it.
- **Write** — `16 KiB + 2 × identifier chars + 3 × WriteValueBytes(value)` (capped). The `3 ×` term is required: the reservation
is the batch budget the ORIGIN admits the write against (`DataWriteExecutor`: `3 × EstimatedRetainedBytes + 512 + 2 ×
identifiers`), and `WriteValueBytes` (the former `FitsWriteBudget` bound) is ≥ that estimate for every kind. A first draft
without it would have refused strings over ~4 K chars at the origin (`A_large_string_write_reserves_what_the_origin_admits_it_against`).
- **Monitored-item renewal** — 256 KiB (`LapseRenewalBytes`, the same metadata call the on-demand lapse renewal makes).
The default `MaxPendingBytes` is unchanged: 1 MiB now holds 64 scalar reads (= `MaxConcurrentCalls`). Variable-size reads still
serialize at the default; raising `MaxPendingBytes` buys concurrency for those (docs/Configuration.md).
**Measurement** (`A_max_age_zero_batch_of_scalar_nodes_reads_the_origin_concurrently_within_the_default_budget`: real consumer
SDK session, 4 projected Int32 nodes, `maxAge=0`, 1 MiB budget, origin reads delayed 250 ms):
| | elapsed | max origin reads in flight |
|---|---|---|
| pre-fix | 1016 ms | 1 |
| fix | 285 ms | 4 (the harness's operation limit) |
Not measured on the rig with ScadaBridge-sized batches (no rig run in this change).
## #961 — a projected item refused inside the item-manager create faulted the whole request
**Root cause.** `OrdinaryTagItemManager.CreateMonitoredItem` threw `ServiceResultException(BadUserAccessDenied)` when
`TryAcquireProjectedItem` failed. SDK 2.0.1 `CustomNodeManager2.CreateMonitoredItems` calls the protected `CreateMonitoredItem`
per item under `Lock` with no catch, so the throw became a service fault for every item in the request. Since #940 this was only
the remainder after the per-item probe: the authority changing between probe and create, and `StartSubscription` refusing
(`MaxStreams` cohorts — one per connection × serving identity × publishing interval — all in use, or a closing cohort).
**Fix.**
- `TryAcquireProjectedItem` reports why: `BadResourceUnavailable` when the authority admitted the caller but `StartSubscription`
refused (the demand still valid), else `BadUserAccessDenied` (provisional).
- `OtOpcUaNodeManager` overrides the protected `CreateMonitoredItem`: a `ServiceResultException` becomes THIS item's status.
Nothing leaks — the item manager releases what it reserved before throwing, and the base deletes an item it already created
before rethrowing.
- After `base.CreateMonitoredItems` (outside `Lock`) every projected item the probe admitted but the create answered
`BadUserAccessDenied` is re-classified exactly like the probe (`ProjectedSubscribeRefusal`): granted lapse ⇒
`BadResourceUnavailable` (its renewal starts), real refusal ⇒ `BadUserAccessDenied`, admitted again by now ⇒
`BadResourceUnavailable` (a transient race; the retry succeeds).
## Red / green (Runtime.Tests)
| Test (`Trait Issue`) | pre-fix | fix |
|---|---|---|
| 960 `Scalar_reads_reserve_their_shape_bound_so_concurrent_reads_share_the_default_budget` | **FAIL** | pass |
| 960 `A_waiting_whole_cap_read_holds_back_smaller_reads_until_it_is_admitted` | **FAIL** | pass |
| 960 `Scalar_writes_are_dispatched_concurrently_within_the_default_budget` | **FAIL** | pass |
| 960 `A_max_age_zero_batch_of_scalar_nodes_reads_the_origin_concurrently_within_the_default_budget` (wire) | **FAIL** (1 in flight) | pass |
| 960 `Cold_sdk_read_budget…` / `Sdk_write_budget…` (assert the sized budget now) | **FAIL** | pass |
| 960 `Variable_size_read_reserves_the_full_configured_budget_until_physical_completion` (control) | pass | pass |
| 960 `A_large_string_write_reserves_what_the_origin_admits_it_against` (guards the 3 × term) | pass | pass |
| 960 `GrpcDataProjectedReadReservationTests` (13, codec pins) | n/a (new API) | pass |
| 961 `A_projected_item_refused_for_stream_capacity_at_create_fails_only_that_item` (wire) | **FAIL** (request fault `BadUserAccessDenied`) | pass |
| 961 `A_projected_item_whose_lease_lapses_between_the_probe_and_the_create_is_retryable_for_that_item_only` (wire) | **FAIL** (request fault) | pass |
Adjusted for #960 (they encoded "one operation holds the whole budget"): `Cancelled_clamped_write_keeps_capacity…` (30 KiB budget
= one scalar write), `Full_write_quota_rejects_large_array…` (the held write is now ~2 MiB so the second does not fit beside it),
`A_max_age_zero_batch_larger_than_the_unary_budget_is_pumped…` (budget = one scalar reservation; asserts 1 in flight),
`Sdk_mapped_write_uses_default_one_mib_budget_and_is_dispatched_once` (asserts the sized write budget, < 64 KiB and above the
origin's scalar accounting, instead of the whole 1 MiB).
Suites: Runtime.Tests `FullyQualifiedName~DataConnections` 1005/1005 (after the last adjustment), OpcUaServer.Tests 1460 passed,
2 skipped, 0 failed.
Not live-gated (no rig run in this change).
@@ -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 ||
@@ -189,7 +189,12 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
response.Results.ToArray()!.ShouldHaveSingleItem().ShouldBe(outcome == DataWriteState.DriverConfirmedSuccess
? StatusCodes.Good : StatusCodes.UncertainLastUsableValue);
writes.Calls.ShouldBe(1, "neither a success nor an ambiguous outcome may be replayed");
writes.Value.ShouldBe(77); writes.Budget.ShouldNotBeNull().MaxBytes.ShouldBe(1024 * 1024);
writes.Value.ShouldBe(77);
// #960: within the default 1 MiB budget a scalar write reserves (and carries) what it needs, not all of it — enough for
// the origin's write accounting (3 × the 288 B scalar estimate + 512 + identifiers).
var budget = writes.Budget.ShouldNotBeNull().MaxBytes;
budget.ShouldBeLessThan(64 * 1024);
budget.ShouldBeGreaterThan(ProjectedDataAccess.ProjectedEnvelopeBytes + 3 * 288);
}, maxUnaryBytes: 1024 * 1024, allowWrite: true);
}
@@ -221,10 +221,14 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
/// <summary>Like <c>FakeConnections</c>, counting browse, metadata and read calls separately.</summary>
private sealed class CountingConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource
{
private int _browse, _metadata, _read;
private int _browse, _metadata, _read, _readsInFlight, _maxReadsInFlight;
public int BrowseCalls => Volatile.Read(ref _browse);
public int MetadataCalls => Volatile.Read(ref _metadata);
public int ReadCalls => Volatile.Read(ref _read);
/// <summary>#960: the most origin reads ever in flight at once.</summary>
public int MaxConcurrentReads => Volatile.Read(ref _maxReadsInFlight);
/// <summary>#960: how long each origin read takes (real time), so concurrent reads overlap measurably.</summary>
public TimeSpan ReadDelay { get; set; }
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken) =>
ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(connectionId == "link" ? new Lease(new Connection(peer.Connection(), this)) : null);
private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease
@@ -242,8 +246,19 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
{ Interlocked.Increment(ref owner._browse); return inner.BrowseAsync(request, cancellationToken); }
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken)
{ Interlocked.Increment(ref owner._metadata); return inner.GetMetadataAsync(request, cancellationToken); }
public Task<IReadOnlyList<DataReadResult>> ReadAsync(DataReadRequest request, CancellationToken cancellationToken)
{ Interlocked.Increment(ref owner._read); return inner.ReadAsync(request, cancellationToken); }
public async Task<IReadOnlyList<DataReadResult>> ReadAsync(DataReadRequest request, CancellationToken cancellationToken)
{
Interlocked.Increment(ref owner._read);
var now = Interlocked.Increment(ref owner._readsInFlight);
for (var seen = Volatile.Read(ref owner._maxReadsInFlight); now > seen; seen = Volatile.Read(ref owner._maxReadsInFlight))
if (Interlocked.CompareExchange(ref owner._maxReadsInFlight, now, seen) == seen) break;
try
{
if (owner.ReadDelay > TimeSpan.Zero) await Task.Delay(owner.ReadDelay, cancellationToken);
return await inner.ReadAsync(request, cancellationToken);
}
finally { Interlocked.Decrement(ref owner._readsInFlight); }
}
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => inner.WriteAsync(request, cancellationToken);
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken) => inner.SubscribeAsync(cancellationToken);
public ValueTask DisposeAsync() => inner.DisposeAsync();
@@ -175,32 +175,115 @@ public sealed partial class GrpcDataProjectedAccessTests
access.ScheduleRead(demand!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
var update = await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
update.Snapshot.Value.ShouldBe(42);
fixture.ReadBudget.ShouldNotBeNull().MaxBytes.ShouldBe(1024 * 1024);
// #960: a scalar read reserves (and may decode) only what its declared shape can answer, within the configured limit.
fixture.ReadBudget.ShouldNotBeNull().MaxBytes.ShouldBe(ProjectedDataAccess.ProjectedEnvelopeBytes);
await fixture.ConnectionDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
}
[Fact(Timeout = 30000), Trait("Phase", "P10")]
public async Task Clamped_read_reserves_the_full_configured_budget_until_physical_completion()
[Fact(Timeout = 30000), Trait("Phase", "P10"), Trait("Issue", "960")]
public async Task Variable_size_read_reserves_the_full_configured_budget_until_physical_completion()
{
// A String value has no declared bound, so its read keeps the whole per-read cap (#960 sizes only bounded shapes).
using var fixture = new AccessFixture(readOnly: true) { BlockAcquire = true }; using var access = fixture.Create(maxBytes: 1024 * 1024);
fixture.Publish(42);
UseValueKind(fixture, DataValueKind.String);
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var first).ShouldBeTrue();
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var second).ShouldBeTrue();
var sdkBudget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024);
try
{
access.ScheduleRead(first!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
first = null; // admitted work owns the lease
await fixture.AcquireEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
access.ScheduleRead(second!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeFalse();
second!.IsValid.ShouldBeTrue("a rejected admission leaves ownership with the caller");
fixture.ReleaseAcquire.TrySetResult();
await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
SpinWait.SpinUntil(() => access.ScheduleRead(second, sdkBudget, fixture.Clock.GetTimestamp()), TimeSpan.FromSeconds(5)).ShouldBeTrue();
second = null; // admitted work owns the lease
second = null;
fixture.ReadBudget.ShouldNotBeNull().MaxBytes.ShouldBe(1024 * 1024);
}
finally { fixture.ReleaseAcquire.TrySetResult(); first?.Dispose(); second?.Dispose(); }
}
[Fact(Timeout = 30000), Trait("Phase", "P10"), Trait("Issue", "960")]
public async Task Scalar_reads_reserve_their_shape_bound_so_concurrent_reads_share_the_default_budget()
{
// The production default: DataConnections:MaxPendingBytes = 1 MiB. Before #960 every read reserved all of it, so only
// ONE projected read (or write) could be in flight per node. The operation-count limit (4 here) is the bound now.
using var fixture = new AccessFixture(readOnly: true) { BlockAcquire = true }; using var access = fixture.Create(maxDemands: 8, maxBytes: 1024 * 1024);
fixture.Publish(42);
var sdkBudget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024);
var demands = new List<IProjectedDemandLease?>();
try
{
for (var i = 0; i < 5; i++)
{
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue();
demands.Add(demand);
}
var admitted = 0;
for (var i = 0; i < 4; i++)
if (access.ScheduleRead(demands[i]!, sdkBudget, fixture.Clock.GetTimestamp())) { admitted++; demands[i] = null; }
admitted.ShouldBe(4, "four scalar reads fit the 1 MiB budget at once");
access.ScheduleRead(demands[4]!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeFalse("the operation-count limit still bounds them");
fixture.ReleaseAcquire.TrySetResult();
SpinWait.SpinUntil(() => access.ScheduleRead(demands[4]!, sdkBudget, fixture.Clock.GetTimestamp()), TimeSpan.FromSeconds(5)).ShouldBeTrue();
demands[4] = null;
await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
}
finally { fixture.ReleaseAcquire.TrySetResult(); foreach (var demand in demands) demand?.Dispose(); }
}
[Fact(Timeout = 30000), Trait("Phase", "P10"), Trait("Issue", "960")]
public async Task A_waiting_whole_cap_read_holds_back_smaller_reads_until_it_is_admitted()
{
// Scalar reads now share the budget; a whole-cap (String) read that waits for capacity must not be starved by them.
using var fixture = new AccessFixture(readOnly: true, streams: true) { BlockAcquire = true };
using var access = fixture.Create(maxDemands: 8, maxBytes: 1024 * 1024);
var stringMetadata = fixture.SecondProof!.Metadata with { ValueKind = DataValueKind.String };
fixture.SecondProof = fixture.SecondProof with { Metadata = stringMetadata, OriginMetadata = fixture.SecondProof.OriginMetadata with { ValueKind = DataValueKind.String } };
fixture.SecondDefinition = fixture.SecondDefinition! with { Metadata = stringMetadata };
fixture.Publish(42);
var sdkBudget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024);
var ct = TestContext.Current.CancellationToken;
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var first).ShouldBeTrue();
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var second).ShouldBeTrue();
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var third).ShouldBeTrue();
access.TryAcquire(fixture.SecondNodeId, fixture.Caller, DataOperations.Read, out var large).ShouldBeTrue();
try
{
access.ScheduleRead(first!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
first = null;
(await access.ReadNowAsync(large!, sdkBudget, fixture.Clock.GetTimestamp(), ct)).Status.ShouldBe(ProjectedOriginReadStatus.NotAdmitted);
access.ScheduleRead(second!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeFalse("a waiting whole-cap read holds back smaller ones");
// A waiter that gives up stops holding them back once the window lapses.
fixture.Advance(ProjectedDataAccess.ReadDrainWindow + TimeSpan.FromMilliseconds(1));
access.ScheduleRead(second!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
second = null;
// It waits again; the scalar reads in flight finish and it is admitted ahead of the third.
(await access.ReadNowAsync(large!, sdkBudget, fixture.Clock.GetTimestamp(), ct)).Status.ShouldBe(ProjectedOriginReadStatus.NotAdmitted);
access.ScheduleRead(third!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeFalse();
fixture.ReleaseAcquire.TrySetResult();
Task<ProjectedOriginRead>? read = null;
SpinWait.SpinUntil(() =>
{
var attempt = access.ReadNowAsync(large!, sdkBudget, fixture.Clock.GetTimestamp(), ct);
if (attempt.IsCompletedSuccessfully && attempt.Result.Status == ProjectedOriginReadStatus.NotAdmitted) return false;
read = attempt; return true;
}, TimeSpan.FromSeconds(5)).ShouldBeTrue("the waiting read is admitted once the scalar reads finish");
await read!.WaitAsync(TimeSpan.FromSeconds(5), ct);
SpinWait.SpinUntil(() => access.ScheduleRead(third!, sdkBudget, fixture.Clock.GetTimestamp()), TimeSpan.FromSeconds(5)).ShouldBeTrue();
third = null;
}
finally { fixture.ReleaseAcquire.TrySetResult(); first?.Dispose(); second?.Dispose(); third?.Dispose(); large?.Dispose(); }
}
private static void UseValueKind(AccessFixture fixture, DataValueKind kind)
{
var metadata = fixture.Proof.Metadata with { ValueKind = kind };
fixture.Proof = fixture.Proof with { Metadata = metadata, OriginMetadata = fixture.Proof.OriginMetadata with { ValueKind = kind } };
fixture.Definition = fixture.Definition with { Metadata = metadata };
}
[Fact(Timeout = 30000)]
public async Task Read_without_subscribe_permission_preserves_origin_age_timestamps_and_source_proof()
{
@@ -250,12 +333,70 @@ public sealed partial class GrpcDataProjectedAccessTests
var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024);
var result = await access.WriteAsync(demand!, 42, budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken);
result.State.ShouldBe(DataWriteState.OutcomeUnknown);
fixture.SentWrite.ShouldNotBeNull().Budget.MaxBytes.ShouldBe(1024 * 1024);
// #960: a scalar write reserves what it needs (envelope + the origin's write accounting), not the whole configured limit.
var sent = fixture.SentWrite.ShouldNotBeNull();
sent.Budget.MaxBytes.ShouldBeLessThan(ScalarWriteBytesBound);
sent.Budget.MaxBytes.ShouldBeGreaterThanOrEqualTo(OriginWriteAccounting(sent, 288));
fixture.WriteCalls.ShouldBe(1);
}
finally { demand?.Dispose(); }
}
/// <summary>#960: more than one scalar write's reservation (envelope + identifiers + 3 × 288), less than two.</summary>
private const long ScalarWriteBytesBound = 30 * 1024;
/// <summary>What the origin's DataWriteExecutor admits a one-item write batch against (3 × retained estimate + 512 + identifiers).</summary>
private static long OriginWriteAccounting(WriteBatch sent, long valueEstimate)
{
var item = sent.Items.ShouldHaveSingleItem();
return 3 * valueEstimate + 512 + 2L * ((item.CorrelationId?.Length ?? 0) + (item.OperationId?.Length ?? 0) +
(item.View.Subject?.Length ?? 0) + (item.View.MappingId?.Length ?? 0) + (item.View.Address.OriginClusterId?.Length ?? 0) +
(item.View.Address.NamespaceUri?.Length ?? 0) + (item.View.Address.IdentifierKind?.Length ?? 0) +
(item.View.Address.Identifier?.Length ?? 0) + (item.ExpectedServingIncarnation?.Length ?? 0));
}
[Fact(Timeout = 30000), Trait("Phase", "P10"), Trait("Issue", "960")]
public async Task A_large_string_write_reserves_what_the_origin_admits_it_against()
{
// Sized below the cap, a write must still carry the budget the ORIGIN checks it against, or a long string that the
// whole-cap reservation used to carry is refused there ("Write batch exceeds its byte limit").
using var fixture = new AccessFixture(writable: true); using var access = fixture.Create(maxBytes: 1024 * 1024);
UseValueKind(fixture, DataValueKind.String);
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var demand).ShouldBeTrue();
try
{
var text = new string('x', 20_000);
var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024);
(await access.WriteAsync(demand!, text, budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken)).State
.ShouldBe(DataWriteState.OutcomeUnknown);
var sent = fixture.SentWrite.ShouldNotBeNull();
sent.Budget.MaxBytes.ShouldBeGreaterThanOrEqualTo(OriginWriteAccounting(sent, 288 + 2L * text.Length));
sent.Budget.MaxBytes.ShouldBeLessThan(1024 * 1024);
}
finally { demand?.Dispose(); }
}
[Fact(Timeout = 30000), Trait("Phase", "P10"), Trait("Issue", "960")]
public async Task Scalar_writes_are_dispatched_concurrently_within_the_default_budget()
{
using var fixture = new AccessFixture(writable: true) { BlockWrite = true }; using var access = fixture.Create(maxBytes: 1024 * 1024);
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var first).ShouldBeTrue();
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var second).ShouldBeTrue();
try
{
var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024);
var one = access.WriteAsync(first!, 42, budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken);
await fixture.WriteEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
var two = access.WriteAsync(second!, 43, budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken);
SpinWait.SpinUntil(() => Volatile.Read(ref fixture.WriteCalls) == 2 || two.IsCompleted, TimeSpan.FromSeconds(5));
fixture.WriteCalls.ShouldBe(2, "a second write is dispatched while the first is in flight, not rejected for capacity");
fixture.ReleaseWrite.TrySetResult();
(await one.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.OutcomeUnknown);
(await two.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.OutcomeUnknown);
}
finally { fixture.ReleaseWrite.TrySetResult(); first?.Dispose(); second?.Dispose(); }
}
[Fact(Timeout = 30000), Trait("Phase", "P10")]
public async Task Clamped_write_rejects_oversized_value_before_dispatch()
{
@@ -276,7 +417,8 @@ public sealed partial class GrpcDataProjectedAccessTests
[Fact(Timeout = 30000), Trait("Phase", "P10")]
public async Task Cancelled_clamped_write_keeps_capacity_until_the_physical_send_finishes()
{
using var fixture = new AccessFixture(writable: true) { BlockWrite = true }; using var access = fixture.Create(maxBytes: 1024 * 1024);
// A budget that holds one scalar write's reservation but not two (#960), so the held one leaves no room for another.
using var fixture = new AccessFixture(writable: true) { BlockWrite = true }; using var access = fixture.Create(maxBytes: ScalarWriteBytesBound);
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var first).ShouldBeTrue();
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var second).ShouldBeTrue();
using var cancel = new CancellationTokenSource();
@@ -79,7 +79,7 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
using var origin = new LocalDataFixture(additionalRawNodes: 3, servingGeneration: 1);
origin.Publish(42);
var connections = new CountingConnections(origin);
// 1 MiB unary budget = ONE read in flight at a time (each reserves it all), as in production by default.
// A unary budget of exactly one scalar read's reservation (#960) = ONE read in flight at a time.
await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
@@ -90,6 +90,36 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
var results = read.Results.ToArray()!;
results.ShouldAllBe(r => StatusCode.IsGood(r.StatusCode), string.Join(", ", results.Select(r => r.StatusCode.ToString())));
connections.ReadCalls.ShouldBe(4);
connections.MaxConcurrentReads.ShouldBe(1);
}, connectionSource: connections, maxUnaryBytes: ProjectedDataAccess.ProjectedEnvelopeBytes);
}
// ---------------------------------------------------------------- #960
[Fact(Timeout = 90000), Trait("Issue", "960")]
public async Task A_max_age_zero_batch_of_scalar_nodes_reads_the_origin_concurrently_within_the_default_budget()
{
var ct = TestContext.Current.CancellationToken;
using var origin = new LocalDataFixture(additionalRawNodes: 3, servingGeneration: 1);
origin.Publish(42);
var connections = new CountingConnections(origin) { ReadDelay = TimeSpan.FromMilliseconds(250) };
// The production default DataConnections:MaxPendingBytes (1 MiB). Before #960 each read reserved all of it, so the four
// origin reads ran one after another (~4 x 250 ms); the harness's operation limit (4) is now the only bound.
await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray();
children.Length.ShouldBe(4);
var timer = System.Diagnostics.Stopwatch.StartNew();
var read = await client.ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Both,
children.Select(c => new ReadValueId { NodeId = c, AttributeId = Attributes.Value }).ToArray(), ct);
timer.Stop();
var results = read.Results.ToArray()!;
TestContext.Current.TestOutputHelper?.WriteLine(
$"#960: 4 maxAge=0 scalar reads, 250 ms origin each: {timer.ElapsedMilliseconds} ms, max {connections.MaxConcurrentReads} in flight");
results.ShouldAllBe(r => StatusCode.IsGood(r.StatusCode), string.Join(", ", results.Select(r => r.StatusCode.ToString())));
connections.ReadCalls.ShouldBe(4);
connections.MaxConcurrentReads.ShouldBe(4, "the four origin reads run concurrently, not one at a time");
}, connectionSource: connections, maxUnaryBytes: 1024 * 1024);
}
@@ -344,6 +374,82 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
}
// ---------------------------------------------------------------- #961
private static MonitoredItemCreateRequest ItemRequest(NodeId node, uint handle) => new()
{
ItemToMonitor = new ReadValueId { NodeId = node, AttributeId = Attributes.Value },
MonitoringMode = MonitoringMode.Reporting,
RequestedParameters = new MonitoringParameters { ClientHandle = handle, SamplingInterval = 100, QueueSize = 1, DiscardOldest = true },
};
[Fact(Timeout = 90000), Trait("Issue", "961")]
public async Task A_projected_item_refused_for_stream_capacity_at_create_fails_only_that_item()
{
var ct = TestContext.Current.CancellationToken;
LocalDataFixture? peer = null;
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions);
peer = origin; subscriptions.SampleClock = origin.Clock;
var connections = new RefusingConnections(origin);
// The harness allows 2 origin streams; one stream (cohort) is opened per publishing interval.
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
foreach (var interval in new double[] { 500, 1000 })
{
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), interval, 300, 1, 0, true, 0, ct)).SubscriptionId;
(await CreateItem(client, sub, anchor, 1, ct)).ShouldBe(StatusCodes.Good);
}
var third = (await client.CreateSubscriptionAsync(new RequestHeader(), 2000, 300, 1, 0, true, 0, ct)).SubscriptionId;
var response = await client.CreateMonitoredItemsAsync(new RequestHeader(), third, TimestampsToReturn.Both,
[ItemRequest(anchor, 1), ItemRequest(VariableIds.Server_ServerStatus_State, 2)], ct);
var results = response.Results.ToArray()!;
results[0].StatusCode.ShouldBe(StatusCodes.BadResourceUnavailable, "no origin stream can take it: retryable, for this item only");
results[1].StatusCode.ShouldBe(StatusCodes.Good, "the rest of the batch is created");
}, connectionSource: connections);
}
[Fact(Timeout = 90000), Trait("Issue", "961")]
public async Task A_projected_item_whose_lease_lapses_between_the_probe_and_the_create_is_retryable_for_that_item_only()
{
var ct = TestContext.Current.CancellationToken;
LocalDataFixture? peer = null;
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions);
peer = origin; subscriptions.SampleClock = origin.Clock;
var connections = new RefusingConnections(origin);
ZB.MOM.WW.OtOpcUa.OpcUaServer.OtOpcUaNodeManager? manager = null;
await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, _, _, anchor) =>
{
var client = (SessionClient)session;
await BrowseAll(client, anchor, 1);
var lapsed = 0;
// The authority changes after CreateMonitoredItems' per-item probe admitted the item, under the create's Lock.
manager.ShouldNotBeNull().BeforeProjectedItemAcquireForTests = _ =>
{
if (Interlocked.Exchange(ref lapsed, 1) == 0) origin.Clock.Advance(TimeSpan.FromSeconds(16));
};
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
var response = await client.CreateMonitoredItemsAsync(new RequestHeader(), sub, TimestampsToReturn.Both,
[ItemRequest(anchor, 1), ItemRequest(VariableIds.Server_ServerStatus_State, 2)], ct);
manager.BeforeProjectedItemAcquireForTests = null;
var results = response.Results.ToArray()!;
lapsed.ShouldBe(1, "precondition: the create ran after the probe");
results[0].StatusCode.ShouldBe(StatusCodes.BadResourceUnavailable, "a lapse the caller is granted is retryable, not an access denial");
results[1].StatusCode.ShouldBe(StatusCodes.Good, "the rest of the batch is created");
// ...and the retry succeeds once the on-demand renewal the classification started has committed.
var created = false;
for (var i = 0; i < 100 && !created; i++)
{
created = await CreateItem(client, sub, anchor, 3, ct) == StatusCodes.Good;
if (!created) await Task.Delay(50, ct);
}
created.ShouldBeTrue();
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale, onHistory: (_, m) => manager = m);
}
private static async Task<StatusCode> Write(SessionClient client, NodeId node, int value, CancellationToken ct) =>
(await client.WriteAsync(new RequestHeader(),
[new WriteValue { NodeId = node, AttributeId = Attributes.Value, Value = new Opc.Ua.DataValue(new Variant(value), StatusCodes.Good) }], ct))
@@ -0,0 +1,88 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using DataValue = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue;
using ReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
/// <summary>
/// #960: a projected read reserves only what its node's declared shape can answer, and that reservation is the read's
/// decode limit. These pin the constants against the REAL wire codec: a response carrying the widest value of each bounded
/// shape, with long serving identifiers, must decode within its reservation.
/// </summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Issue", "960")]
public sealed class GrpcDataProjectedReadReservationTests
{
private static readonly ServingIdentity Serving = new(new string('n', 128), Guid.NewGuid().ToString("D") + new string('i', 92),
"Primary", long.MaxValue, long.MaxValue, long.MaxValue);
private static DataMetadata Metadata(DataValueKind kind, int length = 0, DataValueKind? element = null) =>
new(new DataView(new DataAddress("cluster", "https://zb.com/otopcua/raw", "s", "Plant/Speed"), DataRealm.Raw, null, 0, "Plant/Speed"),
"Speed", "Variable", kind, kind == DataValueKind.Array ? 1 : -1, kind == DataValueKind.Array ? [length] : [], false,
DataOperations.Read, 1, null, null, false, element, Serving);
public static TheoryData<string> BoundedShapes => new() { "Int64", "Double", "Timestamp", "Guid", "Int32[1000]", "Double[64]", "Guid[64]", "Timestamp[64]" };
private static (DataMetadata Metadata, DataValue Value) Widest(string shape)
{
var timestamp = DateTimeOffset.MaxValue.AddTicks(-1).ToUniversalTime();
return shape switch
{
"Int64" => (Metadata(DataValueKind.Int64), DataValue.FromScalar(DataValueKind.Int64, long.MinValue)),
"Double" => (Metadata(DataValueKind.Double), DataValue.FromScalar(DataValueKind.Double, double.MinValue)),
"Timestamp" => (Metadata(DataValueKind.Timestamp), DataValue.FromScalar(DataValueKind.Timestamp, timestamp)),
"Guid" => (Metadata(DataValueKind.Guid), DataValue.FromScalar(DataValueKind.Guid, Guid.NewGuid())),
"Int32[1000]" => (Metadata(DataValueKind.Array, 1000, DataValueKind.Int32),
DataValue.FromArray(DataValueKind.Int32, Enumerable.Repeat((object)int.MinValue, 1000).ToArray(), [1000])),
"Double[64]" => (Metadata(DataValueKind.Array, 64, DataValueKind.Double),
DataValue.FromArray(DataValueKind.Double, Enumerable.Repeat((object)double.MinValue, 64).ToArray(), [64])),
"Guid[64]" => (Metadata(DataValueKind.Array, 64, DataValueKind.Guid),
DataValue.FromArray(DataValueKind.Guid, Enumerable.Range(0, 64).Select(_ => (object)Guid.NewGuid()).ToArray(), [64])),
"Timestamp[64]" => (Metadata(DataValueKind.Array, 64, DataValueKind.Timestamp),
DataValue.FromArray(DataValueKind.Timestamp, Enumerable.Repeat((object)timestamp, 64).ToArray(), [64])),
_ => throw new ArgumentOutOfRangeException(nameof(shape)),
};
}
[Theory]
[MemberData(nameof(BoundedShapes))]
public void The_widest_value_of_a_bounded_shape_decodes_within_its_read_reservation(string shape)
{
var (metadata, value) = Widest(shape);
var reservation = ProjectedDataAccess.ReadReservationBytes(metadata, 4 * 1024 * 1024);
reservation.ShouldBeLessThan(4 * 1024 * 1024L, "a bounded shape is never charged the whole cap");
var sample = new DataSample(value, 0x80000000u, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, Serving, long.MaxValue);
var wire = DataProtoMapper.EncodeReadResponse([new ReadResult("0", DataItemStatus.Good, DataReadiness.Ready, TimeSpan.MaxValue, sample,
new string('d', 256), AgeBounds: new(TimeSpan.Zero, TimeSpan.FromDays(1)))]);
wire.Serving = DataProtoMapper.EncodeServing(Serving);
var decoded = DataProtoMapper.DecodeReadResponse(wire, new DataDecodeLimits(1, (int)reservation));
try { decoded.ShouldHaveSingleItem().Sample.ShouldNotBeNull(); }
finally { foreach (var item in decoded) item.Dispose(); }
// The origin's own admission of the same answer (LocalDataServices.ReadAsync: retained estimate + 256).
(value.EstimatedRetainedBytes + 256).ShouldBeLessThanOrEqualTo(reservation);
}
[Theory]
[InlineData(DataValueKind.String)]
[InlineData(DataValueKind.Bytes)]
[InlineData(DataValueKind.Unspecified)]
public void An_unbounded_shape_keeps_the_whole_per_read_cap(DataValueKind kind) =>
ProjectedDataAccess.ReadReservationBytes(Metadata(kind), 1024 * 1024).ShouldBe(1024 * 1024);
[Fact]
public void A_variable_length_or_string_array_keeps_the_whole_per_read_cap()
{
ProjectedDataAccess.ReadReservationBytes(Metadata(DataValueKind.Array, 0, DataValueKind.Int32), 1024 * 1024).ShouldBe(1024 * 1024);
ProjectedDataAccess.ReadReservationBytes(Metadata(DataValueKind.Array, 8, DataValueKind.String), 1024 * 1024).ShouldBe(1024 * 1024);
}
[Fact]
public void A_reservation_never_exceeds_the_configured_cap()
{
ProjectedDataAccess.ReadReservationBytes(Metadata(DataValueKind.Int32), 1100).ShouldBe(1100);
ProjectedDataAccess.ReadReservationBytes(Metadata(DataValueKind.Array, 100_000, DataValueKind.Double), 1024 * 1024).ShouldBe(1024 * 1024);
}
}
@@ -19,7 +19,9 @@ public sealed partial class GrpcDataProjectedAccessTests
var large = new int[20_000];
try
{
var pending = access.WriteAsync(first!, new[] { 1, 2, 3 }, budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken);
// #960: a write reserves what its value needs, so the held write is itself large enough (~2 MiB of the 4 MiB) that the
// second (~2.5 MiB) no longer fits beside it.
var pending = access.WriteAsync(first!, new int[16_000], budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken);
await fixture.WriteEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
var before = GC.GetAllocatedBytesForCurrentThread();
var rejected = access.WriteAsync(second!, large, budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken);