diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs index 365da1766..39d37782a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.History.cs @@ -23,6 +23,8 @@ public sealed partial class GrpcDataConnection : IDataHistoryService internal const uint BadTooManyOperations = 0x80100000u; internal const uint BadTimeout = 0x800A0000u; internal const uint BadNoCommunication = 0x80310000u; + /// An origin admits at most one item per this many bytes of a request's byte budget (LocalDataServices.CheckBudget). + internal const long MinimumBytesPerItem = 256; private const byte EnvelopeTag = 0xC7, EnvelopeVersion = 1; private TimeSpan _historyTimeout = TimeSpan.FromSeconds(30); @@ -135,48 +137,104 @@ public sealed partial class GrpcDataConnection : IDataHistoryService /// /// Reads on one selected endpoint in sub-batches of at most the endpoint's advertised MaxBatchItems — taken from the /// capabilities this call already negotiated, so no extra probe (H3 review round 2). The assembly budget is shared across - /// the sub-batches; once it is spent the remaining items are BadTooManyOperations, unsent. Null = the endpoint failed - /// before answering the FIRST sub-batch (a fresh read may move); a later failure answers the rest - /// BadNoCommunication (resumed items BadContinuationPointInvalid), never moving a half-served request. + /// the sub-batches, and each sub-batch carries at most one item per of what is left + /// (the origin's admission rule, round 3 S2). Once the budget is spent — exhausted, too small for one more item, or a + /// sub-batch's own assembly refused (S3) — the remaining items are BadTooManyOperations marked + /// , unsent. Null = the endpoint failed before answering the + /// FIRST sub-batch (a fresh read may move); a later failure is recorded, nothing more is sent to that endpoint, and the + /// rest is BadNoCommunication (resumed items BadContinuationPointInvalid), never moving a half-served + /// request. A resumed item answered unsent has its origin token released (it is still live there). Anything that + /// escapes (a caller cancel, a fault) first disposes the collected answers and releases their new continuations (S1). /// private async Task ServeSplitAsync(Selected selected, int endpoint, DataHistoryReadRequest request, DataHistoryReadItem[] items, int[] pending, long start, CancellationToken cancellationToken) { var batch = Math.Max(1, selected.Capabilities.Limits.MaxBatchItems); - if (pending.Length <= batch) return await ServeAsync(selected, endpoint, request, items, pending, start, cancellationToken).ConfigureAwait(false); - var answers = new DataHistoryReadResult[pending.Length]; + if (pending.Length <= batch) return (await ServeAsync(selected, endpoint, request, items, pending, start, cancellationToken).ConfigureAwait(false)).Results; + var answers = new DataHistoryReadResult?[pending.Length]; long used = 0; - for (var offset = 0; offset < pending.Length; offset += batch) + bool spent = false, failed = false; + try { - var chunk = pending.Skip(offset).Take(batch).ToArray(); - var left = request.Budget.MaxBytes - used; - DataHistoryReadResult[]? served = null; - if (left > 0) + for (var offset = 0; offset < pending.Length;) { + var left = request.Budget.MaxBytes - used; + var fitting = spent || failed ? 0 : (int)Math.Min(batch, Math.Max(0, left) / MinimumBytesPerItem); + if (fitting <= 0) + { + for (var k = offset; k < pending.Length; k++) + { + var item = request.Items[pending[k]]; + var resumed = item.Continuation is not null; + if (resumed) _ = ReleaseOnEndpointAsync(selected, items[pending[k]].Continuation); // unsent: still live at the origin + answers[k] = failed + ? new(item.CorrelationId, resumed ? BadContinuationPointInvalid : BadNoCommunication, [], null) + : new(item.CorrelationId, BadTooManyOperations, [], null, "History assembly budget exceeded.") { ConsumerBudgetRefused = true }; + } + break; + } + + var chunk = pending.Skip(offset).Take(fitting).ToArray(); + DataHistoryReadResult[]? served; try { - served = await ServeAsync(selected, endpoint, request with { Budget = request.Budget with { MaxBytes = left } }, items, chunk, start, + var call = await ServeAsync(selected, endpoint, request with { Budget = request.Budget with { MaxBytes = left } }, items, chunk, start, cancellationToken).ConfigureAwait(false); + served = call.Results; + failed = call.EndpointFailed; // answered, but the endpoint failed mid-way: send it nothing more (nit a) } - catch (Exception ex) when (offset > 0 && ex is not OutOfMemoryException && !cancellationToken.IsCancellationRequested) { served = null; } - if (served is null && offset == 0) return null; + catch (Exception ex) when (offset > 0 && !cancellationToken.IsCancellationRequested + && ex is InvalidOperationException or ArgumentException or RpcException or HttpRequestException) + { + // An endpoint fault after a served sub-batch: recorded like any endpoint failure (round 3 S6), and the + // request stays on this endpoint (half served) with nothing more sent to it (nit a). + RecordFailure(ex); + served = null; + } + if (served is null) + { + if (offset == 0) return null; + failed = true; + continue; + } + + for (var k = 0; k < chunk.Length; k++) + { + var answer = served[k]; + foreach (var sample in answer.Samples) used += sample.Value.EstimatedRetainedBytes; + if (answer.ConsumerBudgetRefused) spent = true; + answers[offset + k] = answer; + } + offset += chunk.Length; } - for (var k = 0; k < chunk.Length; k++) - { - var item = request.Items[chunk[k]]; - var answer = served?[k] ?? new(item.CorrelationId, - left <= 0 ? BadTooManyOperations : item.Continuation is not null ? BadContinuationPointInvalid : BadNoCommunication, [], null); - foreach (var sample in answer.Samples) used += sample.Value.EstimatedRetainedBytes; - answers[offset + k] = answer; - } + return answers.Select(x => x!).ToArray(); + } + catch + { + Abandon(selected, answers); + throw; } - - return answers; } - /// Reads on one selected endpoint and assembles its chunks; null = the endpoint failed before answering (a fresh read may move). - private async Task ServeAsync(Selected selected, int endpoint, DataHistoryReadRequest request, + /// Disposes answers that will never be handed out and releases the new origin continuations they carry. + private void Abandon(Selected selected, IEnumerable answers) + { + foreach (var answer in answers) + { + if (answer is null) continue; + answer.Dispose(); + if (answer.Continuation is { } wrapped && TryUnwrap(wrapped, out _, out _, out var token)) _ = ReleaseOnEndpointAsync(selected, token); + } + } + + /// + /// Reads on one selected endpoint and assembles its chunks. Results null = the endpoint failed before answering (a fresh + /// read may move); EndpointFailed = it answered (per node) but failed on the way, so a caller splitting a + /// request sends it nothing more. Anything that escapes first releases every origin token this assembly holds — finished + /// nodes' continuations, chunk tokens, and the tokens of a response it rejected (H3 review round 3 S6). + /// + private async Task<(DataHistoryReadResult[]? Results, bool EndpointFailed)> ServeAsync(Selected selected, int endpoint, DataHistoryReadRequest request, DataHistoryReadItem[] items, int[] pending, long start, CancellationToken cancellationToken) { var batch = pending.Select(i => items[i]).ToArray(); @@ -187,6 +245,10 @@ public sealed partial class GrpcDataConnection : IDataHistoryService var current = batch; var map = Enumerable.Range(0, batch.Length).ToArray(); var first = true; + var endpointFailed = false; + var chunkTokensReleased = false; + W.HistoryReadResponse? unprocessed = null; // a received response whose tokens are not yet owned by final[] / current + IReadOnlyList? decoded = null; try { while (current.Length > 0) @@ -211,6 +273,7 @@ public sealed partial class GrpcDataConnection : IDataHistoryService { // A caller cancel is never an outcome: surface it as cancellation, and let go of held chunk tokens. if (!first) ReleaseChunkTokens(selected, current); + chunkTokensReleased = true; throw new OperationCanceledException("History read cancelled by the caller.", ex, cancellationToken); } catch (RpcException ex) when (ex.StatusCode is StatusCode.FailedPrecondition or StatusCode.Unimplemented) @@ -229,23 +292,22 @@ public sealed partial class GrpcDataConnection : IDataHistoryService } catch (RpcException ex) when (first && ex.StatusCode is StatusCode.Unavailable or StatusCode.Unauthenticated or StatusCode.PermissionDenied && !cancellationToken.IsCancellationRequested) - { RecordFailure(ex); return null; } + { RecordFailure(ex); chunkTokensReleased = true; return (null, true); } catch (RpcException ex) { RecordFailure(ex); if (!first) ReleaseChunkTokens(selected, current); // the origin still holds their remainders foreach (var k in map) final[k] ??= new(batch[k].CorrelationId, BadNoCommunication, [], null); + endpointFailed = true; break; } first = false; + unprocessed = response; Verify(response.Serving, selected); - var decoded = DataHistoryProtoMapper.DecodeResponse(response, Limits(request.Budget, selected.Capabilities) with + decoded = DataHistoryProtoMapper.DecodeResponse(response, Limits(request.Budget, selected.Capabilities) with { MaxValueElements = int.MaxValue, MaxBytes = _maxMessageBytes }); if (decoded.Count != current.Length || decoded.Where((r, k) => r.CorrelationId != current[k].CorrelationId).Any()) - { - foreach (var r in decoded) r.Dispose(); throw new InvalidOperationException("History response has unexpected items."); - } var nextItems = new List(); var nextMap = new List(); for (var k = 0; k < decoded.Count; k++) @@ -274,6 +336,7 @@ public sealed partial class GrpcDataConnection : IDataHistoryService } current = nextItems.ToArray(); map = nextMap.ToArray(); + unprocessed = null; decoded = null; // every token of this response is now in final[] or current } var answers = new DataHistoryReadResult[batch.Length]; for (var k = 0; k < batch.Length; k++) @@ -288,15 +351,23 @@ public sealed partial class GrpcDataConnection : IDataHistoryService } answers[k] = result with { Samples = (IReadOnlyList?)assembled[k] ?? [] }; } - return answers; + return (answers, endpointFailed); } catch { foreach (var list in assembled) foreach (var sample in list ?? []) sample.Dispose(); + foreach (var r in decoded ?? []) r.Dispose(); + // Nothing this assembly holds is handed out: release every origin token it owns (round 3 S6). + foreach (var r in final) + if (r?.Continuation is { } wrapped && TryUnwrap(wrapped, out _, out _, out var token)) _ = ReleaseOnEndpointAsync(selected, token); + if (!first && !chunkTokensReleased) ReleaseChunkTokens(selected, current); + foreach (var item in unprocessed?.Items ?? []) + if (item.HasContinuation) _ = ReleaseOnEndpointAsync(selected, item.Continuation.ToByteArray()); throw; } } + /// Releases continuations on their issuing endpoints (); best effort. public async Task ReleaseHistoryAsync(IReadOnlyList continuations, CancellationToken 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 987634c86..a68f634ee 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedHistoryAccess.cs @@ -389,7 +389,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl internal const int DefaultBatchItems = 100; /// An origin admits at most one item per this many bytes of a request's byte budget. - internal const long MinimumBytesPerItem = 256; + internal const long MinimumBytesPerItem = GrpcDataConnection.MinimumBytesPerItem; private static ProjectedHistoryOutcome Fail(uint status) => new(status, []); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs index 965d96590..de76e9f29 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataHistoryClientTests.cs @@ -251,6 +251,106 @@ public sealed class GrpcDataHistoryClientTests foreach (var r in again) r.Dispose(); } + // ---- H3 review round 3 ------------------------------------------------------------------------------------------- + + private static readonly long SampleBytes = new DataHistorySample(DataValue.FromScalar(DataValueKind.Double, 1.0), 0, null, null) + .Value.EstimatedRetainedBytes; // the fake answers two Double samples per item per chunk + + private static DataHistoryReadRequest Many(int count, long? maxBytes = null) => new(Request().Details, + Enumerable.Range(0, count).Select(i => new DataHistoryReadItem("n" + i, View)).ToArray(), maxBytes is { } b ? Budget with { MaxBytes = b } : Budget); + + private static async Task AwaitReleased(Endpoint a, Func done) + { + var deadline = DateTime.UtcNow.AddSeconds(10); + while (DateTime.UtcNow < deadline) + { + byte[][] released; + lock (a.Released) released = a.Released.ToArray(); + if (done(released)) return; + await Task.Delay(20, TestContext.Current.CancellationToken); + } + } + + private static int ReleasedCount(Endpoint a, byte[] token) { lock (a.Released) return a.Released.Count(t => t.SequenceEqual(token)); } + + [Fact] + [Trait("Phase", "H3")] + public async Task A_cancel_in_a_later_sub_batch_releases_the_earlier_sub_batches_new_continuations() + { + // S1: sub-batch 1 answered (two new page continuations); the caller cancels during sub-batch 2 — nothing is stranded. + var a = new Endpoint("a") { BatchItems = 2, PageToken = [9, 9, 9], HangOnDataCall = 2 }; + await using var connection = Connect([a]); + using var cancel = new CancellationTokenSource(); + var read = connection.ReadHistoryAsync(Many(4), cancel.Token); + var deadline = DateTime.UtcNow.AddSeconds(10); + while (Volatile.Read(ref a.DataCalls) < 2 && DateTime.UtcNow < deadline) await Task.Delay(10, TestContext.Current.CancellationToken); + await cancel.CancelAsync(); + await Should.ThrowAsync(() => read); + await AwaitReleased(a, r => r.Count(t => t.SequenceEqual(new byte[] { 9, 9, 9 })) >= 2); + ReleasedCount(a, [9, 9, 9]).ShouldBe(2, "both continuations sub-batch 1 opened are released"); + } + + [Fact] + [Trait("Phase", "H3")] + public async Task A_later_sub_batch_is_trimmed_to_the_origins_byte_admission_and_the_rest_is_a_consumer_budget_refusal() + { + // S2: after sub-batch 1 only room for ONE item is left (256 B); sending two would break the origin's count <= MaxBytes/256 + // rule (an RpcException ⇒ a recorded endpoint failure). Trimmed: [2, 1], the rest refused unsent, no endpoint failure. + var a = new Endpoint("a") { BatchItems = 2, EnforceAdmission = true }; + await using var connection = Connect([a]); + var results = await connection.ReadHistoryAsync(Many(4, 4 * SampleBytes + 256), TestContext.Current.CancellationToken); + results.Take(2).ShouldAllBe(r => r.StatusCode == 0u && r.Samples.Count == 2); + results.Skip(2).ShouldAllBe(r => r.StatusCode == 0x80100000u && r.ConsumerBudgetRefused); + a.CallSizes.ShouldBe([2, 1]); + foreach (var r in results) r.Dispose(); + var again = await connection.ReadHistoryAsync(Many(1), TestContext.Current.CancellationToken); + again.Single().StatusCode.ShouldBe(0u, "a budget refusal is not an endpoint failure"); + foreach (var r in again) r.Dispose(); + } + + [Fact] + [Trait("Phase", "H3")] + public async Task A_sub_batch_whose_assembly_overflows_spends_the_budget_and_nothing_more_is_sent() + { + // S3: sub-batch 2 refuses n3 inside its own assembly while what was KEPT is still below the budget — n4, n5 unsent. + var a = new Endpoint("a") { BatchItems = 2 }; + await using var connection = Connect([a]); + var results = await connection.ReadHistoryAsync(Many(6, 7 * SampleBytes), TestContext.Current.CancellationToken); + results.Take(3).ShouldAllBe(r => r.StatusCode == 0u); + results.Skip(3).ShouldAllBe(r => r.StatusCode == 0x80100000u && r.ConsumerBudgetRefused); + a.CallSizes.ShouldBe([2, 2]); + foreach (var r in results) r.Dispose(); + } + + [Fact] + [Trait("Phase", "H3")] + public async Task After_a_sub_batch_endpoint_failure_nothing_more_is_sent_to_that_endpoint() + { + // Nit (a): sub-batch 2 fails (recorded); sub-batch 3 is answered unsent. + var a = new Endpoint("a") { BatchItems = 2, FailAfterFirst = Grpc.Core.StatusCode.Internal }; + await using var connection = Connect([a]); + var results = await connection.ReadHistoryAsync(Many(5), TestContext.Current.CancellationToken); + results.Take(2).ShouldAllBe(r => r.StatusCode == 0u); + results.Skip(2).ShouldAllBe(r => r.StatusCode == 0x80310000u); + a.CallSizes.ShouldBe([2, 2]); + foreach (var r in results) r.Dispose(); + } + + [Fact] + [Trait("Phase", "H3")] + public async Task A_rejected_follow_up_chunk_releases_every_token_the_assembly_holds() + { + // S6: n0 completes on call 1 (a new page continuation in final[]); n1 continues; call 2's answer is malformed. + var a = new Endpoint("a") { PageToken = [9, 9, 9], Chunks = 3, MalformedFromDataCall = 2 }; + a.ChunksByItem["n0"] = 1; + await using var connection = Connect([a]); + var results = await connection.ReadHistoryAsync(Many(2), TestContext.Current.CancellationToken); + results.ShouldAllBe(r => r.StatusCode == 0x80310000u); + await AwaitReleased(a, r => r.Any(t => t.SequenceEqual(new byte[] { 9, 9, 9 })) && r.Any(t => t.SequenceEqual(new byte[] { 7, 7 }))); + ReleasedCount(a, [9, 9, 9]).ShouldBe(1, "n0's finished continuation is released"); + ReleasedCount(a, [7, 7]).ShouldBeGreaterThan(0, "n1's chunk tokens are released"); + } + [Fact] public async Task A_failure_mid_assembly_releases_the_origin_chunk_tokens_it_holds() { @@ -262,9 +362,10 @@ public sealed class GrpcDataHistoryClientTests a.Released.ShouldContain(t => t.SequenceEqual(new byte[] { 7, 7 }), "the chunk token the failed follow-up carried is released"); } - private static GrpcDataConnection Connect(Endpoint[] endpoints, TimeSpan? historyTimeout = null) + private static GrpcDataConnection Connect(Endpoint[] endpoints, TimeSpan? historyTimeout = null, Action? onManager = null) { var manager = new DataConnectionManager("consumer", 1); + onManager?.Invoke(manager); manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); var router = new Router(endpoints); return new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), endpoints.Select(e => new Uri($"https://{e.Name}.test")), @@ -294,6 +395,15 @@ public sealed class GrpcDataHistoryClientTests /// Fail every HistoryRead after the first with this status. public Grpc.Core.StatusCode? FailAfterFirst { get; set; } public int Chunks { get; init; } = 1; + /// Per correlation id chunk counts (overrides ). + public Dictionary ChunksByItem { get; } = new(); + /// Refuse a call carrying more than one item per 256 B of its byte budget (the origin's admission rule). + public bool EnforceAdmission { get; set; } + /// The data (non-release) HistoryRead call that never answers (honours the request's token). + public int? HangOnDataCall { get; set; } + /// From this data call on, answers carry unexpected correlation ids. + public int? MalformedFromDataCall { get; set; } + public int DataCalls; public byte[]? PageToken { get; init; } public int HistoryCalls; public List<(string Path, string? Features)> Headers { get; } = []; @@ -332,6 +442,10 @@ public sealed class GrpcDataHistoryClientTests var wire = W.HistoryReadRequest.Parser.ParseFrom(bytes.AsSpan(5).ToArray()); LastBudgetTimeout = TimeSpan.FromTicks(wire.Budget.TimeoutTicks); if (!wire.ReleaseContinuations) lock (CallSizes) CallSizes.Add(wire.Items.Count); + var dataCall = wire.ReleaseContinuations ? 0 : Interlocked.Increment(ref DataCalls); + if (EnforceAdmission && !wire.ReleaseContinuations && wire.Items.Count > wire.Budget.MaxBytes / 256) + return Status(Grpc.Core.StatusCode.InvalidArgument); + if (dataCall != 0 && dataCall == HangOnDataCall) await Task.Delay(Timeout.Infinite, token); var response = new W.HistoryReadResponse { Serving = DataProtoMapper.EncodeServing(Serving) }; if (!wire.ReleaseContinuations && call > 1 && FailAfterFirst is { } later) { @@ -340,7 +454,7 @@ public sealed class GrpcDataHistoryClientTests } if (wire.ReleaseContinuations) { - foreach (var item in wire.Items) Released.Add(item.Continuation.ToByteArray()); + lock (Released) foreach (var item in wire.Items) Released.Add(item.Continuation.ToByteArray()); foreach (var item in wire.Items) response.Items.Add(new W.HistoryReadResult { CorrelationId = item.CorrelationId }); } else @@ -350,12 +464,13 @@ public sealed class GrpcDataHistoryClientTests { var key = item.CorrelationId; int left; - lock (_chunkLeft) left = _chunkLeft[key] = item.HasContinuation && _chunkLeft.TryGetValue(key, out var l) && l > 0 ? l - 1 : Chunks - 1; + lock (_chunkLeft) left = _chunkLeft[key] = item.HasContinuation && _chunkLeft.TryGetValue(key, out var l) && l > 0 ? l - 1 + : (ChunksByItem.TryGetValue(key, out var c) ? c : Chunks) - 1; using var s1 = new DataHistorySample(DataValue.FromScalar(DataValueKind.Double, 1.0), 0, DateTimeOffset.UnixEpoch, null); using var s2 = new DataHistorySample(DataValue.FromScalar(DataValueKind.Double, 2.0), 0, null, null); var result = new DataHistoryReadResult(key, 0, [s1, s2], left > 0 ? [7, 7] : PageToken, null, left > 0); response.Items.Add(DataHistoryProtoMapper.EncodeResult(result)); - if (Malformed) response.Items[^1].CorrelationId = "not-" + key; + if (Malformed || dataCall >= MalformedFromDataCall) response.Items[^1].CorrelationId = "not-" + key; } } message = response;