fix(grpc-data): H3 review round 3 nits b/c/d — no origin cursor stranded on Bad, scope moves or a serve-time throw

- 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).
This commit is contained in:
Joseph Doherty
2026-11-24 07:15:16 -05:00
parent 30d66fdc7c
commit f1b23abcb4
6 changed files with 157 additions and 7 deletions
@@ -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<ProjectedHistoryNode, double[]> Answer { get; init; } = _ => [1.0, 2.0];
/// <summary>When set, the FIRST node's first sample carries this value (e.g. one the SDK boundary cannot convert).</summary>
public object? FirstValue { get; init; }
/// <summary>When set, every call waits on it (a projected read holding its slot).</summary>
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());
}
@@ -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;
/// <summary>
/// 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
/// <c>BadContinuationPointInvalid</c> (its token cannot be presented again), a fresh one <c>BadNoCommunication</c>.
/// </summary>
[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<byte[]> _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<IReadOnlyList<DataHistoryReadResult>> ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken)
{
OnRead();
byte k = 8;
return Task.FromResult<IReadOnlyList<DataHistoryReadResult>>(request.Items
.Select(i => new DataHistoryReadResult(i.CorrelationId, 0, [], [k++])).ToArray());
}
public Task ReleaseAsync(IReadOnlyList<byte[]> continuations, CancellationToken cancellationToken)
{
lock (_released) _released.AddRange(continuations);
return Task.CompletedTask;
}
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken) => throw new NotSupportedException();
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}
@@ -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 }
/// <summary>
/// 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,