using System.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Configuration.Entities; using ZB.MOM.WW.OtOpcUa.Configuration.Enums; using ZB.MOM.WW.OtOpcUa.Configuration.Validation; namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests; /// /// lmxopcua#1049 (#998 C-10 follow-up) on the real provider. The raw-tree parent links are LOGICAL foreign keys, /// so the race the review described — user A's "is the device empty?" check passes, user B adds a tag under it, /// A deletes the device — really commits both on SQL Server, and the deploy gate's DanglingReference rule is /// what names the orphan. And because the deploy reads its whole snapshot under SNAPSHOT isolation, a /// concurrent, perfectly consistent commit landing MID-read cannot make the gate report a dangling row that never /// existed in any committed state (a parent read before the commit, its child read after it). /// [Trait("Category", "SchemaCompliance")] [Collection(nameof(SchemaComplianceCollection))] public sealed class DanglingReferenceSqlServerTests { private readonly SchemaComplianceFixture _fixture; /// Initializes a new instance of the class. /// The migrated test database. public DanglingReferenceSqlServerTests(SchemaComplianceFixture fixture) => _fixture = fixture; private OtOpcUaConfigDbContext NewContext(params IInterceptor[] interceptors) => new( new DbContextOptionsBuilder().UseSqlServer(_fixture.ConnectionString) .AddInterceptors(interceptors).Options); private static string Id(string prefix) => $"{prefix}-{Guid.NewGuid():N}"; private static Tag NewTag(string tagId, string deviceId) => new() { TagId = tagId, DeviceId = deviceId, Name = tagId, DataType = "Int32", AccessLevel = TagAccessLevel.Read, TagConfig = "{}", }; /// Seeds cluster → driver → device; returns (driverId, deviceId). private (string DriverId, string DeviceId) SeedDevice() { var clusterId = Id("cl")[..30]; var driverId = Id("di"); var deviceId = Id("dev"); using var db = NewContext(); db.ServerClusters.Add(new ServerCluster { ClusterId = clusterId, Name = Id("Cluster"), Enterprise = "zb", Site = "dev", NodeCount = 1, RedundancyMode = RedundancyMode.None, CreatedBy = "t1049", }); db.DriverInstances.Add(new DriverInstance { DriverInstanceId = driverId, ClusterId = clusterId, Name = Id("drv"), DriverType = "Modbus", DriverConfig = "{}", }); db.Devices.Add(new Device { DeviceId = deviceId, DriverInstanceId = driverId, Name = Id("plc"), DeviceConfig = "{}" }); db.SaveChanges(); return (driverId, deviceId); } private static IEnumerable DanglingFor(DraftSnapshot draft, string tagId) => DraftValidator.Validate(draft).Where(e => e.Code == DraftValidator.DanglingReferenceCode && e.Context == tagId); /// /// The review's race, interleaved on two real connections: A's emptiness check, B's tag add, A's device delete. /// Both commit (no FK); the deploy snapshot then names the orphaned tag. /// [Fact] public async Task A_device_deleted_while_a_tag_is_added_under_it_is_reported_by_the_deploy_gate() { var ct = TestContext.Current.CancellationToken; var (_, deviceId) = SeedDevice(); var tagId = Id("tag"); await using (var userA = NewContext()) { await using var tx = await userA.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct); (await userA.Tags.AnyAsync(t => t.DeviceId == deviceId, ct)).ShouldBeFalse(); // "the device is empty" await using (var userB = NewContext()) { userB.Tags.Add(NewTag(tagId, deviceId)); await userB.SaveChangesAsync(ct); // commits while A's check result is already stale } userA.Devices.Remove(await userA.Devices.SingleAsync(d => d.DeviceId == deviceId, ct)); await userA.SaveChangesAsync(ct); await tx.CommitAsync(ct); } await using var deploy = NewContext(); var draft = await DraftSnapshotFactory.FromConfigDbAsync(deploy, ct); draft.Tags.ShouldContain(t => t.TagId == tagId); draft.Devices.ShouldNotContain(d => d.DeviceId == deviceId); DanglingFor(draft, tagId).ShouldHaveSingleItem().Message.ShouldContain($"Device '{deviceId}'"); } /// /// A device and its tag added together in ONE commit that lands after the snapshot read has passed the Devices /// table but before it reads Tags: under the factory's SNAPSHOT transaction neither is seen, so no false /// DanglingReference. Positive control: the same interleave inside a READ COMMITTED transaction (the /// factory then reads in the caller's transaction) DOES report the tag as dangling — so the isolation, not the /// timing, is what keeps the gate honest; and a read after the commit sees both rows and no error. /// [Fact] public async Task A_consistent_commit_landing_mid_read_is_never_reported_as_dangling_under_snapshot_isolation() { var ct = TestContext.Current.CancellationToken; var (driverId, deviceId) = SeedDevice(); // Snapshot read (the deploy path): the concurrent commit is invisible. var (lateDevice, lateTag) = (Id("dev"), Id("tag")); await using (var db = NewContext(new CommitDeviceAndTagWhenDeviceMaterialises(_fixture.ConnectionString, deviceId, driverId, lateDevice, lateTag))) { var draft = await DraftSnapshotFactory.FromConfigDbAsync(db, ct); draft.Tags.ShouldNotContain(t => t.TagId == lateTag); DanglingFor(draft, lateTag).ShouldBeEmpty(); } // Positive control 1: the same interleave read unisolated produces exactly the false positive. var (lateDevice2, lateTag2) = (Id("dev"), Id("tag")); await using (var db = NewContext(new CommitDeviceAndTagWhenDeviceMaterialises(_fixture.ConnectionString, deviceId, driverId, lateDevice2, lateTag2))) { await using var tx = await db.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct); var draft = await DraftSnapshotFactory.FromConfigDbAsync(db, ct); draft.Tags.ShouldContain(t => t.TagId == lateTag2); DanglingFor(draft, lateTag2).ShouldHaveSingleItem(); } // Positive control 2: both commits really landed, and a read started afterwards sees them whole. await using var after = NewContext(); var later = await DraftSnapshotFactory.FromConfigDbAsync(after, ct); later.Tags.ShouldContain(t => t.TagId == lateTag); later.Devices.ShouldContain(d => d.DeviceId == lateDevice); DanglingFor(later, lateTag).ShouldBeEmpty(); DanglingFor(later, lateTag2).ShouldBeEmpty(); } /// /// When the snapshot read materialises the seeded device (Devices is read before Tags), commits a NEW device and a /// tag under it — one consistent transaction — on a separate connection. /// private sealed class CommitDeviceAndTagWhenDeviceMaterialises( string connectionString, string triggerDeviceId, string driverId, string newDeviceId, string newTagId) : IMaterializationInterceptor { private int _fired; public object InitializedInstance(MaterializationInterceptionData materializationData, object entity) { if (entity is Device d && d.DeviceId == triggerDeviceId && Interlocked.Exchange(ref _fired, 1) == 0) { using var other = new OtOpcUaConfigDbContext( new DbContextOptionsBuilder().UseSqlServer(connectionString).Options); other.Devices.Add(new Device { DeviceId = newDeviceId, DriverInstanceId = driverId, Name = newDeviceId, DeviceConfig = "{}" }); other.Tags.Add(NewTag(newTagId, newDeviceId)); other.SaveChanges(); } return entity; } } }