From f1b23abcb42bc3cbdcff849edcc5850d7ff9ca4b Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 07:15:16 -0500 Subject: [PATCH] =?UTF-8?q?fix(grpc-data):=20H3=20review=20round=203=20nit?= =?UTF-8?q?s=20b/c/d=20=E2=80=94=20no=20origin=20cursor=20stranded=20on=20?= =?UTF-8?q?Bad,=20scope=20moves=20or=20a=20serve-time=20throw?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - b: ProjectedHistoryAccess releases the prior origin cursor on any Bad answer to a resumed node (and on a mismatched answer) — an unsent refusal left it open at the origin; idempotent. - c: DataConnectionDeploymentLease, when its scope moves while a history answer is in flight, releases the dropped answer's new continuations (best effort); resumed items are BadContinuationPointInvalid, fresh ones BadNoCommunication. - d: ProjectedHistoryRead: a throw while serving outcome i (FromClr on an unconvertible value, a store fault) releases outcome i's cursor unless the store already owns it, and every later outcome's. Each red on revert (mutation). --- .../ProjectedHistoryRead.cs | 27 ++++++-- .../DataConnectionDeploymentRuntime.cs | 16 ++++- .../DataConnections/ProjectedHistoryAccess.cs | 4 ++ .../ProjectedHistoryReadTests.cs | 22 +++++++ .../GrpcDataDeployedHistoryLeaseTests.cs | 66 +++++++++++++++++++ .../GrpcDataProjectedHistoryWireTests.cs | 29 +++++++- 6 files changed, 157 insertions(+), 7 deletions(-) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeployedHistoryLeaseTests.cs diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs index d78d130b3..53ffdb3be 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs @@ -198,16 +198,34 @@ public sealed partial class OtOpcUaNodeManager return; } - for (var i = 0; i < pending.Count; i++) + var done = 0; // outcomes [0, done) are fully handed over (a continuation saved to the store, or released) + ProjectedHistoryContinuation? handedOver = null; // outcome `done`'s continuation once the store owns it (or released it) + try + { + for (var i = 0; i < pending.Count; i++) + { + handedOver = null; + ServeProjectedOutcome(pending[i].Handle, outcomes[i]); + done = i + 1; + } + } + catch + { + // H3 review round 3 nit (d): a throw for outcome i (FromClr on an unconvertible value, a store fault) strands no + // origin cursor: outcome i's — unless the store already owns it — and every later outcome's are released. + for (var j = done; j < outcomes.Count; j++) + if (outcomes[j].Continuation is { } c && !ReferenceEquals(c, handedOver)) c.Release(); + throw; + } + + void ServeProjectedOutcome(NodeHandle handle, ProjectedHistoryOutcome outcome) { - var handle = pending[i].Handle; - var outcome = outcomes[i]; var status = new StatusCode(outcome.StatusCode); if (StatusCode.IsBad(status)) { outcome.Continuation?.Release(); SetProjectedStatus(handle, results, errors, status); - continue; + return; } byte[]? cp = null; @@ -215,6 +233,7 @@ public sealed partial class OtOpcUaNodeManager { var key = MapKey(handle.NodeId); cp = SaveRemoteContinuation(session, store, key.Realm, key.Id, HistoryBindingTag(handle.NodeId), epoch, next); + handedOver = next; // saved (store-owned) or already released by SaveRemoteContinuation } var values = new List(outcome.Samples.Count); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs index 42a3e3d6b..96cce8cf0 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs @@ -541,13 +541,25 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistor catch (Exception ex) when (ex is InvalidOperationException or UnauthorizedAccessException or OperationCanceledException && !cancellationToken.IsCancellationRequested) { + // The scope moved while the answer was in flight: the answer is dropped, so the new origin continuations it carries are + // released (best effort) rather than stranded until the origin's idle expiry (H3 review round 3 nit c). + var orphans = value.Select(x => x.Continuation).OfType().ToArray(); foreach (var item in value) item.Dispose(); - return Unavailable(request); // the scope moved while the answer was in flight + if (orphans.Length > 0) _ = ReleaseQuietlyAsync(history, orphans); + return Unavailable(request); } } + private static async Task ReleaseQuietlyAsync(IDataHistoryService history, byte[][] continuations) + { + try { await history.ReleaseAsync(continuations, CancellationToken.None).ConfigureAwait(false); } + catch (Exception ex) when (ex is not OutOfMemoryException) { } // best effort; the origin's idle expiry is the backstop + } + + /// A resumed item's token cannot be presented again: BadContinuationPointInvalid; a fresh one BadNoCommunication. private static DataHistoryReadResult[] Unavailable(DataHistoryReadRequest request) => request.Items - .Select(x => new DataHistoryReadResult(x.CorrelationId, GrpcDataConnection.BadNoCommunication, [], null)).ToArray(); + .Select(x => new DataHistoryReadResult(x.CorrelationId, + x.Continuation is not null ? GrpcDataConnection.BadContinuationPointInvalid : GrpcDataConnection.BadNoCommunication, [], null)).ToArray(); Task> IDataHistoryService.ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) => ReadHistoryAsync(request, cancellationToken); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs index d79634496..e2ca73cb9 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs @@ -302,6 +302,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl var answer = answers[k]; if (answer.CorrelationId != items[k].CorrelationId) { + (nodes[i].Resume as RemoteCursor)?.ReleaseOrigin(); outcomes[i] = Fail(BadNoCommunication); continue; // its token (if any) is released in the finally } @@ -326,6 +327,9 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl : null; outcomes[i] = new ProjectedHistoryOutcome(answer.StatusCode, samples, next); assigned[k] = true; + // Round 3 nit (b): a Bad answer to a resume may have left the prior origin cursor unconsumed (refused + // unsent, a failed call) — release it; idempotent, and a no-op at the origin when it was consumed. + if ((answer.StatusCode & 0x80000000u) != 0 && nodes[i].Resume is RemoteCursor resumedFrom) resumedFrom.ReleaseOrigin(); } } finally diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ProjectedHistoryReadTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ProjectedHistoryReadTests.cs index 93b276111..ac9afe89f 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ProjectedHistoryReadTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ProjectedHistoryReadTests.cs @@ -195,6 +195,25 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable access.Calls.ShouldBe(calls); } + [Fact] + [Trait("Phase", "H3")] + public async Task A_throw_while_serving_one_outcome_releases_every_later_outcomes_cursor() + { + // H3 review round 3 nit (d): outcome 0's value cannot cross the SDK boundary (FromClr throws) — outcome 1's origin cursor + // must not be stranded; outcome 0's is already the session store's (saved before the throw), so it is not released twice. + var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead); + nm.HistoryContinuationStore = new InMemoryHistoryContinuationStore(); + var a = Project(nm, f, "Speed", historizing: true); + var b = Project(nm, f, "Flow", historizing: true); + var access = new FakeAccess { Paged = true, FirstValue = new object() }; + nm.ProjectedHistoryAccess = access; + try { Raw(nm, f.Identity, [a, b]); } + catch (ArgumentException) { } // the fault itself is the node manager's to surface; only the cursors matter here + access.Issued.Count.ShouldBe(2); + access.Issued[1].Released.ShouldBe(1, "the later outcome's cursor is released"); + access.Issued[0].Released.ShouldBe(0, "the store owns the saved cursor"); + } + [Fact] public void Unset_bounds_travel_absent_and_AtTime_carries_its_times() { @@ -442,6 +461,8 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable public bool Paged { get; init; } public uint Status { get; init; } public Func Answer { get; init; } = _ => [1.0, 2.0]; + /// When set, the FIRST node's first sample carries this value (e.g. one the SDK boundary cannot convert). + public object? FirstValue { get; init; } /// When set, every call waits on it (a projected read holding its slot). public TaskCompletionSource? Hold { get; set; } @@ -468,6 +489,7 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable Issued.Add(next); } var samples = Answer(node).Select((v, i) => new OriginHistorySample(v, 0, T0.AddSeconds(i), null)).ToArray(); + if (FirstValue is { } poison && ReferenceEquals(node, nodes[0]) && samples.Length > 0) samples[0] = samples[0] with { Value = poison }; return new ProjectedHistoryOutcome(Status, Status == 0 ? samples : [], next); }).ToArray()); } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeployedHistoryLeaseTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeployedHistoryLeaseTests.cs new file mode 100644 index 000000000..9bc3c8f0c --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDeployedHistoryLeaseTests.cs @@ -0,0 +1,66 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// H3 review round 3 nit (c): the deployment lease drops a history answer when its scope moves while the answer is in flight — +/// the new origin continuations that answer carries are released (not stranded), and a resumed item is +/// BadContinuationPointInvalid (its token cannot be presented again), a fresh one BadNoCommunication. +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H3")] +public sealed class GrpcDataDeployedHistoryLeaseTests +{ + private static readonly DataView View = new(new("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "x"); + + [Fact] + public async Task A_scope_move_during_the_answer_releases_its_new_continuations() + { + var current = true; + var inner = new Inner { OnRead = () => current = false }; + var lease = new DataConnectionDeploymentLease(inner, CancellationToken.None, DataOperations.HistoryRead, TimeSpan.FromSeconds(5), + 16, 16, 1 << 20, 1, 1, 1 << 20, () => current, () => { }); + var request = new DataHistoryReadRequest(new DataHistoryRawDetails(null, DateTimeOffset.UnixEpoch.AddDays(1), 2, false), + [new("fresh", View), new("resumed", View, null, [1])], new DataBudget(TimeSpan.FromSeconds(5), 16, 1 << 20)); + var results = await lease.ReadHistoryAsync(request, TestContext.Current.CancellationToken); + results[0].StatusCode.ShouldBe(0x80310000u); + results[1].StatusCode.ShouldBe(0x804A0000u); + var deadline = DateTime.UtcNow.AddSeconds(5); + while (inner.ReleasedCount == 0 && DateTime.UtcNow < deadline) await Task.Delay(10, TestContext.Current.CancellationToken); + inner.Released.ShouldBe([[8], [9]], ignoreOrder: true); + } + + private sealed class Inner : IDataConnection, IDataHistoryService + { + public Action OnRead { get; init; } = () => { }; + private readonly List _released = []; + public int ReleasedCount { get { lock (_released) return _released.Count; } } + public byte[][] Released { get { lock (_released) return _released.ToArray(); } } + public DataTarget Target => new(DataTargetMode.Cluster, "c", null); + public TimeProvider Clock => TimeProvider.System; + + public Task> ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) + { + OnRead(); + byte k = 8; + return Task.FromResult>(request.Items + .Select(i => new DataHistoryReadResult(i.CorrelationId, 0, [], [k++])).ToArray()); + } + + public Task ReleaseAsync(IReadOnlyList continuations, CancellationToken cancellationToken) + { + lock (_released) _released.AddRange(continuations); + return Task.CompletedTask; + } + + public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task> ReadAsync(ReadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task SubscribeAsync(CancellationToken cancellationToken) => throw new NotSupportedException(); + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs index da07939cb..5589cd552 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedHistoryWireTests.cs @@ -443,6 +443,30 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests }, localPermissions: 15, allowHistory: true, connectionSource: connections); } + [Fact(Timeout = 90000)] + [Trait("Phase", "H3")] + public async Task A_bad_answer_to_a_resume_releases_the_prior_origin_cursor() + { + // H3 review round 3 nit (b): the connection answered the resume Bad without sending it — the origin still holds page 1's + // cursor; the consumer releases it (positive control: the store returns to 0). + await using var originServer = await HistoryOrigin.StartAsync(7); + using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port); + var connections = new HistorySwitchConnections(origin); + ProjectedHistoryAccess? history = null; + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var page = await RawHistory(client, anchor, 2, default); + origin.Services.HistoryOpenContinuations.ShouldBe(1); + connections.Mode = HistoryMode.RefuseResumedUnsent; + (await RawHistory(client, anchor, 2, page.ContinuationPoint)).StatusCode.Code.ShouldBe(StatusCodes.BadNoCommunication.Code); + await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0); + origin.Services.HistoryOpenContinuations.ShouldBe(0, "the unconsumed prior cursor was released"); + connections.Mode = HistoryMode.Pass; + }, localPermissions: 15, allowHistory: true, connectionSource: connections, onHistory: (h, _) => history = h); + } + [Fact(Timeout = 90000)] [Trait("Phase", "H3")] public async Task An_origins_budget_refusal_is_a_per_node_answer_and_never_stops_the_request() @@ -509,7 +533,7 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests } } - public enum HistoryMode { Pass, Hang, Throw, Retired, Poison, BudgetRefused, OriginRefusedFresh } + public enum HistoryMode { Pass, Hang, Throw, Retired, Poison, BudgetRefused, OriginRefusedFresh, RefuseResumedUnsent } /// /// One long-lived origin connection whose HISTORY path can be switched to never answer (then fault as a cancelled gRPC call, @@ -578,6 +602,9 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests case HistoryMode.BudgetRefused: return request.Items.Select(i => new DataHistoryReadResult(i.CorrelationId, 0x80100000u, [], null, "History assembly budget exceeded.") { ConsumerBudgetRefused = true }).ToArray(); + case HistoryMode.RefuseResumedUnsent when request.Items.Any(i => i.Continuation is not null): + // Answered Bad without the origin ever seeing the resume: its cursor is still open there. + return request.Items.Select(i => new DataHistoryReadResult(i.CorrelationId, 0x80310000u, [], null)).ToArray(); case HistoryMode.OriginRefusedFresh when request.Items.All(i => i.Continuation is null): // The ORIGIN's own refusal, whose text also mentions a budget (LocalDataServices.History). return request.Items.Select(i => new DataHistoryReadResult(i.CorrelationId, 0x80100000u, [], null,