5cccfd75ce
Wave 3 of the 2026-12-02 review (docs/reviews/2026-12-02/01-runtime.md R-2/3/7/8/9/10/12/13/21/22/23/24, 02-opcuaserver.md U-10/11/12/13). Consumer (ProjectedDataAccess cohort): - R-2: a cohort's OpenSubscription declared a snapshot budget of 1 item, which the origin uses to size the stream's handle table, so the 2nd item was refused LimitExceeded and the cohort re-opened in a loop (two projected items of one interval broke each other). Opens/adds/removes are now batched (IDataSubscriptionCommandLimits, <=256 items, bounded by estimated snapshot bytes) and paced (32 burst, 32/s, <=4 commands or snapshots outstanding). - R-7: control events no longer share the bounded frame queue; a failed Remove can no longer Stop() the cohort. - R-10: a local capacity refusal (TryPublishOrBackpressure -> CapacityExhausted) is retried for up to 2 s instead of invalidating healthy evidence and retiring the route. - R-13: RemoteSubscription mutates its handle/version tables in place; the cohort caches the source per binding and drops the per-sample LINQ in EvidenceFor. - R-8: only an unselectable endpoint arms the discovery backoff; a caller cancel is OperationCanceledException. - R-24: the condition stream cancels and observes a pending frame read before disposing the enumerator. Origin (DataSubscriptionSession / SamplePartition / SourceInterestLease): - R-2 (found by the perf harness): the delivery index was sized MaxPendingFrames x 16 = 1024, so the 1025th item of a stream stopped the session after its ack; it now covers MaxMonitoredItems. - R-3: interest reads count only own-ticket matches (scan budget separate), re-queue a lagging tick, and catch up from per-source last-change versions when the bounded history rolled off - no more "Source change history expired". - R-9: a partition quiet bump resets a lease only when one of ITS sources was invalidated (per-source quiet version) or its binding retired; partition-wide invalidation still resets all. - R-12: the per-item publish verdict is memoised per (catalog instance, authority generation) for <=1 s; Commit under the session lock re-checks identity only. - R-21/R-22/R-23: registry prune is interval/capacity driven; a cleared history session refuses chunks; the snapshot barrier is decided and armed under the same gate its release is decided under. Node manager: U-10 projected live items indexed by node; U-11 anchor removal / root-leaf swap tombstone the anchor's own monitored node; U-12 per-parent child count; U-13 per-condition verdict index. Also: Issue934_r1_N1 test clears its metadata failure before ending the stream (test-only sequencing race, reproduced with a 200 ms delay; production behaviour correct). Perf (Category=Perf, OTOPCUA_GRPCDATA_PERF=1): 10k-item cohort opens in 3.3 s / 80 commands / 1 stream (before: never opens); 100 source versions at 1k/s -> 11,036 item values in 569 ms.
194 lines
12 KiB
C#
194 lines
12 KiB
C#
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;
|
|
|
|
/// <summary>#994: the small Wave 3 fixes (review 2026-12-02 R-12, R-21, R-22, R-23, R-24).</summary>
|
|
[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<DataSubscriptionSession>();
|
|
var sink = new HeldFirstSnapshotEndSink();
|
|
var writer = subscription.ShouldBeAssignableTo<IDataSubscriptionTransport>().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<string> Frames = new();
|
|
private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
private int _ends;
|
|
internal void ReleaseFirstSnapshotEnd() => _release.TrySetResult();
|
|
public ValueTask<IDataPreparedSubscriptionDelivery> PrepareAsync(DataSubscriptionFrame frame, long reservedBytes,
|
|
CancellationToken cancellationToken) => ValueTask.FromResult<IDataPreparedSubscriptionDelivery>(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<NotSupportedException>(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<int> 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<ZB.MOM.WW.OtOpcUa.Core.Authorization.AclScopeRef,
|
|
IReadOnlyList<ZB.MOM.WW.OtOpcUa.Core.Authorization.NodeAclPath>>());
|
|
view.CanPublish().ShouldBeFalse("a revocation is never served from the memo");
|
|
}
|
|
}
|