fix(grpc-data): H3 review round 2 — one non-local history slot share; claim loop never leaks

Remote peers reading this node (OriginHistoryPort) and this node's projected
reads now draw on ONE N - max(1, N/4) semaphore, created together with the
N-slot batch limiter from the same N, so both together can never take the
last (local) slot (two independent first-use sizings could also disagree —
which made OriginHistoryLimiterTests order-dependent and hang the earlier
run). The projected claim loop releases every claimed cursor if anything
throws while the batch is assembled. Red/green: the shared-slot assertion
fails with a per-port semaphore.
This commit is contained in:
Joseph Doherty
2026-11-24 06:25:19 -05:00
parent 022b297836
commit 37cbeff480
5 changed files with 93 additions and 71 deletions
@@ -89,23 +89,18 @@ public sealed class OriginHistoryPort(OtOpcUaNodeManager nodeManager) : IOriginH
private readonly OtOpcUaNodeManager _nm = nodeManager ?? throw new ArgumentNullException(nameof(nodeManager));
private (IHistorianDataSource Source, OriginHistoryServing? Serving)? _serving;
private SemaphoreSlim? _remoteSlots;
private readonly Lock _slotsGate = new();
/// <summary>
/// The share of the node manager's process-wide history batch limiter (N = <c>MaxConcurrentHistoryReadBatches</c>)
/// remote peers may hold: N - max(1, N/4), at least 1. The rest stays free for local OPC UA HistoryRead.
/// NON-LOCAL reads may hold: N - max(1, N/4), at least 1. The rest stays free for local OPC UA HistoryRead.
/// </summary>
public static int RemoteSlots(int batches) => Math.Max(1, batches - Math.Max(1, batches / 4));
/// <summary>Remote slots currently free (diagnostics/tests).</summary>
/// <summary>Non-local slots currently free (diagnostics/tests) — shared with the node's projected reads (H3 review round 2).</summary>
public int AvailableRemoteSlots => Slots().CurrentCount;
private SemaphoreSlim Slots()
{
if (_remoteSlots is { } slots) return slots;
lock (_slotsGate) return _remoteSlots ??= new SemaphoreSlim(RemoteSlots(Math.Max(1, _nm.MaxConcurrentHistoryReadBatches)));
}
// ONE semaphore for every non-local history read of this node manager: remote peers here AND projected reads to other
// origins. Two independent N - max(1, N/4) shares would still let both together starve local history.
private SemaphoreSlim Slots() => _nm.GetNonLocalHistoryLimiter();
/// <inheritdoc />
/// <remarks>Cached per historian source instance: the catalog asks per node, so this is a reference compare, not a rebuild.</remarks>
@@ -9961,10 +9961,28 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
if (gate is not null) return gate;
lock (_historyReadBatchLimiterLock)
{
return _historyReadBatchLimiter ??= new SemaphoreSlim(Math.Max(1, MaxConcurrentHistoryReadBatches));
if (_historyReadBatchLimiter is { } created) return created;
// H3 review round 2: the NON-LOCAL share is sized from the SAME N at the same moment, so it can never exceed
// N - max(1, N/4) of the limiter that actually exists (two independent first-use sizings could disagree).
var batches = Math.Max(1, MaxConcurrentHistoryReadBatches);
_nonLocalHistoryLimiter = new SemaphoreSlim(OriginHistoryPort.RemoteSlots(batches));
return _historyReadBatchLimiter = new SemaphoreSlim(batches);
}
}
private volatile SemaphoreSlim? _nonLocalHistoryLimiter;
/// <summary>
/// The NON-LOCAL share of the history batch slots — remote peers reading this origin (<see cref="OriginHistoryPort"/>) and
/// this node's projected reads to other origins, together: <see cref="OriginHistoryPort.RemoteSlots"/> of the N the shared
/// limiter was created with (both are created together, at first use).
/// </summary>
internal SemaphoreSlim GetNonLocalHistoryLimiter()
{
GetHistoryReadBatchLimiter();
return _nonLocalHistoryLimiter!;
}
/// <summary>Link the SDK request lifetime to the application's per-batch history deadline.</summary>
/// <param name="context">The request's server context.</param>
/// <returns>The linked deadline source, or null when neither request nor application can cancel.</returns>
@@ -26,20 +26,6 @@ public sealed partial class OtOpcUaNodeManager
set => Volatile.Write(ref _projectedHistoryAccess, value);
}
private volatile SemaphoreSlim? _projectedHistoryLimiter;
private readonly Lock _projectedHistoryLimiterGate = new();
/// <summary>
/// The projected share of the history batch slots, sized once from <see cref="MaxConcurrentHistoryReadBatches"/> at first
/// use (as the shared limiter is): <see cref="OriginHistoryPort.RemoteSlots"/>.
/// </summary>
internal SemaphoreSlim GetProjectedHistoryLimiter()
{
if (_projectedHistoryLimiter is { } gate) return gate;
lock (_projectedHistoryLimiterGate)
return _projectedHistoryLimiter ??= new SemaphoreSlim(OriginHistoryPort.RemoteSlots(Math.Max(1, MaxConcurrentHistoryReadBatches)));
}
/// <summary>Serves local handles through the port (unchanged) and projected handles remotely, each into its own slot.</summary>
private void ServeHistoryReadSplit(
ServerSystemContext context,
@@ -83,51 +69,63 @@ public sealed partial class OtOpcUaNodeManager
var aggregates = details is ReadProcessedDetails processed ? processed.AggregateType : default;
var pending = new List<(NodeHandle Handle, ProjectedHistoryNode Node)>(handles.Count);
foreach (var handle in handles)
ProjectedHistoryContinuation? claimed = null;
try
{
var key = MapKey(handle.NodeId);
var tag = HistoryBindingTag(handle.NodeId);
var cp = nodesToRead[handle.Index].ContinuationPoint;
ProjectedHistoryContinuation? resume = null;
if (cp.Length > 0)
foreach (var handle in handles)
{
// Single-use: the take removes the SDK slot. A cursor of another node / kind / epoch is refused AND released.
var state = store.TryTake(session, cp.ToArray());
if (state is not { Kind: HistoryCursorKind.Remote, Remote: { } cursor }
|| !HistoryContinuationMatches(state, key.Realm, key.Id, tag, epoch)
|| !cursor.TryClaimForResume())
var key = MapKey(handle.NodeId);
var tag = HistoryBindingTag(handle.NodeId);
var cp = nodesToRead[handle.Index].ContinuationPoint;
ProjectedHistoryContinuation? resume = null;
if (cp.Length > 0)
{
state?.Remote?.Release();
SetProjectedStatus(handle, results, errors, StatusCodes.BadContinuationPointInvalid);
// Single-use: the take removes the SDK slot. A cursor of another node / kind / epoch is refused AND released.
var state = store.TryTake(session, cp.ToArray());
if (state is not { Kind: HistoryCursorKind.Remote, Remote: { } cursor }
|| !HistoryContinuationMatches(state, key.Realm, key.Id, tag, epoch)
|| !cursor.TryClaimForResume())
{
state?.Remote?.Release();
SetProjectedStatus(handle, results, errors, StatusCodes.BadContinuationPointInvalid);
continue;
}
resume = cursor;
claimed = cursor;
}
if (access is null || identity is null || remote is null)
{
// No projection gateway, no session identity, or a variant a remote read never serves (a modified read).
resume?.ReleaseEvenIfClaimed();
SetProjectedStatus(handle, results, errors, StatusCodes.BadHistoryOperationUnsupported);
continue;
}
resume = cursor;
}
if (access is null || identity is null || remote is null)
{
// No projection gateway, no session identity, or a variant a remote read never serves (a modified read).
resume?.ReleaseEvenIfClaimed();
SetProjectedStatus(handle, results, errors, StatusCodes.BadHistoryOperationUnsupported);
continue;
}
uint? aggregateId = null;
if (remote is DataHistoryProcessedDetails && resume is null)
{
// Consumer-side unknown aggregate: refused up front, unsent (the origin refuses what IT cannot serve).
var aggregate = aggregates[handle.Index];
if (AggregateFunctionMap.Map(aggregate) is null || aggregate.NamespaceIndex != 0 || !aggregate.TryGetValue(out uint numeric))
uint? aggregateId = null;
if (remote is DataHistoryProcessedDetails && resume is null)
{
SetProjectedStatus(handle, results, errors, StatusCodes.BadAggregateNotSupported);
continue;
// Consumer-side unknown aggregate: refused up front, unsent (the origin refuses what IT cannot serve).
var aggregate = aggregates[handle.Index];
if (AggregateFunctionMap.Map(aggregate) is null || aggregate.NamespaceIndex != 0 || !aggregate.TryGetValue(out uint numeric))
{
SetProjectedStatus(handle, results, errors, StatusCodes.BadAggregateNotSupported);
continue;
}
aggregateId = numeric;
}
aggregateId = numeric;
pending.Add((handle, new ProjectedHistoryNode(handle.NodeId, aggregateId, resume)));
}
pending.Add((handle, new ProjectedHistoryNode(handle.NodeId, aggregateId, resume)));
}
catch
{
// H3 review round 2: whatever throws while the batch is assembled, no claimed cursor leaks its origin continuation.
claimed?.ReleaseEvenIfClaimed();
foreach (var p in pending) p.Node.Resume?.ReleaseEvenIfClaimed();
throw;
}
if (pending.Count == 0) return;
@@ -138,10 +136,10 @@ public sealed partial class OtOpcUaNodeManager
foreach (var node in nodes) node.Resume?.ReleaseEvenIfClaimed();
}
// H3 review D3: projected reads may hold at most N - max(1, N/4) of the N process-wide history batch slots (the rule
// OriginHistoryPort.RemoteSlots applies to remote peers), so a slow origin can never starve local HistoryRead /
// HistoryUpdate. Exhausted => BadTooManyOperations for the projected half, unsent; the local half is unaffected.
var projectedSlots = GetProjectedHistoryLimiter();
// H3 review D3: projected reads and remote peers TOGETHER hold at most N - max(1, N/4) of the N process-wide history batch
// slots (OriginHistoryPort.RemoteSlots; one shared semaphore), so neither a slow origin nor busy peers can starve local
// HistoryRead / HistoryUpdate. Exhausted => BadTooManyOperations for the projected half, unsent; the local half is unaffected.
var projectedSlots = GetNonLocalHistoryLimiter();
if (!projectedSlots.Wait(0))
{
ReleaseResumes();
@@ -247,7 +247,7 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable
// (d) the projected sub-limit is exhausted (limiter rejection).
(cursor, cp) = HeldPoint();
var limiter = nm.GetProjectedHistoryLimiter();
var limiter = nm.GetNonLocalHistoryLimiter();
var taken = 0;
while (limiter.Wait(0, TestContext.Current.CancellationToken)) taken++;
try
@@ -265,7 +265,7 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable
}
[Fact]
public async Task Projected_reads_cannot_take_every_history_slot_local_history_is_still_served()
public async Task Projected_reads_and_remote_peers_together_cannot_take_every_history_slot_local_history_is_still_served()
{
// H3 review D3: projected reads hold at most N - max(1, N/4) of the N shared batch slots.
var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
@@ -288,6 +288,14 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable
.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
refused[0].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code);
slow.Entries.ShouldBe(3);
// H3 review round 2: remote peers reading THIS node share the same non-local slots — refused too, unsent — so the
// origin port and the projected path together can never take the last (local) slot.
var port = new OriginHistoryPort(nm);
port.AvailableRemoteSlots.ShouldBe(0);
var peer = await port.ReadAsync(new OriginHistoryCursors("peer", "channel", 4), "peer", () => "serving",
new DataHistoryRawDetails(new DateTimeOffset(T0), new DateTimeOffset(T0.AddHours(1)), 5, false),
[new OriginHistoryItem(AddressSpaceRealm.Raw, "Plant/LocalSlot", "tag", null, null)], TestContext.Current.CancellationToken);
peer.Single().StatusCode.ShouldBe(StatusCodes.BadTooManyOperations.Code);
var (localResults, localErrors) = Raw(nm, f.Identity, [local]);
StatusCode.IsGood(localErrors[0].StatusCode).ShouldBeTrue(localErrors[0].StatusCode.ToString());
localResults[0].StatusCode.Code.ShouldBe(StatusCodes.GoodNoData.Code);
@@ -24,22 +24,25 @@ public sealed class OriginHistoryLimiterTests(HistoryReadPortServerFixture fx) :
var source = new BlockingSource();
try
{
fx.Nm.MaxConcurrentHistoryReadBatches = 4; // the limiter is sized at first use; this fixture is fresh
// The limiter is sized ONCE per node manager, at first use: with the shared fixture another test may have sized it
// already (H3 review round 2: the non-local share is now one node-manager semaphore), so saturate what exists.
fx.Nm.MaxConcurrentHistoryReadBatches = 4;
fx.Nm.HistorianDataSource = source;
var port = new OriginHistoryPort(fx.Nm);
OriginHistoryPort.RemoteSlots(4).ShouldBe(3);
var slots = port.AvailableRemoteSlots;
var details = new DataHistoryRawDetails(new DateTimeOffset(T0), new DateTimeOffset(T0.AddSeconds(5)), 1, false);
var item = new OriginHistoryItem(AddressSpaceRealm.Uns, "port/dbl", "peer:uns", null, null);
var remote = Enumerable.Range(0, 3).Select(i => port.ReadAsync(new OriginHistoryCursors("peer", "c" + i, 4), "peer", () => "inc",
var remote = Enumerable.Range(0, slots).Select(i => port.ReadAsync(new OriginHistoryCursors("peer", "c" + i, 4), "peer", () => "inc",
details, [item], CancellationToken.None)).ToArray();
await source.WaitForCalls(3);
await source.WaitForCalls(slots);
var refused = (await port.ReadAsync(new OriginHistoryCursors("peer", "c9", 4), "peer", () => "inc", details, [item], CancellationToken.None)).Single();
refused.StatusCode.ShouldBe(StatusCodes.BadTooManyOperations.Code, "the remote share is full");
// A local (SDK-path) read still gets the reserved slot.
var local = Task.Run(() => fx.Nm.ReadHistory(OriginHistoryPort.ToVariant(details),
[new HistoryReadPortItem(AddressSpaceRealm.Uns, "port/dbl", null, default, "urn:local")],
fx.Nm.SessionHistoryContinuationScope(null), CancellationToken.None));
await source.WaitForCalls(4);
await source.WaitForCalls(slots + 1);
source.Release.TrySetResult();
(await local).Single().Status.Code.ShouldNotBe(StatusCodes.BadTooManyOperations.Code);
foreach (var r in await Task.WhenAll(remote)) r.Single().StatusCode.ShouldNotBe(StatusCodes.BadTooManyOperations.Code);
@@ -64,7 +67,7 @@ public sealed class OriginHistoryLimiterTests(HistoryReadPortServerFixture fx) :
var port = new OriginHistoryPort(fx.Nm);
var details = new DataHistoryRawDetails(new DateTimeOffset(T0), new DateTimeOffset(T0.AddSeconds(5)), 1, false);
var item = new OriginHistoryItem(AddressSpaceRealm.Uns, "port/dbl", "peer:uns", null, null);
var slots = OriginHistoryPort.RemoteSlots(fx.Nm.MaxConcurrentHistoryReadBatches);
var slots = port.AvailableRemoteSlots; // the node manager's non-local share, sized once at first use
using var cancelled = new CancellationTokenSource();
await cancelled.CancelAsync();
for (var i = 0; i < slots + 3; i++)