diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/MigrationScratchDatabase.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/MigrationScratchDatabase.cs
index 0a799a862..2bc217091 100644
--- a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/MigrationScratchDatabase.cs
+++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/MigrationScratchDatabase.cs
@@ -29,13 +29,15 @@ internal sealed class MigrationScratchDatabase : IDisposable
var saPassword = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SA_PASSWORD") ?? DefaultSaPassword;
DatabaseName = $"{SchemaComplianceFixture.TestDatabasePrefix}{DateTime.UtcNow:yyyyMMddHHmmss}_{Guid.NewGuid():N}";
ConnectionString =
- $"Server={server};Database={DatabaseName};User Id=sa;Password={saPassword};TrustServerCertificate=True;Encrypt=False;";
+ $"Server={server};Database={DatabaseName};User Id=sa;Password={saPassword};TrustServerCertificate=True;Encrypt=False;" +
+ $"Connect Timeout={SchemaComplianceFixture.ConnectTimeoutSeconds};";
}
/// Opens a context on the scratch database.
/// A new context.
public OtOpcUaConfigDbContext NewContext() =>
- new(new DbContextOptionsBuilder().UseSqlServer(ConnectionString).Options);
+ new(new DbContextOptionsBuilder()
+ .UseSqlServer(ConnectionString, o => o.CommandTimeout(SchemaComplianceFixture.MigrationCommandTimeoutSeconds)).Options);
/// Migrates (up) to , or to the latest when null.
/// The migration id or name to stop at.
diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/SchemaComplianceFixture.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/SchemaComplianceFixture.cs
index 1ef229e8c..581930b95 100644
--- a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/SchemaComplianceFixture.cs
+++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/SchemaComplianceFixture.cs
@@ -26,9 +26,15 @@ public sealed class SchemaComplianceFixture : IDisposable
private static readonly Lazy Reaper = new(RunReaper, LazyThreadSafetyMode.ExecutionAndPublication);
/// Gets the name of the test database.
- public string DatabaseName { get; }
+ public string DatabaseName { get; private set; } = null!;
/// Gets the connection string for the test database.
- public string ConnectionString { get; }
+ public string ConnectionString { get; private set; } = null!;
+
+ /// #1114: connection-open budget — the shared docker host is often heavily loaded (as ControlPlane.Tests, #1111).
+ internal const int ConnectTimeoutSeconds = 60;
+
+ /// #1114: per-statement budget for creating + migrating the database (as ControlPlane.Tests, #1111).
+ internal const int MigrationCommandTimeoutSeconds = 300;
/// Initializes a new instance of the SchemaComplianceFixture class.
public SchemaComplianceFixture()
@@ -42,16 +48,51 @@ public sealed class SchemaComplianceFixture : IDisposable
// Migrate() below throws as it always has.
_ = Reaper.Value;
- DatabaseName = $"{TestDatabasePrefix}{DateTime.UtcNow:yyyyMMddHHmmss}_{Guid.NewGuid():N}";
- ConnectionString =
- $"Server={server};Database={DatabaseName};User Id=sa;Password={saPassword};TrustServerCertificate=True;Encrypt=False;";
+ // #1114: a migration whose applock was lost to a dropped connection is retried ONCE under a fresh name.
+ for (var attempt = 1; ; attempt++)
+ {
+ DatabaseName = $"{TestDatabasePrefix}{DateTime.UtcNow:yyyyMMddHHmmss}_{Guid.NewGuid():N}";
+ ConnectionString =
+ $"Server={server};Database={DatabaseName};User Id=sa;Password={saPassword};TrustServerCertificate=True;Encrypt=False;" +
+ $"Connect Timeout={ConnectTimeoutSeconds};";
- var options = new DbContextOptionsBuilder()
- .UseSqlServer(ConnectionString)
- .Options;
+ // #1114: the migration runs with a generous command timeout (the provider's 30 s default was overrun by a
+ // single migration statement on the loaded shared server, #1111).
+ var options = new DbContextOptionsBuilder()
+ .UseSqlServer(ConnectionString, o => o.CommandTimeout(MigrationCommandTimeoutSeconds))
+ .Options;
- using var ctx = new OtOpcUaConfigDbContext(options);
- ctx.Database.Migrate();
+ try
+ {
+ using var ctx = new OtOpcUaConfigDbContext(options);
+ ctx.Database.Migrate();
+ return;
+ }
+ catch (Exception ex) when (attempt == 1 && IsLostMigrationLock(ex))
+ {
+ Dispose(); // drop the half-migrated database; the retry mints a new name
+ }
+ }
+ }
+
+ ///
+ /// #1114: whether a migration failed because EF's migration applock (__EFMigrationsLock) was lost — on a
+ /// heavily loaded server a dropped connection releases the session lock, and the final sp_releaseapplock
+ /// then fails with "Cannot release the application lock … because it is not currently held" (SQL error 1223).
+ /// The database is left half-migrated, so the harness retries ONCE under a fresh database name.
+ ///
+ /// The migration failure.
+ /// for a lost migration lock.
+ internal static bool IsLostMigrationLock(Exception ex)
+ {
+ for (var e = ex; e is not null; e = e.InnerException)
+ {
+ if (e is SqlException sql && (sql.Number == 1223
+ || sql.Message.Contains("not currently held", StringComparison.OrdinalIgnoreCase)))
+ return true;
+ if (e.Message.Contains("Cannot release the application lock", StringComparison.OrdinalIgnoreCase)) return true;
+ }
+ return false;
}
/// Opens a new SQL connection to the test database.
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/AdminUiSqlServerFixture.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/AdminUiSqlServerFixture.cs
index 3ba93e001..ab6c1011d 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/AdminUiSqlServerFixture.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/AdminUiSqlServerFixture.cs
@@ -43,10 +43,10 @@ namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests;
public sealed class AdminUiSqlServerFixture : IDisposable
{
/// Gets the name of the per-run test database, or when SQL is unreachable.
- public string? DatabaseName { get; }
+ public string? DatabaseName { get; private set; }
/// Gets the connection string for the test database, or when SQL is unreachable.
- public string? ConnectionString { get; }
+ public string? ConnectionString { get; private set; }
///
/// Gets the reason the SQL-backed tests cannot run (server unreachable, migration failed), or
@@ -82,27 +82,37 @@ public sealed class AdminUiSqlServerFixture : IDisposable
// Mint from the same constant the reaper's LIKE anchors on — a rename that touched only one of the
// two would leave every future database unreapable, with nothing to signal it.
- DatabaseName =
- $"{AdminUiSqlServer.TestDatabasePrefix}{DateTime.UtcNow:yyyyMMddHHmmss}_{Guid.NewGuid():N}";
- ConnectionString = AdminUiSqlServer.ConnectionStringFor(DatabaseName);
-
- try
+ for (var attempt = 1; ; attempt++)
{
- var options = new DbContextOptionsBuilder()
- .UseSqlServer(ConnectionString)
- .Options;
+ DatabaseName =
+ $"{AdminUiSqlServer.TestDatabasePrefix}{DateTime.UtcNow:yyyyMMddHHmmss}_{Guid.NewGuid():N}";
+ ConnectionString = AdminUiSqlServer.ConnectionStringFor(DatabaseName);
- using var ctx = new OtOpcUaConfigDbContext(options);
- ctx.Database.Migrate();
- }
- catch (Exception ex)
- {
- // A half-created database would leak, so tear it down before standing the suite down.
- TryDropDatabase();
- SkipReason = $"Could not migrate the AdminUI SQL test database: {ex.Message}";
- DatabaseName = null;
- ConnectionString = null;
- return;
+ try
+ {
+ // #1114: a generous migration command timeout (the shared server is often loaded, #1111).
+ var options = new DbContextOptionsBuilder()
+ .UseSqlServer(ConnectionString, o => o.CommandTimeout(AdminUiSqlServer.MigrationCommandTimeoutSeconds))
+ .Options;
+
+ using var ctx = new OtOpcUaConfigDbContext(options);
+ ctx.Database.Migrate();
+ break;
+ }
+ catch (Exception lockLost) when (attempt == 1 && AdminUiSqlServer.IsLostMigrationLock(lockLost))
+ {
+ // #1114: the migration applock was lost to a dropped connection — retry ONCE under a fresh name.
+ TryDropDatabase();
+ }
+ catch (Exception ex)
+ {
+ // A half-created database would leak, so tear it down before standing the suite down.
+ TryDropDatabase();
+ SkipReason = $"Could not migrate the AdminUI SQL test database: {ex.Message}";
+ DatabaseName = null;
+ ConnectionString = null;
+ return;
+ }
}
_factory = new SqlServerContextFactory(ConnectionString);
@@ -147,6 +157,12 @@ internal static class AdminUiSqlServer
private const string DefaultSaPassword = "OtOpcUaDev_2026!";
private const int ProbeTimeoutSeconds = 3;
+ /// #1114: connection-open budget — the shared docker host is often heavily loaded (as ControlPlane.Tests, #1111).
+ internal const int ConnectTimeoutSeconds = 60;
+
+ /// #1114: per-statement budget for creating + migrating the database (as ControlPlane.Tests, #1111).
+ internal const int MigrationCommandTimeoutSeconds = 300;
+
/// How long a test database must have existed before the reaper considers it certainly orphaned.
private static readonly TimeSpan OrphanAge = TimeSpan.FromHours(24);
@@ -171,7 +187,27 @@ internal static class AdminUiSqlServer
var password = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SA_PASSWORD") ?? DefaultSaPassword;
return $"Server={server};Database={database};User Id=sa;Password={password};" +
- "TrustServerCertificate=True;Encrypt=False;";
+ $"TrustServerCertificate=True;Encrypt=False;Connect Timeout={ConnectTimeoutSeconds};";
+ }
+
+ ///
+ /// #1114: whether a migration failed because EF's migration applock (__EFMigrationsLock) was lost — on a
+ /// heavily loaded server a dropped connection releases the session lock, and the final sp_releaseapplock
+ /// then fails with "Cannot release the application lock … because it is not currently held" (SQL error 1223).
+ /// The database is left half-migrated, so the harness retries ONCE under a fresh database name.
+ ///
+ /// The migration failure.
+ /// for a lost migration lock.
+ internal static bool IsLostMigrationLock(Exception ex)
+ {
+ for (var e = ex; e is not null; e = e.InnerException)
+ {
+ if (e is SqlException sql && (sql.Number == 1223
+ || sql.Message.Contains("not currently held", StringComparison.OrdinalIgnoreCase)))
+ return true;
+ if (e.Message.Contains("Cannot release the application lock", StringComparison.OrdinalIgnoreCase)) return true;
+ }
+ return false;
}
private static int RunReaper() =>
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Harness/SqlServerTestDatabase.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Harness/SqlServerTestDatabase.cs
index 21ccbc660..bea4051c6 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Harness/SqlServerTestDatabase.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Harness/SqlServerTestDatabase.cs
@@ -19,9 +19,9 @@ public sealed class SqlServerTestDatabase : IDisposable
private const string DefaultSaPassword = "OtOpcUaDev_2026!";
/// Gets the connection string of the migrated database.
- public string ConnectionString { get; }
+ public string ConnectionString { get; private set; } = null!;
- private readonly string _databaseName;
+ private string _databaseName = null!;
/// Connection-open budget: the shared docker host is often heavily loaded (#1111).
private const int ConnectTimeoutSeconds = 60;
@@ -40,10 +40,27 @@ public sealed class SqlServerTestDatabase : IDisposable
{
var server = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SERVER") ?? DefaultServer;
var saPassword = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SA_PASSWORD") ?? DefaultSaPassword;
- _databaseName = $"OtOpcUaConfig_Test_{DateTime.UtcNow:yyyyMMddHHmmss}_{Guid.NewGuid():N}";
- ConnectionString =
- $"Server={server};Database={_databaseName};User Id=sa;Password={saPassword};TrustServerCertificate=True;Encrypt=False;" +
- $"Connect Timeout={ConnectTimeoutSeconds};";
+ // #1114: a migration whose applock was lost to a dropped connection is retried ONCE under a fresh name.
+ for (var attempt = 1; ; attempt++)
+ {
+ _databaseName = $"OtOpcUaConfig_Test_{DateTime.UtcNow:yyyyMMddHHmmss}_{Guid.NewGuid():N}";
+ ConnectionString =
+ $"Server={server};Database={_databaseName};User Id=sa;Password={saPassword};TrustServerCertificate=True;Encrypt=False;" +
+ $"Connect Timeout={ConnectTimeoutSeconds};";
+ try
+ {
+ CreateAndMigrate(targetMigration);
+ return;
+ }
+ catch (Exception ex) when (attempt == 1 && IsLostMigrationLock(ex))
+ {
+ Dispose(); // drop the half-migrated database; the retry mints a new name
+ }
+ }
+ }
+
+ private void CreateAndMigrate(string? targetMigration)
+ {
// #1111: the migration runs with a generous command timeout. Several SQL-backed classes create + migrate their
// own database in parallel on a SHARED server, and under load a single migration statement (observed: the
// migration lock's sp_releaseapplock) overran the provider's 30 s default — failing whichever test happened to
@@ -54,6 +71,26 @@ public sealed class SqlServerTestDatabase : IDisposable
else ctx.GetService().Migrate(targetMigration);
}
+ ///
+ /// #1114: whether a migration failed because EF's migration applock (__EFMigrationsLock) was lost — on a
+ /// heavily loaded server a dropped connection releases the session lock, and the final sp_releaseapplock
+ /// then fails with "Cannot release the application lock … because it is not currently held" (SQL error 1223).
+ /// The database is left half-migrated, so the harness retries ONCE under a fresh database name.
+ ///
+ /// The migration failure.
+ /// for a lost migration lock.
+ internal static bool IsLostMigrationLock(Exception ex)
+ {
+ for (var e = ex; e is not null; e = e.InnerException)
+ {
+ if (e is SqlException sql && (sql.Number == 1223
+ || sql.Message.Contains("not currently held", StringComparison.OrdinalIgnoreCase)))
+ return true;
+ if (e.Message.Contains("Cannot release the application lock", StringComparison.OrdinalIgnoreCase)) return true;
+ }
+ return false;
+ }
+
/// A new context on the database.
/// The context.
public OtOpcUaConfigDbContext NewContext() =>
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Harness/SqlServerTestDatabaseTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Harness/SqlServerTestDatabaseTests.cs
new file mode 100644
index 000000000..488845f29
--- /dev/null
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Harness/SqlServerTestDatabaseTests.cs
@@ -0,0 +1,25 @@
+using Shouldly;
+using Xunit;
+
+namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness;
+
+/// #1114: the harness retries DB creation once, but only on a lost migration applock.
+public sealed class SqlServerTestDatabaseTests
+{
+ [Fact]
+ public void A_lost_migration_applock_is_recognised_even_when_wrapped()
+ {
+ var lost = new InvalidOperationException(
+ "Cannot release the application lock (Database Principal: 'public', Resource: '__EFMigrationsLock') " +
+ "because it is not currently held.");
+ SqlServerTestDatabase.IsLostMigrationLock(lost).ShouldBeTrue();
+ SqlServerTestDatabase.IsLostMigrationLock(new Exception("migration failed", lost)).ShouldBeTrue();
+ }
+
+ [Fact]
+ public void Any_other_migration_failure_is_not_retried()
+ {
+ SqlServerTestDatabase.IsLostMigrationLock(new InvalidOperationException("Invalid column name 'X'.")).ShouldBeFalse();
+ SqlServerTestDatabase.IsLostMigrationLock(new TimeoutException("Execution Timeout Expired.")).ShouldBeFalse();
+ }
+}