fix(grpc-data): H2 review2-2..6 - byte-bounded pages, one deadline, no leaked cursors

Each node's Raw page is clamped from a per-value byte estimate of its catalog type (wide strings/arrays get small
pages plus a continuation) and sub-batches are sized by estimated bytes, so the in-flight read respects
MaxHistoryResponseBytes; AtTime/Processed whose values x estimate exceed the budget are refused per node with a
diagnostic. One deadline per request: nodes not started when it passes are deferred (transport) or BadTimeout
(direct). Every refusal releases the page cursor it was just given; releasing, invalidating or expiring a chunk
releases the page cursor behind it; results are disposed on the exception path. Chunk bindings use per-node details.
OpcUaServer IVT for Runtime.Tests/Host.Tests so tests can hold real page cursors.
This commit is contained in:
Joseph Doherty
2026-11-23 23:16:14 -05:00
parent eb29360d47
commit a3da73e1e7
5 changed files with 231 additions and 66 deletions
@@ -29,6 +29,8 @@
<!-- R2-08 (03/S2): the outage-sim integration test drives the internal static
OpcUaApplicationHost.HandleImpersonation against the real LDAP library. -->
<InternalsVisibleTo Include="ZB.MOM.WW.OtOpcUa.Host.IntegrationTests"/>
<InternalsVisibleTo Include="ZB.MOM.WW.OtOpcUa.Host.Tests"/>
<InternalsVisibleTo Include="ZB.MOM.WW.OtOpcUa.Runtime.Tests"/>
<!-- Gitea #562: the over-the-wire event-revalidation test asserts the server-side fan-out, because a
deleted item resurrected onto a notifier is invisible to the client that deleted it. -->
<InternalsVisibleTo Include="ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests"/>
@@ -102,77 +102,95 @@ public sealed partial class LocalDataServices
if (request.Details is DataHistoryAtTimeDetails atTime && atTime.RequestedTimesUtc.Count > limits.ValuesPerPage)
return Record(request, All(BadTooManyOperations, "More requested times than the origin's history values per page."));
if (!_historySessions.TryAdmit(context.PrincipalId, limits.ConcurrentReads)) return Record(request, All(BadTooManyOperations));
var results = new DataHistoryReadResult?[request.Items.Count];
try
{
var session = _historySessions.Get(context, channel, SessionCapacity(limits.ConcurrentReads, batchLimit));
var details = Clamp(request.Details, limits.ValuesPerPage);
var detailsKey = DetailsKey(details);
var incarnation = ServingIncarnation();
// Per-request memory bound: the response budget (transport: the export's response cap; direct: the caller's
// MaxBytes). Nodes are read in sub-batches sized so a sub-batch at the per-page ceiling fits it, and no further
// sub-batch starts once the budget is spent — those nodes are deferred (transport) or BadTooManyOperations (direct).
// Per-request memory bound, in BYTES: the response budget (transport: the export's response cap; direct: the
// caller's MaxBytes). Each node's page is clamped from a per-value byte estimate of its catalog type (wide arrays
// and strings get small pages, returning a continuation for the rest); nodes are read in sub-batches whose
// estimated in-flight bytes fit the budget, and no sub-batch starts once the budget is spent or the request's one
// deadline has passed — those nodes are deferred (transport) or BadTooManyOperations / BadTimeout (direct).
var budget = ResponseBudget(chunked, limits.ResponseBytes, request.Budget.MaxBytes);
var subBatch = (int)Math.Clamp(budget / Math.Max(1L, (long)limits.ValuesPerPage * 64L), 1L, Math.Max(1, request.Items.Count));
var results = new DataHistoryReadResult?[request.Items.Count];
var nodes = new LocalDataNode?[request.Items.Count];
var deferred = new bool[request.Items.Count];
var pending = new List<(int Index, OriginHistoryItem Item)>();
var nodeDetails = new DataHistoryDetails?[request.Items.Count];
var keys = new string?[request.Items.Count];
var deferred = new Deferral[request.Items.Count];
var pending = new List<(int Index, OriginHistoryItem Item, long PageBytes)>();
for (var i = 0; i < request.Items.Count; i++)
{
var item = request.Items[i];
if (!Gate(catalog, context, item.View, out var node)) { results[i] = new(item.CorrelationId, Refused, [], null); continue; }
nodes[i] = node;
var valueBytes = EstimateValueBytes(node.Metadata, request.Details);
var details = NodeDetails(request.Details, limits.ValuesPerPage, budget, valueBytes);
nodeDetails[i] = details;
keys[i] = DetailsKey(details);
var continuation = item.Continuation;
if (session.TakeChunk(item.Continuation) is { } chunk)
{
// A chunk token resumes the transport's remainder; it is bound to the view, details and serving identity.
if (chunk.View != node.Metadata.View || chunk.DetailsKey != detailsKey || chunk.Incarnation != incarnation)
{ results[i] = Invalid(item, chunk); continue; }
// A chunk token resumes the transport's remainder; it is bound to the view, the node's details and serving identity.
if (chunk.View != node.Metadata.View || chunk.DetailsKey != keys[i] || chunk.Incarnation != incarnation)
{ results[i] = Invalid(item, chunk, session); continue; }
if (!chunk.Deferred)
{ results[i] = new(item.CorrelationId, chunk.StatusCode, chunk.Remaining, chunk.Continuation, chunk.Diagnostic); continue; }
continuation = chunk.Continuation; // a deferred node is read now, from where it was
}
if (Buckets(details) > limits.ValuesPerPage)
var values = ValuesPerNode(details);
if (details is not DataHistoryRawDetails && (values > limits.ValuesPerPage || values * valueBytes > budget))
{
results[i] = new(item.CorrelationId, BadTooManyOperations, [], null, "More processing intervals than the origin's history values per page.");
session.Cursors.Release(continuation);
results[i] = new(item.CorrelationId, BadTooManyOperations, [], null, details is DataHistoryAtTimeDetails
? "Too many requested times for the origin's history limits; request fewer times per call."
: "Too many processing intervals for the origin's history limits; use a longer interval or a shorter window.");
continue;
}
pending.Add((i, new OriginHistoryItem(Realm(node), node.Metadata.View.Address.Identifier, BindingTag(node.Metadata.View),
item.AggregateId, continuation)));
item.AggregateId, continuation), values * valueBytes));
}
// ONE deadline for the whole request (H2 review): a node not started when it passes is deferred, never read late.
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
deadline.CancelAfter(request.Budget.Timeout);
long used = 0;
for (var start = 0; start < pending.Count; start += subBatch)
foreach (var group in pending.GroupBy(x => keys[x.Index]!))
{
var slice = pending.Skip(start).Take(subBatch).ToArray();
if (used >= budget)
var members = group.ToArray();
var pageBytes = Math.Max(1L, members.Max(x => x.PageBytes));
var subBatch = (int)Math.Clamp(budget / pageBytes, 1L, members.Length);
for (var start = 0; start < members.Length; start += subBatch)
{
foreach (var (index, portItem) in slice)
var slice = members.Skip(start).Take(subBatch).ToArray();
if (used >= budget || deadline.IsCancellationRequested)
{
deferred[index] = true;
results[index] = new(request.Items[index].CorrelationId, 0, [], portItem.Continuation);
var reason = used >= budget ? Deferral.Budget : Deferral.Deadline;
cancellationToken.ThrowIfCancellationRequested();
foreach (var (index, portItem, _) in slice)
{
deferred[index] = reason;
results[index] = new(request.Items[index].CorrelationId, 0, [], portItem.Continuation);
}
continue;
}
IReadOnlyList<OriginHistoryOutcome> outcomes;
try
{
outcomes = await _history.ReadAsync(session.Cursors, context.PrincipalId, ServingIncarnation, nodeDetails[slice[0].Index]!,
slice.Select(x => x.Item).ToArray(), deadline.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
// The deadline passed before the port answered: every in-flight node is BadTimeout, as the port itself answers.
outcomes = slice.Select(_ => new OriginHistoryOutcome(0x800A0000u, [], null, false)).ToArray();
}
cancellationToken.ThrowIfCancellationRequested(); // a caller cancel is never a backend outcome
for (var k = 0; k < slice.Length; k++)
{
var index = slice[k].Index;
var result = ToResult(request.Items[index], nodes[index]!, outcomes[k], nodeDetails[index]!);
results[index] = result;
foreach (var sample in result.Samples) used += SampleBytes(sample, nodes[index]!.Metadata);
}
continue;
}
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
deadline.CancelAfter(request.Budget.Timeout);
IReadOnlyList<OriginHistoryOutcome> outcomes;
try
{
outcomes = await _history.ReadAsync(session.Cursors, context.PrincipalId, ServingIncarnation, details,
slice.Select(x => x.Item).ToArray(), deadline.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
// The budget expired before the port answered: every in-flight node is BadTimeout, as the port itself answers.
outcomes = slice.Select(_ => new OriginHistoryOutcome(0x800A0000u, [], null, false)).ToArray();
}
cancellationToken.ThrowIfCancellationRequested(); // a caller cancel is never a backend outcome
for (var k = 0; k < slice.Length; k++)
{
var index = slice[k].Index;
var result = ToResult(request.Items[index], nodes[index]!, outcomes[k], details);
results[index] = result;
foreach (var sample in result.Samples) used += SampleBytes(sample, nodes[index]!.Metadata);
}
}
// Authority may have moved while the backend answered: re-check every served item before handing anything back.
@@ -180,19 +198,64 @@ public sealed partial class LocalDataServices
if (nodes[i] is { } node && results[i]!.StatusCode != Refused
&& (!Ready(catalog) || !Allowed(catalog, context, node, DataOperations.HistoryRead) || !IsHistorized(node)))
{
session.Cursors.Release(results[i]!.Continuation);
results[i]!.Dispose();
results[i] = new(request.Items[i].CorrelationId, Refused, [], null);
deferred[i] = false;
deferred[i] = Deferral.None;
}
var final = results.Select(x => x!).ToArray();
final = chunked
? Chunk(final, nodes, deferred, session, detailsKey, incarnation, budget, RemainderBudget(limits, budget))
? Chunk(final, nodes, deferred, session, keys, incarnation, budget, RemainderBudget(limits, budget))
: Direct(final, deferred);
return Record(request, final);
}
catch
{
foreach (var result in results) result?.Dispose();
throw;
}
finally { _historySessions.Leave(context.PrincipalId); }
}
/// <summary>Why a node was not read in this request.</summary>
private enum Deferral { None, Budget, Deadline }
/// <summary>
/// A conservative per-value wire-size estimate from the node's catalog type (value + status + two timestamps +
/// framing): scalars 48 B, strings/bytes 1 KiB (no declared length), arrays element size × declared length (1,024
/// elements when unknown). Processed values are aggregate doubles.
/// </summary>
internal static long EstimateValueBytes(DataMetadata metadata, DataHistoryDetails details)
{
const long overhead = 40;
if (details is DataHistoryProcessedDetails) return overhead + 16;
static long Scalar(DataValueKind kind) => kind is DataValueKind.String or DataValueKind.Bytes ? 1024 : 16;
if (metadata.ValueKind != DataValueKind.Array) return overhead + Scalar(metadata.ValueKind);
var length = metadata.Dimensions.Count > 0 && metadata.Dimensions[0] > 0 ? metadata.Dimensions[0] : 1024;
return overhead + 16 + (long)length * (Scalar(metadata.ArrayElementKind ?? DataValueKind.Double) + 4);
}
/// <summary>
/// The node's request details: a Raw page is the requested count clamped to the per-page ceiling AND to what the byte
/// budget can carry at the node's value size (at least one value). Deterministic per (request, node type, limits), so a
/// resume binds the same details hash.
/// </summary>
private static DataHistoryDetails NodeDetails(DataHistoryDetails details, int valuesPerPage, long budget, long valueBytes)
{
if (details is not DataHistoryRawDetails raw) return details;
var byBytes = (uint)Math.Clamp(budget / Math.Max(1L, valueBytes), 1L, valuesPerPage);
var requested = raw.NumValuesPerNode == 0 ? (uint)valuesPerPage : raw.NumValuesPerNode;
return raw with { NumValuesPerNode = Math.Min(requested, Math.Min((uint)valuesPerPage, byBytes)) };
}
/// <summary>Values one node can return for these details (Raw page, Processed intervals, AtTime times).</summary>
private static long ValuesPerNode(DataHistoryDetails details) => details switch
{
DataHistoryRawDetails raw => raw.NumValuesPerNode + (raw.ReturnBounds ? 2 : 0),
DataHistoryAtTimeDetails atTime => atTime.RequestedTimesUtc.Count,
_ => Buckets(details),
};
internal Task ReleaseHistoryAsync(DataAuthenticatedContext context, IReadOnlyList<byte[]> continuations, DataHistoryChannel channel,
CancellationToken cancellationToken)
{
@@ -234,20 +297,16 @@ public sealed partial class LocalDataServices
return IsHistorized(node);
}
private static DataHistoryReadResult Invalid(DataHistoryReadItem item, OriginHistorySession.Chunk chunk)
private static DataHistoryReadResult Invalid(DataHistoryReadItem item, OriginHistorySession.Chunk chunk, OriginHistorySession session)
{
foreach (var sample in chunk.Remaining) sample.Dispose();
session.Cursors.Release(chunk.Continuation); // the page cursor behind the chunk is gone with it
return new(item.CorrelationId, BadContinuationPointInvalid, [], null);
}
private static string BindingTag(DataView view) =>
"peer:" + (view.Realm == DataRealm.Raw ? "raw:" : "uns:") + view.Address.NamespaceUri;
/// <summary>Raw pages at the export's per-page ceiling: 0 (all) or more than it is served as pages of the ceiling.</summary>
private static DataHistoryDetails Clamp(DataHistoryDetails details, int valuesPerPage) => details is DataHistoryRawDetails raw
&& (raw.NumValuesPerNode == 0 || raw.NumValuesPerNode > (uint)valuesPerPage)
? raw with { NumValuesPerNode = (uint)valuesPerPage } : details;
private static void ValidateDetails(DataHistoryReadRequest request)
{
switch (request.Details)
@@ -309,18 +368,19 @@ public sealed partial class LocalDataServices
/// continuation. A single value larger than the whole budget, or a chunk the session / budget cannot hold, is
/// BadTooManyOperations for that node — explicit, never a silent truncation.
/// </summary>
private static DataHistoryReadResult[] Chunk(DataHistoryReadResult[] results, LocalDataNode?[] nodes, bool[] deferred,
OriginHistorySession session, string detailsKey, string incarnation, long budget, long remainderBudget)
private static DataHistoryReadResult[] Chunk(DataHistoryReadResult[] results, LocalDataNode?[] nodes, Deferral[] deferred,
OriginHistorySession session, string?[] keys, string incarnation, long budget, long remainderBudget)
{
long used = 0;
for (var i = 0; i < results.Length; i++)
{
var result = results[i];
used += 32 + 3L * (result.CorrelationId.Length + (result.Diagnostic?.Length ?? 0));
if (deferred[i])
if (deferred[i] != Deferral.None)
{
var token = session.SaveChunk(new OriginHistorySession.Chunk(nodes[i]!.Metadata.View, detailsKey, incarnation, [],
var token = session.SaveChunk(new OriginHistorySession.Chunk(nodes[i]!.Metadata.View, keys[i]!, incarnation, [],
0, result.Continuation, null, 0, 0, Deferred: true), remainderBudget);
if (token is null) session.Cursors.Release(result.Continuation);
results[i] = token is null
? new(result.CorrelationId, BadTooManyOperations, [], null, "Origin history session is full.")
: new(result.CorrelationId, 0, [], token, null, ChunkContinues: true);
@@ -337,19 +397,23 @@ public sealed partial class LocalDataServices
}
if (oversized)
{
session.Cursors.Release(result.Continuation);
result.Dispose();
results[i] = new(result.CorrelationId, BadTooManyOperations, [], null, "A history value exceeds the origin's response limit.");
results[i] = new(result.CorrelationId, BadTooManyOperations, [], null,
"A history value exceeds the origin's response limit; it cannot be served remotely.");
continue;
}
if (fit == result.Samples.Count) continue;
var remaining = result.Samples.Skip(fit).ToArray();
var bytes = remaining.Sum(x => SampleBytes(x, nodes[i]?.Metadata));
var saved = session.SaveChunk(new OriginHistorySession.Chunk(nodes[i]!.Metadata.View, detailsKey, incarnation, remaining,
var saved = session.SaveChunk(new OriginHistorySession.Chunk(nodes[i]!.Metadata.View, keys[i]!, incarnation, remaining,
result.StatusCode, result.Continuation, result.Diagnostic, 0, bytes), remainderBudget);
if (saved is null)
{
session.Cursors.Release(result.Continuation);
result.Dispose();
results[i] = new(result.CorrelationId, BadTooManyOperations, [], null, "Origin history remainder budget is full.");
results[i] = new(result.CorrelationId, BadTooManyOperations, [], null,
"Origin history remainder budget is full; retry with a lower NumValuesPerNode.");
continue;
}
results[i] = new(result.CorrelationId, result.StatusCode, result.Samples.Take(fit).ToArray(), saved, null, ChunkContinues: true);
@@ -358,12 +422,14 @@ public sealed partial class LocalDataServices
}
/// <summary>A direct consumer is never handed chunks: a node deferred by the request budget is BadTooManyOperations.</summary>
private static DataHistoryReadResult[] Direct(DataHistoryReadResult[] results, bool[] deferred)
private static DataHistoryReadResult[] Direct(DataHistoryReadResult[] results, Deferral[] deferred)
{
for (var i = 0; i < results.Length; i++)
if (deferred[i])
if (deferred[i] == Deferral.Budget)
results[i] = new(results[i].CorrelationId, BadTooManyOperations, [], null,
"Request byte budget spent before this node was read; read it in a later request.");
else if (deferred[i] == Deferral.Deadline)
results[i] = new(results[i].CorrelationId, 0x800A0000u, [], null, "Request deadline passed before this node was read.");
return results;
}
@@ -90,7 +90,12 @@ internal sealed class OriginHistorySession
/// <summary>Releases a chunk or a page token (idempotent).</summary>
public void Release(byte[]? token)
{
if (TakeChunk(token) is { } chunk) { foreach (var sample in chunk.Remaining) sample.Dispose(); return; }
if (TakeChunk(token) is { } chunk)
{
foreach (var sample in chunk.Remaining) sample.Dispose();
Cursors.Release(chunk.Continuation); // the page cursor behind the chunk goes with it
return;
}
Cursors.Release(token);
}
@@ -117,6 +122,7 @@ internal sealed class OriginHistorySession
private void Drop(Chunk chunk)
{
_owner.ReleaseBytes(Principal, chunk.Bytes);
Cursors.Release(chunk.Continuation);
foreach (var sample in chunk.Remaining) sample.Dispose();
}
}