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:
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user