Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorOffThreadWritesTests.cs
T
Joseph Doherty 69f475392c fix(controlplane): #1051 coordinator dispatch seed + terminal writes off the actor thread; driver-operation audit write retried
H-6 remainder: ConfigPublishCoordinator runs the dispatch guard/seed (incl. the #977 superseded close) and the
Sealed/PartiallyFailed/TimedOut writes through RunDbWork - a pool-thread task whose outcome is applied on the actor
thread while a Busy behaviour stashes everything else. A failed write is rethrown when it reports back (same
restart-and-recover contract as before); recovery runs the same work inline (failure = failed load).
H-3 remainder: a transient Restart/Reconnect ConfigEdit audit failure is retried (1 s doubling, 30 s cap, 6 attempts);
a ConfigDb rejection (poison allowlist) is not.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 15:07:25 -05:00

254 lines
12 KiB
C#

using Akka.Actor;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
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.Coordinators;
using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests;
/// <summary>
/// lmxopcua#1051 (#996 / review H-6 remainder): the dispatch guard + expected-set seed and the terminal
/// Sealed / PartiallyFailed / TimedOut writes used to be blocking EF calls on the coordinator's thread, so a slow or
/// unreachable ConfigDb held the Akka dispatcher thread for a connect timeout per call. They now run on a pool
/// thread; the coordinator stashes what arrives meanwhile and decides once the write reports back. Each test holds a
/// write open on a gate and proves the actor still answers <see cref="Identify"/> (auto-received, so it is answered
/// only when the actor's thread is free), then releases the gate and checks the write landed (positive control).
/// </summary>
public sealed class ConfigPublishCoordinatorOffThreadWritesTests : ControlPlaneActorTestBase
{
private static readonly RevisionHash Revision = RevisionHash.Parse(new string('f', 64));
private static readonly TimeSpan NoTimeout = TimeSpan.FromMinutes(5);
private static readonly TimeSpan ProbeBudget = TimeSpan.FromSeconds(2);
[Fact]
public async Task Dispatch_guard_and_seed_do_not_hold_the_coordinator_thread()
{
var ct = TestContext.Current.CancellationToken;
var dbName = Guid.NewGuid().ToString("N");
var direct = NewInMemoryDbFactory(dbName);
var gated = new GatedDbFactory(NewInMemoryDbFactory(dbName));
var coordinator = Spawn(gated);
// Let the recovery load finish (ungated), then close the gate before the dispatch.
WaitForReady(ct);
// Seeded only once the coordinator is Ready: a Dispatching row present at start is re-driven by recovery itself.
Seed(direct, ["site-a-1:4053"], out var deploymentId);
gated.Close();
coordinator.Tell(new DispatchDeployment(deploymentId, Revision, CorrelationId.NewId()));
gated.WaitEntered(TimeSpan.FromSeconds(5)).ShouldBeTrue("the dispatch must reach the ConfigDb");
var identity = await coordinator.Ask<ActorIdentity>(new Identify("probe"), ProbeBudget, ct);
identity.Subject.ShouldBe(coordinator, "the coordinator thread must not wait on the dispatch's ConfigDb calls");
// An ack that arrives while the seed is in flight is held (stashed), not lost: it counts once the seed lands.
coordinator.Tell(new ApplyAck(deploymentId, NodeId.Parse("site-a-1:4053"), ApplyAckOutcome.Applied, null, CorrelationId.NewId()));
gated.Open();
AwaitAssert(() =>
{
using var db = direct.CreateDbContext();
db.Deployments.Single().Status.ShouldBe(DeploymentStatus.Sealed);
db.NodeDeploymentStates.Single().Status.ShouldBe(NodeDeploymentStatus.Applied);
}, duration: PresenceBudget, cancellationToken: ct);
}
[Theory]
[InlineData(ApplyAckOutcome.Applied, DeploymentStatus.Sealed)]
[InlineData(ApplyAckOutcome.Failed, DeploymentStatus.PartiallyFailed)]
public async Task Terminal_write_after_the_last_ack_does_not_hold_the_coordinator_thread(ApplyAckOutcome outcome, DeploymentStatus expected)
{
var ct = TestContext.Current.CancellationToken;
var dbName = Guid.NewGuid().ToString("N");
var direct = NewInMemoryDbFactory(dbName);
var gated = new GatedDbFactory(NewInMemoryDbFactory(dbName));
var coordinator = Spawn(gated);
WaitForReady(ct);
// Seeded only once the coordinator is Ready: a Dispatching row present at start is re-driven by recovery itself.
Seed(direct, ["site-a-1:4053"], out var deploymentId);
coordinator.Tell(new DispatchDeployment(deploymentId, Revision, CorrelationId.NewId()));
AwaitAssert(() =>
{
using var db = direct.CreateDbContext();
db.Deployments.Single().Status.ShouldBe(DeploymentStatus.AwaitingApplyAcks);
}, duration: PresenceBudget, cancellationToken: ct);
// The ack's own row write goes through; the terminal write that follows it is held on the gate.
gated.CloseAfter(1);
coordinator.Tell(new ApplyAck(deploymentId, NodeId.Parse("site-a-1:4053"), outcome, null, CorrelationId.NewId()));
gated.WaitEntered(TimeSpan.FromSeconds(5)).ShouldBeTrue("the terminal write must reach the ConfigDb");
var identity = await coordinator.Ask<ActorIdentity>(new Identify("probe"), ProbeBudget, ct);
identity.Subject.ShouldBe(coordinator, "the coordinator thread must not wait on the terminal ConfigDb write");
gated.Open();
AwaitAssert(() =>
{
using var db = direct.CreateDbContext();
db.Deployments.Single().Status.ShouldBe(expected);
}, duration: PresenceBudget, cancellationToken: ct);
}
[Fact]
public async Task Deadline_TimedOut_write_does_not_hold_the_coordinator_thread_and_names_the_silent_node()
{
var ct = TestContext.Current.CancellationToken;
var dbName = Guid.NewGuid().ToString("N");
var direct = NewInMemoryDbFactory(dbName);
var gated = new GatedDbFactory(NewInMemoryDbFactory(dbName));
var coordinator = Spawn(gated);
WaitForReady(ct);
// Seeded only once the coordinator is Ready: a Dispatching row present at start is re-driven by recovery itself.
Seed(direct, ["site-a-1:4053"], out var deploymentId);
coordinator.Tell(new DispatchDeployment(deploymentId, Revision, CorrelationId.NewId()));
AwaitAssert(() =>
{
using var db = direct.CreateDbContext();
db.Deployments.Single().Status.ShouldBe(DeploymentStatus.AwaitingApplyAcks);
}, duration: PresenceBudget, cancellationToken: ct);
gated.Close();
coordinator.Tell(new ConfigPublishCoordinator.DeadlineElapsed(deploymentId));
gated.WaitEntered(TimeSpan.FromSeconds(5)).ShouldBeTrue("the TimedOut write must reach the ConfigDb");
var identity = await coordinator.Ask<ActorIdentity>(new Identify("probe"), ProbeBudget, ct);
identity.Subject.ShouldBe(coordinator, "the coordinator thread must not wait on the TimedOut ConfigDb write");
gated.Open();
AwaitAssert(() =>
{
using var db = direct.CreateDbContext();
var row = db.Deployments.Single();
row.Status.ShouldBe(DeploymentStatus.TimedOut);
row.FailureReason.ShouldNotBeNull();
row.FailureReason.ShouldContain("site-a-1:4053");
}, duration: PresenceBudget, cancellationToken: ct);
}
/// <summary>
/// A terminal write that FAILS keeps the pre-#1051 contract: the coordinator restarts, recovers the still-in-flight
/// row from the ConfigDb and decides it again — here the recovered row has every ack landed, so it seals.
/// </summary>
[Fact]
public void Failed_seal_write_restarts_and_recovery_seals()
{
var ct = TestContext.Current.CancellationToken;
var dbName = Guid.NewGuid().ToString("N");
var direct = NewInMemoryDbFactory(dbName);
var gated = new GatedDbFactory(NewInMemoryDbFactory(dbName));
var coordinator = Spawn(gated);
WaitForReady(ct);
Seed(direct, ["site-a-1:4053"], out var deploymentId);
coordinator.Tell(new DispatchDeployment(deploymentId, Revision, CorrelationId.NewId()));
AwaitAssert(() =>
{
using var db = direct.CreateDbContext();
db.Deployments.Single().Status.ShouldBe(DeploymentStatus.AwaitingApplyAcks);
}, duration: PresenceBudget, cancellationToken: ct);
// The ack row lands; the very next context (the seal) throws once.
gated.FailAfter(1);
coordinator.Tell(new ApplyAck(deploymentId, NodeId.Parse("site-a-1:4053"), ApplyAckOutcome.Applied, null, CorrelationId.NewId()));
AwaitAssert(() =>
{
gated.Failures.ShouldBe(1);
using var db = direct.CreateDbContext();
db.Deployments.Single().Status.ShouldBe(DeploymentStatus.Sealed);
}, duration: PresenceBudget, cancellationToken: ct);
}
private readonly ConfigPublishCoordinatorReadiness _readiness = new();
private IActorRef Spawn(IDbContextFactory<OtOpcUaConfigDbContext> factory) => Sys.ActorOf(ConfigPublishCoordinator.Props(
factory, NoTimeout, readiness: _readiness,
loadRetryMin: TimeSpan.FromMilliseconds(50), loadRetryMax: TimeSpan.FromMilliseconds(200)));
private void WaitForReady(CancellationToken ct) =>
AwaitAssert(() => _readiness.Current.State.ShouldBe(ConfigPublishCoordinatorState.Ready),
duration: PresenceBudget, cancellationToken: ct);
private static void Seed(IDbContextFactory<OtOpcUaConfigDbContext> factory, string[] nodeIds, out DeploymentId id)
{
id = DeploymentId.NewId();
using var db = factory.CreateDbContext();
db.ServerClusters.Add(new ServerCluster
{
ClusterId = "SITE-A", Name = "Site A", Enterprise = "zb", Site = "site-a",
NodeCount = (byte)nodeIds.Length, RedundancyMode = RedundancyMode.None, CreatedBy = "test",
});
foreach (var nodeId in nodeIds)
db.ClusterNodes.Add(new ClusterNode
{
NodeId = nodeId, ClusterId = "SITE-A", Host = nodeId.Split(':')[0],
ApplicationUri = $"urn:OtOpcUa:{nodeId}", Enabled = true, CreatedBy = "test",
});
db.Deployments.Add(new Deployment
{
DeploymentId = id.Value, RevisionHash = Revision.Value, Status = DeploymentStatus.Dispatching, CreatedBy = "test",
});
db.SaveChanges();
}
/// <summary>
/// A factory whose context creation can be held on a gate (a connect that does not answer) or made to throw. Both
/// can be armed to take effect only after N more contexts have been created.
/// </summary>
private sealed class GatedDbFactory(IDbContextFactory<OtOpcUaConfigDbContext> inner) : IDbContextFactory<OtOpcUaConfigDbContext>
{
private readonly ManualResetEventSlim _gate = new(initialState: true);
private readonly SemaphoreSlim _entered = new(0);
private int _closeAfter = -1;
private int _failAfter = -1;
private int _created;
private int _failures;
public int Created => Volatile.Read(ref _created);
public int Failures => Volatile.Read(ref _failures);
public void Close() => _gate.Reset();
public void CloseAfter(int passes) => Volatile.Write(ref _closeAfter, passes);
public void FailAfter(int passes) => Volatile.Write(ref _failAfter, passes);
public void Open() { Volatile.Write(ref _closeAfter, -1); _gate.Set(); }
public bool WaitEntered(TimeSpan timeout) => _entered.Wait(timeout);
public OtOpcUaConfigDbContext CreateDbContext()
{
Interlocked.Increment(ref _created);
if (Countdown(ref _closeAfter)) _gate.Reset();
if (Countdown(ref _failAfter))
{
Interlocked.Increment(ref _failures);
throw new InvalidOperationException("ConfigDb unreachable (test)");
}
if (!_gate.IsSet)
{
_entered.Release();
_gate.Wait();
}
return inner.CreateDbContext();
}
/// <summary>True exactly once: when an armed countdown reaches zero on this call.</summary>
private static bool Countdown(ref int counter)
{
while (true)
{
var current = Volatile.Read(ref counter);
if (current < 0) return false;
if (Interlocked.CompareExchange(ref counter, current == 0 ? -1 : current - 1, current) != current) continue;
return current == 0;
}
}
}
}