using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
/// #994: the small Wave 3 fixes (review 2026-12-02 R-12, R-21, R-22, R-23, R-24).
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Issue", "994")]
public sealed class GrpcDataWave3SmallFixTests
{
private static byte[] Hash(int seed)
{
var hash = new byte[32];
BitConverter.GetBytes(seed).CopyTo(hash, 0);
return hash;
}
// R-21: every Claim used to copy and scan the WHOLE table (ToArray + CanRetire per entry) under the registry lock.
[Fact]
public void R21_a_claim_against_thousands_of_retained_entries_does_not_copy_the_table()
{
var clock = new ManualTimeProvider();
var registry = new WriteOperationRegistry("inc", 10_000, 64L * 1024 * 1024, TimeSpan.FromSeconds(30), clock);
for (var i = 0; i < 5000; i++) registry.Claim("p", "op-" + i, "inc", Hash(i)).Kind.ShouldBe(WriteClaimKind.Owner);
registry.Claim("p", "warm", "inc", Hash(-1));
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 100; i++) registry.Claim("p", "more-" + i, "inc", Hash(10_000 + i)).Kind.ShouldBe(WriteClaimKind.Owner);
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
// A 5,000-entry KeyValuePair copy is ~200 KB per claim (~20 MB for 100); a claim itself is well under 2 KB.
allocated.ShouldBeLessThan(2_000_000, $"allocated {allocated} bytes for 100 claims");
}
[Fact]
public void R21_retirement_still_happens_past_retention_and_at_capacity()
{
var clock = new ManualTimeProvider();
var registry = new WriteOperationRegistry("inc", 2, 64 * 1024, TimeSpan.FromSeconds(30), clock);
var first = registry.Claim("p", "a", "inc", Hash(1)).Claim!;
var second = registry.Claim("p", "b", "inc", Hash(2)).Claim!;
registry.Claim("p", "c", "inc", Hash(3)).Kind.ShouldBe(WriteClaimKind.Capacity, "both entries are still live");
first.TryMarkDispatched().ShouldBeTrue(); first.Complete(new(DataWriteState.OutcomeUnknown, 0x80000000u, null)).ShouldBeTrue();
first.PhysicalFinished();
second.Complete(new(DataWriteState.RejectedBeforeDispatch, 0x80000000u, null)).ShouldBeTrue();
registry.Claim("p", "a", "inc", Hash(1)).Kind.ShouldBe(WriteClaimKind.Existing, "inside retention a duplicate joins");
clock.Advance(TimeSpan.FromSeconds(31));
// Capacity is never refused while a retirable entry remains, and a reused id past retention is a fresh owner.
registry.Claim("p", "c", "inc", Hash(3)).Kind.ShouldBe(WriteClaimKind.Owner);
registry.Claim("p", "a", "inc", Hash(9)).Kind.ShouldBe(WriteClaimKind.Owner);
}
// R-22: a request still holding a session that a channel close / LRU eviction cleared stored its chunk in the orphan;
// nothing ever swept it, so its bytes stayed charged to the principal until restart.
[Fact]
public void R22_a_chunk_saved_into_a_cleared_session_is_refused_and_charges_nothing()
{
var sessions = new OriginHistorySessions(TimeProvider.System);
var caller = new DataAuthenticatedContext("a", "key-a", "v1", null, 1);
var session = sessions.Get(caller, new DataHistoryChannel("c", CancellationToken.None), 4);
var view = new DataView(new("c", "u", "string", "x"), DataRealm.Raw, null, 0, "x");
session.Clear(); // the channel closed while a request was between its last check and SaveChunk
session.SaveChunk(new OriginHistorySession.Chunk(view, "k", "i", [], 0, null, null, 0, 100), 1000).ShouldBeNull();
sessions.RetainedBytes("a").ShouldBe(0);
// Positive control: a live session still stores and charges.
var live = sessions.Get(caller, new DataHistoryChannel("d", CancellationToken.None), 4);
live.SaveChunk(new OriginHistorySession.Chunk(view, "k", "i", [], 0, null, null, 0, 100), 1000).ShouldNotBeNull();
sessions.RetainedBytes("a").ShouldBe(100);
}
// R-23: the worker checked "is a snapshot incomplete" under the gate, released it, THEN armed the barrier; a SnapshotEnd
// committed in between found the barrier unarmed (its release a no-op) and the later arm stuck every following command
// until its acknowledgement timeout. The hook runs where that window was and completes the snapshot inside it.
[Fact(Timeout = 30000)]
public async Task R23_a_snapshot_completing_right_after_the_barrier_decision_still_releases_the_deferred_modify()
{
var ct = TestContext.Current.CancellationToken;
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) =>
new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity)))
{
fixture.Publish(10);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(ct);
var session = subscription.ShouldBeOfType();
var sink = new HeldFirstSnapshotEndSink();
var writer = subscription.ShouldBeAssignableTo().RunDeliveryAsync(sink, ct);
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), ct);
await sink.FirstSnapshotEndHeld.Task.WaitAsync(ct); // the open's snapshot is not complete yet
using var committed = new ManualResetEventSlim();
session.SnapshotEndReleasedForTests = committed.Set; // after the commit decided (and ran) its barrier release
var decided = 0;
session.AfterSnapshotBarrierCheckForTests = () =>
{
if (Interlocked.Exchange(ref decided, 1) != 0) return;
sink.ReleaseFirstSnapshotEnd();
committed.Wait(TimeSpan.FromSeconds(10)).ShouldBeTrue();
};
await subscription.SendAsync(new ModifySubscriptionItems("s", 1, "modify", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings with { Deadband = 5 })]), ct);
await Task.WhenAny(sink.ModifyAck.Task, writer).WaitAsync(TimeSpan.FromSeconds(4), ct);
Volatile.Read(ref decided).ShouldBe(1, "positive control: the modify was deferred behind the open's snapshot");
sink.ModifyAck.Task.IsCompleted.ShouldBeTrue("the deferred modify must run once the snapshot completed: " + string.Join(" | ", sink.Frames));
}
}
private sealed class HeldFirstSnapshotEndSink : IDataSubscriptionDeliverySink
{
internal readonly TaskCompletionSource FirstSnapshotEndHeld = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource ModifyAck = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly System.Collections.Concurrent.ConcurrentQueue Frames = new();
private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
private int _ends;
internal void ReleaseFirstSnapshotEnd() => _release.TrySetResult();
public ValueTask PrepareAsync(DataSubscriptionFrame frame, long reservedBytes,
CancellationToken cancellationToken) => ValueTask.FromResult(new Prepared(frame));
public async ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken)
{
var frame = ((Prepared)prepared).Frame;
Frames.Enqueue(frame switch
{
DataSubscriptionAck ack => "ack:" + ack.CommandId,
DataSubscriptionControl control => control.Kind + (control.Diagnostic is { } d ? ":" + d : ""),
_ => frame.GetType().Name
});
if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd } && Interlocked.Increment(ref _ends) == 1)
{
FirstSnapshotEndHeld.TrySetResult();
await _release.Task.WaitAsync(cancellationToken);
}
if (frame is DataSubscriptionAck { CommandId: "modify" }) ModifyAck.TrySetResult();
}
private sealed class Prepared(DataSubscriptionFrame frame) : IDataPreparedSubscriptionDelivery
{
internal DataSubscriptionFrame Frame { get; } = frame;
public long RetainedBytes => 1;
public void Dispose() { }
}
}
// R-24: the condition stream left a MoveNextAsync pending across iterations and then disposed the async iterator with
// `await using` — which throws NotSupportedException mid-MoveNext, replacing the stream's real failure.
[Fact]
public async Task R24_teardown_of_a_pending_frame_read_neither_throws_nor_leaves_the_read_unobserved()
{
var ct = TestContext.Current.CancellationToken;
// Positive control: the language behaviour the old teardown hit.
var naive = Frames(ct).GetAsyncEnumerator(ct);
var naivePending = naive.MoveNextAsync().AsTask();
await Should.ThrowAsync(async () => await naive.DisposeAsync());
_ = naivePending.ContinueWith(static t => _ = t.Exception, TaskScheduler.Default);
using var stop = CancellationTokenSource.CreateLinkedTokenSource(ct);
var frames = Frames(stop.Token).GetAsyncEnumerator(stop.Token);
var pending = frames.MoveNextAsync().AsTask();
await ProjectedStreamTeardown.StopAsync(stop, pending, frames); // must not throw
pending.IsCompleted.ShouldBeTrue("the pending read was cancelled and observed before disposal");
stop.IsCancellationRequested.ShouldBeTrue();
}
private static async IAsyncEnumerable Frames([System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken token)
{
await Task.Delay(Timeout.Infinite, token);
yield return 1;
}
// R-12: each delivered value frame ran the full catalog-resolve + export-ancestry + ACL walk 3-4 times (once under the
// session lock). The verdict is now memoised per (catalog instance, authority generation) for at most a second.
[Fact]
public void R12_the_publish_verdict_is_evaluated_once_per_catalog_and_authority_and_a_revocation_still_lands_at_once()
{
using var fixture = new LocalDataFixture();
var target = new DataTarget(DataTargetMode.Node, "cluster", fixture.Serving.NodeId);
fixture.Services.AuthorizeSubscription(fixture.Context, target, fixture.Raw, out var view).ShouldBe(DataItemStatus.Good);
var before = fixture.Services.PublishVerdictEvaluationsForTests;
for (var i = 0; i < 1000; i++) view!.CanPublish().ShouldBeTrue();
(fixture.Services.PublishVerdictEvaluationsForTests - before).ShouldBe(1, "one walk serves every frame of this authority");
fixture.Clock.Advance(LocalDataServices.PublishVerdictTtl);
view!.CanPublish().ShouldBeTrue();
(fixture.Services.PublishVerdictEvaluationsForTests - before).ShouldBe(2, "re-proved once the TTL passed");
// An authority publish (here: the grant withdrawn) misses the memo on the very next frame.
var key = new ZB.MOM.WW.OtOpcUa.Configuration.Entities.ApiKey { ApiKeyId = "peer-key", Name = "peer-key", Principal = "peer", SecretHash = "hash", Enabled = true };
fixture.Authority.Apply("cluster", "revoked", [key], [], new Dictionary>());
view.CanPublish().ShouldBeFalse("a revocation is never served from the memo");
}
}