Merge #1111 SQL recovery test: no product race (flip is row-version bound; mutation proves the test catches a reopen); test now waits for coordinator Ready, surfaces closure exceptions + a context timeline; SQL test DB migration gets 300 s command / 60 s connect timeouts
This commit is contained in:
+141
-19
@@ -318,68 +318,190 @@ public sealed class ConfigPublishCoordinatorRecoveryTests : ControlPlaneActorTes
|
||||
/// stays TimedOut with no expected set. Positive control: the coordinator is not wedged — the next live
|
||||
/// dispatch is seeded and flipped.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// #1111: this failed once in a rerun with no message captured. Every assertion now carries the
|
||||
/// <see cref="InterposingDbFactory"/> timeline (which coordinator path opened each context, on which thread,
|
||||
/// at what offset), the closure's own outcome, and a dump of both rows, so the next failure names its
|
||||
/// interleaving instead of only its symptom. It also waits for the recovery load to be applied before arming
|
||||
/// the closure and asserts the closure fired between the dispatch's own guard and flip: before that, a late
|
||||
/// recovery load could take the first countdown slot and the test passed without exercising the race.
|
||||
/// </remarks>
|
||||
[Fact]
|
||||
[Trait("Category", "SchemaCompliance")]
|
||||
public async Task On_sql_server_a_closure_between_guard_and_flip_is_not_reopened()
|
||||
{
|
||||
var clock = System.Diagnostics.Stopwatch.StartNew();
|
||||
using var sql = new SqlServerTestDatabase();
|
||||
var inner = sql.Factory();
|
||||
SeedNodes(inner, "site-a-1:4053");
|
||||
var interposer = new InterposingDbFactory(inner);
|
||||
var coordinator = Sys.ActorOf(ConfigPublishCoordinator.Props(interposer, NoTimeout));
|
||||
await Sys.ActorSelection(coordinator.Path).ResolveOne(PresenceBudget, TestContext.Current.CancellationToken); // PreStart ran over an empty table
|
||||
var interposer = new InterposingDbFactory(inner, clock);
|
||||
interposer.Mark("database migrated + nodes seeded");
|
||||
var readiness = new ConfigPublishCoordinatorReadiness();
|
||||
var coordinator = Sys.ActorOf(ConfigPublishCoordinator.Props(interposer, NoTimeout, readiness: readiness));
|
||||
// #1111: wait for the recovery load to have been APPLIED, not merely for the actor to exist. ResolveOne returns
|
||||
// as soon as PreStart ran, but the load runs after a Task.Yield on the pool — under load it can open its
|
||||
// context AFTER the closure is armed, consume the first countdown slot, and make the closure fire before the
|
||||
// guard read instead of between guard and flip (the test then passes without exercising the race).
|
||||
AwaitWithDiag(() => readiness.Current.State.ShouldBe(ConfigPublishCoordinatorState.Ready), interposer.Describe);
|
||||
interposer.Mark("coordinator Ready (recovery load over an empty table applied)");
|
||||
|
||||
// The race proper: a new Dispatching row whose dispatch is interleaved with an AdminOps-style closure.
|
||||
var victim = SeedDeployment(inner, DeploymentStatus.Dispatching, DateTime.UtcNow);
|
||||
DeploymentId? live = null;
|
||||
string Diag() => interposer.Describe() + Environment.NewLine + DumpRows(sql, victim, live);
|
||||
|
||||
interposer.OnSecondCreate(() =>
|
||||
{
|
||||
using var db = sql.NewContext();
|
||||
db.Database.ExecuteSqlRaw(
|
||||
return db.Database.ExecuteSqlRaw(
|
||||
"UPDATE Deployment SET Status = {0}, FailureReason = N'closed as lost' WHERE DeploymentId = {1}",
|
||||
(int)DeploymentStatus.TimedOut, victim.Value);
|
||||
});
|
||||
interposer.Mark($"victim {victim} seeded Dispatching; closure armed");
|
||||
coordinator.Tell(new DispatchDeployment(victim, TestRevision, CorrelationId.NewId()));
|
||||
AwaitAssert(() => interposer.Fired.ShouldBeTrue(), duration: PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
AwaitWithDiag(() => interposer.Fired.ShouldBeTrue(), Diag);
|
||||
// The closure itself landed (a throw here — e.g. the shared SQL host refusing — used to surface only as a
|
||||
// bare "Fired should be true" timeout) ...
|
||||
if (interposer.ClosureError is not null || interposer.ClosureRows != 1)
|
||||
throw new ShouldAssertException(
|
||||
$"the interposed closure did not commit (rows={interposer.ClosureRows})" + Environment.NewLine + Diag(),
|
||||
interposer.ClosureError);
|
||||
// ... and non-vacuity: both counted contexts were the dispatch's own (guard, then the seed + flip), so the
|
||||
// closure committed BETWEEN the guard read and the flip — not before the guard, where any dispatch just skips it.
|
||||
if (interposer.CountedCallers.Count != 2 || !interposer.CountedCallers.All(c => c.Contains("DispatchWrites")))
|
||||
throw new ShouldAssertException(
|
||||
"the closure did not land between the dispatch's guard read and its flip" + Environment.NewLine + Diag());
|
||||
|
||||
// Positive control + ordering: a live row dispatched after it IS flipped, so the victim's dispatch was processed.
|
||||
var live = SeedDeployment(inner, DeploymentStatus.Dispatching, DateTime.UtcNow);
|
||||
coordinator.Tell(new DispatchDeployment(live, TestRevision, CorrelationId.NewId()));
|
||||
AwaitAssert(() =>
|
||||
live = SeedDeployment(inner, DeploymentStatus.Dispatching, DateTime.UtcNow);
|
||||
interposer.Mark($"live {live} seeded Dispatching");
|
||||
coordinator.Tell(new DispatchDeployment(live.Value, TestRevision, CorrelationId.NewId()));
|
||||
AwaitWithDiag(() =>
|
||||
{
|
||||
using var db = sql.NewContext();
|
||||
db.Deployments.AsNoTracking().Single(d => d.DeploymentId == live.Value).Status
|
||||
db.Deployments.AsNoTracking().Single(d => d.DeploymentId == live.Value.Value).Status
|
||||
.ShouldBe(DeploymentStatus.AwaitingApplyAcks);
|
||||
}, duration: PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
}, Diag);
|
||||
interposer.Mark("live flipped");
|
||||
|
||||
// The expected-set count is the load-bearing check: a reopened victim is re-closed TimedOut by the live
|
||||
// dispatch's supersede, so its Status alone would read correctly — but its seeded NodeDeploymentState row stays.
|
||||
using var verify = sql.NewContext();
|
||||
verify.Deployments.AsNoTracking().Single(d => d.DeploymentId == victim.Value).Status
|
||||
.ShouldBe(DeploymentStatus.TimedOut, "the closure must not be reopened");
|
||||
verify.NodeDeploymentStates.Count(s => s.DeploymentId == victim.Value).ShouldBe(0);
|
||||
var victimStatus = verify.Deployments.AsNoTracking().Single(d => d.DeploymentId == victim.Value).Status;
|
||||
var victimExpected = verify.NodeDeploymentStates.Count(s => s.DeploymentId == victim.Value);
|
||||
var diag = Diag();
|
||||
TestContext.Current.TestOutputHelper?.WriteLine(diag);
|
||||
victimStatus.ShouldBe(DeploymentStatus.TimedOut, "the closure must not be reopened" + Environment.NewLine + diag);
|
||||
victimExpected.ShouldBe(0, "the closure must not be reopened (expected set seeded)" + Environment.NewLine + diag);
|
||||
}
|
||||
|
||||
/// <summary>Runs an action just before handing out the SECOND context after arming (HandleDispatch: guard, then flip).</summary>
|
||||
private sealed class InterposingDbFactory(IDbContextFactory<OtOpcUaConfigDbContext> inner)
|
||||
/// <summary>A presence wait whose failure carries <paramref name="diag"/> (built only on failure — #1111).</summary>
|
||||
private void AwaitWithDiag(Action assertion, Func<string> diag)
|
||||
{
|
||||
try
|
||||
{
|
||||
AwaitAssert(assertion, duration: PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
throw new ShouldAssertException(ex.Message + Environment.NewLine + diag(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Both rows (status, reason, expected-set size) for a failure message (#1111).</summary>
|
||||
private static string DumpRows(SqlServerTestDatabase sql, DeploymentId victim, DeploymentId? live)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var db = sql.NewContext();
|
||||
var ids = live is { } l ? new[] { victim.Value, l.Value } : new[] { victim.Value };
|
||||
var rows = db.Deployments.AsNoTracking()
|
||||
.Where(d => ids.Contains(d.DeploymentId))
|
||||
.Select(d => new { d.DeploymentId, d.Status, d.FailureReason })
|
||||
.ToList();
|
||||
var states = db.NodeDeploymentStates.AsNoTracking()
|
||||
.Where(s => ids.Contains(s.DeploymentId))
|
||||
.Select(s => new { s.DeploymentId, s.NodeId, s.Status })
|
||||
.ToList();
|
||||
return "rows: " + string.Join("; ", rows.Select(r =>
|
||||
$"{(r.DeploymentId == victim.Value ? "victim" : "live")} {r.Status} reason='{r.FailureReason}' " +
|
||||
$"nodeStates=[{string.Join(",", states.Where(s => s.DeploymentId == r.DeploymentId).Select(s => $"{s.NodeId}:{s.Status}"))}]"));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return $"rows: <dump failed: {ex.GetType().Name}: {ex.Message}>";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs an action just before handing out the SECOND context after arming (HandleDispatch: guard, then flip),
|
||||
/// and records every context hand-out — offset, thread, countdown, and the coordinator frame that asked —
|
||||
/// plus the action's outcome (#1111).
|
||||
/// </summary>
|
||||
private sealed class InterposingDbFactory(
|
||||
IDbContextFactory<OtOpcUaConfigDbContext> inner, System.Diagnostics.Stopwatch clock)
|
||||
: IDbContextFactory<OtOpcUaConfigDbContext>
|
||||
{
|
||||
private Action? _action;
|
||||
private readonly System.Collections.Concurrent.ConcurrentQueue<string> _timeline = new();
|
||||
private Func<int>? _action;
|
||||
private int _countdown;
|
||||
private int _creates;
|
||||
public volatile bool Fired;
|
||||
public volatile Exception? ClosureError;
|
||||
public int ClosureRows = -1;
|
||||
|
||||
public void OnSecondCreate(Action action)
|
||||
/// <summary>Who asked for each context that counted towards the countdown, in order.</summary>
|
||||
public System.Collections.Concurrent.ConcurrentQueue<string> CountedCallers { get; } = new();
|
||||
|
||||
public void OnSecondCreate(Func<int> action)
|
||||
{
|
||||
_action = action;
|
||||
Volatile.Write(ref _countdown, 2);
|
||||
}
|
||||
|
||||
public void Mark(string what) =>
|
||||
_timeline.Enqueue($" +{clock.ElapsedMilliseconds,6} ms [t{Environment.CurrentManagedThreadId,3}] test: {what}");
|
||||
|
||||
public string Describe() => "timeline:" + Environment.NewLine + string.Join(Environment.NewLine, _timeline);
|
||||
|
||||
public OtOpcUaConfigDbContext CreateDbContext()
|
||||
{
|
||||
if (Volatile.Read(ref _countdown) > 0 && Interlocked.Decrement(ref _countdown) == 0)
|
||||
var n = Interlocked.Increment(ref _creates);
|
||||
var before = Volatile.Read(ref _countdown);
|
||||
var counted = before > 0;
|
||||
var fire = counted && Interlocked.Decrement(ref _countdown) == 0;
|
||||
var caller = Caller();
|
||||
if (counted) CountedCallers.Enqueue(caller);
|
||||
_timeline.Enqueue(
|
||||
$" +{clock.ElapsedMilliseconds,6} ms [t{Environment.CurrentManagedThreadId,3}] create #{n} " +
|
||||
$"(countdown {before}{(fire ? " -> FIRE" : "")}) from {caller}");
|
||||
if (fire)
|
||||
{
|
||||
_action?.Invoke();
|
||||
try
|
||||
{
|
||||
ClosureRows = _action!();
|
||||
_timeline.Enqueue($" +{clock.ElapsedMilliseconds,6} ms closure committed ({ClosureRows} row)");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ClosureError = ex;
|
||||
_timeline.Enqueue($" +{clock.ElapsedMilliseconds,6} ms closure THREW {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
Fired = true;
|
||||
}
|
||||
return inner.CreateDbContext();
|
||||
}
|
||||
|
||||
private static string Caller()
|
||||
{
|
||||
var frames = new System.Diagnostics.StackTrace(2, false).GetFrames()
|
||||
.Select(f => f.GetMethod())
|
||||
.Where(m => m?.DeclaringType?.FullName?.Contains("ConfigPublishCoordinator", StringComparison.Ordinal) == true)
|
||||
.Select(m => $"{m!.DeclaringType!.Name}.{m.Name}")
|
||||
.Take(2)
|
||||
.ToList();
|
||||
return frames.Count == 0 ? "<unknown>" : string.Join(" <- ", frames);
|
||||
}
|
||||
}
|
||||
|
||||
private static DeploymentId SeedDeployment(
|
||||
|
||||
@@ -23,6 +23,12 @@ public sealed class SqlServerTestDatabase : IDisposable
|
||||
|
||||
private readonly string _databaseName;
|
||||
|
||||
/// <summary>Connection-open budget: the shared docker host is often heavily loaded (#1111).</summary>
|
||||
private const int ConnectTimeoutSeconds = 60;
|
||||
|
||||
/// <summary>Per-statement budget for creating + migrating the database (#1111).</summary>
|
||||
private const int MigrationCommandTimeoutSeconds = 300;
|
||||
|
||||
/// <summary>Creates and migrates the database.</summary>
|
||||
public SqlServerTestDatabase() : this(null)
|
||||
{
|
||||
@@ -36,8 +42,14 @@ public sealed class SqlServerTestDatabase : IDisposable
|
||||
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;";
|
||||
using var ctx = NewContext();
|
||||
$"Server={server};Database={_databaseName};User Id=sa;Password={saPassword};TrustServerCertificate=True;Encrypt=False;" +
|
||||
$"Connect Timeout={ConnectTimeoutSeconds};";
|
||||
// #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
|
||||
// be constructing its database, with nothing about the behaviour under test involved.
|
||||
using var ctx = new OtOpcUaConfigDbContext(new DbContextOptionsBuilder<OtOpcUaConfigDbContext>()
|
||||
.UseSqlServer(ConnectionString, o => o.CommandTimeout(MigrationCommandTimeoutSeconds)).Options);
|
||||
if (targetMigration is null) ctx.Database.Migrate();
|
||||
else ctx.GetService<Microsoft.EntityFrameworkCore.Migrations.IMigrator>().Migrate(targetMigration);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user