Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataStreamOrderingTests.cs
T
Joseph Doherty efd749da0f fix(grpc-data): #966 a modify's replacement no longer emits a live delta before its snapshot
The suspected ordering gap was real. A modify that replaces an item commits on the delivery side (the ack's
commit): the replacement enters _items (it was already registered with the delivery scheduler at staging) and its
snapshot job goes to _committedSnapshots, which only the NEXT tick moves to the pump. A tick already past that
dequeue that then reads a source change (e.g. from a sibling item on the same source, whose interest group survives
the modify) marks the source dirty. The scheduler hands it the replacement's handle, and ConsiderAsync sent the
newer value as a live delta before SnapshotBegin. The snapshot that followed carried the older captured value.

ConsiderAsync now defers an item whose interest group is not snapshot-complete. LastConsidered is left unchanged,
and the group's own lease (its cursor starts at the snapshot capture) yields the change once SnapshotEnd commits.
The same guard covers added and recovered items. Nothing starves: an undelivered SnapshotEnd stops the stream.

Deterministic test (BeforeDirtyTickForTests hold + gated modify ack + publish under the hold): red 3/3 before
(value:R:20 | begin | snapshot:R:10), green after, with a positive control that 20 is delivered after the end.
Parallel in-process stress of the unhooked scenario (2 items on one source, modify one under continuous publish):
60/40000 violations before (10000 x widths 2/4/6/8), 0/40000 after.
2026-12-02 13:12:27 -05:00

1373 lines
89 KiB
C#

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;
[Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P06")]
public sealed class GrpcDataStreamOrderingTests
{
[Fact(Timeout = 30000)]
public async Task Coalescing_notice_is_delivered_when_the_latest_value_returns_to_the_baseline()
{
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 8, 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(1);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var session = subscription.ShouldBeOfType<DataSubscriptionSession>();
var queued = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
session.OnCandidateQueuedForTests = (_, version) => { if (version == 3) queued.TrySetResult(true); };
var sink = new SequencedLiveSink();
var writer = subscription.ShouldBeAssignableTo<IDataSubscriptionTransport>()
.RunDeliveryAsync(sink, TestContext.Current.CancellationToken);
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(10),
[new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken);
await sink.SnapshotEnd.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2); fixture.Hub.ProcessPending();
fixture.Clock.Advance(TimeSpan.FromMilliseconds(200));
await sink.FirstLiveEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
HubTest.Publish(fixture.Hub, fixture.Ticket, 3, 3); fixture.Hub.ProcessPending();
fixture.Clock.Advance(TimeSpan.FromMilliseconds(200));
await queued.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
HubTest.Publish(fixture.Hub, fixture.Ticket, 4, 2); fixture.Hub.ProcessPending();
await subscription.SendAsync(new AddSubscriptionItems("s", 1, "probe", TimeSpan.FromSeconds(10), []),
TestContext.Current.CancellationToken);
sink.ReleaseFirst();
await sink.ProbeAck.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
fixture.Clock.Advance(TimeSpan.FromSeconds(5));
await sink.Heartbeat.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
var events = sink.Events.ToArray();
events.ShouldContain("coalesced", "a suppressed replacement must not hide the loss indication");
events.ShouldNotContain("value-3");
events.ShouldNotContain("value-4");
await subscription.DisposeAsync();
await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
}
}
[Fact(Timeout = 30000)]
public async Task Direct_modify_ack_is_not_published_when_authority_is_revoked_during_commit_cleanup()
{
using var demand = new BlockingFirstLeaseDemand();
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(TestContext.Current.CancellationToken);
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), TestContext.Current.CancellationToken);
await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken)
.GetAsyncEnumerator(TestContext.Current.CancellationToken);
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionAck>();
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin);
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionValues>().Dispose();
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotEnd);
await subscription.SendAsync(new ModifySubscriptionItems("s", 1, "modify", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings with { SamplingInterval = TimeSpan.FromMilliseconds(100) })]), TestContext.Current.CancellationToken);
var next = Task.Run(async () => await reader.MoveNextAsync(), TestContext.Current.CancellationToken);
try
{
await demand.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
fixture.Activation.Begin("revoke-during-modify-cleanup");
}
finally { demand.Release(); }
(await next.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeFalse();
}
}
[Fact(Timeout = 30000)]
public async Task A_queued_candidate_rechecks_due_time_after_the_previous_blocked_write_commits()
{
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(1);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var session = subscription.ShouldBeOfType<DataSubscriptionSession>();
var queued = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
session.OnCandidateQueuedForTests = (_, version) => { if (version == 3) queued.TrySetResult(true); };
var sink = new SequencedLiveSink();
var writer = subscription.ShouldBeAssignableTo<IDataSubscriptionTransport>().RunDeliveryAsync(sink, TestContext.Current.CancellationToken);
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(10),
[new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken);
await sink.SnapshotEnd.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
fixture.Clock.Advance(TimeSpan.FromSeconds(1));
HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2); fixture.Hub.ProcessPending();
fixture.Clock.Advance(TimeSpan.FromMilliseconds(200));
await sink.FirstLiveEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
HubTest.Publish(fixture.Hub, fixture.Ticket, 3, 3); fixture.Hub.ProcessPending();
fixture.Clock.Advance(TimeSpan.FromMilliseconds(200));
await queued.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
await subscription.SendAsync(new AddSubscriptionItems("s", 1, "probe", TimeSpan.FromSeconds(5),
[new("probe", fixture.Raw, settings)]), TestContext.Current.CancellationToken);
sink.ReleaseFirst();
await sink.ProbeAck.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
sink.Version3Written.Task.IsCompleted.ShouldBeFalse("the preceding write advanced the next due time");
fixture.Clock.Advance(TimeSpan.FromSeconds(1));
await sink.Version3Written.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
await subscription.DisposeAsync();
await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
}
}
[Fact(Timeout = 30000)]
public async Task Superseded_queued_value_emits_coalescing_control_before_the_newest_delta()
{
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 4, 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(1);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var session = subscription.ShouldBeOfType<DataSubscriptionSession>();
var queued = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
session.OnCandidateQueuedForTests = (_, version) => { if (version == 3) queued.TrySetResult(true); };
var sink = new SequencedLiveSink();
var writer = subscription.ShouldBeAssignableTo<IDataSubscriptionTransport>().RunDeliveryAsync(sink, TestContext.Current.CancellationToken);
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(10),
[new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken);
await sink.SnapshotEnd.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2); fixture.Hub.ProcessPending();
fixture.Clock.Advance(TimeSpan.FromMilliseconds(200));
await sink.FirstLiveEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
HubTest.Publish(fixture.Hub, fixture.Ticket, 3, 3); fixture.Hub.ProcessPending();
fixture.Clock.Advance(TimeSpan.FromMilliseconds(200));
await queued.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
HubTest.Publish(fixture.Hub, fixture.Ticket, 4, 4); fixture.Hub.ProcessPending();
sink.ReleaseFirst();
fixture.Clock.Advance(TimeSpan.FromMilliseconds(200));
await sink.Version4Written.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
var events = sink.Events.ToArray();
Array.IndexOf(events, "coalesced").ShouldBeGreaterThanOrEqualTo(0);
Array.IndexOf(events, "coalesced").ShouldBeLessThan(Array.IndexOf(events, "value-4"));
events.ShouldNotContain("value-3");
await subscription.DisposeAsync();
await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
}
}
[Fact(Timeout = 30000)]
public async Task Revocation_during_post_prepare_snapshot_validation_prevents_transport_handoff()
{
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(1);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var sink = new PostPrepareGateSink(fixture.Hub, blockSnapshot: true);
var writer = subscription.ShouldBeAssignableTo<IDataSubscriptionTransport>()
.RunDeliveryAsync(sink, TestContext.Current.CancellationToken);
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),
TestContext.Current.CancellationToken);
try
{
await sink.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
fixture.Activation.Begin("revoke-after-check");
}
finally { sink.Release(); }
await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
sink.BlockedValueWrites.ShouldBe(0);
}
}
[Fact(Timeout = 30000)]
public async Task Revocation_during_post_prepare_live_eligibility_prevents_transport_handoff()
{
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(1);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var sink = new PostPrepareGateSink(fixture.Hub, blockSnapshot: false);
var writer = subscription.ShouldBeAssignableTo<IDataSubscriptionTransport>()
.RunDeliveryAsync(sink, TestContext.Current.CancellationToken);
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),
TestContext.Current.CancellationToken);
await sink.SnapshotEnd.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2); fixture.Hub.ProcessPending();
fixture.Clock.Advance(TimeSpan.FromMilliseconds(200));
try
{
await sink.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
fixture.Activation.Begin("revoke-after-eligibility-start");
}
finally { sink.Release(); }
await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
sink.BlockedValueWrites.ShouldBe(0);
}
}
[Fact(Timeout = 30000)]
public async Task Direct_handoff_does_not_certify_stale_age_after_a_blocking_final_check()
{
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)))
using (var release = new ManualResetEventSlim())
{
fixture.Publish(1);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var session = subscription.ShouldBeOfType<DataSubscriptionSession>();
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),
TestContext.Current.CancellationToken);
await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken)
.GetAsyncEnumerator(TestContext.Current.CancellationToken);
(await reader.MoveNextAsync()).ShouldBeTrue(); // ack
(await reader.MoveNextAsync()).ShouldBeTrue(); // begin
var entered = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
session.BeforeDirectCommitForTests = () =>
{
session.BeforeDirectCommitForTests = null; entered.TrySetResult(true);
if (!release.Wait(TimeSpan.FromSeconds(5))) throw new TimeoutException();
};
var move = Task.Run(async () => await reader.MoveNextAsync(), TestContext.Current.CancellationToken);
try
{
await entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
fixture.Clock.Advance(TimeSpan.FromSeconds(2));
}
finally { release.Set(); }
(await move.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue();
using var values = reader.Current.ShouldBeOfType<DataSubscriptionValues>();
var bounds = values.Items.ShouldHaveSingleItem().AgeBounds;
bounds.IsFresh(TimeSpan.FromSeconds(1)).ShouldBeFalse();
if (bounds.Upper is { } upper) upper.ShouldBeGreaterThanOrEqualTo(TimeSpan.FromSeconds(2));
}
}
[Fact(Timeout = 30000)]
public async Task Local_facades_preserve_node_and_cluster_target_identity_in_demand_admission()
{
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(3);
var nodeTarget = new DataTarget(DataTargetMode.Node, "cluster", "node-a");
var clusterTarget = new DataTarget(DataTargetMode.Cluster, "cluster", null);
await using var node = fixture.Services.Create(fixture.Context, nodeTarget);
await using var cluster = fixture.Services.Create(fixture.Context, clusterTarget);
await using var nodeSubscription = await node.SubscribeAsync(TestContext.Current.CancellationToken);
await using var clusterSubscription = await cluster.SubscribeAsync(TestContext.Current.CancellationToken);
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
await nodeSubscription.SendAsync(new OpenSubscription("node", 1, "open-node", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken);
await clusterSubscription.SendAsync(new OpenSubscription("cluster", 1, "open-cluster", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken);
await using var nodeReader = nodeSubscription.ReadAllAsync(TestContext.Current.CancellationToken)
.GetAsyncEnumerator(TestContext.Current.CancellationToken);
await using var clusterReader = clusterSubscription.ReadAllAsync(TestContext.Current.CancellationToken)
.GetAsyncEnumerator(TestContext.Current.CancellationToken);
(await nodeReader.MoveNextAsync()).ShouldBeTrue();
(await clusterReader.MoveNextAsync()).ShouldBeTrue();
demand.AuthorizedViews.Select(x => x.Target).ShouldContain(nodeTarget);
demand.AuthorizedViews.Select(x => x.Target).ShouldContain(clusterTarget);
demand.AuthorizedViews.Select(x => x.Target.Mode).Distinct().Count().ShouldBe(2);
var views = demand.AuthorizedViews.ToArray();
views[0].Source.ShouldBe(views[1].Source);
var registry = new UpstreamDemandRegistry(2, 2);
var firstKey = new DemandSharingKey(views[0].Source, views[0].Target, views[0].Consistency,
views[0].PrincipalId, views[0].ExportScope, views[0].Serving.CatalogEpoch, views[0].Serving.AuthorityEpoch);
var secondKey = firstKey with { Target = views[1].Target };
registry.TryAdd(firstKey, settings, out var firstLease).ShouldBeTrue();
registry.TryAdd(secondKey, settings, out var secondLease).ShouldBeTrue();
registry.GetState(firstKey)!.InterestCount.ShouldBe(1);
registry.GetState(secondKey)!.InterestCount.ShouldBe(1);
firstLease!.Dispose(); secondLease!.Dispose();
}
}
[Fact(Timeout = 30000)]
public async Task Local_connection_waits_for_physical_ack_before_acknowledging_and_sending_snapshot()
{
var demand = new DeferredSubscriptionDemand();
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(subscriptions: context =>
new LocalSubscriptionService(fixture!.Services, context,
new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity)))
{
fixture.Publish(42);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var item = new DataSubscriptionItem("one", fixture.Raw,
new(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null));
var open = new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), [item], false,
TimeSpan.FromSeconds(30), LocalDataFixture.Budget);
var send = subscription.SendAsync(open, TestContext.Current.CancellationToken);
await demand.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken);
var first = reader.MoveNextAsync().AsTask();
first.IsCompleted.ShouldBeFalse("an unacknowledged physical subscription is not ready");
demand.Accept();
await send;
(await first.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue();
var ack = reader.Current.ShouldBeOfType<DataSubscriptionAck>();
ack.Items.ShouldHaveSingleItem().Status.ShouldBe(DataItemStatus.Good);
ack.Items[0].Handle.ShouldNotBeNull();
(await reader.MoveNextAsync()).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin);
(await reader.MoveNextAsync()).ShouldBeTrue();
using (var values = reader.Current.ShouldBeOfType<DataSubscriptionValues>())
{
values.IsSnapshot.ShouldBeTrue();
values.Items.ShouldHaveSingleItem().Sample.Value.GetScalar().ShouldBe(42);
values.Items[0].Readiness.ShouldBe(DataReadiness.Ready);
}
(await reader.MoveNextAsync()).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotEnd);
}
}
[Fact(Timeout = 30000)]
public async Task Accepted_command_owns_its_item_list_before_the_caller_can_mutate_it()
{
var demand = new DeferredSubscriptionDemand();
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(subscriptions: context =>
new LocalSubscriptionService(fixture!.Services, context,
new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity)))
{
fixture.Publish(1);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5),
[new("first", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget),
TestContext.Current.CancellationToken);
await demand.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
var mutable = new List<DataSubscriptionItem> { new("second", fixture.Raw, settings) };
await subscription.SendAsync(new AddSubscriptionItems("s", 1, "add", TimeSpan.FromSeconds(5), mutable),
TestContext.Current.CancellationToken);
mutable.Clear();
demand.Accept();
await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken)
.GetAsyncEnumerator(TestContext.Current.CancellationToken);
while (true)
{
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue();
if (reader.Current is DataSubscriptionValues values) values.Dispose();
if (reader.Current is DataSubscriptionAck { CommandId: "add" } ack)
{
ack.Items.ShouldHaveSingleItem().ClientItemId.ShouldBe("second");
ack.Items[0].Status.ShouldBe(DataItemStatus.Good);
break;
}
}
}
}
[Fact(Timeout = 30000)]
public async Task A_denied_alias_cannot_inherit_authority_from_a_shared_backing_source()
{
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(subscriptions: context =>
new LocalSubscriptionService(fixture!.Services, context,
new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity)))
{
fixture.Publish(42);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1),
DataChangeTrigger.StatusValue, null);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5),
[new("allowed", fixture.Raw, settings), new("denied", fixture.Uns, settings)], false,
TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken);
await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken);
(await reader.MoveNextAsync()).ShouldBeTrue();
var ack = reader.Current.ShouldBeOfType<DataSubscriptionAck>();
ack.Items[0].Status.ShouldBe(DataItemStatus.Good);
// #957: the ACL hides the UNS alias from this peer, so it is refused like a missing node.
ack.Items[1].Status.ShouldBe(DataItemStatus.NotFound);
ack.Items[1].Handle.ShouldBeNull();
demand.AuthorizedViews.ShouldHaveSingleItem().View.ShouldBe(fixture.Raw);
}
}
[Fact(Timeout = 30000)]
public async Task A_bound_source_without_a_sample_is_waiting_until_a_real_acquisition_arrives()
{
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(subscriptions: context =>
new LocalSubscriptionService(fixture!.Services, context,
new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity)))
{
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
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),
TestContext.Current.CancellationToken);
await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken)
.GetAsyncEnumerator(TestContext.Current.CancellationToken);
(await reader.MoveNextAsync()).ShouldBeTrue();
var ack = reader.Current.ShouldBeOfType<DataSubscriptionAck>();
ack.Items[0].Status.ShouldBe(DataItemStatus.WaitingForInitialData);
ack.Items[0].Handle.ShouldNotBeNull();
(await reader.MoveNextAsync()).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin);
(await reader.MoveNextAsync()).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotEnd);
fixture.Publish(9);
fixture.Clock.Advance(TimeSpan.FromSeconds(1));
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue();
using var values = reader.Current.ShouldBeOfType<DataSubscriptionValues>();
values.Items.ShouldHaveSingleItem().Sample.Value.GetScalar().ShouldBe(9);
values.Items[0].Readiness.ShouldBe(DataReadiness.Ready);
}
}
[Fact(Timeout = 30000), Trait("Phase", "P11")]
public async Task Dirty_aliases_wait_when_snapshot_controls_leave_only_two_outbound_slots()
{
var ct = TestContext.Current.CancellationToken;
var demand = new CountingSnapshotDemand(14);
var capacity = new SubscriptionTransportCapacity(4, 4, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 8, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(subscriptions: context =>
new LocalSubscriptionService(fixture!.Services, context, new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity)))
using (var releaseTick = new ManualResetEventSlim())
{
fixture.Publish(1);
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
var items = Enumerable.Range(0, 12).Select(i => new DataSubscriptionItem("item-" + i, fixture.Raw, settings)).ToArray();
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(ct);
var session = subscription.ShouldBeOfType<DataSubscriptionSession>();
var beforeDirty = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var tickDone = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var firstEnd = 0; var intercepted = 0; var capturedTotal = -1; var capturedValues = -1;
session.SnapshotEndCommittedForTests = () => Interlocked.CompareExchange(ref firstEnd, 1, 0);
session.BeforeDirtyTickForTests = (total, values, interests) =>
{
if (Volatile.Read(ref firstEnd) == 0 || interests == 0 || Interlocked.CompareExchange(ref intercepted, 1, 0) != 0) return;
capturedTotal = total; capturedValues = values;
beforeDirty.TrySetResult(); releaseTick.Wait(ct);
};
session.AfterTickForTests = () => { if (Volatile.Read(ref intercepted) != 0) tickDone.TrySetResult(); };
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(10), items,
false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), ct);
await using var reader = subscription.ReadAllAsync(ct).GetAsyncEnumerator(ct);
var depth = 0; var ends = 0; var sawDelta = false; var frames = new List<string>();
async Task ReadFrame()
{
var moved = await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), ct);
moved.ShouldBeTrue("stream ended before ordered snapshots completed: " + string.Join(" | ", frames));
if (frames.Count < 100) frames.Add(reader.Current switch
{
DataSubscriptionControl c => $"{c.Sequence}:control:{c.Kind}:{c.Diagnostic}",
DataSubscriptionAck a => $"{a.Sequence}:ack:{a.CommandId}",
DataSubscriptionValues v => $"{v.Sequence}:values:{v.IsSnapshot}",
_ => $"{reader.Current.Sequence}:other"
});
if (reader.Current is DataSubscriptionControl control)
{
if (control.Kind == DataStreamControlKind.SnapshotBegin) { depth.ShouldBe(0); depth++; }
if (control.Kind == DataStreamControlKind.SnapshotEnd) { depth.ShouldBe(1); depth--; ends++; }
control.Kind.ShouldNotBe(DataStreamControlKind.Reset);
}
else if (reader.Current is DataSubscriptionValues values)
{
if (values.IsSnapshot) depth.ShouldBe(1);
else { values.Items[0].Sample.Value.GetScalar().ShouldBe(2); sawDelta = true; }
values.Dispose();
}
}
try
{
await ReadFrame(); await ReadFrame(); await ReadFrame();
await subscription.SendAsync(new AddSubscriptionItems("s", 1, "add-a", TimeSpan.FromSeconds(10), [new("a", fixture.Raw, settings)]), ct);
await subscription.SendAsync(new AddSubscriptionItems("s", 1, "add-b", TimeSpan.FromSeconds(10), [new("b", fixture.Raw, settings)]), ct);
await demand.Reached.Task.WaitAsync(TimeSpan.FromSeconds(5), ct);
fixture.Hub.WithPartitionLockForTest(fixture.Ticket.Key, () => { HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2); fixture.Hub.ProcessPending(); });
for (var i = 0; i < 3; i++) await ReadFrame();
demand.Release();
while (ends == 0) await ReadFrame();
await beforeDirty.Task.WaitAsync(TimeSpan.FromSeconds(5), ct);
capturedTotal.ShouldBe(6, "two one-item snapshots occupy six actual outbound frames");
capturedValues.ShouldBe(2, "the remaining four frames are real snapshot controls");
releaseTick.Set();
await tickDone.Task.WaitAsync(TimeSpan.FromSeconds(5), ct);
while (ends < 3) await ReadFrame();
fixture.Clock.Advance(TimeSpan.FromSeconds(1));
while (!sawDelta) await ReadFrame();
depth.ShouldBe(0);
}
finally { releaseTick.Set(); demand.Release(); }
}
}
[Fact(Timeout = 30000), Trait("Phase", "P11")]
public async Task Concurrent_snapshot_jobs_do_not_nest_or_interleave()
{
var demand = new CountingSnapshotDemand(14);
var capacity = new SubscriptionTransportCapacity(4, 4, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 8, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(subscriptions: context =>
new LocalSubscriptionService(fixture!.Services, context, new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity)))
{
fixture.Publish(1);
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
var items = Enumerable.Range(0, 12).Select(i => new DataSubscriptionItem("item-" + i, fixture.Raw, settings)).ToArray();
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(10), items,
false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken);
await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken);
var trace = new List<string>();
async Task NextFrame()
{
var moved = await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
moved.ShouldBeTrue("stream ended; bounded frames: " + string.Join(" | ", trace));
if (trace.Count < 64)
trace.Add(reader.Current switch
{
DataSubscriptionControl control => $"{control.Sequence}:control:{control.Kind}:{control.Diagnostic}",
DataSubscriptionAck ack => $"{ack.Sequence}:ack:{ack.CommandId}",
DataSubscriptionValues values => $"{values.Sequence}:values:snapshot={values.IsSnapshot}:versions={string.Join(",", values.Items.Select(item => item.Sample.Version))}",
_ => $"{reader.Current.Sequence}:other"
});
}
await NextFrame(); reader.Current.ShouldBeOfType<DataSubscriptionAck>();
await NextFrame(); reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin);
await NextFrame(); reader.Current.ShouldBeOfType<DataSubscriptionValues>().Dispose();
// Stop reading while the first snapshot exceeds the bounded queue, and wait until two further adds have reached the worker.
await subscription.SendAsync(new AddSubscriptionItems("s", 1, "add-a", TimeSpan.FromSeconds(10), [new("a", fixture.Raw, settings)]), TestContext.Current.CancellationToken);
await subscription.SendAsync(new AddSubscriptionItems("s", 1, "add-b", TimeSpan.FromSeconds(10), [new("b", fixture.Raw, settings)]), TestContext.Current.CancellationToken);
await demand.Reached.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
fixture.Hub.WithPartitionLockForTest(fixture.Ticket.Key, () => { HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2); fixture.Hub.ProcessPending(); });
// The worker is held in the third acquisition, leaving room for its control frames
// without overflowing the two reserved control slots.
for (var i = 0; i < 3; i++)
{
await NextFrame();
reader.Current.ShouldBeOfType<DataSubscriptionValues>().Dispose();
}
demand.Release();
var depth = 1; var ends = 0; var sawDelta = false;
while (ends < 3)
{
await NextFrame();
if (reader.Current is DataSubscriptionControl control)
{
if (control.Kind == DataStreamControlKind.SnapshotBegin) { depth.ShouldBe(0, "a previous snapshot must finish first"); depth++; }
else if (control.Kind == DataStreamControlKind.SnapshotEnd) { depth.ShouldBe(1); depth--; ends++; }
}
else if (reader.Current is DataSubscriptionValues value)
{
if (value.IsSnapshot) depth.ShouldBe(1);
else { value.Items[0].Sample.Value.GetScalar().ShouldBe(2); sawDelta = true; }
value.Dispose();
}
}
fixture.Clock.Advance(TimeSpan.FromSeconds(1));
while (!sawDelta)
{
await NextFrame();
if (reader.Current is not DataSubscriptionValues delta) continue;
using (delta) { if (!delta.IsSnapshot) { delta.Items[0].Sample.Value.GetScalar().ShouldBe(2); sawDelta = true; } }
}
}
}
[Fact(Timeout = 30000)]
public async Task Snapshot_larger_than_queue_finishes_frozen_values_before_a_racing_delta()
{
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 4, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(additionalRawNodes: 4, subscriptions: context =>
new LocalSubscriptionService(fixture!.Services, context,
new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity)))
{
fixture.Publish(1);
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
var items = Enumerable.Range(0, 5).Select(i =>
{
var view = i == 0 ? fixture.Raw : fixture.Raw with
{
Address = fixture.Raw.Address with { Identifier = fixture.Raw.Address.Identifier + (i - 1) },
Subject = fixture.Raw.Subject + (i - 1)
};
return new DataSubscriptionItem("item-" + i, view, settings);
}).ToArray();
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(10), items,
false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken);
await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken)
.GetAsyncEnumerator(TestContext.Current.CancellationToken);
(await reader.MoveNextAsync()).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionAck>().Items.Count.ShouldBe(5);
(await reader.MoveNextAsync()).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin);
(await reader.MoveNextAsync()).ShouldBeTrue();
using (var first = reader.Current.ShouldBeOfType<DataSubscriptionValues>())
first.Items.ShouldHaveSingleItem().Sample.Value.GetScalar().ShouldBe(1);
fixture.Clock.Advance(TimeSpan.FromSeconds(2));
// Arrange successful ingress; nonblocking contention deliberately invalidates a
// source and is covered separately from frozen-snapshot/delta ordering.
fixture.Hub.WithPartitionLockForTest(fixture.Ticket.Key, () =>
{
HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2);
fixture.Hub.ProcessPending();
});
var frozen = 1;
while (true)
{
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue();
if (reader.Current is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }) break;
using var values = reader.Current.ShouldBeOfType<DataSubscriptionValues>();
values.IsSnapshot.ShouldBeTrue();
values.Items.ShouldHaveSingleItem().Sample.Value.GetScalar().ShouldBe(1);
values.Items[0].AgeBounds.Lower.ShouldNotBeNull();
values.Items[0].AgeBounds.Lower!.Value.ShouldBeGreaterThanOrEqualTo(TimeSpan.FromSeconds(2));
frozen++;
}
frozen.ShouldBe(5);
fixture.Clock.Advance(TimeSpan.FromMilliseconds(200));
var delivered = new HashSet<ulong>();
while (delivered.Count < 5)
{
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue();
if (reader.Current is DataSubscriptionControl control)
{
control.Kind.ShouldBe(DataStreamControlKind.Heartbeat, $"Unexpected {control.Kind}: {control.Diagnostic}");
continue;
}
using var delta = reader.Current.ShouldBeOfType<DataSubscriptionValues>();
delta.IsSnapshot.ShouldBeFalse();
delta.Items.ShouldHaveSingleItem().Sample.Value.GetScalar().ShouldBe(2);
delivered.Add(delta.Items[0].Handle.Handle);
}
}
}
[Fact(Timeout = 30000)]
public async Task Direct_frame_retains_its_resource_charge_after_session_disposal()
{
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(1, 1, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(subscriptions: context =>
new LocalSubscriptionService(fixture!.Services, context,
new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity)))
{
fixture.Publish(7);
var baseline = fixture.Hub.Resources.RetainedBytes;
await using var connection = fixture.Connection();
var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
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),
TestContext.Current.CancellationToken);
await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken)
.GetAsyncEnumerator(TestContext.Current.CancellationToken);
(await reader.MoveNextAsync()).ShouldBeTrue(); // ack
(await reader.MoveNextAsync()).ShouldBeTrue(); // begin
(await reader.MoveNextAsync()).ShouldBeTrue();
var frame = reader.Current.ShouldBeOfType<DataSubscriptionValues>();
await subscription.DisposeAsync();
fixture.Hub.Resources.RetainedBytes.ShouldBeGreaterThan(baseline);
capacity.Snapshots.TryAcquire("peer", 1, out _).ShouldBeFalse("escaped snapshot frame still owns its snapshot permit");
frame.Items.ShouldHaveSingleItem().Sample.Value.GetScalar().ShouldBe(7);
frame.Dispose();
fixture.Hub.Resources.RetainedBytes.ShouldBe(baseline);
capacity.Snapshots.TryAcquire("peer", 1, out var next).ShouldBeTrue();
next!.Dispose();
}
}
[Fact(Timeout = 30000)]
public async Task Expired_original_key_fences_a_value_blocked_in_transport_preparation()
{
var demand = new DeferredSubscriptionDemand();
demand.Accept();
var capacity = new SubscriptionTransportCapacity(1, 1, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(subscriptions: context =>
new LocalSubscriptionService(fixture!.Services, context,
new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity)))
{
fixture.Publish(42);
var baselineBytes = fixture.Hub.Resources.RetainedBytes;
var shortKey = fixture.Context with { CredentialExpiresUtc = fixture.Clock.GetUtcNow().AddSeconds(2) };
await using var connection = fixture.Services.Create(shortKey, new(DataTargetMode.Node, "cluster", "node-a"));
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var transport = subscription.ShouldBeAssignableTo<IDataSubscriptionTransport>();
var sink = new BlockingValuePreparationSink();
var writer = transport.RunDeliveryAsync(sink, TestContext.Current.CancellationToken);
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1),
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),
TestContext.Current.CancellationToken);
await sink.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
fixture.Clock.Advance(TimeSpan.FromSeconds(3));
await subscription.DisposeAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
capacity.ActiveOperations.ShouldBe(1, "a sink ignoring cancellation still owns its physical slot");
fixture.Hub.Resources.RetainedBytes.ShouldBeGreaterThan(baselineBytes);
capacity.Snapshots.TryAcquire("peer", 1, out _).ShouldBeFalse();
sink.Release();
await sink.ValueDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
try { await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); }
catch (OperationCanceledException) { }
sink.ValueWrites.ShouldBe(0, "the final key/authority gate follows preparation");
capacity.ActiveOperations.ShouldBe(0);
fixture.Hub.Resources.RetainedBytes.ShouldBe(baselineBytes);
capacity.Snapshots.TryAcquire("peer", 1, out var next).ShouldBeTrue();
next!.Dispose();
}
}
[Fact(Timeout = 30000)]
public async Task A_write_ignoring_cancellation_retains_frame_and_capacity_until_its_actual_completion()
{
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(1, 1, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(subscriptions: context =>
new LocalSubscriptionService(fixture!.Services, context,
new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity)))
{
fixture.Publish(42);
var baseline = fixture.Hub.Resources.RetainedBytes;
await using var connection = fixture.Connection();
var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var transport = subscription.ShouldBeAssignableTo<IDataSubscriptionTransport>();
var sink = new BlockingValueWriteSink();
var writer = transport.RunDeliveryAsync(sink, TestContext.Current.CancellationToken);
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(2), LocalDataFixture.Budget),
TestContext.Current.CancellationToken);
await sink.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
fixture.Clock.Advance(TimeSpan.FromSeconds(3));
await subscription.DisposeAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
capacity.ActiveOperations.ShouldBe(1);
fixture.Hub.Resources.RetainedBytes.ShouldBeGreaterThan(baseline);
sink.Value!.Items.ShouldHaveSingleItem().Sample.Value.GetScalar().ShouldBe(42);
sink.Release();
await sink.ValueDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
try { await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); }
catch (OperationCanceledException) { }
capacity.ActiveOperations.ShouldBe(0);
fixture.Hub.Resources.RetainedBytes.ShouldBe(baseline);
}
}
[Fact(Timeout = 30000)]
public async Task Remove_ack_is_a_barrier_before_readding_the_same_client_item()
{
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(subscriptions: context =>
new LocalSubscriptionService(fixture!.Services, context,
new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity)))
{
fixture.Publish(1);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1),
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),
TestContext.Current.CancellationToken);
await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken);
(await reader.MoveNextAsync()).ShouldBeTrue();
var old = reader.Current.ShouldBeOfType<DataSubscriptionAck>().Items[0].Handle!;
(await reader.MoveNextAsync()).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin);
(await reader.MoveNextAsync()).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionValues>().Dispose();
(await reader.MoveNextAsync()).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotEnd);
HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2);
fixture.Hub.ProcessPending();
fixture.Clock.Advance(TimeSpan.FromSeconds(1));
var remove = subscription.SendAsync(new RemoveSubscriptionItems("s", 1, "remove", TimeSpan.FromSeconds(5), [old]),
TestContext.Current.CancellationToken);
while (true)
{
(await reader.MoveNextAsync()).ShouldBeTrue();
if (reader.Current is DataSubscriptionValues earlier) earlier.Dispose();
if (reader.Current is DataSubscriptionAck { CommandId: "remove" }) break;
}
await remove;
var add = subscription.SendAsync(new AddSubscriptionItems("s", 1, "add", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings)]), TestContext.Current.CancellationToken);
DataItemHandle? replacement = null;
while (replacement is null)
{
(await reader.MoveNextAsync()).ShouldBeTrue();
if (reader.Current is DataSubscriptionValues values)
{
values.Items.ShouldNotContain(x => x.Handle == old);
values.Dispose();
}
if (reader.Current is DataSubscriptionAck { CommandId: "add" } ack)
{
ack.Items[0].Status.ShouldBe(DataItemStatus.Good);
ack.Items[0].Handle.ShouldNotBeNull();
replacement = ack.Items[0].Handle;
}
}
await add;
replacement.Handle.ShouldNotBe(old.Handle);
}
}
[Fact(Timeout = 30000)]
public async Task Changing_the_filter_acknowledges_a_new_revision_before_its_snapshot()
{
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(subscriptions: context =>
new LocalSubscriptionService(fixture!.Services, context,
new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity)))
{
fixture.Publish(10);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
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),
TestContext.Current.CancellationToken);
await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken)
.GetAsyncEnumerator(TestContext.Current.CancellationToken);
(await reader.MoveNextAsync()).ShouldBeTrue();
var original = reader.Current.ShouldBeOfType<DataSubscriptionAck>().Items[0].Handle!;
(await reader.MoveNextAsync()).ShouldBeTrue(); // begin
(await reader.MoveNextAsync()).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionValues>().Dispose();
(await reader.MoveNextAsync()).ShouldBeTrue(); // end
var modified = settings with { Deadband = 5 };
await subscription.SendAsync(new ModifySubscriptionItems("s", 1, "modify", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, modified)]), TestContext.Current.CancellationToken);
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue();
var ack = reader.Current.ShouldBeOfType<DataSubscriptionAck>();
ack.CommandId.ShouldBe("modify");
var replacement = ack.Items.ShouldHaveSingleItem().Handle;
replacement.ShouldNotBeNull();
replacement.ShouldNotBe(original);
(await reader.MoveNextAsync()).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin);
(await reader.MoveNextAsync()).ShouldBeTrue();
using var snapshot = reader.Current.ShouldBeOfType<DataSubscriptionValues>();
snapshot.Items.ShouldHaveSingleItem().Handle.ShouldBe(replacement);
snapshot.Items[0].Sample.Value.GetScalar().ShouldBe(10);
}
}
// #962: a modify that replaces an item is committed on the DELIVERY side (the ack's commit), which releases the
// replaced item's interest group and disposes its SourceInterestLease. A tick already running on the command worker
// may have captured that lease before the commit; reading it afterwards fails exactly like an expired change history,
// and the session used to answer a successful modify with "Reset: Source change history expired.". This holds a tick
// at the capture point, commits the modify under it, then lets the tick read the released lease.
[Fact(Timeout = 30000)]
public async Task Modify_committed_while_a_tick_holds_the_replaced_interest_continues_with_the_replacement_snapshot()
{
var ct = TestContext.Current.CancellationToken;
using var demand = new FirstLeaseReleaseSignalDemand();
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 HeldModifyAckSink();
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.FirstSnapshotEnd.Task.WaitAsync(ct);
var armed = 0;
var tickHolding = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
session.BeforeDirtyTickForTests = (_, _, interests) =>
{
if (interests == 0 || Interlocked.Exchange(ref armed, 0) == 0) return;
tickHolding.TrySetResult(true);
// This tick captured the original item's interest lease; hold it until the modify commit releases it.
demand.FirstReleased.Wait(TimeSpan.FromSeconds(10));
};
await subscription.SendAsync(new ModifySubscriptionItems("s", 1, "modify", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings with { Deadband = 5 })]), ct);
await sink.ModifyAckHeld.Task.WaitAsync(ct); // the ack is in the transport, not yet committed
Volatile.Write(ref armed, 1);
fixture.Clock.Advance(TimeSpan.FromMilliseconds(100)); // the session tick timer queues a tick
await tickHolding.Task.WaitAsync(ct);
demand.FirstReleased.IsSet.ShouldBeFalse(); // positive control: the held tick predates the commit
sink.ReleaseModifyAck();
await Task.WhenAny(sink.SecondSnapshotEnd.Task, writer).WaitAsync(ct);
demand.FirstReleased.IsSet.ShouldBeTrue();
var frames = sink.Frames.ToArray();
var trace = string.Join(" | ", frames);
frames.ShouldNotContain(frame => frame.StartsWith("reset", StringComparison.Ordinal), trace);
var ack = Array.FindIndex(frames, frame => frame.StartsWith("ack:modify:", StringComparison.Ordinal));
ack.ShouldBeGreaterThan(0, trace);
var replacement = frames[ack]["ack:modify:".Length..];
replacement.ShouldNotBe(sink.OriginalHandle);
frames.Skip(ack + 1).Take(3).ShouldBe(["begin", $"snapshot:{replacement}:10", "end"], trace);
}
}
// #966: the modify's replacement item enters _items (and was registered with the delivery scheduler at staging) the
// moment the ack commits on the delivery side, but its snapshot job only reaches the pump on the NEXT tick. A tick
// already past that dequeue which then reads a source change (here from a sibling item on the same source, whose
// interest group survives the modify) marks the source dirty, and the scheduler hands it the replacement's handle.
// Before the fix that emitted a live delta for the replacement ahead of its SnapshotBegin/Snapshot/End.
[Fact(Timeout = 30000)]
public async Task Modify_committed_mid_tick_does_not_emit_a_replacement_delta_before_its_snapshot()
{
var ct = TestContext.Current.CancellationToken;
using var demand = new FirstLeaseReleaseSignalDemand();
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 HeldModifyAckSink();
var writer = subscription.ShouldBeAssignableTo<IDataSubscriptionTransport>().RunDeliveryAsync(sink, ct);
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
// "one" and "two" share a source and one interest group, so the group outlives the modify of "one".
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings), new("two", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30),
LocalDataFixture.Budget), ct);
await sink.FirstSnapshotEnd.Task.WaitAsync(ct);
var armed = 0;
var tickHolding = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
session.BeforeDirtyTickForTests = (_, _, interests) =>
{
if (interests == 0 || Interlocked.Exchange(ref armed, 0) == 0) return;
tickHolding.TrySetResult(true);
// Past this tick's committed-snapshot dequeue: hold it until the modify commits on the delivery side.
demand.FirstReleased.Wait(TimeSpan.FromSeconds(10));
};
await subscription.SendAsync(new ModifySubscriptionItems("s", 1, "modify", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings with { Deadband = 5 })]), ct);
await sink.ModifyAckHeld.Task.WaitAsync(ct); // replacement snapshot captured (10), ack not yet committed
Volatile.Write(ref armed, 1);
fixture.Clock.Advance(TimeSpan.FromMilliseconds(100)); // the session tick timer queues a tick
await tickHolding.Task.WaitAsync(ct);
HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 20); fixture.Hub.ProcessPending(); // a change after the replacement's capture, readable from the surviving group
demand.FirstReleased.IsSet.ShouldBeFalse(); // positive control: the held tick predates the commit
sink.ReleaseModifyAck();
await Task.WhenAny(sink.SecondSnapshotEnd.Task, writer).WaitAsync(ct);
demand.FirstReleased.IsSet.ShouldBeTrue();
var ackIndex = -1;
string? replacement = null;
var deadline = DateTime.UtcNow.AddSeconds(10);
while (true)
{
var frames = sink.Frames.ToArray();
var trace = string.Join(" | ", frames);
frames.ShouldNotContain(frame => frame.StartsWith("reset", StringComparison.Ordinal), trace);
ackIndex = Array.FindIndex(frames, frame => frame.StartsWith("ack:modify:", StringComparison.Ordinal));
ackIndex.ShouldBeGreaterThan(0, trace);
replacement = frames[ackIndex]["ack:modify:".Length..];
replacement.ShouldNotBe(sink.OriginalHandle);
var after = frames.Skip(ackIndex + 1).Where(frame => frame.Contains($":{replacement}:", StringComparison.Ordinal) ||
frame is "begin" or "end").ToArray();
// The replacement's first frames are its snapshot; its live delta (20) only after the snapshot end.
after.Take(3).ShouldBe(["begin", $"snapshot:{replacement}:10", "end"], trace);
// Positive control: the change the guard deferred is not lost; the replacement's own interest delivers it.
if (after.Contains($"value:{replacement}:20")) break;
if (DateTime.UtcNow > deadline) throw new ShouldAssertException("Replacement never delivered 20: " + trace);
fixture.Clock.Advance(TimeSpan.FromMilliseconds(100));
await Task.Delay(20, ct);
}
}
}
[Fact(Timeout = 30000)]
public async Task Quiet_control_only_session_expires_without_renewal_or_further_commands()
{
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)))
{
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
await subscription.SendAsync(new OpenSubscription("watch", 1, "open", TimeSpan.FromSeconds(5), [], true,
TimeSpan.FromSeconds(2), LocalDataFixture.Budget), TestContext.Current.CancellationToken);
await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken)
.GetAsyncEnumerator(TestContext.Current.CancellationToken);
(await reader.MoveNextAsync()).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionAck>().CommandId.ShouldBe("open");
fixture.Clock.Advance(TimeSpan.FromSeconds(2));
await Should.ThrowAsync<InvalidOperationException>(() => subscription.SendAsync(
new AddSubscriptionItems("watch", 1, "late", TimeSpan.FromSeconds(1), []), TestContext.Current.CancellationToken));
(await reader.MoveNextAsync()).ShouldBeFalse();
}
}
[Fact]
public void Removed_handle_never_becomes_current_after_readd()
{
var handles = new SubscriptionItemHandleTable("stream", 1, 4);
var first = handles.Add("item");
handles.IsCurrent(first).ShouldBeTrue();
handles.Remove(first).ShouldBeTrue();
var second = handles.Add("item");
second.Handle.ShouldNotBe(first.Handle);
handles.IsCurrent(first).ShouldBeFalse();
handles.IsCurrent(second).ShouldBeTrue();
}
[Fact]
public void Revision_and_epoch_are_checked_even_if_the_numeric_handle_matches()
{
var handles = new SubscriptionItemHandleTable("stream", 7, 4);
var current = handles.Add("item");
handles.IsCurrent(current with { ItemRevision = current.ItemRevision + 1 }).ShouldBeFalse();
handles.IsCurrent(current with { StreamEpoch = current.StreamEpoch + 1 }).ShouldBeFalse();
handles.IsCurrent(current with { SubscriptionId = "other" }).ShouldBeFalse();
handles.IsCurrent(current).ShouldBeTrue();
}
}
internal sealed class DeferredSubscriptionDemand : ISubscriptionDemandSource
{
private readonly TaskCompletionSource<bool> _accepted = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource<bool> Entered = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly List<SubscriptionAuthorizedView> AuthorizedViews = [];
public async ValueTask<SubscriptionDemandResult> AcquireAsync(SubscriptionAuthorizedView view,
DataSubscriptionSettings settings, CancellationToken cancellationToken)
{
lock (AuthorizedViews) AuthorizedViews.Add(view);
Entered.TrySetResult(true);
await _accepted.Task.WaitAsync(cancellationToken);
return new(DataItemStatus.Good, settings, 1, new NoopLease());
}
internal void Accept() => _accepted.TrySetResult(true);
private sealed class NoopLease : IDisposable { public void Dispose() { } }
}
internal sealed class BlockingFirstLeaseDemand : ISubscriptionDemandSource, IDisposable
{
private readonly ManualResetEventSlim _release = new();
private int _calls;
internal readonly TaskCompletionSource<bool> Entered = new(TaskCreationOptions.RunContinuationsAsynchronously);
public ValueTask<SubscriptionDemandResult> AcquireAsync(SubscriptionAuthorizedView view,
DataSubscriptionSettings settings, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return ValueTask.FromResult(new SubscriptionDemandResult(DataItemStatus.Good, settings, 1,
new Lease(this, Interlocked.Increment(ref _calls) == 1)));
}
internal void Release() => _release.Set();
public void Dispose() { _release.Set(); _release.Dispose(); }
private sealed class Lease(BlockingFirstLeaseDemand owner, bool blocks) : IDisposable
{
public void Dispose()
{
if (!blocks) return;
owner.Entered.TrySetResult(true);
if (!owner._release.Wait(TimeSpan.FromSeconds(5))) throw new TimeoutException();
}
}
}
internal sealed class BlockingValuePreparationSink : IDataSubscriptionDeliverySink
{
internal readonly TaskCompletionSource<bool> Entered = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource<bool> ValueDisposed = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource<bool> _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal int ValueWrites;
public async ValueTask<IDataPreparedSubscriptionDelivery> PrepareAsync(DataSubscriptionFrame frame,
long reservedBytes, CancellationToken cancellationToken)
{
if (frame is DataSubscriptionValues)
{
Entered.TrySetResult(true);
await _release.Task; // intentionally ignores cancellation
}
return new Prepared(frame is DataSubscriptionValues, ValueDisposed);
}
public ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken)
{
if (((Prepared)prepared).Value) Interlocked.Increment(ref ValueWrites);
return ValueTask.CompletedTask;
}
internal void Release() => _release.TrySetResult(true);
private sealed class Prepared(bool value, TaskCompletionSource<bool> disposed) : IDataPreparedSubscriptionDelivery
{
internal bool Value { get; } = value;
public long RetainedBytes => 1;
public void Dispose() { if (Value) disposed.TrySetResult(true); }
}
}
internal sealed class PostPrepareGateSink(PartitionedSampleHub hub, bool blockSnapshot) : IDataSubscriptionDeliverySink
{
private readonly ManualResetEventSlim _release = new();
internal readonly TaskCompletionSource<bool> Entered = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource<bool> SnapshotEnd = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal int BlockedValueWrites;
public ValueTask<IDataPreparedSubscriptionDelivery> PrepareAsync(DataSubscriptionFrame frame, long reservedBytes,
CancellationToken cancellationToken)
{
if (frame is DataSubscriptionValues values && values.IsSnapshot == blockSnapshot)
{
if (blockSnapshot) hub.BeforeSnapshotValidationForTests = Block;
else hub.BeforeReadForTests = _ => Block();
}
return ValueTask.FromResult<IDataPreparedSubscriptionDelivery>(new Prepared(frame));
}
private void Block()
{
hub.BeforeSnapshotValidationForTests = null; hub.BeforeReadForTests = null;
Entered.TrySetResult(true);
if (!_release.Wait(TimeSpan.FromSeconds(5))) throw new TimeoutException();
}
public ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken)
{
var frame = ((Prepared)prepared).Frame;
if (frame is DataSubscriptionValues values && values.IsSnapshot == blockSnapshot)
Interlocked.Increment(ref BlockedValueWrites);
if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }) SnapshotEnd.TrySetResult(true);
return ValueTask.CompletedTask;
}
internal void Release() => _release.Set();
private sealed class Prepared(DataSubscriptionFrame frame) : IDataPreparedSubscriptionDelivery
{
internal DataSubscriptionFrame Frame { get; } = frame;
public long RetainedBytes => 1;
public void Dispose() { }
}
}
internal sealed class SequencedLiveSink : IDataSubscriptionDeliverySink
{
internal readonly TaskCompletionSource<bool> SnapshotEnd = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource<bool> FirstLiveEntered = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource<bool> ProbeAck = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource<bool> Version3Written = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource<bool> Version4Written = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource<bool> Heartbeat = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly System.Collections.Concurrent.ConcurrentQueue<string> Events = new();
private readonly TaskCompletionSource<bool> _releaseFirst = new(TaskCreationOptions.RunContinuationsAsynchronously);
private ulong _firstHandle;
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;
if (frame is DataSubscriptionAck { CommandId: "open" } open) _firstHandle = open.Items[0].Handle!.Handle;
if (frame is DataSubscriptionAck { CommandId: "probe" }) ProbeAck.TrySetResult(true);
if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }) SnapshotEnd.TrySetResult(true);
if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Heartbeat }) Heartbeat.TrySetResult(true);
if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Coalesced }) Events.Enqueue("coalesced");
if (frame is not DataSubscriptionValues { IsSnapshot: false } values || values.Items[0].Handle.Handle != _firstHandle) return;
var version = values.Items[0].Sample.Version;
if (version == 2)
{
FirstLiveEntered.TrySetResult(true);
await _releaseFirst.Task; // intentionally gated transport write
}
Events.Enqueue("value-" + version);
if (version == 3) Version3Written.TrySetResult(true);
if (version == 4) Version4Written.TrySetResult(true);
}
internal void ReleaseFirst() => _releaseFirst.TrySetResult(true);
private sealed class Prepared(DataSubscriptionFrame frame) : IDataPreparedSubscriptionDelivery
{
internal DataSubscriptionFrame Frame { get; } = frame;
public long RetainedBytes => 1;
public void Dispose() { }
}
}
internal sealed class BlockingValueWriteSink : IDataSubscriptionDeliverySink
{
internal readonly TaskCompletionSource<bool> Entered = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource<bool> ValueDisposed = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource<bool> _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal DataSubscriptionValues? Value;
public ValueTask<IDataPreparedSubscriptionDelivery> PrepareAsync(DataSubscriptionFrame frame, long reservedBytes,
CancellationToken cancellationToken) => ValueTask.FromResult<IDataPreparedSubscriptionDelivery>(new Prepared(frame, ValueDisposed));
public async ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken)
{
if (((Prepared)prepared).Frame is not DataSubscriptionValues value) return;
Value = value; Entered.TrySetResult(true);
await _release.Task; // intentionally ignores cancellation after transport handoff
}
internal void Release() => _release.TrySetResult(true);
private sealed class Prepared(DataSubscriptionFrame frame, TaskCompletionSource<bool> disposed) : IDataPreparedSubscriptionDelivery
{
internal DataSubscriptionFrame Frame { get; } = frame;
public long RetainedBytes => 1;
public void Dispose() { if (Frame is DataSubscriptionValues) disposed.TrySetResult(true); }
}
}
internal sealed class CountingSnapshotDemand(int target) : ISubscriptionDemandSource
{
private int _count;
internal readonly TaskCompletionSource Reached = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal void Release() => _release.TrySetResult();
public async ValueTask<SubscriptionDemandResult> AcquireAsync(SubscriptionAuthorizedView view, DataSubscriptionSettings settings, CancellationToken cancellationToken)
{
if (Interlocked.Increment(ref _count) == target) { Reached.TrySetResult(); await _release.Task.WaitAsync(cancellationToken); }
return new SubscriptionDemandResult(DataItemStatus.Good, settings, 1, new Lease());
}
private sealed class Lease : IDisposable { public void Dispose() { } }
}
/// <summary>#962: the first item's demand lease signals when it is disposed (the replaced item's release).</summary>
internal sealed class FirstLeaseReleaseSignalDemand : ISubscriptionDemandSource, IDisposable
{
internal readonly ManualResetEventSlim FirstReleased = new();
private int _calls;
public ValueTask<SubscriptionDemandResult> AcquireAsync(SubscriptionAuthorizedView view,
DataSubscriptionSettings settings, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var lease = new Lease(Interlocked.Increment(ref _calls) == 1 ? FirstReleased : null);
return ValueTask.FromResult(new SubscriptionDemandResult(DataItemStatus.Good, settings, 1, lease));
}
public void Dispose() => FirstReleased.Dispose();
private sealed class Lease(ManualResetEventSlim? released) : IDisposable
{
public void Dispose() => released?.Set();
}
}
/// <summary>#962: records every frame and holds the transport write of the "modify" ack until released.</summary>
internal sealed class HeldModifyAckSink : IDataSubscriptionDeliverySink
{
internal readonly TaskCompletionSource<bool> FirstSnapshotEnd = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource<bool> SecondSnapshotEnd = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource<bool> ModifyAckHeld = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly System.Collections.Concurrent.ConcurrentQueue<string> Frames = new();
internal string? OriginalHandle;
private readonly TaskCompletionSource<bool> _releaseModifyAck = new(TaskCreationOptions.RunContinuationsAsynchronously);
private int _snapshotEnds;
public ValueTask<IDataPreparedSubscriptionDelivery> PrepareAsync(DataSubscriptionFrame frame, long reservedBytes,
CancellationToken cancellationToken) => ValueTask.FromResult<IDataPreparedSubscriptionDelivery>(new Prepared(frame));
public async ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken)
{
switch (((Prepared)prepared).Frame)
{
case DataSubscriptionAck { CommandId: "open" } open:
OriginalHandle = Handle(open.Items[0].Handle);
Frames.Enqueue("ack:open:" + OriginalHandle);
break;
case DataSubscriptionAck { CommandId: "modify" } modify:
ModifyAckHeld.TrySetResult(true);
await _releaseModifyAck.Task.WaitAsync(cancellationToken); // intentionally gated transport write
Frames.Enqueue("ack:modify:" + Handle(modify.Items[0].Handle));
break;
case DataSubscriptionAck other: Frames.Enqueue("ack:" + other.CommandId); break;
case DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotBegin }: Frames.Enqueue("begin"); break;
case DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }:
Frames.Enqueue("end");
(Interlocked.Increment(ref _snapshotEnds) == 1 ? FirstSnapshotEnd : SecondSnapshotEnd).TrySetResult(true);
break;
case DataSubscriptionControl { Kind: DataStreamControlKind.Reset } reset: Frames.Enqueue("reset:" + reset.Diagnostic); break;
case DataSubscriptionControl control: Frames.Enqueue(control.Kind.ToString()); break;
case DataSubscriptionValues values:
foreach (var item in values.Items)
Frames.Enqueue((values.IsSnapshot ? "snapshot:" : "value:") + Handle(item.Handle) + ":" + item.Sample.Value.GetScalar());
break;
}
}
internal void ReleaseModifyAck() => _releaseModifyAck.TrySetResult(true);
private static string Handle(DataItemHandle? handle) =>
handle?.Handle.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "none";
private sealed class Prepared(DataSubscriptionFrame frame) : IDataPreparedSubscriptionDelivery
{
internal DataSubscriptionFrame Frame { get; } = frame;
public long RetainedBytes => 1;
public void Dispose() { }
}
}