fix(grpc-data): H3 review D2/D3/D5 — claimed cursors never leak; projected slot sub-limit
D2: Release() after TryClaimForResume() was a no-op, so a claimed cursor leaked its origin continuation on every exit that never sent it (no gateway/identity, deadline spent after the local half, limiter rejection, a gateway fault). New ReleaseEvenIfClaimed() (at most once) on every post-claim exit; any exception from the gateway now fails the projected half per node instead of escaping. D3: projected reads hold at most N - max(1, N/4) of the N shared history batch slots (OriginHistoryPort.RemoteSlots), Wait(0) => BadTooManyOperations for the projected half, so a slow origin cannot starve local HistoryRead/HistoryUpdate. D5: a Remote cursor presented to a local node (raw/modified/events take paths) is released when it is taken. Red/green: each test fails with its fix reverted.
This commit is contained in:
@@ -462,7 +462,14 @@ public sealed partial class OtOpcUaNodeManager
|
||||
public byte[]? Save(HistoryContinuationState state, HistoryContinuationBinding binding) =>
|
||||
nm._historyContinuationStore.Save(session, state);
|
||||
|
||||
public HistoryContinuationState? TryTake(byte[] continuationPoint, HistoryContinuationBinding binding) =>
|
||||
nm._historyContinuationStore.TryTake(session, continuationPoint);
|
||||
public HistoryContinuationState? TryTake(byte[] continuationPoint, HistoryContinuationBinding binding)
|
||||
{
|
||||
var state = nm._historyContinuationStore.TryTake(session, continuationPoint);
|
||||
if (state?.Remote is not { } remote) return state;
|
||||
// H3 review D5: a projected node's Remote cursor presented to a LOCAL node is invalid here (the port refuses an
|
||||
// unknown/mismatched cursor) — but it was taken out of the session, so release its origin continuation now.
|
||||
remote.Release();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
/// </summary>
|
||||
public abstract class ProjectedHistoryContinuation
|
||||
{
|
||||
private int _released;
|
||||
private int _claimed, _released;
|
||||
|
||||
/// <summary>Creates a cursor bound to one projected node.</summary>
|
||||
/// <param name="realm">The projected node's realm.</param>
|
||||
@@ -31,20 +31,34 @@ public abstract class ProjectedHistoryContinuation
|
||||
public string LocalIdentifier { get; }
|
||||
|
||||
/// <summary>True once the cursor was released or handed back for a resume (it is single-use either way).</summary>
|
||||
public bool IsSpent => Volatile.Read(ref _released) != 0;
|
||||
public bool IsSpent => Volatile.Read(ref _released) != 0 || Volatile.Read(ref _claimed) != 0;
|
||||
|
||||
/// <summary>
|
||||
/// Best-effort, idempotent, non-blocking release of the origin continuation (<c>releaseContinuationPoints</c>, session
|
||||
/// close, eviction, a store refusal). The origin's idle expiry is the backstop.
|
||||
/// close, eviction, a store refusal). A no-op once the cursor was claimed for a resume: the resume owns it from then on
|
||||
/// (and uses <see cref="ReleaseEvenIfClaimed"/> on every exit that does not send it). The origin's idle expiry is the
|
||||
/// backstop.
|
||||
/// </summary>
|
||||
public void Release()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _released, 1) == 0) OnRelease();
|
||||
if (Volatile.Read(ref _claimed) != 0) return;
|
||||
ReleaseOnce();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the origin continuation whether or not the cursor was claimed for a resume — for every post-claim exit that
|
||||
/// never sends it (refused, limiter-rejected, timed out, faulted). Never releases twice.
|
||||
/// </summary>
|
||||
public void ReleaseEvenIfClaimed() => ReleaseOnce();
|
||||
|
||||
/// <summary>Marks the cursor as handed back for a resume: the resume read owns the origin token from here on.</summary>
|
||||
/// <returns><c>false</c> when it was already released or resumed.</returns>
|
||||
public bool TryClaimForResume() => Interlocked.Exchange(ref _released, 1) == 0;
|
||||
public bool TryClaimForResume() => Volatile.Read(ref _released) == 0 && Interlocked.Exchange(ref _claimed, 1) == 0;
|
||||
|
||||
private void ReleaseOnce()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _released, 1) == 0) OnRelease();
|
||||
}
|
||||
|
||||
/// <summary>Forwards the release to the origin (called at most once).</summary>
|
||||
protected abstract void OnRelease();
|
||||
|
||||
@@ -9045,6 +9045,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
// Single-use take. A miss (unknown / evicted / malformed / a RAW cursor) ⇒ BadContinuationPointInvalid
|
||||
// for THIS node only.
|
||||
var state = _historyContinuationStore.TryTake(session, inboundCp.ToArray());
|
||||
// H3: a projected node's Remote cursor taken here is a miss — release its origin continuation.
|
||||
state?.Remote?.Release();
|
||||
// A point is bound to the node that issued it: another node's source name is a miss too.
|
||||
var boundKey = MapKey(handle.NodeId);
|
||||
if (state is null || !HistoryContinuationMatches(state, boundKey.Realm, boundKey.Id, HistoryBindingTag(handle.NodeId), historyEpoch) || state.Kind != HistoryCursorKind.Events || state.Tagname != sourceName)
|
||||
|
||||
@@ -26,6 +26,20 @@ 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,
|
||||
@@ -94,7 +108,7 @@ public sealed partial class OtOpcUaNodeManager
|
||||
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?.Release();
|
||||
resume?.ReleaseEvenIfClaimed();
|
||||
SetProjectedStatus(handle, results, errors, StatusCodes.BadHistoryOperationUnsupported);
|
||||
continue;
|
||||
}
|
||||
@@ -119,46 +133,69 @@ public sealed partial class OtOpcUaNodeManager
|
||||
if (pending.Count == 0) return;
|
||||
var nodes = pending.Select(p => p.Node).ToArray();
|
||||
IReadOnlyList<ProjectedHistoryOutcome>? outcomes = null;
|
||||
// The same process-wide batch limiter as local reads: a remote read also holds an SDK request thread.
|
||||
WithHistoryBatchLimiter(pending, () =>
|
||||
void ReleaseResumes()
|
||||
{
|
||||
TimeSpan remaining;
|
||||
if (HistoryReadDeadline > TimeSpan.Zero)
|
||||
{
|
||||
remaining = HistoryReadDeadline - Stopwatch.GetElapsedTime(started);
|
||||
if (remaining <= TimeSpan.Zero)
|
||||
{
|
||||
outcomes = nodes.Select(_ => new ProjectedHistoryOutcome(StatusCodes.BadTimeout.Code, [])).ToArray();
|
||||
foreach (var node in nodes) node.Resume?.Release();
|
||||
return;
|
||||
}
|
||||
}
|
||||
else remaining = TimeSpan.Zero;
|
||||
foreach (var node in nodes) node.Resume?.ReleaseEvenIfClaimed();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
outcomes = access!.ReadAsync(identity!, remote!, nodes, remaining,
|
||||
context.OperationContext?.CancellationToken ?? CancellationToken.None).GetAwaiter().GetResult();
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// The SDK request ended: a timeout for this caller, never an origin fault (the access owns the resumes).
|
||||
outcomes = nodes.Select(_ => new ProjectedHistoryOutcome(StatusCodes.BadTimeout.Code, [])).ToArray();
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidOperationException or ArgumentException or ObjectDisposedException)
|
||||
{
|
||||
outcomes = nodes.Select(_ => new ProjectedHistoryOutcome(StatusCodes.BadNoCommunication.Code, [])).ToArray();
|
||||
}
|
||||
}, p =>
|
||||
// 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();
|
||||
if (!projectedSlots.Wait(0))
|
||||
{
|
||||
p.Node.Resume?.Release();
|
||||
SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadTooManyOperations);
|
||||
});
|
||||
ReleaseResumes();
|
||||
foreach (var p in pending) SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadTooManyOperations);
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// The same process-wide batch limiter as local reads: a remote read also holds an SDK request thread.
|
||||
WithHistoryBatchLimiter(pending, () =>
|
||||
{
|
||||
TimeSpan remaining;
|
||||
if (HistoryReadDeadline > TimeSpan.Zero)
|
||||
{
|
||||
remaining = HistoryReadDeadline - Stopwatch.GetElapsedTime(started);
|
||||
if (remaining <= TimeSpan.Zero)
|
||||
{
|
||||
outcomes = nodes.Select(_ => new ProjectedHistoryOutcome(StatusCodes.BadTimeout.Code, [])).ToArray();
|
||||
ReleaseResumes();
|
||||
return;
|
||||
}
|
||||
}
|
||||
else remaining = TimeSpan.Zero;
|
||||
|
||||
try
|
||||
{
|
||||
outcomes = access!.ReadAsync(identity!, remote!, nodes, remaining,
|
||||
context.OperationContext?.CancellationToken ?? CancellationToken.None).GetAwaiter().GetResult();
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// Whatever escaped the gateway — the SDK request ending is a timeout, never an origin fault. The gateway
|
||||
// normally owns the resumes; releasing them again is idempotent, so nothing claimed can leak (H3 review D2).
|
||||
var status = ex is OperationCanceledException ? StatusCodes.BadTimeout.Code : StatusCodes.BadNoCommunication.Code;
|
||||
outcomes = nodes.Select(_ => new ProjectedHistoryOutcome(status, [])).ToArray();
|
||||
ReleaseResumes();
|
||||
}
|
||||
}, p =>
|
||||
{
|
||||
p.Node.Resume?.ReleaseEvenIfClaimed();
|
||||
SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadTooManyOperations);
|
||||
});
|
||||
}
|
||||
finally
|
||||
{
|
||||
projectedSlots.Release();
|
||||
}
|
||||
|
||||
if (outcomes is null) return; // the limiter rejected the batch
|
||||
if (outcomes.Count != pending.Count)
|
||||
{
|
||||
foreach (var o in outcomes) o.Continuation?.Release();
|
||||
ReleaseResumes();
|
||||
foreach (var p in pending) SetProjectedStatus(p.Handle, results, errors, StatusCodes.BadInternalError);
|
||||
return;
|
||||
}
|
||||
|
||||
+122
-3
@@ -206,6 +206,115 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable
|
||||
atTime.UseSimpleBounds.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_claimed_cursor_is_released_on_every_exit_that_never_sends_it()
|
||||
{
|
||||
// H3 review D2: Release() after a claim is a no-op, so each post-claim exit must use ReleaseEvenIfClaimed — exactly once.
|
||||
var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
|
||||
var store = new InMemoryHistoryContinuationStore();
|
||||
nm.HistoryContinuationStore = store;
|
||||
var node = Project(nm, f, "Leak", historizing: true);
|
||||
var paging = new FakeAccess { Paged = true };
|
||||
nm.ProjectedHistoryAccess = paging;
|
||||
|
||||
(FakeCursor Cursor, ByteString Cp) HeldPoint()
|
||||
{
|
||||
var (results, _) = Raw(nm, f.Identity, [node]);
|
||||
results[0].ContinuationPoint.IsEmpty.ShouldBeFalse();
|
||||
return (paging.Issued[^1], results[0].ContinuationPoint);
|
||||
}
|
||||
|
||||
// (a) the gateway disappears between the issue and the resume.
|
||||
var (cursor, cp) = HeldPoint();
|
||||
nm.ProjectedHistoryAccess = null;
|
||||
Raw(nm, f.Identity, [node], cp).Errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code);
|
||||
cursor.Released.ShouldBe(1);
|
||||
nm.ProjectedHistoryAccess = paging;
|
||||
|
||||
// (b) the gateway throws (anything): BadNoCommunication, the resume released, nothing escapes.
|
||||
(cursor, cp) = HeldPoint();
|
||||
nm.ProjectedHistoryAccess = new FakeAccess { Throw = new InvalidCastException("boom") };
|
||||
Raw(nm, f.Identity, [node], cp).Errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadNoCommunication.Code);
|
||||
cursor.Released.ShouldBe(1);
|
||||
nm.ProjectedHistoryAccess = paging;
|
||||
|
||||
// (c) the request deadline was spent by the time the projected half starts.
|
||||
(cursor, cp) = HeldPoint();
|
||||
nm.HistoryReadDeadline = TimeSpan.FromTicks(1);
|
||||
Raw(nm, f.Identity, [node], cp).Errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code);
|
||||
cursor.Released.ShouldBe(1);
|
||||
nm.HistoryReadDeadline = TimeSpan.FromSeconds(60);
|
||||
|
||||
// (d) the projected sub-limit is exhausted (limiter rejection).
|
||||
(cursor, cp) = HeldPoint();
|
||||
var limiter = nm.GetProjectedHistoryLimiter();
|
||||
var taken = 0;
|
||||
while (limiter.Wait(0, TestContext.Current.CancellationToken)) taken++;
|
||||
try
|
||||
{
|
||||
Raw(nm, f.Identity, [node], cp).Errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code);
|
||||
cursor.Released.ShouldBe(1);
|
||||
}
|
||||
finally { limiter.Release(taken); }
|
||||
|
||||
// Positive control: a normal resume claims the cursor and does NOT release it (the read owns the token).
|
||||
(cursor, cp) = HeldPoint();
|
||||
Raw(nm, f.Identity, [node], cp).Errors[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
|
||||
cursor.Released.ShouldBe(0);
|
||||
paging.Issued.Where(c => !ReferenceEquals(c, paging.Issued[^1])).ShouldAllBe(c => c.Released <= 1, "never released twice");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Projected_reads_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);
|
||||
nm.MaxConcurrentHistoryReadBatches = 4; // => 3 projected slots, 1 always left for local history
|
||||
nm.EnsureVariable("Plant/LocalSlot", "Plant", "LocalSlot", "Double", false, AddressSpaceRealm.Raw, historianTagname: "L.slot");
|
||||
var local = nm.TryGetVariable("Plant/LocalSlot", AddressSpaceRealm.Raw)!.NodeId;
|
||||
var node = Project(nm, f, "Slow", historizing: true);
|
||||
var hold = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var slow = new FakeAccess { Hold = hold };
|
||||
nm.ProjectedHistoryAccess = slow;
|
||||
var held = Enumerable.Range(0, 3).Select(_ => Task.Run(() => Raw(nm, f.Identity, [node]))).ToArray();
|
||||
var deadline = DateTime.UtcNow.AddSeconds(10);
|
||||
while (Volatile.Read(ref slow.Entries) < 3 && DateTime.UtcNow < deadline) await Task.Delay(10, TestContext.Current.CancellationToken);
|
||||
slow.Entries.ShouldBe(3, "three projected reads hold the three projected slots");
|
||||
try
|
||||
{
|
||||
// A fourth projected read is refused at once, unsent; local history is still served.
|
||||
// (Bounded: without the sub-limit this read would take the 4th shared slot and wait on the held gateway.)
|
||||
var (_, refused) = await Task.Run(() => Raw(nm, f.Identity, [node]))
|
||||
.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
refused[0].StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code);
|
||||
slow.Entries.ShouldBe(3);
|
||||
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);
|
||||
}
|
||||
finally { hold.SetResult(); }
|
||||
foreach (var (_, errors) in await Task.WhenAll(held)) StatusCode.IsGood(errors[0].StatusCode).ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_remote_cursor_presented_to_a_local_node_is_invalid_and_released()
|
||||
{
|
||||
// H3 review D5: the local take removes the SDK slot, so it must release the origin continuation.
|
||||
var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead);
|
||||
var store = new InMemoryHistoryContinuationStore();
|
||||
nm.HistoryContinuationStore = store;
|
||||
nm.EnsureVariable("Plant/LocalCp", "Plant", "LocalCp", "Double", false, AddressSpaceRealm.Raw, historianTagname: "L.cp");
|
||||
var local = nm.TryGetVariable("Plant/LocalCp", AddressSpaceRealm.Raw)!.NodeId;
|
||||
var node = Project(nm, f, "Remote", historizing: true);
|
||||
var access = new FakeAccess { Paged = true };
|
||||
nm.ProjectedHistoryAccess = access;
|
||||
var (results, _) = Raw(nm, f.Identity, [node]);
|
||||
var (_, errors) = Raw(nm, f.Identity, [local], results[0].ContinuationPoint);
|
||||
errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
|
||||
access.Issued.Single().Released.ShouldBe(1);
|
||||
store.Count.ShouldBe(0);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
private static (List<SdkHistoryReadResult> Results, List<ServiceResult> Errors) Raw(OtOpcUaNodeManager nm, IUserIdentity? identity,
|
||||
@@ -326,12 +435,22 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable
|
||||
public uint Status { get; init; }
|
||||
public Func<ProjectedHistoryNode, double[]> Answer { get; init; } = _ => [1.0, 2.0];
|
||||
|
||||
public Task<IReadOnlyList<ProjectedHistoryOutcome>> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details,
|
||||
/// <summary>When set, every call waits on it (a projected read holding its slot).</summary>
|
||||
public TaskCompletionSource? Hold { get; set; }
|
||||
public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
/// <summary>When set, every call throws it (after claiming nothing — the cursors are the caller's to release).</summary>
|
||||
public Exception? Throw { get; set; }
|
||||
public int Entries;
|
||||
|
||||
public async Task<IReadOnlyList<ProjectedHistoryOutcome>> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details,
|
||||
IReadOnlyList<ProjectedHistoryNode> nodes, TimeSpan deadline, CancellationToken cancellationToken)
|
||||
{
|
||||
Calls++;
|
||||
Interlocked.Increment(ref Calls);
|
||||
LastNodes = nodes;
|
||||
return Task.FromResult<IReadOnlyList<ProjectedHistoryOutcome>>(nodes.Select(node =>
|
||||
if (Interlocked.Increment(ref Entries) > 0) Entered.TrySetResult();
|
||||
if (Hold is { } hold) await hold.Task.ConfigureAwait(false);
|
||||
if (Throw is { } error) throw error;
|
||||
return (nodes.Select(node =>
|
||||
{
|
||||
FakeCursor? next = null;
|
||||
if (Paged)
|
||||
|
||||
Reference in New Issue
Block a user