using System.IO.Compression; using System.Text; using Akka.Actor; using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin; using ZB.MOM.WW.OtOpcUa.Commons.Types; using ZB.MOM.WW.OtOpcUa.Configuration; using ZB.MOM.WW.OtOpcUa.Configuration.Entities; using ZB.MOM.WW.OtOpcUa.Configuration.Enums; using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations; using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests; /// /// #955 — the deploy compose's transaction isolation, on the real provider. The compose used to run /// SERIALIZABLE, which range-locked every config table for the whole validate + compose + gzip: a concurrent /// edit waited for the deploy, an uncommitted edit made the deploy wait for it, and an edit touching a table /// the compose had already read plus one it had not yet read deadlocked with it (measured: the first /// deadlock costs ~5 s — one lock-monitor cycle — and then either side dies; the deploy was the victim 9 of /// 10 times and answered "StartDeployment failed on the server"). It now reads under SNAPSHOT, serialised /// against other composes by an app lock. /// [Trait("Category", "SchemaCompliance")] public sealed class DeployComposeIsolationSqlServerTests : ControlPlaneActorTestBase { private static readonly TimeSpan Budget = TimeSpan.FromSeconds(10); /// /// An edit holding an uncommitted row lock on a config table no longer holds the deploy: it composes /// from the last committed state. Red under SERIALIZABLE — the snapshot read waits on the row lock until /// the editor commits (here: never, within the budget). /// [Fact] public async Task Deploy_is_not_held_by_an_uncommitted_edit_and_ships_the_committed_state() { using var sql = new SqlServerTestDatabase(); await SeedAsync(sql); await using var editor = new SqlConnection(sql.ConnectionString); await editor.OpenAsync(TestContext.Current.CancellationToken); await using var edit = editor.BeginTransaction(); await ExecAsync(editor, edit, "UPDATE Tag SET Name = N'uncommitted-name' WHERE TagId = 'tag-0001'"); var coordinator = CreateTestProbe("coord"); var actor = Sys.ActorOf(AdminOperationsActor.Props(sql.Factory(), coordinator.Ref, Enumerable.Empty())); actor.Tell(new StartDeployment("joe", CorrelationId.NewId(), DeploymentId.NewId())); var reply = ExpectMsg(Budget, cancellationToken: TestContext.Current.CancellationToken); reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, reply.Message); await edit.RollbackAsync(TestContext.Current.CancellationToken); await using var verify = sql.NewContext(); var artifact = Inflate((await verify.Deployments.SingleAsync(TestContext.Current.CancellationToken)).ArtifactBlob); artifact.ShouldNotContain("uncommitted-name"); artifact.ShouldContain("tag-0001"); } /// /// The other direction, which is the deadlock's precondition: while the compose is mid-read, an edit of a /// table it has ALREADY read commits without waiting. Red under SERIALIZABLE — the read's key-range locks /// are held to commit, so the edit hits its lock timeout (1222). /// [Fact] public async Task An_edit_of_an_already_read_table_does_not_wait_for_a_running_deploy() { using var sql = new SqlServerTestDatabase(); await SeedAsync(sql); var editOutcome = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); // Tags is read after ClusterNodes, so editing ClusterNode on the first Tag materialised edits a table the // compose has already read, from inside the compose's read. var factory = new InterceptingFactory(sql.ConnectionString, new EditOnFirstTag(sql.ConnectionString, editOutcome)); var coordinator = CreateTestProbe("coord"); var actor = Sys.ActorOf(AdminOperationsActor.Props(factory, coordinator.Ref, Enumerable.Empty())); actor.Tell(new StartDeployment("joe", CorrelationId.NewId(), DeploymentId.NewId())); var reply = ExpectMsg(Budget, cancellationToken: TestContext.Current.CancellationToken); reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, reply.Message); (await editOutcome.Task.WaitAsync(Budget, TestContext.Current.CancellationToken)).ShouldBe("committed"); await using var verify = sql.NewContext(); (await verify.ClusterNodes.SingleAsync(TestContext.Current.CancellationToken)).Host.ShouldBe("edited-mid-deploy"); } /// /// Composes still serialise: one that queues behind another (an overlapping singleton) waits for it and /// advances the scope revision that compose committed — it neither composes concurrently nor dies on an /// update conflict (3960), which is what taking the row lock first under SNAPSHOT would do. /// [Fact] public async Task A_compose_queued_behind_another_advances_the_revision_that_compose_committed() { using var sql = new SqlServerTestDatabase(); await SeedAsync(sql); await using var other = new SqlConnection(sql.ConnectionString); await other.OpenAsync(TestContext.Current.CancellationToken); await using var otherCompose = other.BeginTransaction(); await ExecAsync(other, otherCompose, AdminOperationsActor.ComposeAppLockSql); await ExecAsync(other, otherCompose, "UPDATE DataConnectionScopeState SET ScopeVersion = 7, Fingerprint = 'other-compose' WHERE Id = 1"); var coordinator = CreateTestProbe("coord"); var actor = Sys.ActorOf(AdminOperationsActor.Props(sql.Factory(), coordinator.Ref, Enumerable.Empty())); actor.Tell(new StartDeployment("joe", CorrelationId.NewId(), DeploymentId.NewId())); // Positive control that it really queued: nothing comes back while the other compose holds the lock. ExpectNoMsg(TimeSpan.FromSeconds(1), TestContext.Current.CancellationToken); await otherCompose.CommitAsync(TestContext.Current.CancellationToken); var reply = ExpectMsg(Budget, cancellationToken: TestContext.Current.CancellationToken); reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, reply.Message); await using var verify = sql.NewContext(); var scope = await verify.DataConnectionScopeStates.AsNoTracking().SingleAsync(TestContext.Current.CancellationToken); scope.ScopeVersion.ShouldBe(8); // 7 (the other compose's) + 1: its fingerprint differs from this snapshot's } private static async Task SeedAsync(SqlServerTestDatabase sql) { await using var db = sql.NewContext(); db.ServerClusters.Add(new ServerCluster { ClusterId = "C1", Name = "c1", Enterprise = "ent", Site = "site", NodeCount = 1, RedundancyMode = RedundancyMode.None, CreatedBy = "t", }); db.ClusterNodes.Add(new ClusterNode { NodeId = "n1", ClusterId = "C1", Host = "h1", ApplicationUri = "urn:n1", CreatedBy = "t" }); db.DriverInstances.Add(new DriverInstance { DriverInstanceId = "d", ClusterId = "C1", Name = "drv", DriverType = "Modbus", DriverConfig = "{}" }); db.Devices.Add(new Device { DeviceId = "dev", DriverInstanceId = "d", Name = "dev", DeviceConfig = "{}" }); for (var i = 0; i < 20; i++) db.Tags.Add(new Tag { TagId = $"tag-{i:D4}", DeviceId = "dev", Name = $"t{i}", DataType = "Float", AccessLevel = TagAccessLevel.Read, TagConfig = "{\"region\":\"HoldingRegisters\",\"address\":1}", }); await db.SaveChangesAsync(TestContext.Current.CancellationToken); } private static async Task ExecAsync(SqlConnection conn, SqlTransaction tx, string text) { await using var cmd = new SqlCommand(text, conn, tx); await cmd.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); } private static string Inflate(byte[] blob) { using var gz = new GZipStream(new MemoryStream(blob), CompressionMode.Decompress); using var reader = new StreamReader(gz, Encoding.UTF8); return reader.ReadToEnd(); } /// On the first Tag the compose materialises, edits ClusterNode on another connection (3 s lock timeout). private sealed class EditOnFirstTag(string connectionString, TaskCompletionSource outcome) : IMaterializationInterceptor { private int _fired; public object InitializedInstance(MaterializationInterceptionData materializationData, object entity) { if (entity is Tag && Interlocked.Exchange(ref _fired, 1) == 0) { try { using var conn = new SqlConnection(connectionString); conn.Open(); using var cmd = new SqlCommand( "SET LOCK_TIMEOUT 3000; UPDATE ClusterNode SET Host = N'edited-mid-deploy' WHERE NodeId = 'n1';", conn); cmd.ExecuteNonQuery(); outcome.TrySetResult("committed"); } catch (SqlException ex) { outcome.TrySetResult($"SqlException {ex.Number}"); } } return entity; } } private sealed class InterceptingFactory(string connectionString, IInterceptor interceptor) : IDbContextFactory { public OtOpcUaConfigDbContext CreateDbContext() => new(new DbContextOptionsBuilder().UseSqlServer(connectionString).AddInterceptors(interceptor).Options); } }