test(sql): #1114 SQL test DB harnesses: 300 s migration / 60 s connect timeouts; retry once on a lost migration applock

Item 4: Configuration.Tests SchemaComplianceFixture + MigrationScratchDatabase
and AdminUI.Tests AdminUiSqlServerFixture get the same 300 s migration command /
60 s connect timeouts ControlPlane.Tests' SqlServerTestDatabase got in #1111.
(Server.Tests / Host.Tests have no SQL Server test-DB harness.)

Item 5: all three harnesses (and ControlPlane's) retry database creation ONCE
under a fresh database name when the migration fails with a lost
__EFMigrationsLock (SQL 1223, 'Cannot release the application lock ... not
currently held'), dropping the half-migrated database first. Any other failure
behaves as before. Recognition is unit-tested in ControlPlane.Tests.
This commit is contained in:
Joseph Doherty
2026-12-05 02:58:36 -05:00
parent 59b17a39a6
commit 5aa7d24db6
5 changed files with 181 additions and 40 deletions
@@ -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};";
}
/// <summary>Opens a context on the scratch database.</summary>
/// <returns>A new context.</returns>
public OtOpcUaConfigDbContext NewContext() =>
new(new DbContextOptionsBuilder<OtOpcUaConfigDbContext>().UseSqlServer(ConnectionString).Options);
new(new DbContextOptionsBuilder<OtOpcUaConfigDbContext>()
.UseSqlServer(ConnectionString, o => o.CommandTimeout(SchemaComplianceFixture.MigrationCommandTimeoutSeconds)).Options);
/// <summary>Migrates (up) to <paramref name="targetMigration"/>, or to the latest when null.</summary>
/// <param name="targetMigration">The migration id or name to stop at.</param>
@@ -26,9 +26,15 @@ public sealed class SchemaComplianceFixture : IDisposable
private static readonly Lazy<int> Reaper = new(RunReaper, LazyThreadSafetyMode.ExecutionAndPublication);
/// <summary>Gets the name of the test database.</summary>
public string DatabaseName { get; }
public string DatabaseName { get; private set; } = null!;
/// <summary>Gets the connection string for the test database.</summary>
public string ConnectionString { get; }
public string ConnectionString { get; private set; } = null!;
/// <summary>#1114: connection-open budget — the shared docker host is often heavily loaded (as ControlPlane.Tests, #1111).</summary>
internal const int ConnectTimeoutSeconds = 60;
/// <summary>#1114: per-statement budget for creating + migrating the database (as ControlPlane.Tests, #1111).</summary>
internal const int MigrationCommandTimeoutSeconds = 300;
/// <summary>Initializes a new instance of the SchemaComplianceFixture class.</summary>
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<OtOpcUaConfigDbContext>()
.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<OtOpcUaConfigDbContext>()
.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
}
}
}
/// <summary>
/// #1114: whether a migration failed because EF's migration applock (<c>__EFMigrationsLock</c>) was lost — on a
/// heavily loaded server a dropped connection releases the session lock, and the final <c>sp_releaseapplock</c>
/// 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.
/// </summary>
/// <param name="ex">The migration failure.</param>
/// <returns><see langword="true"/> for a lost migration lock.</returns>
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;
}
/// <summary>Opens a new SQL connection to the test database.</summary>
@@ -43,10 +43,10 @@ namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests;
public sealed class AdminUiSqlServerFixture : IDisposable
{
/// <summary>Gets the name of the per-run test database, or <see langword="null"/> when SQL is unreachable.</summary>
public string? DatabaseName { get; }
public string? DatabaseName { get; private set; }
/// <summary>Gets the connection string for the test database, or <see langword="null"/> when SQL is unreachable.</summary>
public string? ConnectionString { get; }
public string? ConnectionString { get; private set; }
/// <summary>
/// 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<OtOpcUaConfigDbContext>()
.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<OtOpcUaConfigDbContext>()
.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;
/// <summary>#1114: connection-open budget — the shared docker host is often heavily loaded (as ControlPlane.Tests, #1111).</summary>
internal const int ConnectTimeoutSeconds = 60;
/// <summary>#1114: per-statement budget for creating + migrating the database (as ControlPlane.Tests, #1111).</summary>
internal const int MigrationCommandTimeoutSeconds = 300;
/// <summary>How long a test database must have existed before the reaper considers it certainly orphaned.</summary>
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};";
}
/// <summary>
/// #1114: whether a migration failed because EF's migration applock (<c>__EFMigrationsLock</c>) was lost — on a
/// heavily loaded server a dropped connection releases the session lock, and the final <c>sp_releaseapplock</c>
/// 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.
/// </summary>
/// <param name="ex">The migration failure.</param>
/// <returns><see langword="true"/> for a lost migration lock.</returns>
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() =>
@@ -19,9 +19,9 @@ public sealed class SqlServerTestDatabase : IDisposable
private const string DefaultSaPassword = "OtOpcUaDev_2026!";
/// <summary>Gets the connection string of the migrated database.</summary>
public string ConnectionString { get; }
public string ConnectionString { get; private set; } = null!;
private readonly string _databaseName;
private string _databaseName = null!;
/// <summary>Connection-open budget: the shared docker host is often heavily loaded (#1111).</summary>
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<Microsoft.EntityFrameworkCore.Migrations.IMigrator>().Migrate(targetMigration);
}
/// <summary>
/// #1114: whether a migration failed because EF's migration applock (<c>__EFMigrationsLock</c>) was lost — on a
/// heavily loaded server a dropped connection releases the session lock, and the final <c>sp_releaseapplock</c>
/// 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.
/// </summary>
/// <param name="ex">The migration failure.</param>
/// <returns><see langword="true"/> for a lost migration lock.</returns>
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;
}
/// <summary>A new context on the database.</summary>
/// <returns>The context.</returns>
public OtOpcUaConfigDbContext NewContext() =>
@@ -0,0 +1,25 @@
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness;
/// <summary>#1114: the harness retries DB creation once, but only on a lost migration applock.</summary>
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();
}
}