using System.Security.Cryptography; using System.Threading.Channels; using Microsoft.Extensions.Logging.Abstractions; using Opc.Ua; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Configuration.Entities; using ZB.MOM.WW.OtOpcUa.Configuration.Enums; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.Core.Authorization; using ZB.MOM.WW.OtOpcUa.OpcUaServer; using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; using BrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest; using ReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest; using ReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult; namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; /// /// A3a (plan §5.4, §5.5): the consumer condition runtime over a scripted origin stream — the per-mapping capacity /// decision before anything is materialised (and the item removed), the snapshot barrier, the host caps, 2,000 conditions /// without MaxProjectionNodes, the version rule (removal bypasses it and forgets the version), the lifetime rule (a /// stream end re-snapshots and never removes; only a complete re-snapshot does), staleness, the mapping gate with a real /// , primary placement from deployed config, and demand with linger. /// [Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "A3")] public sealed class GrpcDataProjectedConditionAccessTests { private const string Connection = "conn-a"; [Fact] public async Task A_total_over_MaxConditions_is_ConditionCapacity_and_its_item_removed_before_materialising_other_mappings_unaffected() { await using var f = new Fixture(("map-a", DataRealm.Raw, 2), ("map-b", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-b", total: 2); stream.Records("map-b", Record(Key("x"), 3), Record(Key("y"), 3)); stream.Begin("map-a", total: 3); // Positive control: the removal is the must-arrive effect of the LAST frame, so every earlier frame was processed. await f.WaitAsync(() => stream.Removed.Count == 1); stream.Removed.Single().ShouldBe(stream.HandleOf("map-a"), "the over-limit item is removed, not held open"); f.Sink.Applied.ShouldBeEmpty("nothing is materialised before the barrier"); stream.Complete("map-b"); await f.WaitAsync(() => f.Sink.Applied.Count == 2); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity); f.Access.MappingStatuses(Connection)!["map-b"].ShouldBe(ProjectedConditionMappingStatus.Complete); f.Sink.Applied.ShouldAllBe(u => u.Placements.All(p => p.MappingId == "map-b")); } [Fact] public async Task Two_thousand_conditions_in_one_mapping_materialise_without_MaxProjectionNodes_and_the_host_cap_rejects_before_materialising() { await using var f = new Fixture(("map-a", DataRealm.Raw, 5000)); f.Mappings.Current[0].Mapping.MaxProjectionNodes = 10; using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-a", total: 2000); stream.Records("map-a", Enumerable.Range(0, 2000).Select(i => Record(Key("k" + i), 3)).ToArray()); stream.Complete("map-a"); await f.WaitAsync(() => f.Sink.Applied.Count == 2000); f.Sink.Applied.Select(u => u.State.ConditionKey).Distinct().Count().ShouldBe(2000); f.Mappings.Current[0].Mapping.MaxProjectionNodes.ShouldBe(10, "conditions have their own budget"); // Host cap: 1,999 conditions' worth of nodes ⇒ the 2,000-condition mapping is rejected at begin. await using var capped = new Fixture(new ProjectedConditionOptions(TimeSpan.FromMilliseconds(200), 1999 * 49, long.MaxValue, TimeSpan.FromMilliseconds(50)), ("map-a", DataRealm.Raw, 5000)); using var cappedDemand = capped.Access.AcquireEventDemand(null); var cappedStream = await capped.NextStreamAsync(); cappedStream.Ack(); cappedStream.Begin("map-a", total: 2000); await capped.WaitAsync(() => cappedStream.Removed.Count == 1 && capped.Access.BarriersCompleted(Connection) == 1); capped.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity); capped.Sink.Applied.ShouldBeEmpty("the barrier (the positive control) passed with nothing to materialise"); } [Fact] public async Task Versions_gate_per_key_but_a_removal_bypasses_the_gate_and_forgets_the_version() { await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-a", total: 1); stream.Records("map-a", Record(Key("x"), 5)); stream.Complete("map-a"); await f.WaitAsync(() => f.Sink.Applied.Count == 1); stream.Records("map-a", Record(Key("x"), 4, message: "stale")); // older ⇒ dropped stream.Records("map-a", Record(Key("x"), 5, removed: true)); // removal at the hub watermark (= an applied version) await f.WaitAsync(() => f.Sink.Removed.Count == 1); f.Sink.Applied.ShouldNotContain(u => u.State.Message == "stale"); stream.Records("map-a", Record(Key("x"), 3, message: "re-added")); // the version was forgotten await f.WaitAsync(() => f.Sink.Applied.Any(u => u.State.Message == "re-added")); } [Fact] public async Task A_stream_end_re_snapshots_without_removing_and_only_a_complete_re_snapshot_removes_staleness_in_between() { // map-b (MaxConditions 0) is the positive control: its begin is refused, which must arrive as an item removal. await using var f = new Fixture(("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 0)); using var demand = f.Access.AcquireEventDemand(null); var first = await f.NextStreamAsync(); first.Ack(); first.Begin("map-b", total: 1); first.Begin("map-a", total: 2); first.Records("map-a", Record(Key("x"), 3), Record(Key("y"), 3)); first.Complete("map-a"); await f.WaitAsync(() => f.Sink.Applied.Count == 2); first.End(); // an origin deploy ends the stream (A2 S1) var second = await f.NextStreamAsync(); await f.WaitAsync(() => f.Sink.Stale.Count >= 1); // stale timeout (100 ms) passes before the new snapshot completes f.Sink.Removed.ShouldBeEmpty("a stream end is never 'conditions removed'"); second.Ack(); second.Begin("map-a", total: 1); second.Records("map-a", Record(Key("x"), 9)); second.Begin("map-b", total: 1); await f.WaitAsync(() => second.Removed.Count == 1); // positive control: every earlier frame was processed f.Sink.Removed.ShouldBeEmpty("an incomplete snapshot removes nothing"); second.Complete("map-a"); await f.WaitAsync(() => f.Sink.Removed.Count == 1); f.Sink.Removed.Single().ShouldBe(Key("y")); f.Access.BarriersCompleted(Connection).ShouldBe(2, "one barrier per stream: the first snapshot and the re-snapshot"); } [Fact] public async Task A_mapping_whose_snapshot_times_out_is_Unavailable_the_rest_proceed_and_RefreshRequired_follows() { await using var f = new Fixture(("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); f.Mappings.Current[0].Mapping.ConditionSnapshotTimeoutMilliseconds = 300; f.Mappings.Current[1].Mapping.ConditionSnapshotTimeoutMilliseconds = 300; using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-b", total: 1); stream.Records("map-b", Record(Key("x"), 3)); stream.Complete("map-b"); await f.WaitAsync(() => f.Sink.Applied.Count == 1); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable); await f.WaitAsync(() => f.Sink.RefreshRequired >= 1); // the barrier applies before it asks for the refresh f.Sink.RefreshRequired.ShouldBe(1); } [Fact] public async Task The_primary_placement_comes_from_deployed_config_Raw_first_then_mapping_id_and_SourceName_follows_it() { await using var f = new Fixture(("map-u", DataRealm.Uns, 10), ("map-z", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(); // Stream order deliberately the reverse of the deployed order. foreach (var mapping in new[] { "map-u", "map-z", "map-b" }) { stream.Begin(mapping, total: 1); stream.Records(mapping, Record(Key("x"), 3, placement: mapping == "map-u" ? f.UnsPlacement : f.RawPlacement)); stream.Complete(mapping); } await f.WaitAsync(() => f.Sink.Applied.Count == 1); var update = f.Sink.Applied.Single(); update.Placements.Select(p => p.MappingId).ShouldBe(["map-b", "map-z", "map-u"]); update.SourceName.ShouldBe("Plant/map-b/dev1/HR200", "the primary mapping's branch path + the address below the remote root"); update.Placements[0].FolderLocalSubject.ShouldBe("Plant/map-b/dev1"); } [Fact] public async Task The_gate_is_the_mapping_Subscribe_grant_on_the_placement_folder_and_needs_the_condition_bits() { await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); var placement = new ImportedConditionPlacement("map-a", DataRealm.Raw, f.RawPlacement, "Plant/map-a/dev1", "dev1/HR200"); f.Grant(NodePermissions.Browse | NodePermissions.Subscribe); f.Access.CanSee(f.Identity("reader"), [placement]).ShouldBeTrue(); f.Access.CanSee(f.Identity("someone-else"), [placement]).ShouldBeFalse(); f.Access.CanSee(null, [placement]).ShouldBeFalse(); f.Grant(NodePermissions.Browse); f.Access.CanSee(f.Identity("reader"), [placement]).ShouldBeFalse("Subscribe is the visibility permission (not AlarmRead)"); f.Grant(NodePermissions.Browse | NodePermissions.Subscribe); f.Mappings.Current[0].Mapping.AllowedOperations = DataOperations.Browse | DataOperations.Subscribe; f.Access.CanSee(f.Identity("reader"), [placement]).ShouldBeFalse("a mapping without AlarmSubscribe carries no conditions"); } [Fact] public async Task Demand_opens_the_stream_and_the_linger_closes_it_and_removes_what_it_materialised() { await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); f.Access.IsRunning(Connection).ShouldBeFalse(); var demand = f.Access.AcquireEventDemand(null)!; var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-a", total: 1); stream.Records("map-a", Record(Key("x"), 3)); stream.Complete("map-a"); await f.WaitAsync(() => f.Sink.Applied.Count == 1); demand.Dispose(); f.Access.IsRunning(Connection).ShouldBeTrue("the linger keeps it open"); await f.WaitAsync(() => !f.Access.IsRunning(Connection) && f.Sink.Removed.Count == 1); } // --------------------------------------------------------------------------------------------------------------------- // Review round 1 (a3a-review-round1.md) // --------------------------------------------------------------------------------------------------------------------- private static async Task CompleteFirstAsync(Fixture f, params (string Mapping, DataConditionState[] Records)[] snapshots) { var stream = await f.NextStreamAsync(); stream.Ack(); foreach (var (mapping, records) in snapshots) { stream.Begin(mapping, records.Length); stream.SnapshotRecords(mapping, records); stream.Complete(mapping); } await f.WaitAsync(() => f.Access.BarriersCompleted(Connection) >= 1); return stream; } [Fact] public async Task B1_an_in_stream_multi_frame_re_snapshot_keeps_every_condition_until_complete_then_removes_only_what_it_dropped() { await using var f = new Fixture(("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3), Record(Key("y"), 3), Record(Key("z"), 3)]), ("map-b", [])); await f.WaitAsync(() => f.Sink.Live.Count == 3); // A2 re-snapshots inside a live stream (hub reader reset, retaken incomplete apply): begin, record frames, complete. stream.Begin("map-a", total: 2); stream.SnapshotRecords("map-a", Record(Key("x"), 4)); stream.SnapshotRecords("map-a", Record(Key("y"), 4)); stream.Records("map-b", Record(Key("ctl"), 1)); // positive control: a delta on the other mapping must be applied await f.WaitAsync(() => f.Sink.Live.Contains(Key("ctl"))); f.Sink.Removed.ShouldBeEmpty("a re-snapshot in progress removes nothing (B1)"); f.Sink.Live.ShouldContain(Key("z")); stream.Complete("map-a"); await f.WaitAsync(() => f.Sink.Removed.Count == 1); f.Sink.Removed.Single().ShouldBe(Key("z"), "only the key the COMPLETE re-snapshot no longer lists is removed"); f.Sink.Live.ShouldBe([Key("x"), Key("y"), Key("ctl")], ignoreOrder: true); } [Fact] public async Task B1_an_in_stream_re_snapshot_over_capacity_removes_the_mapping_once_keeps_keys_another_mapping_lists_and_requires_refresh() { await using var f = new Fixture(("map-a", DataRealm.Raw, 2), ("map-b", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3), Record(Key("y"), 3)]), ("map-b", [Record(Key("y"), 3)])); await f.WaitAsync(() => f.Sink.Live.Count == 2); var refreshes = f.Sink.RefreshRequired; stream.Begin("map-a", total: 3); // the origin now lists more than MaxConditions await f.WaitAsync(() => stream.Removed.Count == 1 && f.Sink.Removed.Count == 1); stream.Removed.Single().ShouldBe(stream.HandleOf("map-a")); f.Sink.Removed.Single().ShouldBe(Key("x"), "y is still listed by map-b"); f.Sink.Live.ShouldBe([Key("y")]); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity); // #931 N7: the removal itself carries RefreshRequired to the holders (the sink's §5.2 "removal + RefreshRequired"), so // the reset does not ask a second time. f.Sink.RefreshRequired.ShouldBe(refreshes, "one RefreshRequired per capacity reset: the removal's"); } private static Fixture TimedFixture(int timeoutMs, params (string Id, DataRealm Realm, int MaxConditions)[] mappings) { var f = new Fixture(mappings); foreach (var m in f.Mappings.Current) m.Mapping.ConditionSnapshotTimeoutMilliseconds = timeoutMs; return f; } [Fact] public async Task B2_a_snapshot_completing_after_the_timeout_is_merged_late_and_the_stream_is_kept() { await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-b", total: 1); stream.Records("map-b", Record(Key("x"), 3)); stream.Complete("map-b"); await f.WaitAsync(() => f.Sink.Applied.Count == 1); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable); stream.Begin("map-a", total: 1); // 2,000 conditions arriving 1 s late, in miniature stream.SnapshotRecords("map-a", Record(Key("w"), 3)); stream.Complete("map-a"); await f.WaitAsync(() => f.Sink.Live.Contains(Key("w"))); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Complete); (await f.TryNextStreamAsync(TimeSpan.FromMilliseconds(900))).ShouldBeNull("a late completion cancels the retry"); } [Fact] public async Task B2_an_incomplete_barrier_marks_the_incomplete_mappings_materialised_keys_BadNoCommunication_never_removed() { await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var first = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)]), ("map-b", [Record(Key("y"), 3)])); await f.WaitAsync(() => f.Sink.Live.Count == 2); first.End(); var second = await f.NextStreamAsync(); second.Ack(); second.Begin("map-b", total: 1); second.SnapshotRecords("map-b", Record(Key("y"), 4)); second.Complete("map-b"); // map-a never answers: the barrier passes at the timeout await f.WaitAsync(() => f.Sink.StaleKeys.Contains(Key("x"))); f.Sink.Removed.ShouldBeEmpty("unknown is not gone"); f.Sink.StaleKeys.ShouldNotContain(Key("y")); f.Sink.RefreshRequired.ShouldBeGreaterThanOrEqualTo(1); } [Fact] public async Task B2_S7_a_refused_item_is_an_incomplete_barrier_RefreshRequired_and_the_stream_is_retried_after_a_bounded_wait() { await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(refused: "map-a"); // e.g. a Secondary that advertises but refuses (A2 N7) stream.Begin("map-b", total: 1); stream.Records("map-b", Record(Key("x"), 3)); stream.Complete("map-b"); await f.WaitAsync(() => f.Sink.Applied.Count == 1); await f.WaitAsync(() => f.Sink.RefreshRequired >= 1); // the barrier applies before it asks for the refresh f.Sink.RefreshRequired.ShouldBe(1, "S7: an incomplete barrier from a non-Good ack also requires refresh"); // #930 N2: the retry is IN-STREAM (the item re-added after the bounded wait) — the stream is not ended for it. await f.WaitAsync(() => stream.AddsOf("map-a") == 1); stream.AckAdd("map-a"); stream.Begin("map-a", total: 1); stream.SnapshotRecords("map-a", Record(Key("w"), 3)); stream.Complete("map-a"); await f.WaitAsync(() => f.Sink.Live.Contains(Key("w"))); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Complete); (await f.TryNextStreamAsync(TimeSpan.FromMilliseconds(300))).ShouldBeNull("no new stream: map-b is never re-snapshotted for map-a"); f.Sink.Applied.Count(u => u.State.ConditionKey == Key("x")).ShouldBe(1, "the healthy mapping's condition is not re-applied"); f.Sink.RefreshRequired.ShouldBe(1, "a recovered mapping needs no second RefreshRequired"); } [Fact] public async Task Deviation9_a_condition_stream_served_by_a_Secondary_is_dropped_and_reopened_on_the_Primary() { await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); f.Connections.Roles.Enqueue("Secondary"); using var demand = f.Access.AcquireEventDemand(null); var secondary = await f.NextStreamAsync(); var primary = await f.NextStreamAsync(); secondary.Disposed.ShouldBeTrue("never opened items on a Secondary"); f.Connections.PrimarySubscribes.ShouldBeGreaterThanOrEqualTo(2, "the Primary-only open is asked for"); primary.Ack(); primary.Begin("map-a", 1); primary.SnapshotRecords("map-a", Record(Key("x"), 3)); primary.Complete("map-a"); await f.WaitAsync(() => f.Sink.Live.Contains(Key("x"))); } [Fact] public async Task S6_a_root_whose_metadata_fails_is_Unavailable_and_its_item_is_not_opened() { await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); f.Connections.MetadataFails.Add(0); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Mappings.ShouldBe(["map-b"]); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable); } [Fact] public async Task B4_the_host_caps_are_node_wide_across_connections() { var options = new ProjectedConditionOptions(TimeSpan.FromMilliseconds(200), 3 * 49, long.MaxValue, TimeSpan.FromMilliseconds(50)); await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10, "conn-a"), ("map-b", DataRealm.Raw, 10, "conn-b")); using var demand = f.Access.AcquireEventDemand(null); var streams = new[] { await f.NextStreamAsync(), await f.NextStreamAsync() }; foreach (var stream in streams) { var mapping = stream.Mappings.Single(); stream.Ack(); stream.Begin(mapping, 2); stream.SnapshotRecords(mapping, Record(Key(mapping + "1"), 3), Record(Key(mapping + "2"), 3)); stream.Complete(mapping); } await f.WaitAsync(() => f.Access.BarriersCompleted("conn-a") == 1 && f.Access.BarriersCompleted("conn-b") == 1); streams.Sum(x => x.Removed.Count).ShouldBe(1, "two connections of 2 cannot both fit a 3-condition node cap"); f.Sink.Live.Count.ShouldBe(2); f.Access.ChargedConditions.ShouldBeLessThanOrEqualTo(3); } [Fact] public async Task B4_admission_is_order_independent_a_later_ordered_begin_arriving_first_still_counts() { var options = new ProjectedConditionOptions(TimeSpan.FromMilliseconds(200), 3 * 49, long.MaxValue, TimeSpan.FromMilliseconds(50)); await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-b", 2); stream.Begin("map-a", 2); await f.WaitAsync(() => stream.Removed.Count == 1); stream.Removed.Single().ShouldBe(stream.HandleOf("map-a"), "the second begin is decided against the first one's claim"); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity); } [Fact] public async Task B4_records_past_the_snapshot_total_reset_the_mapping_to_ConditionCapacity_before_materialising() { await using var f = new Fixture(("map-a", DataRealm.Raw, 100)); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-a", total: 1); stream.SnapshotRecords("map-a", Enumerable.Range(0, 50).Select(i => Record(Key("k" + i), 3)).ToArray()); stream.Complete("map-a"); await f.WaitAsync(() => stream.Removed.Count == 1 && f.Access.BarriersCompleted(Connection) == 1); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity); f.Sink.Applied.ShouldBeEmpty("an origin claiming total 1 cannot materialise 50 (the barrier is the positive control)"); f.Access.ChargedConditions.ShouldBe(0); } [Fact] public async Task B4_post_snapshot_delta_growth_past_MaxConditions_resets_the_mapping_and_removes_its_conditions() { await using var f = new Fixture(("map-a", DataRealm.Raw, 2)); using var demand = f.Access.AcquireEventDemand(null); var stream = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)])); await f.WaitAsync(() => f.Sink.Live.Count == 1); stream.Records("map-a", Record(Key("y"), 3), Record(Key("z"), 3)); await f.WaitAsync(() => stream.Removed.Count == 1 && f.Sink.Removed.Contains(Key("x"))); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity); f.Sink.Live.ShouldBeEmpty(); } [Fact] public async Task S2_an_authority_deactivation_moves_the_authority_generation_so_cached_verdicts_are_re_proved() { await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); var before = f.Access.AuthorityGeneration; ((ActiveAuthority)f.Mappings.Current[0].Authority).Active = false; // no deploy, no epoch change f.Access.AuthorityGeneration.ShouldNotBe(before); } [Fact] public async Task S3_a_new_runner_waits_for_the_old_runners_removal_so_a_re_materialised_key_survives() { await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); var demand = f.Access.AcquireEventDemand(null)!; await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)])); await f.WaitAsync(() => f.Sink.Live.Count == 1); var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); f.Sink.RemovalGate = gate; // hold the old runner's removal open demand.Dispose(); await f.WaitAsync(() => !f.Access.IsRunning(Connection)); // linger expired; its removal is now blocked in the sink using var again = f.Access.AcquireEventDemand(null); _ = Task.Delay(400, TestContext.Current.CancellationToken).ContinueWith(_ => gate.TrySetResult(), TaskScheduler.Default); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-a", 1); stream.SnapshotRecords("map-a", Record(Key("x"), 4)); stream.Complete("map-a"); await f.WaitAsync(() => f.Sink.Removed.Count == 1 && f.Sink.Applied.Count == 2); f.Sink.Live.ShouldContain(Key("x"), "the old runner's removal must not land after the new runner materialised the key"); } [Fact] public async Task S4_a_mapping_change_hands_the_materialised_set_over_after_the_old_loop_stopped() { await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)])); await f.WaitAsync(() => f.Sink.Live.Count == 1); f.Mappings.Current[0].Mapping.MaxConditions = 11; // a changed signature ⇒ a new runner, a new stream f.Mappings.Raise(); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-a", 1); stream.SnapshotRecords("map-a", Record(Key("y"), 3)); stream.Complete("map-a"); await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x"))); f.Sink.Live.ShouldBe([Key("y")], "x was handed over (not orphaned) and the new complete set removed it"); } [Fact] public async Task N1_demand_cycles_and_mapping_changes_do_not_chain_runners_so_an_old_runner_is_collectable() { // Verification review r2 N1: each runner kept its predecessor (and that one's record sets), so every linger expiry // + re-subscribe or mapping change added a link R3 → R2 → R1 and memory grew without bound. await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); var demand = f.Access.AcquireEventDemand(null)!; await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)])); var first = f.Access.RunnerReference(Connection)!; var version = 3L; for (var cycle = 0; cycle < 3; cycle++) { demand.Dispose(); await f.WaitAsync(() => !f.Access.IsRunning(Connection)); // linger expired demand = f.Access.AcquireEventDemand(null)!; await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), ++version)])); } for (var change = 0; change < 2; change++) { f.Mappings.Current[0].Mapping.MaxConditions++; // a changed signature ⇒ a new runner, a new stream f.Mappings.Raise(); await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), ++version)])); } f.Sink.Live.ShouldBe([Key("x")], "the hand-over still works across every cycle"); for (var i = 0; i < 3; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } first.IsAlive.ShouldBeFalse("the current runner must not keep a chain of predecessors reachable"); demand.Dispose(); } // --------------------------------------------------------------------------------------------------------------------- internal static string Key(string seed) => Convert.ToBase64String(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(seed))).TrimEnd('=').Replace('+', '-').Replace('/', '_'); private static DataConditionState Record(string key, long version, bool removed = false, string message = "high", DataView? placement = null) { var info = removed ? null : new DataConditionInfo("AlarmConditionType", "HR200", DataConditionSourceKind.Native, [placement ?? Fixture.DefaultRawPlacement], 3); return new DataConditionState(key, version, removed, !removed, info, true, false, true, true, 0, 500, message, 0, null, 0, DateTimeOffset.UtcNow, true, new DataActivationMarker("inc", 1)); } // --------------------------------------------------------------------------------------------------------------------- // #930 (N2/N3) and #931 (N4/N5/N7/N8) — A4 // --------------------------------------------------------------------------------------------------------------------- private static Fixture LongRetryFixture(TimeSpan longRetry, int timeoutMs, params (string Id, DataRealm Realm, int MaxConditions)[] mappings) { var f = new Fixture(Fixture.DefaultOptions with { LongRetryDelay = longRetry }, mappings); foreach (var m in f.Mappings.Current) m.Mapping.ConditionSnapshotTimeoutMilliseconds = timeoutMs; return f; } [Fact] public async Task N2_a_definitive_refusal_waits_the_long_backoff_on_the_open_stream_never_storming_the_healthy_mapping() { await using var f = LongRetryFixture(TimeSpan.FromSeconds(30), 300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(DataItemStatus.Denied, "map-a"); stream.Begin("map-b", total: 1); stream.Records("map-b", Record(Key("x"), 3)); stream.Complete("map-b"); await f.WaitAsync(() => f.Sink.Applied.Count == 1); // A transient refusal would be retried after the 300 ms snapshot timeout (and, before #930, the stream ended for it). (await f.TryNextStreamAsync(TimeSpan.FromSeconds(1.5))).ShouldBeNull("the stream is kept"); stream.AddsOf("map-a").ShouldBe(0, "Denied is definitive: the long backoff, not the snapshot timeout"); f.Sink.Applied.Count.ShouldBe(1, "map-b is not re-snapshotted"); f.Sink.RefreshRequired.ShouldBe(1); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable); } [Fact] public async Task N2_an_unchanged_incomplete_set_on_a_new_stream_sends_no_second_RefreshRequired_a_changed_one_does() { await using var f = LongRetryFixture(TimeSpan.FromSeconds(30), 300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var first = await f.NextStreamAsync(); first.Ack(DataItemStatus.Denied, "map-a"); first.Begin("map-b", total: 1); first.Records("map-b", Record(Key("x"), 3)); first.Complete("map-b"); await f.WaitAsync(() => f.Sink.RefreshRequired == 1); first.End(); var second = await f.NextStreamAsync(); second.Ack(DataItemStatus.Denied, "map-a"); // still refused: the same incomplete set second.Begin("map-b", total: 1); second.SnapshotRecords("map-b", Record(Key("x"), 4)); second.Complete("map-b"); await f.WaitAsync(() => f.Access.BarriersCompleted(Connection) == 2); f.Sink.RefreshRequired.ShouldBe(1, "the clients were already told about map-a"); second.End(); var third = await f.NextStreamAsync(); third.Ack(DataItemStatus.Denied, "map-a", "map-b"); // a changed incomplete set ⇒ told again (positive control) // The barrier count moves before the barrier's RefreshRequired, so wait for the refresh itself. It is also the positive // control for the second stream's absence: had that barrier asked, this would read 3. await f.WaitAsync(() => f.Sink.RefreshRequired >= 2); await Task.Delay(100, TestContext.Current.CancellationToken); f.Sink.RefreshRequired.ShouldBe(2); } [Fact] public async Task N3_a_ConditionCapacity_mapping_is_re_added_in_stream_on_the_long_timer_and_recovers_when_under_its_limit() { await using var f = LongRetryFixture(TimeSpan.FromMilliseconds(400), 30_000, ("map-a", DataRealm.Raw, 2), ("map-b", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-a", total: 3); // over its MaxConditions stream.Begin("map-b", total: 1); stream.SnapshotRecords("map-b", Record(Key("x"), 3)); stream.Complete("map-b"); await f.WaitAsync(() => f.Sink.Live.Contains(Key("x"))); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity); await f.WaitAsync(() => stream.AddsOf("map-a") == 1); stream.AckAdd("map-a"); stream.Begin("map-a", total: 2); // the origin dropped back under the limit stream.SnapshotRecords("map-a", Record(Key("y"), 3), Record(Key("z"), 3)); stream.Complete("map-a"); await f.WaitAsync(() => f.Sink.Live.Contains(Key("y")) && f.Sink.Live.Contains(Key("z"))); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Complete); (await f.TryNextStreamAsync(TimeSpan.FromMilliseconds(300))).ShouldBeNull("recovered on the open stream"); } [Fact] public async Task N3_a_retry_still_over_capacity_stays_ConditionCapacity_and_is_retried_again_never_removing_what_another_mapping_lists() { await using var f = LongRetryFixture(TimeSpan.FromMilliseconds(300), 30_000, ("map-a", DataRealm.Raw, 1), ("map-b", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-a", total: 2); stream.Begin("map-b", total: 1); stream.SnapshotRecords("map-b", Record(Key("x"), 3)); stream.Complete("map-b"); await f.WaitAsync(() => stream.AddsOf("map-a") == 1); stream.AckAdd("map-a"); stream.Begin("map-a", total: 2); await f.WaitAsync(() => stream.AddsOf("map-a") == 2); // backoff doubled, still in-stream // A4 review r1 B1: the second capacity reset's remove used the first one's command id, which the transport refuses // (the FakeStream now does too), ending the stream. f.Connections.Streams.Reader.TryPeek(out _).ShouldBeFalse("both capacity resets stayed on the open stream"); lock (stream.Removed) stream.Removed.Count.ShouldBe(2, "each reset removed its item"); f.Sink.Removed.ShouldBeEmpty("map-b's key is never removed by map-a's retries (T2)"); f.Sink.Live.ShouldBe([Key("x")]); } [Fact] public async Task N4_streams_that_never_reach_a_barrier_back_off_exponentially() { var options = Fixture.DefaultOptions with { MaxReconnectDelay = TimeSpan.FromMilliseconds(400) }; await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10)); f.Connections.MetadataFails.Add(0); // every mapping's root fails ⇒ every stream ends before a barrier using var demand = f.Access.AcquireEventDemand(null); await Task.Delay(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken); var calls = Volatile.Read(ref f.Connections.MetadataCalls); calls.ShouldBeGreaterThan(2, "it keeps retrying"); // Fixed 50 ms reconnects would make ~40 attempts in 2 s; 50, 100, 200, 400, 400… makes ≤ ~8. calls.ShouldBeLessThan(12); } [Fact] public async Task N5_held_stale_keys_are_charged_beside_a_known_mappings_new_claim_but_overlap_an_unknown_mappings() { var options = Fixture.DefaultOptions with { MaxImportedConditionNodes = 3 * 49 }; // 3 conditions on the node await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); foreach (var m in f.Mappings.Current) m.Mapping.ConditionSnapshotTimeoutMilliseconds = 300; f.Mappings.Current[0].Mapping.ConditionStaleTimeoutMilliseconds = 60_000; f.Mappings.Current[1].Mapping.ConditionStaleTimeoutMilliseconds = 60_000; using var demand = f.Access.AcquireEventDemand(null); var first = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3), Record(Key("y"), 3)]), ("map-b", [Record(Key("z"), 3)])); await f.WaitAsync(() => f.Sink.Live.Count == 3); first.End(); var second = await f.NextStreamAsync(); second.Ack(); second.Begin("map-b", total: 1); second.SnapshotRecords("map-b", Record(Key("z"), 4)); second.Complete("map-b"); // map-a never answers: x, y held stale (unlisted) await f.WaitAsync(() => f.Sink.StaleKeys.Contains(Key("x"))); // map-b (known) now re-lists z plus a new w: 4 conditions would be held — over the 3-condition cap. second.Begin("map-b", total: 2); await f.WaitAsync(() => f.Access.MappingStatuses(Connection)!["map-b"] == ProjectedConditionMappingStatus.ConditionCapacity); f.Sink.Live.ShouldNotContain(Key("w")); f.Sink.Removed.ShouldBeEmpty("map-a is unknown: nothing is removed (T2)"); } [Fact] public async Task N8_a_stopped_runner_is_not_kept_parked_after_its_removal_finished() { await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); var demand = f.Access.AcquireEventDemand(null)!; var stream = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)])); await f.WaitAsync(() => f.Sink.Live.Count == 1); demand.Dispose(); await f.WaitAsync(() => !f.Access.IsRunning(Connection) && f.Sink.Removed.Count == 1); await f.WaitAsync(() => !f.Access.IsParked(Connection)); f.Access.RunnerReference(Connection).ShouldBeNull("a connection that never returns pins no runner"); stream.Disposed.ShouldBeTrue(); } [Fact] public async Task A4_consumer_diagnostics_show_stream_state_snapshot_time_counts_vs_limits_capacity_and_state_unknown() { await using var f = LongRetryFixture(TimeSpan.FromMinutes(10), 30_000, ("map-a", DataRealm.Raw, 2), ("map-b", DataRealm.Raw, 10)); var idle = f.Access.Diagnostics.CaptureConsumer(Connection).ShouldNotBeNull(); idle.StreamState.ShouldBe("idle"); idle.Mappings.Select(x => x.MappingId).ShouldBe(["map-a", "map-b"]); f.Access.Diagnostics.CaptureConsumer("not-a-condition-connection").ShouldBeNull(); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-a", total: 3); // over its MaxConditions of 2 stream.Begin("map-b", total: 2); stream.SnapshotRecords("map-b", Record(Key("x"), 3), Record(Key("y"), 3) with { StateKnown = false }); stream.Complete("map-b"); await f.WaitAsync(() => f.Sink.Live.Count == 2); var live = f.Access.Diagnostics.CaptureConsumer(Connection).ShouldNotBeNull(); live.StreamState.ShouldBe("live"); live.SnapshotAtUtc.ShouldNotBeNull(); (live.Materialised, live.StateUnknown, live.CapacityRejections).ShouldBe((2, 1, 1L)); live.Mappings.ShouldBe([new ZB.MOM.WW.OtOpcUa.Commons.Interfaces.ConditionMappingDiagnostics("map-a", "ConditionCapacity", 3, 2), new ZB.MOM.WW.OtOpcUa.Commons.Interfaces.ConditionMappingDiagnostics("map-b", "Complete", 2, 10)]); live.ChargedConditions.ShouldBe(2); live.HostConditionLimit.ShouldBe(122_500 / 49); } // --------------------------------------------------------------------------------------------------------------------- // A4 review round 1 (S1–S4, NITs). B1 is pinned by the FakeStream's command-id uniqueness rule (it made // N3_a_retry_still_over_capacity… red) plus the no-new-stream assertion there. // --------------------------------------------------------------------------------------------------------------------- [Fact] public async Task R1_S1_a_retry_snapshot_slower_than_the_timeout_still_completes_late_on_the_open_stream() { await using var f = LongRetryFixture(TimeSpan.FromSeconds(30), 500, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(DataItemStatus.Unavailable, "map-a"); // transient ⇒ retried after the snapshot timeout stream.Begin("map-b", total: 1); stream.SnapshotRecords("map-b", Record(Key("x"), 3)); stream.Complete("map-b"); await f.WaitAsync(() => stream.AddsOf("map-a") == 1); stream.AckAdd("map-a"); stream.Begin("map-a", total: 2); stream.SnapshotRecords("map-a", Record(Key("y"), 3)); // The retry's deadline passes with the listing half delivered … await f.WaitAsync(() => f.Access.MappingStatuses(Connection)!["map-a"] == ProjectedConditionMappingStatus.Unavailable); // … and the rest arrives before the next retry (2× the timeout later): the late completion is taken. stream.SnapshotRecords("map-a", Record(Key("z"), 3)); stream.Complete("map-a"); await f.WaitAsync(() => f.Sink.Live.Contains(Key("y")) && f.Sink.Live.Contains(Key("z"))); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Complete); stream.AddsOf("map-a").ShouldBe(1, "no restart was needed"); } [Fact] public async Task R1_S2_a_late_ack_of_a_superseded_retry_removes_the_orphaned_origin_item_and_the_mapping_recovers() { await using var f = LongRetryFixture(TimeSpan.FromSeconds(30), 300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(DataItemStatus.Unavailable, "map-a"); stream.Begin("map-b", total: 1); stream.SnapshotRecords("map-b", Record(Key("x"), 3)); stream.Complete("map-b"); await f.WaitAsync(() => stream.AddsOf("map-a") == 1); // retry #1: its ack is slow await f.WaitAsync(() => stream.AddsOf("map-a") == 2); // #1 declared timed out; retry #2 replaced its command var orphan = stream.AckAddAt("map-a", 0); // the origin did open #1 — acked late await f.WaitAsync(() => { lock (stream.Removed) return stream.Removed.Contains(orphan); }); stream.AckAdd("map-a", DataItemStatus.InvalidArgument); // #2 reached the origin while #1 was open: duplicate await f.WaitAsync(() => stream.AddsOf("map-a") == 3); // the orphan is gone, so the next re-add is accepted stream.AckAdd("map-a"); stream.Begin("map-a", total: 1); stream.SnapshotRecords("map-a", Record(Key("y"), 3)); stream.Complete("map-a"); await f.WaitAsync(() => f.Sink.Live.Contains(Key("y"))); f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Complete); f.Connections.Streams.Reader.TryPeek(out _).ShouldBeFalse("recovered on the open stream"); } [Fact] public async Task R1_S2_consecutive_InvalidArgument_refusals_of_in_stream_re_adds_end_the_stream_as_a_backstop() { await using var f = LongRetryFixture(TimeSpan.FromSeconds(30), 200, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(DataItemStatus.Unavailable, "map-a"); stream.Begin("map-b", total: 1); stream.SnapshotRecords("map-b", Record(Key("x"), 3)); stream.Complete("map-b"); for (var i = 1; i < ProjectedConditionAccess.MaxInvalidArgumentRefusals; i++) { await f.WaitAsync(() => stream.AddsOf("map-a") == i); stream.AckAdd("map-a", DataItemStatus.InvalidArgument); } await f.WaitAsync(() => stream.AddsOf("map-a") == ProjectedConditionAccess.MaxInvalidArgumentRefusals); f.Connections.Streams.Reader.TryPeek(out _).ShouldBeFalse("fewer refusals keep the stream"); stream.AckAdd("map-a", DataItemStatus.InvalidArgument); (await f.TryNextStreamAsync(TimeSpan.FromSeconds(5))).ShouldNotBeNull("the origin holds an item we lost: only a new stream clears it"); } [Fact] public async Task R1_S3_another_mappings_held_stale_keys_are_not_overlap_for_a_mapping_that_never_listed_them() { var options = Fixture.DefaultOptions with { MaxImportedConditionNodes = 3 * 49 }; // 3 conditions on the node await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10), ("map-c", DataRealm.Raw, 10)); foreach (var m in f.Mappings.Current) { m.Mapping.ConditionSnapshotTimeoutMilliseconds = 300; m.Mapping.ConditionStaleTimeoutMilliseconds = 60_000; } using var demand = f.Access.AcquireEventDemand(null); var first = await CompleteFirstAsync(f, ("map-a", []), ("map-c", [Record(Key("x"), 3), Record(Key("y"), 3)])); await f.WaitAsync(() => f.Sink.Live.Count == 2); first.End(); var second = await f.NextStreamAsync(); second.Ack(DataItemStatus.Denied, "map-c"); // map-c's x, y are held stale (unknown ≠ gone) // map-a never listed x or y: its 2 new keys + the 2 held would be 4 on a 3-condition node. second.Begin("map-a", total: 2); await f.WaitAsync(() => f.Access.MappingStatuses(Connection)!["map-a"] == ProjectedConditionMappingStatus.ConditionCapacity); f.Sink.Live.Count.ShouldBe(2); f.Sink.Removed.ShouldBeEmpty("map-c is unknown: nothing is removed (T2)"); } [Fact] public async Task R1_S4_SourceName_stays_on_the_deployed_primary_while_it_is_unavailable_and_moves_only_when_its_listing_changes() { await using var f = LongRetryFixture(TimeSpan.FromSeconds(30), 300, ("map-r", DataRealm.Raw, 10), ("map-u", DataRealm.Uns, 10)); foreach (var m in f.Mappings.Current) m.Mapping.ConditionStaleTimeoutMilliseconds = 60_000; using var demand = f.Access.AcquireEventDemand(null); var first = await CompleteFirstAsync(f, ("map-r", [Record(Key("x"), 3)]), ("map-u", [Record(Key("x"), 3, placement: f.UnsPlacement)])); await f.WaitAsync(() => f.Sink.Applied.Count >= 1); var rawName = f.Sink.Applied.Last().SourceName; rawName.ShouldStartWith("Plant/map-r/"); first.End(); var second = await f.NextStreamAsync(); second.Ack(DataItemStatus.Denied, "map-r"); // a runtime refusal, not a deployed-config change second.Begin("map-u", total: 1); second.SnapshotRecords("map-u", Record(Key("x"), 4, placement: f.UnsPlacement)); second.Complete("map-u"); await f.WaitAsync(() => f.Sink.Applied.Any(u => u.State.Version == 4)); var held = f.Sink.Applied.Last(u => u.State.Version == 4); held.Placements.Select(p => p.MappingId).ShouldBe(["map-u"], "only the contributing placement is materialised"); held.SourceName.ShouldBe(rawName, "SourceName does not follow a runtime refusal"); second.End(); // Positive control: once the Raw mapping is known again and no longer lists x, SourceName moves. var third = await f.NextStreamAsync(); third.Ack(); third.Begin("map-r", total: 0); third.Complete("map-r"); third.Begin("map-u", total: 1); third.SnapshotRecords("map-u", Record(Key("x"), 5, placement: f.UnsPlacement)); third.Complete("map-u"); await f.WaitAsync(() => f.Sink.Applied.Any(u => u.State.Version == 5)); f.Sink.Applied.Last(u => u.State.Version == 5).SourceName.ShouldStartWith("Plant/map-u/"); } [Fact] public async Task R1_NIT_consumer_resyncs_count_streams_that_opened_not_failed_connect_attempts() { var options = Fixture.DefaultOptions with { MaxReconnectDelay = TimeSpan.FromMilliseconds(100) }; await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10)); f.Connections.MetadataFails.Add(0); // every attempt ends before a stream opens using (f.Access.AcquireEventDemand(null)) { await f.WaitAsync(() => Volatile.Read(ref f.Connections.MetadataCalls) >= 4); f.Access.Diagnostics.CaptureConsumer(Connection)!.Resyncs.ShouldBe(0); } await using var g = new Fixture(("map-a", DataRealm.Raw, 10)); // positive control: an opened stream that ends counts using var demand = g.Access.AcquireEventDemand(null); var stream = await CompleteFirstAsync(g, ("map-a", [Record(Key("x"), 3)])); stream.End(); await g.WaitAsync(() => g.Access.Diagnostics.CaptureConsumer(Connection)!.Resyncs >= 1); } /// /// A4 F1–F3 (live gate): every deploy begins a catalog attempt whose mapping set is EMPTY until it completes. The consumer /// used to treat that as "connection removed": every imported condition was removed and re-created after the deploy (a /// fresh node ⇒ a phantom event per condition, an origin transition delivered twice, new EventIds with the old ones /// BadEventIdUnknown). The conditions are now held across the attempt and handed to the next runner; only a SETTLED set /// without the connection removes them. /// [Fact] public async Task F1_a_deploys_empty_suspended_mapping_set_holds_the_conditions_and_only_a_settled_set_without_the_connection_removes_them() { await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)])); await f.WaitAsync(() => f.Sink.Live.Count == 1); var placements = f.Mappings.Current.ToList(); var list = (List)f.Mappings.Current; // A deploy: AttemptBegan (empty + suspended) … AttemptCompleted (the same placements, settled). list.Clear(); f.Mappings.Suspended = true; f.Mappings.Raise(); await f.WaitAsync(() => !f.Access.IsRunning(Connection)); list.AddRange(placements); f.Mappings.Suspended = false; f.Mappings.Raise(); var stream = await f.NextStreamAsync(); stream.Ack(); stream.Begin("map-a", 1); stream.SnapshotRecords("map-a", Record(Key("x"), 3)); stream.Complete("map-a"); await f.WaitAsync(() => f.Access.BarriersCompleted(Connection) >= 1 && f.Sink.Applied.Count >= 2); // positive control: re-snapshot applied f.Sink.Removed.ShouldBeEmpty("a deploy's undecided empty set is not a removal"); f.Sink.Live.ShouldBe([Key("x")]); // A deploy whose settled set no longer has the connection DOES remove (after the hold). list.Clear(); f.Mappings.Suspended = true; f.Mappings.Raise(); await f.WaitAsync(() => !f.Access.IsRunning(Connection)); f.Sink.Removed.ShouldBeEmpty(); f.Mappings.Suspended = false; f.Mappings.Raise(); await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x"))); f.Sink.Live.ShouldBeEmpty(); } [Fact] public async Task R1_NIT_consumer_counters_of_a_removed_connection_are_pruned() { await using var f = LongRetryFixture(TimeSpan.FromSeconds(30), 300, ("map-a", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); var stream = await f.NextStreamAsync(); stream.Ack(DataItemStatus.Denied, "map-a"); await f.WaitAsync(() => f.Sink.RefreshRequired >= 1); f.Access.Diagnostics.HasConsumerCounters(Connection).ShouldBeTrue(); ((List)f.Mappings.Current).Clear(); f.Mappings.Raise(); f.Access.Diagnostics.HasConsumerCounters(Connection).ShouldBeFalse(); } private sealed class Fixture : IAsyncDisposable { internal static readonly DataView DefaultRawPlacement = new(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant/dev1/HR200"), DataRealm.Raw, null, 0, "Plant/dev1/HR200"); public DataView RawPlacement => DefaultRawPlacement; public DataView UnsPlacement { get; } = new(new DataAddress("origin", "https://zb.com/otopcua/uns", "string", "Area/Line/Filler/HR200"), DataRealm.Uns, null, 0, "Area/Line/Filler/HR200"); private readonly DataPlaneAuthorityState _state = new(); private readonly ApiKey _key = new() { ApiKeyId = "key-a", Name = "key-a", Principal = "reader", SecretHash = "hash", Enabled = true, ExpiresUtc = DateTime.UtcNow.AddHours(1) }; public FakeMappings Mappings { get; } public FakeSink Sink { get; } = new(); public FakeConnections Connections { get; } = new(); public ProjectedConditionAccess Access { get; } public Fixture(params (string Id, DataRealm Realm, int MaxConditions)[] mappings) : this(DefaultOptions, mappings) { } public static ProjectedConditionOptions DefaultOptions => new(TimeSpan.FromMilliseconds(200), 122_500, long.MaxValue, TimeSpan.FromMilliseconds(50)); public Fixture(ProjectedConditionOptions options, params (string Id, DataRealm Realm, int MaxConditions)[] mappings) : this(options, mappings.Select(m => (m.Id, m.Realm, m.MaxConditions, Connection)).ToArray()) { } public Fixture(ProjectedConditionOptions options, params (string Id, DataRealm Realm, int MaxConditions, string Connection)[] mappings) { Grant(NodePermissions.Browse | NodePermissions.Subscribe); Mappings = new FakeMappings(mappings.Select(m => Placement(m.Id, m.Realm, m.MaxConditions, m.Connection)).ToList()); var policy = new DataOperationPolicy(_state, new TriePermissionEvaluator(_state.Tries, TimeProvider.System), TimeProvider.System); Access = new ProjectedConditionAccess(Mappings, Connections, policy, () => Sink, TimeProvider.System, options, NullLogger.Instance); } public void Grant(NodePermissions permissions) => _state.Apply("c1", "rev-" + (int)permissions, [_key], [new NodeAcl { NodeAclId = "acl", ClusterId = "c1", Principal = "reader", ScopeKind = NodeAclScopeKind.RawFolder, ScopeId = "folder", PermissionFlags = permissions }], new Dictionary> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant"])] }); public RoleCarryingUserIdentity Identity(string principal) => new(new UserNameIdentityToken { UserName = "apikey" }, [], principal, _key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(_key), DateTimeOffset.UtcNow.AddMinutes(5)); private static ProjectedMappingPlacement Placement(string id, DataRealm realm, int maxConditions, string connection) { var mapping = new RemoteNamespaceMapping { RemoteNamespaceMappingId = id, DataConnectionId = connection, Enabled = true, Realm = realm, RemoteRealm = realm, AllowedOperations = DataOperations.Browse | DataOperations.Subscribe | DataOperations.AlarmSubscribe, MaxConditions = maxConditions, ConditionStaleTimeoutMilliseconds = 100, ConditionSnapshotTimeoutMilliseconds = 30_000, BranchName = id, RemoteNamespaceUri = realm == DataRealm.Raw ? "https://zb.com/otopcua/raw" : "https://zb.com/otopcua/uns", RemoteIdentifierKind = "string", RemoteIdentifier = realm == DataRealm.Raw ? "Plant" : "Area", }; var segments = new[] { "Plant", id }; var anchor = new DataView(new DataAddress("origin", mapping.RemoteNamespaceUri, "string", mapping.RemoteIdentifier), realm, id, 1, string.Join('/', segments)); var scope = new NodeScope { ClusterId = "c1", Kind = realm == DataRealm.Raw ? NodeHierarchyKind.Raw : NodeHierarchyKind.Uns, Segments = segments }; return new ProjectedMappingPlacement(mapping, anchor, anchor, scope, ["local-parent"], new ActiveAuthority()); } public async Task NextStreamAsync() => await Connections.Streams.Reader.ReadAsync(TestContext.Current.CancellationToken); /// The next stream within , or null. public async Task TryNextStreamAsync(TimeSpan within) { using var cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); cts.CancelAfter(within); try { return await Connections.Streams.Reader.ReadAsync(cts.Token); } catch (OperationCanceledException) when (!TestContext.Current.CancellationToken.IsCancellationRequested) { return null; } } public async Task WaitAsync(Func condition) { var deadline = DateTime.UtcNow.AddSeconds(10); while (!condition()) { if (DateTime.UtcNow > deadline) condition().ShouldBeTrue("condition not met within 10 s"); await Task.Delay(20, TestContext.Current.CancellationToken); } } public ValueTask DisposeAsync() { Access.Dispose(); return ValueTask.CompletedTask; } } private sealed class ActiveAuthority : IDataMappedCatalogAuthority { public long CatalogEpoch => 1; public long AuthorityEpoch => 1; public bool Active { get; set; } = true; public bool IsActive => Active; } internal sealed class FakeMappings(List current) : IProjectedConditionMappings { public IReadOnlyList Current { get; } = current; public event Action? Changed; public void Raise() => Changed?.Invoke(); /// A4 F1–F3: a catalog attempt in progress (its Current is the undecided empty set). public bool Suspended { get; set; } } internal sealed class FakeSink : IProjectedConditionSink { private readonly object _gate = new(); private readonly List _applied = []; private readonly List _removed = []; private readonly List _stale = []; private readonly List _staleKeys = []; private readonly HashSet _live = new(StringComparer.Ordinal); private int _refresh; public IReadOnlyList Applied { get { lock (_gate) return _applied.ToList(); } } public IReadOnlyList Removed { get { lock (_gate) return _removed.ToList(); } } public IReadOnlyList Stale { get { lock (_gate) return _stale.ToList(); } } public IReadOnlyList StaleKeys { get { lock (_gate) return _staleKeys.ToList(); } } /// The keys the sink holds right now (applied minus removed). public IReadOnlyCollection Live { get { lock (_gate) return _live.ToList(); } } public int RefreshRequired => Volatile.Read(ref _refresh); /// When set, a removal blocks until released (the S3 race window, held open). public TaskCompletionSource? RemovalGate { get; set; } public void ApplyConditions(IReadOnlyList updates) { lock (_gate) { _applied.AddRange(updates); foreach (var u in updates) _live.Add(u.State.ConditionKey); } } public void RemoveConditions(string connectionId, IReadOnlyCollection conditionKeys) { RemovalGate?.Task.Wait(TimeSpan.FromSeconds(10)); lock (_gate) { _removed.AddRange(conditionKeys); foreach (var k in conditionKeys) _live.Remove(k); } } public void MarkConnectionStale(string connectionId) { lock (_gate) _stale.Add(connectionId); } public void MarkConditionsStale(string connectionId, IReadOnlyCollection conditionKeys) { lock (_gate) _staleKeys.AddRange(conditionKeys); } public void RequireRefresh(string connectionId) => Interlocked.Increment(ref _refresh); } internal sealed class FakeConnections : IGrpcDataAdapterConnectionSource { public Channel Streams { get; } = Channel.CreateUnbounded(); /// Metadata answers Bad for these root indexes (deployed order). public HashSet MetadataFails { get; } = []; /// #931 N4: metadata requests made (one per stream attempt, plus in-stream root retries). public int MetadataCalls; /// The serving roles of the next streams (Primary when empty). public Queue Roles { get; } = new(); public int PrimarySubscribes; public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken) => ValueTask.FromResult(new Lease(new FakeConnection(this))); private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease { public IDataConnection Connection => connection; public CancellationToken CancellationToken => CancellationToken.None; public ValueTask DisposeAsync() => ValueTask.CompletedTask; } } private sealed class FakeConnection(FakeConnections owner) : IDataConnection, IDataPrimarySubscriptionSource { public Task SubscribePrimaryAsync(CancellationToken cancellationToken) { Interlocked.Increment(ref owner.PrimarySubscribes); return SubscribeAsync(cancellationToken); } public DataTarget Target { get; } = new(DataTargetMode.Cluster, "origin", null); public TimeProvider Clock => TimeProvider.System; public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => throw new NotSupportedException(); public Task BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => Interlocked.Increment(ref owner.MetadataCalls) < 0 ? throw new InvalidOperationException() : Task.FromResult>>(request.Views.Select((v, i) => owner.MetadataFails.Contains(i) ? new DataItemResult("0", DataItemStatus.Unavailable, null, null) : new DataItemResult("0", DataItemStatus.Good, new DataMetadata(v with { Subject = v.Address.Identifier }, v.Address.Identifier, "Folder", DataValueKind.Null, -1, [], false, DataOperations.Browse, 1, null, null, false), null)).ToArray()); public Task> ReadAsync(ReadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => throw new NotSupportedException(); public Task SubscribeAsync(CancellationToken cancellationToken) { string role; lock (owner.Roles) role = owner.Roles.TryDequeue(out var next) ? next : "Primary"; var stream = new FakeStream(role); owner.Streams.Writer.TryWrite(stream); return Task.FromResult(stream); } public ValueTask DisposeAsync() => ValueTask.CompletedTask; } internal sealed class FakeStream(string role = "Primary") : IDataSubscription, IDataSubscriptionProvenance { public ServingIdentity Serving { get; } = new("origin-1", "inc-1", role, 1, 1); public bool Disposed { get; private set; } /// The mapping ids this stream opened items for. public IReadOnlyList Mappings => Open.Items.Select(x => x.ClientItemId).ToArray(); private readonly Channel _frames = Channel.CreateUnbounded(); private readonly TaskCompletionSource _open = new(TaskCreationOptions.RunContinuationsAsynchronously); private long _sequence; public List Removed { get; } = []; /// #930: in-stream item re-adds (retries), in order. public List Adds { get; } = []; private readonly Dictionary _current = new(StringComparer.Ordinal); private ulong _nextHandle = 100; /// Every command id this stream has accepted (A4 review r1 B1). private readonly HashSet _commandIds = new(StringComparer.Ordinal); public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken) { // A4 review r1 B1: the real transport refuses a command id already used on the stream (GrpcDataConnection // `_usedCommands`, "Command capacity or duplicate command"), and the origin one still pending // (DataSubscriptionSession); either ends the consumer's stream. The fake enforces the stricter (transport) rule. lock (_commandIds) if (!_commandIds.Add(command.CommandId)) throw new InvalidOperationException("Command capacity or duplicate command."); if (command is OpenSubscription open) _open.TrySetResult(open); if (command is RemoveSubscriptionItems remove) lock (Removed) Removed.AddRange(remove.Items); if (command is AddSubscriptionItems add) lock (Adds) Adds.Add(add); return Task.CompletedTask; } /// How many re-adds named . public int AddsOf(string mapping) { lock (Adds) return Adds.Count(a => a.Items.Any(i => i.ClientItemId == mapping)); } /// Acks the latest re-add of (Good ⇒ a fresh handle that later frames use). public void AckAdd(string mapping, DataItemStatus status = DataItemStatus.Good) { AddSubscriptionItems add; lock (Adds) add = Adds.Last(a => a.Items.Any(i => i.ClientItemId == mapping)); DataItemHandle? handle = null; if (status == DataItemStatus.Good) { handle = new DataItemHandle(Open.SubscriptionId, Open.StreamEpoch, ++_nextHandle, 1); lock (_current) _current[mapping] = handle; } _frames.Writer.TryWrite(new DataSubscriptionAck(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, add.CommandId, [new DataSubscriptionItemAck(mapping, status, handle, null, status == DataItemStatus.Good ? null : "refused")])); } /// A4 review r1 S2: acks the -th re-add of (a late ack), Good. public DataItemHandle AckAddAt(string mapping, int index) { AddSubscriptionItems add; lock (Adds) add = Adds.Where(a => a.Items.Any(i => i.ClientItemId == mapping)).ElementAt(index); var handle = new DataItemHandle(Open.SubscriptionId, Open.StreamEpoch, ++_nextHandle, 1); _frames.Writer.TryWrite(new DataSubscriptionAck(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, add.CommandId, [new DataSubscriptionItemAck(mapping, DataItemStatus.Good, handle, null, null)])); return handle; } public IAsyncEnumerable ReadAllAsync(CancellationToken cancellationToken) => _frames.Reader.ReadAllAsync(cancellationToken); public ValueTask DisposeAsync() { Disposed = true; _frames.Writer.TryComplete(); return ValueTask.CompletedTask; } private OpenSubscription Open => _open.Task.Wait(TimeSpan.FromSeconds(10)) ? _open.Task.Result : throw new TimeoutException("no open"); public DataItemHandle HandleOf(string mapping) { lock (_current) if (_current.TryGetValue(mapping, out var current)) return current; var index = Open.Items.Select((x, i) => (x, i)).Single(x => x.x.ClientItemId == mapping).i; return new DataItemHandle(Open.SubscriptionId, Open.StreamEpoch, (ulong)(index + 1), 1); } public void Ack(params string[] refused) => Ack(DataItemStatus.Unavailable, refused); public void Ack(DataItemStatus refusal, params string[] refused) => _frames.Writer.TryWrite(new DataSubscriptionAck(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, "open", Open.Items.Select(x => refused.Contains(x.ClientItemId) ? new DataSubscriptionItemAck(x.ClientItemId, refusal, null, x.Settings, "refused") : new DataSubscriptionItemAck(x.ClientItemId, DataItemStatus.Good, HandleOf(x.ClientItemId), x.Settings, null)).ToArray())); /// Snapshot record frames exactly as the A2 origin frames them (is_snapshot, no total). public void SnapshotRecords(string mapping, params DataConditionState[] records) { foreach (var chunk in records.Chunk(128)) Frame(mapping, true, null, chunk, false); } public void Begin(string mapping, int total) => Frame(mapping, true, total, [], false); public void Records(string mapping, params DataConditionState[] records) { foreach (var chunk in records.Chunk(128)) Frame(mapping, false, null, chunk, false); } public void Complete(string mapping) => Frame(mapping, true, null, [], true); public void End() => _frames.Writer.TryComplete(); private void Frame(string mapping, bool snapshot, int? total, IReadOnlyList items, bool complete) => _frames.Writer.TryWrite(new DataSubscriptionConditions(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, HandleOf(mapping), snapshot, total, items, complete)); } }