From ae9d917b731c8dd62646788774a5a233386d13ea Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Sat, 5 Dec 2026 00:45:50 -0500 Subject: [PATCH] test(controlplane): #1111 guard-and-flip reopen test: wait for recovery, prove non-vacuity, capture the interleaving On_sql_server_a_closure_between_guard_and_flip_is_not_reopened failed once with no message. Interleaving analysis + repro found no product race (the guard-RowVersion-conditioned flip held in every run, and removing that conditioning makes the test fail), but three test-side defects: - Vacuous interleaving: ResolveOne returns once PreStart ran, while the recovery load runs after a Task.Yield on the pool. A late load could take the interposer's first countdown slot, so the closure fired BEFORE the guard read and the test passed without exercising the race. The test now waits for ConfigPublishCoordinatorReadiness == Ready and asserts both counted contexts came from DispatchWrites. - A throwing closure (shared SQL refusing / timing out) surfaced only as a bare "Fired should be true" timeout; it is now captured and reported with its exception. - No context on failure: every assertion now carries a timeline of context hand-outs (offset, thread, countdown, calling coordinator frame), the closure outcome and a dump of both rows. The reproduced failures were all in SqlServerTestDatabase construction: transport errors / connection refused while the shared central SQL was stopped, and a migration statement (sp_releaseapplock) overrunning the 30 s default command timeout while several SQL-backed classes migrate in parallel on a loaded server. Migration now runs with a 300 s command timeout and a 60 s connect timeout. Co-Authored-By: Claude --- .../ConfigPublishCoordinatorRecoveryTests.cs | 160 +++++++++++++++--- .../Harness/SqlServerTestDatabase.cs | 16 +- 2 files changed, 155 insertions(+), 21 deletions(-) diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorRecoveryTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorRecoveryTests.cs index 91a947c8d..e50d1aa31 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorRecoveryTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorRecoveryTests.cs @@ -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. /// + /// + /// #1111: this failed once in a rerun with no message captured. Every assertion now carries the + /// 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. + /// [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); } - /// Runs an action just before handing out the SECOND context after arming (HandleDispatch: guard, then flip). - private sealed class InterposingDbFactory(IDbContextFactory inner) + /// A presence wait whose failure carries (built only on failure — #1111). + private void AwaitWithDiag(Action assertion, Func 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); + } + } + + /// Both rows (status, reason, expected-set size) for a failure message (#1111). + 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: "; + } + } + + /// + /// 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). + /// + private sealed class InterposingDbFactory( + IDbContextFactory inner, System.Diagnostics.Stopwatch clock) : IDbContextFactory { - private Action? _action; + private readonly System.Collections.Concurrent.ConcurrentQueue _timeline = new(); + private Func? _action; private int _countdown; + private int _creates; public volatile bool Fired; + public volatile Exception? ClosureError; + public int ClosureRows = -1; - public void OnSecondCreate(Action action) + /// Who asked for each context that counted towards the countdown, in order. + public System.Collections.Concurrent.ConcurrentQueue CountedCallers { get; } = new(); + + public void OnSecondCreate(Func 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 ? "" : string.Join(" <- ", frames); + } } private static DeploymentId SeedDeployment( 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 8aa841de8..21ccbc660 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 @@ -23,6 +23,12 @@ public sealed class SqlServerTestDatabase : IDisposable private readonly string _databaseName; + /// Connection-open budget: the shared docker host is often heavily loaded (#1111). + private const int ConnectTimeoutSeconds = 60; + + /// Per-statement budget for creating + migrating the database (#1111). + private const int MigrationCommandTimeoutSeconds = 300; + /// Creates and migrates the database. 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() + .UseSqlServer(ConnectionString, o => o.CommandTimeout(MigrationCommandTimeoutSeconds)).Options); if (targetMigration is null) ctx.Database.Migrate(); else ctx.GetService().Migrate(targetMigration); }