diff --git a/docs/DriverLifecycle.md b/docs/DriverLifecycle.md index 31bc628fd..6064f68da 100644 --- a/docs/DriverLifecycle.md +++ b/docs/DriverLifecycle.md @@ -197,8 +197,11 @@ Things to know before touching any of this: - **Restart/Reconnect reply = the dispatch (#996, review H-3).** `AdminOperationsActor` handles `RestartDriver` / `ReconnectDriver` as synchronous receives: dispatch to the nodes, reply success, then write the `ConfigEdit` audit row on a pool - thread. An audit-write failure is logged (with op, driver, user, correlation) and never changes the reply — it used to answer - "failed" for a command already on its way (the operator retried ⇒ a second restart) and suspended the admin mailbox for a connect timeout. + thread. An audit-write failure never changes the reply — it used to answer "failed" for a command already on its way (the operator + retried ⇒ a second restart) and suspended the admin mailbox for a connect timeout. Since #1051 a TRANSIENT failure is retried on a + doubling backoff (1 s → 30 s cap, `MaxDriverAuditAttempts` = 6 attempts ≈ 30 s of outage); a write the ConfigDb REJECTS (the + coordinator's poison allowlist) is not retried; past the cap the record is logged at Error and dropped. At-least-once: a write + that committed but reported failure can repeat the row. - ⚠️ **The supervision route is the invisible one, and it was the worst.** There is **no** `SupervisorStrategy` anywhere under `src/Server`, so a child that throws gets Akka's default `Restart`. diff --git a/docs/Redundancy.md b/docs/Redundancy.md index ae15892e3..af189f357 100644 --- a/docs/Redundancy.md +++ b/docs/Redundancy.md @@ -835,8 +835,12 @@ deployment green fleet-wide. Now: thread (`AckPersisted` is piped back; one write per node at a time, a newer ack for the same node waits behind it) and decides count/seal on the actor thread. With the ConfigDb slow or unreachable (no EF retry strategy ⇒ a connect timeout per call) the timeouts now overlap instead of serialising N × timeout of unresponsive mailbox; the deadline kicks its whole unpersisted backlog off at - once and decides as soon as the last write lands. The dispatch guard/seed and the terminal seal/fail/timeout writes are still - synchronous single calls (see the follow-up issue). + once and decides as soon as the last write lands. Since #1051 the dispatch guard + expected-set seed (and the #977 superseded + close) and the terminal Sealed/PartiallyFailed/TimedOut writes run off-thread too (`RunDbWork`): the coordinator enters a `Busy` + behaviour that stashes everything but the write's outcome, so each decision stays sequential while the dispatcher thread is free. + A failed terminal/seed write is rethrown on the actor thread when it reports back — the same restart-and-recover contract as the + old throwing `SaveChanges`. Recovery (`ApplyRecovery`, once per singleton start) runs the same work inline, so a failure there is + still a failed load retried on the backoff. - **Central records it without a status-model change.** `ConfigPublishCoordinator.PersistNodeAck` keeps the node's `NodeDeploymentState.Status = Applied` and writes `FailureReason = "Applied degraded: "` (`ConfigPublishCoordinator.IsDegraded` = Applied **and** a reason). The deployment still **seals** — diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs index 247fbe0a7..19ea128e2 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs @@ -11,6 +11,7 @@ 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.Configuration.Validation; +using ZB.MOM.WW.OtOpcUa.ControlPlane.Coordinators; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using ZB.MOM.WW.OtOpcUa.Core.Scripting; @@ -21,7 +22,7 @@ namespace ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations; /// a deployment" workflow plus (eventually) all mutating live-edit ops invoked by the admin UI. /// Routed to via from anywhere in the cluster. /// -public sealed class AdminOperationsActor : ReceiveActor +public sealed class AdminOperationsActor : ReceiveActor, IWithTimers { private readonly IDbContextFactory _dbFactory; private readonly IActorRef _coordinator; @@ -50,6 +51,21 @@ public sealed class AdminOperationsActor : ReceiveActor /// #950: how long an /alerts ack/shelve waits for the nodes' verdicts. private readonly TimeSpan _alarmVerdictWindow; + /// #1051: first retry delay of a failed driver-operation audit write (doubles, capped at 30 s). + private readonly TimeSpan _driverAuditRetryDelay; + + /// Gets or sets the timer scheduler (the #1051 audit-write retry backoff). + public ITimerScheduler Timers { get; set; } = null!; + + /// Default first retry delay of a failed Restart/Reconnect ConfigEdit audit write (#1051). + public static readonly TimeSpan DefaultDriverAuditRetryDelay = TimeSpan.FromSeconds(1); + + /// + /// Attempts (first write + retries) at a Restart/Reconnect ConfigEdit audit row before it is logged and dropped + /// (#1051): 1 + 2 + 4 + 8 + 16 s of backoff, about half a minute of ConfigDb outage covered. + /// + public const int MaxDriverAuditAttempts = 6; + /// The StartDeployment whose compose is running off-actor, or null. See . private StartDeployment? _composeInFlight; @@ -66,6 +82,7 @@ public sealed class AdminOperationsActor : ReceiveActor /// #950: how long an /alerts ack/shelve waits for the nodes' verdicts; defaults to . /// lmxopcua#971 follow-up: the deploy-time script compile gate, or to skip it. /// How a refused script is treated (Error default | Warn | Off). + /// #1051: first retry delay of a failed Restart/Reconnect ConfigEdit audit write; defaults to . /// Props configured to create an AdminOperationsActor. public static Props Props( IDbContextFactory dbFactory, @@ -76,10 +93,11 @@ public sealed class AdminOperationsActor : ReceiveActor TimeSpan? applyDeadline = null, TimeSpan? alarmVerdictWindow = null, IDeployScriptChecker? scriptChecker = null, - ScriptCompileGateMode scriptCompileGateMode = ScriptCompileGateMode.Error) => + ScriptCompileGateMode scriptCompileGateMode = ScriptCompileGateMode.Error, + TimeSpan? driverAuditRetryDelay = null) => Akka.Actor.Props.Create(() => new AdminOperationsActor(dbFactory, coordinator, probes, tagConfigValidationMode, meshRouter, applyDeadline, - alarmVerdictWindow, scriptChecker, scriptCompileGateMode)); + alarmVerdictWindow, scriptChecker, scriptCompileGateMode, driverAuditRetryDelay)); /// Initializes a new instance of the AdminOperationsActor. /// Factory for creating config database contexts. @@ -91,6 +109,7 @@ public sealed class AdminOperationsActor : ReceiveActor /// #950: the /alerts verdict collection window. /// lmxopcua#971 follow-up: the deploy-time script compile gate, or to skip it. /// How a refused script is treated (Error default | Warn | Off). + /// #1051: first retry delay of a failed driver-operation audit write. public AdminOperationsActor( IDbContextFactory dbFactory, IActorRef coordinator, @@ -100,8 +119,10 @@ public sealed class AdminOperationsActor : ReceiveActor TimeSpan? applyDeadline = null, TimeSpan? alarmVerdictWindow = null, IDeployScriptChecker? scriptChecker = null, - ScriptCompileGateMode scriptCompileGateMode = ScriptCompileGateMode.Error) + ScriptCompileGateMode scriptCompileGateMode = ScriptCompileGateMode.Error, + TimeSpan? driverAuditRetryDelay = null) { + _driverAuditRetryDelay = driverAuditRetryDelay ?? DefaultDriverAuditRetryDelay; _scriptChecker = scriptCompileGateMode == ScriptCompileGateMode.Off ? null : scriptChecker; _scriptCompileGateMode = scriptCompileGateMode; _alarmVerdictWindow = alarmVerdictWindow ?? AlarmCommandVerdictCollector.DefaultWindow; @@ -123,6 +144,7 @@ public sealed class AdminOperationsActor : ReceiveActor Receive(HandleRestartDriver); Receive(HandleReconnectDriver); Receive(HandleDriverOperationAuditFailed); + Receive(m => StartDriverOperationAudit(m.Audit)); Receive(HandleAcknowledgeAlarm); Receive(HandleShelveAlarm); } @@ -900,6 +922,12 @@ public sealed class AdminOperationsActor : ReceiveActor // Audit off the mailbox. Cluster state is read HERE (actor thread); the DB work is a pool-thread task. var sourceNode = Akka.Cluster.Cluster.Get(Context.System).SelfAddress.Host ?? "unknown"; + StartDriverOperationAudit(new DriverOperationAudit(op, driverInstanceId, actor, correlationId, sourceNode, Attempt: 1)); + } + + /// One attempt at the ConfigEdit row of a dispatched driver operation, on a pool thread (#996 / H-3). + private void StartDriverOperationAudit(DriverOperationAudit audit) + { var factory = _dbFactory; Task.Run(async () => { @@ -907,21 +935,60 @@ public sealed class AdminOperationsActor : ReceiveActor db.ConfigEdits.Add(new ConfigEdit { EntityType = "DriverInstance", - EntityId = Guid.TryParse(driverInstanceId, out var guid) ? guid : Guid.Empty, - FieldsJson = $"{{\"op\":\"{op}\",\"driverInstanceId\":{System.Text.Json.JsonSerializer.Serialize(driverInstanceId)}}}", - EditedBy = actor, - SourceNode = sourceNode, + EntityId = Guid.TryParse(audit.DriverInstanceId, out var guid) ? guid : Guid.Empty, + FieldsJson = $"{{\"op\":\"{audit.Op}\",\"driverInstanceId\":{System.Text.Json.JsonSerializer.Serialize(audit.DriverInstanceId)}}}", + EditedBy = audit.Actor, + SourceNode = audit.SourceNode, }); await db.SaveChangesAsync().ConfigureAwait(false); - }).PipeTo(Self, failure: ex => new DriverOperationAuditFailed(op, driverInstanceId, actor, correlationId, ex)); + }).PipeTo(Self, failure: ex => new DriverOperationAuditFailed(audit, ex is AggregateException { InnerException: { } inner } ? inner : ex)); } - private void HandleDriverOperationAuditFailed(DriverOperationAuditFailed m) => - _log.Warning(m.Error, - "AdminOps: the audit row for {Op} of {DriverInstanceId} by {User} could NOT be written (correlation {CorrelationId}); " + - "the command WAS dispatched and the operator was told so", - m.Op, m.DriverInstanceId, m.Actor, m.CorrelationId); + /// + /// lmxopcua#1051 (H-3 remainder): a failed audit write is RETRIED on a doubling backoff (capped at 30 s) up to + /// attempts — a ConfigDb blip used to lose the operator's Restart/Reconnect + /// from the audit timeline. A write the database REJECTS (constraint, truncation — the coordinator's poison + /// allowlist) fails identically every time and is not retried. Either way the command's reply is untouched: it was + /// dispatched. At-least-once: a write that committed but reported failure (a timeout after commit) can repeat a row. + /// + private void HandleDriverOperationAuditFailed(DriverOperationAuditFailed m) + { + var a = m.Audit; + var poison = ConfigPublishCoordinator.IsPoison(m.Error); + if (!poison && a.Attempt < MaxDriverAuditAttempts) + { + var delay = TimeSpan.FromTicks(Math.Min( + TimeSpan.FromSeconds(30).Ticks, _driverAuditRetryDelay.Ticks * (1L << Math.Min(a.Attempt - 1, 20)))); + if (a.Attempt == 1) + _log.Warning(m.Error, + "AdminOps: the audit row for {Op} of {DriverInstanceId} by {User} could not be written (correlation {CorrelationId}); " + + "retrying in {Delay}. The command WAS dispatched and the operator was told so", + a.Op, a.DriverInstanceId, a.Actor, a.CorrelationId, delay); + else + _log.Warning( + "AdminOps: still cannot write the audit row for {Op} of {DriverInstanceId} by {User} (attempt {Attempt}: {Error}); retrying in {Delay}", + a.Op, a.DriverInstanceId, a.Actor, a.Attempt, m.Error.Message, delay); + Timers.StartSingleTimer(a.RetryKey, new RetryDriverOperationAudit(a with { Attempt = a.Attempt + 1 }), delay); + return; + } + + _log.Error(m.Error, + "AdminOps: the audit row for {Op} of {DriverInstanceId} by {User} (correlation {CorrelationId}) could NOT be written " + + "after {Attempts} attempt(s) ({Why}) and is dropped; the command WAS dispatched and the operator was told so", + a.Op, a.DriverInstanceId, a.Actor, a.CorrelationId, a.Attempt, poison ? "rejected by the ConfigDb" : "ConfigDb unavailable"); + } + + /// A dispatched driver operation's audit record, and which attempt at writing it this is (#1051). + private sealed record DriverOperationAudit( + string Op, string DriverInstanceId, string Actor, object CorrelationId, string SourceNode, int Attempt) + { + /// The retry timer's key: one pending retry per audit record. + public Guid RetryKey { get; init; } = Guid.NewGuid(); + } /// The off-thread ConfigEdit audit write for a dispatched driver operation failed (#996 / H-3). - private sealed record DriverOperationAuditFailed(string Op, string DriverInstanceId, string Actor, object CorrelationId, Exception Error); + private sealed record DriverOperationAuditFailed(DriverOperationAudit Audit, Exception Error); + + /// The backoff tick of a failed audit write (#1051). + private sealed record RetryDriverOperationAudit(DriverOperationAudit Audit); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Coordinators/ConfigPublishCoordinator.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Coordinators/ConfigPublishCoordinator.cs index 515d957f0..50b185964 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Coordinators/ConfigPublishCoordinator.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Coordinators/ConfigPublishCoordinator.cs @@ -76,6 +76,16 @@ namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Coordinators; /// (driver-only nodes never write their own row), so a failed PersistNodeAck re-queues the ack on a timer /// instead of throwing — a throw would restart the actor and drop it. /// +/// +/// No ConfigDb call blocks the coordinator thread in steady state (#996 / #1051, review H-6). Ack writes run +/// on pool threads and report back (AckPersisted). The dispatch guard + expected-set seed and the terminal +/// Sealed / PartiallyFailed / TimedOut writes run on a pool thread too, through : the +/// coordinator enters a Busy behaviour that STASHES everything except the write's outcome, so the decision it +/// is making stays strictly sequential (nothing is decided against half-written state) while the Akka dispatcher +/// thread is released for the connect timeout. A failed terminal write still throws on the actor thread when its +/// outcome arrives, keeping the restart-and-recover contract. The recovery path (, once per +/// singleton start) runs the same work inline, so a failure there stays a failed load retried on the backoff. +/// /// public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithUnboundedStash { @@ -183,6 +193,21 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU private DeploymentId? _current; private HashSet _expectedAcks = new(NodeIdComparer); + /// + /// True while runs: then executes inline, so a failure is a + /// failed load (retried on the backoff) exactly as before #1051 rather than a restart. + /// + private bool _inlineDbWork; + + /// The ticket of the off-thread write this incarnation is waiting on in Busy; 0 when none. + private long _busyTicket; + + /// What to do on the actor thread when the write identified by reports back. + private Action? _onDbWorkDone; + + /// Process-wide so a late outcome from a previous incarnation can never match the current one's ticket. + private static long s_nextTicket; + /// Gets the timer scheduler for managing apply deadlines. public ITimerScheduler Timers { get; set; } = null!; @@ -247,6 +272,8 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU Receive(HandleRecoveryLoadFailed); Receive(_ => StartRecoveryLoad()); Receive(_ => { /* DPS subscribe confirmation */ }); + // A write a previous incarnation started reports to the same ref; it is nothing to this one. + Receive(_ => { }); Receive(msg => { _log.Info( @@ -272,8 +299,70 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU Receive(_ => { }); Receive(_ => { }); Receive(_ => { }); + Receive(_ => { }); } + /// + /// While an off-thread dispatch / terminal write runs (#1051): only its outcome is handled; everything else is + /// stashed and replayed, in arrival order, once the outcome has been applied. + /// + private void Busy() + { + Receive(done => + { + if (done.Ticket != _busyTicket) return; // a previous incarnation's write + var apply = _onDbWorkDone!; + _onDbWorkDone = null; + _busyTicket = 0; + UnbecomeStacked(); + // Unstash BEFORE applying: the outcome may start the next write (Busy again — the replay is re-stashed in + // order), or throw to restart the actor (the replayed messages are already back in the mailbox). + Stash.UnstashAll(); + apply(done.Result, done.Error); + }); + ReceiveAny(_ => Stash.Stash()); + } + + /// + /// Runs (ConfigDb I/O touching no actor state) off the actor thread and applies its + /// outcome on the actor thread, stashing every other message meanwhile (#996 / #1051, review H-6). Inline during + /// recovery (). + /// + /// The database work; receives the context factory. + /// Applied on the actor thread with the work's result. + /// Applied on the actor thread with the work's exception (unwrapped). + private void RunDbWork( + Func, T> work, Action onSuccess, Action onFailure) + { + if (_inlineDbWork) + { + T result; + try { result = work(_dbFactory); } + catch (Exception ex) { onFailure(ex); return; } + onSuccess(result); + return; + } + + var ticket = Interlocked.Increment(ref s_nextTicket); + _busyTicket = ticket; + _onDbWorkDone = (result, error) => + { + if (error is null) onSuccess((T)result!); + else onFailure(error); + }; + var factory = _dbFactory; + // Task.Run: a factory/provider that throws synchronously still faults the TASK, never this thread. + Task.Run(() => (object?)work(factory)).PipeTo( + Self, + success: r => new DbWorkDone(ticket, r, null), + failure: ex => new DbWorkDone(ticket, null, ex is AggregateException { InnerException: { } inner } ? inner : ex)); + BecomeStacked(Busy); + } + + /// A failed terminal / dispatch write: rethrown on the actor thread so the supervisor restarts the actor and + /// recovery re-reads the still-in-flight row — the pre-#1051 contract of a throwing SaveChanges. + private static void Rethrow(Exception ex) => System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(ex); + /// protected override void PreStart() { @@ -373,6 +462,7 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU Timers.Cancel(LoadRetryTimerKey); try { + _inlineDbWork = true; ApplyRecovery(msg.Inflight); } catch (Exception ex) @@ -382,6 +472,10 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU HandleRecoveryLoadFailed(new RecoveryLoadFailed(ex)); return; } + finally + { + _inlineDbWork = false; + } if (_failedLoads > 0) _log.Info("ConfigPublishCoordinator loaded its recovery state after {Failed} failed attempt(s)", _failedLoads); @@ -410,11 +504,8 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU if (malformed is not null) { _log.Error("Coordinator cannot recover deployment {Id}: {Problem}. Closing it as PartiallyFailed", _current, malformed); - using var db = _dbFactory.CreateDbContext(); - UpdateDeploymentStatus(db, _current.Value, DeploymentStatus.PartiallyFailed, onlyIfInFlight: true); - SetFailureReason(db, Truncate( + WriteTerminal(_dbFactory, _current.Value, DeploymentStatus.PartiallyFailed, sealNow: false, Truncate( $"The deploy coordinator could not recover this deployment: {malformed}. Redeploy.")); - db.SaveChanges(); ResetForNext(); return; } @@ -518,6 +609,27 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU return; } + // Gitea #977 (H-4): a DIFFERENT deployment still in flight is closed (in the same off-thread work, after the + // guard) before the new one is adopted. Captured HERE, on the actor thread; Busy keeps it stable meanwhile. + Supersede? supersede = _current is { } prior && prior != msg.DeploymentId + ? new Supersede(prior, _acks.Count, _expectedAcks.Count) + : null; + + // #1051 (H-6): the guard read, the superseded close and the expected-set seed are ConfigDb round-trips — off the + // actor thread; the decisions below are applied when the work reports back. + RunDbWork( + factory => DispatchWrites(factory, msg.DeploymentId, supersede), + outcome => ApplyDispatch(msg, supersede, outcome), + Rethrow); + } + + /// + /// The ConfigDb half of a dispatch: the terminal-state guard, the superseded close, and the expected-set seed + + /// AwaitingApplyAcks flip. Static and touching no actor state: it runs on a pool thread (#1051). + /// + private static DispatchOutcome DispatchWrites( + IDbContextFactory dbFactory, DeploymentId id, Supersede? supersede) + { // Terminal-state guard (fix round 1): a late or re-delivered dispatch for a row that is already // Sealed / PartiallyFailed / TimedOut — e.g. one AdminOps closed as a lost dispatch while this message // was still queued — must never flip it back to AwaitingApplyAcks or seed an expected set for it. @@ -527,68 +639,70 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU // TimedOut between the guard and the flip, and the flip would silently reopen the row. With the guard's // RowVersion, any change since the guard read makes the flip a concurrency conflict instead. byte[]? guardRowVersion; - using (var check = _dbFactory.CreateDbContext()) + using (var check = dbFactory.CreateDbContext()) { var guard = check.Deployments .AsNoTracking() - .Where(d => d.DeploymentId == msg.DeploymentId.Value) + .Where(d => d.DeploymentId == id.Value) .Select(d => new { d.Status, d.RowVersion }) .FirstOrDefault(); if (guard?.Status is DeploymentStatus.Sealed or DeploymentStatus.PartiallyFailed or DeploymentStatus.TimedOut) - { - _log.Warning( - "Ignoring DispatchDeployment {Id}: the deployment is already {Status} (a late or duplicated dispatch)", - msg.DeploymentId, guard.Status); - if (_current == msg.DeploymentId) ResetForNext(); - return; - } + return new DispatchOutcome(DispatchVerdict.AlreadyTerminal, guard.Status, null, null, null); guardRowVersion = guard?.RowVersion; } - // Gitea #977 (H-4): a DIFFERENT deployment is still in flight. Adopting the new one overwrites _current, clears - // the acks and replaces the single deadline timer — so nothing would ever write a terminal status for the old - // one: its row stayed AwaitingApplyAcks forever and AdminOps refused every later deploy as - // AnotherDeploymentInFlight. Close it first (TimedOut, only if still in flight, with a reason naming the - // successor), then adopt the new one. - if (_current is { } prior && prior != msg.DeploymentId) CloseSuperseded(prior, msg.DeploymentId); - - _current = msg.DeploymentId; - _acks.Clear(); - _degraded.Clear(); + Exception? supersedeError = null; + if (supersede is not null) + { + // Never fatal: a failed write is logged and the new dispatch proceeds — the AdminOps lost-dispatch closure + // and the coordinator's recovery remain the backstops for a row this could not close. + try + { + WriteTerminal(dbFactory, supersede.Prior, DeploymentStatus.TimedOut, sealNow: false, Truncate( + $"Superseded by deployment {id} before its acks completed ({supersede.Acked}/{supersede.Expected} landed). " + + "Its nodes were dispatched the newer deployment instead; redeploy this revision if it is still wanted.")); + } + catch (Exception ex) + { + supersedeError = ex; + } + } // Seed NodeDeploymentState rows so a failover knows which nodes were expected to ack. - using (var db = _dbFactory.CreateDbContext()) + try { - // Idempotent on a re-dispatch (PreStart re-drives a lost dispatch through this handler): rows + using var db = dbFactory.CreateDbContext(); + HashSet expected; + // Idempotent on a re-dispatch (recovery re-drives a lost dispatch through this handler): rows // already seeded for this deployment ARE the expected set — re-discovering would both duplicate // the primary key and let a node toggled since the first attempt change who is expected. var seeded = db.NodeDeploymentStates .AsNoTracking() - .Where(x => x.DeploymentId == msg.DeploymentId.Value) + .Where(x => x.DeploymentId == id.Value) .Select(x => x.NodeId) .ToList(); if (seeded.Count > 0) { - _expectedAcks = seeded.Select(NodeId.Parse).ToHashSet(NodeIdComparer); + expected = seeded.Select(NodeId.Parse).ToHashSet(NodeIdComparer); } else { // Discovery reuses this context rather than opening a second one — it reads the same // ClusterNode table the NodeDeploymentState rows below are FK-bound to, so a single // context keeps the expected set and the seeded rows consistent by construction. - _expectedAcks = DiscoverDriverNodes(db); + expected = DiscoverDriverNodes(db); - foreach (var node in _expectedAcks) + foreach (var node in expected) { db.NodeDeploymentStates.Add(new NodeDeploymentState { NodeId = node.Value, - DeploymentId = msg.DeploymentId.Value, + DeploymentId = id.Value, Status = NodeDeploymentStatus.Applying, }); } } - UpdateDeploymentStatus(db, msg.DeploymentId, DeploymentStatus.AwaitingApplyAcks, rowVersion: guardRowVersion); + UpdateDeploymentStatus(db, id, DeploymentStatus.AwaitingApplyAcks, rowVersion: guardRowVersion); try { db.SaveChanges(); @@ -596,16 +710,63 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU catch (DbUpdateConcurrencyException) { // The row moved after the guard read (on SQL Server: AdminOps closed it as a lost dispatch). The - // expected-set rows and the flip were one SaveChanges, so nothing was written; nothing is - // published and the coordinator is free for the next deployment. + // expected-set rows and the flip were one SaveChanges, so nothing was written. + return new DispatchOutcome(DispatchVerdict.Conflict, null, null, supersedeError, null); + } + return new DispatchOutcome(DispatchVerdict.Seeded, null, expected, supersedeError, null); + } + catch (Exception ex) + { + // Reported, not thrown, so the superseded close's outcome is still applied before the rethrow. + return new DispatchOutcome(DispatchVerdict.Failed, null, null, supersedeError, ex); + } + } + + /// Applies a dispatch's ConfigDb outcome on the actor thread: adopt + publish + arm the deadline, or not. + private void ApplyDispatch(DispatchDeployment msg, Supersede? supersede, DispatchOutcome outcome) + { + if (outcome.Verdict == DispatchVerdict.AlreadyTerminal) + { + _log.Warning( + "Ignoring DispatchDeployment {Id}: the deployment is already {Status} (a late or duplicated dispatch)", + msg.DeploymentId, outcome.TerminalStatus); + if (_current == msg.DeploymentId) ResetForNext(); + return; + } + + if (supersede is not null) + { + if (outcome.SupersedeError is null) + _log.Warning( + "Deployment {Id} was still in flight ({Acked}/{Total} acks) when deployment {Next} was dispatched — closed as TimedOut (superseded)", + supersede.Prior, supersede.Acked, supersede.Expected, msg.DeploymentId); + else + _log.Error(outcome.SupersedeError, + "Deployment {Id} was superseded by {Next} but could not be closed; it may stay in flight until recovery or the lost-dispatch closure ends it", + supersede.Prior, msg.DeploymentId); + ResetForNext(); + } + + _current = msg.DeploymentId; + _acks.Clear(); + _degraded.Clear(); + + switch (outcome.Verdict) + { + case DispatchVerdict.Conflict: _log.Warning( "DispatchDeployment {Id} abandoned: the deployment changed state while it was being dispatched " + "(closed as a lost dispatch?) — not reopening it", msg.DeploymentId); ResetForNext(); return; - } + case DispatchVerdict.Failed: + // As before #1051: a dispatch whose seed throws restarts the actor; recovery re-drives or closes the row. + Rethrow(outcome.Error!); + return; } + _expectedAcks = outcome.Expected!; + // Per-cluster mesh Phase 2: hand off to the transport router rather than publishing // directly, so this actor no longer knows which transport is in force. if (_meshRouter is not null) _meshRouter.Tell(new MeshCommand(DeploymentsTopic, msg)); @@ -628,43 +789,28 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU } /// - /// Gitea #977 (H-4): writes the terminal for the in-flight deployment - /// that is about to replace, and resets the per-deployment - /// state. Conditioned on the row still being in flight (a row something else already closed is left alone), and - /// never fatal: a failed write is logged and the new dispatch proceeds — the AdminOps lost-dispatch closure and - /// the coordinator's recovery remain the backstops for a row this could not close. + /// Writes one terminal status (and optional reason) for , conditioned on the row still being + /// in flight (review L8: a terminal outcome is written once). Static: runs on a pool thread (#1051) or inline. /// - private void CloseSuperseded(DeploymentId prior, DeploymentId successor) + private static bool WriteTerminal( + IDbContextFactory dbFactory, DeploymentId id, DeploymentStatus status, bool sealNow, string? reason) { - var acked = _acks.Count; - var expected = _expectedAcks.Count; - try - { - using var db = _dbFactory.CreateDbContext(); - UpdateDeploymentStatus(db, prior, DeploymentStatus.TimedOut, onlyIfInFlight: true); - var entry = TrackStub(db, prior, onlyIfInFlight: true); - if (entry is not null) - { - entry.Entity.FailureReason = Truncate( - $"Superseded by deployment {successor} before its acks completed ({acked}/{expected} landed). " + - "Its nodes were dispatched the newer deployment instead; redeploy this revision if it is still wanted."); - entry.Property(x => x.FailureReason).IsModified = true; - } - db.SaveChanges(); - _log.Warning( - "Deployment {Id} was still in flight ({Acked}/{Total} acks) when deployment {Next} was dispatched — closed as TimedOut (superseded)", - prior, acked, expected, successor); - } - catch (Exception ex) - { - _log.Error(ex, - "Deployment {Id} was superseded by {Next} but could not be closed; it may stay in flight until recovery or the lost-dispatch closure ends it", - prior, successor); - } - - ResetForNext(); + using var db = dbFactory.CreateDbContext(); + UpdateDeploymentStatus(db, id, status, sealNow: sealNow, onlyIfInFlight: true); + if (reason is not null) SetFailureReason(db, id, reason); + db.SaveChanges(); + return true; } + /// The deployment a dispatch replaces (#977 H-4), captured on the actor thread. + private sealed record Supersede(DeploymentId Prior, int Acked, int Expected); + + private enum DispatchVerdict { Seeded, AlreadyTerminal, Conflict, Failed } + + /// The ConfigDb outcome of a dispatch (#1051). + private sealed record DispatchOutcome( + DispatchVerdict Verdict, DeploymentStatus? TerminalStatus, HashSet? Expected, Exception? SupersedeError, Exception? Error); + private void HandleAck(ApplyAck msg) { if (_current is null || msg.DeploymentId != _current.Value) @@ -920,42 +1066,48 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU private void SealDeployment() { - if (_current is null) return; - using var db = _dbFactory.CreateDbContext(); - UpdateDeploymentStatus(db, _current.Value, DeploymentStatus.Sealed, sealNow: true, onlyIfInFlight: true); - if (_degraded.Count > 0) - { - // Still Sealed: every node DID apply this revision and is running it, and "latest sealed" is - // what drift detection and the publish actor's fallback key on, so a degraded deploy that was not - // sealed would make the fleet look one revision behind what it actually runs. Sealed is not the - // same as clean, though: the deployment's reason names the degraded nodes (per-node detail is on - // each NodeDeploymentState row) and the seal logs at Warning. - var nodes = _degraded.Select(n => n.Value).Order(StringComparer.OrdinalIgnoreCase).ToList(); - SetFailureReason(db, Truncate( - $"Sealed with a degraded address-space apply on {nodes.Count} node(s): {string.Join(", ", nodes)}. " + - "See each node's NodeDeploymentState.FailureReason; re-deploying the same revision re-applies it.")); - db.SaveChanges(); - _log.Warning( - "Deployment {Id} sealed DEGRADED (acks={Count}) — the address-space apply was degraded on: {Nodes}", - _current.Value, _acks.Count, string.Join(", ", nodes)); - ResetForNext(); - return; - } + if (_current is not { } id) return; + var acked = _acks.Count; + // Still Sealed when degraded: every node DID apply this revision and is running it, and "latest sealed" is + // what drift detection and the publish actor's fallback key on, so a degraded deploy that was not + // sealed would make the fleet look one revision behind what it actually runs. Sealed is not the + // same as clean, though: the deployment's reason names the degraded nodes (per-node detail is on + // each NodeDeploymentState row) and the seal logs at Warning. + var degraded = _degraded.Select(n => n.Value).Order(StringComparer.OrdinalIgnoreCase).ToList(); + var reason = degraded.Count > 0 + ? Truncate( + $"Sealed with a degraded address-space apply on {degraded.Count} node(s): {string.Join(", ", degraded)}. " + + "See each node's NodeDeploymentState.FailureReason; re-deploying the same revision re-applies it.") + : null; - db.SaveChanges(); - _log.Info("Deployment {Id} sealed (acks={Count})", _current.Value, _acks.Count); - ResetForNext(); + // #1051 (H-6): off the actor thread; a failure restarts the actor and recovery re-decides the in-flight row. + RunDbWork( + factory => WriteTerminal(factory, id, DeploymentStatus.Sealed, sealNow: true, reason), + _ => + { + if (degraded.Count > 0) + _log.Warning( + "Deployment {Id} sealed DEGRADED (acks={Count}) — the address-space apply was degraded on: {Nodes}", + id, acked, string.Join(", ", degraded)); + else + _log.Info("Deployment {Id} sealed (acks={Count})", id, acked); + ResetForNext(); + }, + Rethrow); } private void MarkPartiallyFailed() { - if (_current is null) return; - using var db = _dbFactory.CreateDbContext(); - UpdateDeploymentStatus(db, _current.Value, DeploymentStatus.PartiallyFailed, onlyIfInFlight: true); - db.SaveChanges(); - _log.Warning("Deployment {Id} partially failed; acks={Acks}", _current.Value, - string.Join(",", _acks.Select(kv => $"{kv.Key.Value}={kv.Value}"))); - ResetForNext(); + if (_current is not { } id) return; + var acks = string.Join(",", _acks.Select(kv => $"{kv.Key.Value}={kv.Value}")); + RunDbWork( + factory => WriteTerminal(factory, id, DeploymentStatus.PartiallyFailed, sealNow: false, reason: null), + _ => + { + _log.Warning("Deployment {Id} partially failed; acks={Acks}", id, acks); + ResetForNext(); + }, + Rethrow); } private void HandleDeadline(DeadlineElapsed msg) @@ -1016,35 +1168,46 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU return; } - using var db = _dbFactory.CreateDbContext(); - UpdateDeploymentStatus(db, _current.Value, DeploymentStatus.TimedOut, onlyIfInFlight: true); + var id = _current.Value; if (_expectedAcks.Count == 0) { - SetFailureReason(db, Truncate( - "Dispatch was lost before any node was expected to ack (coordinator restart or singleton " + - "hand-over mid-dispatch) and the apply deadline has passed. Redeploy.")); - db.SaveChanges(); - _log.Warning( - "Deployment {Id} timed out with NO expected-ack rows: the dispatch was lost before any node was " + - "expected and the {Deadline} apply deadline has passed. Closed as TimedOut — redeploy", - _current.Value, _applyDeadline); - ResetForNext(); + // #1051 (H-6): every terminal write runs off the actor thread (inline during recovery). + RunDbWork( + factory => WriteTerminal(factory, id, DeploymentStatus.TimedOut, sealNow: false, Truncate( + "Dispatch was lost before any node was expected to ack (coordinator restart or singleton " + + "hand-over mid-dispatch) and the apply deadline has passed. Redeploy.")), + _ => + { + _log.Warning( + "Deployment {Id} timed out with NO expected-ack rows: the dispatch was lost before any node was " + + "expected and the {Deadline} apply deadline has passed. Closed as TimedOut — redeploy", + id, _applyDeadline); + ResetForNext(); + }, + Rethrow); return; } // Name the silent nodes, not just the counts. Since the expected set became DB-derived this // is the failure an operator meets after deploying while a configured node is switched off, // so it has to say which node — "4/5 acks landed" leaves them reading logs on five machines. var missing = _expectedAcks.Where(n => !_acks.ContainsKey(n)).Select(n => n.Value).Order().ToList(); + var acked = _acks.Count; + var expected = _expectedAcks.Count; // lmxopcua#784: persist the same answer on the deployment row, so GET /api/deployments/{id} says which // node to fix instead of TimedOut + a null reason (only the no-expected-rows branch above set one). - SetFailureReason(db, TimeoutFailureReason(_acks.Count, _expectedAcks.Count, missing)); - db.SaveChanges(); - _log.Warning( - "Deployment {Id} timed out after {Deadline} ({Acked}/{Total} acks landed). " + - "No ack from: {MissingNodes}. Each is an enabled, non-maintenance ClusterNode row — start " + - "the node, or set ClusterNode.MaintenanceMode = 1 if it is down for maintenance, then redeploy", - _current.Value, _applyDeadline, _acks.Count, _expectedAcks.Count, string.Join(", ", missing)); - ResetForNext(); + var reason = TimeoutFailureReason(acked, expected, missing); + RunDbWork( + factory => WriteTerminal(factory, id, DeploymentStatus.TimedOut, sealNow: false, reason), + _ => + { + _log.Warning( + "Deployment {Id} timed out after {Deadline} ({Acked}/{Total} acks landed). " + + "No ack from: {MissingNodes}. Each is an enabled, non-maintenance ClusterNode row — start " + + "the node, or set ClusterNode.MaintenanceMode = 1 if it is down for maintenance, then redeploy", + id, _applyDeadline, acked, expected, string.Join(", ", missing)); + ResetForNext(); + }, + Rethrow); } /// @@ -1104,6 +1267,9 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU /// The outcome of an off-thread ack write (#996 / H-6): error = persisted. private sealed record AckPersisted(ApplyAck Ack, Exception? Error); + /// The outcome of a write (#1051), matched to the waiting write by ticket. + private sealed record DbWorkDone(long Ticket, object? Result, Exception? Error); + /// An ack whose persist failed, re-delivered by its retry timer. private sealed record RetryAckPersist(ApplyAck Ack); @@ -1161,11 +1327,10 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU } } - /// Stages the current deployment's failure reason onto the stub staged. - private void SetFailureReason(OtOpcUaConfigDbContext db, string reason) + /// Stages a deployment's failure reason onto the stub staged. + private static void SetFailureReason(OtOpcUaConfigDbContext db, DeploymentId id, string reason) { - if (_current is null) return; - var entry = TrackStub(db, _current.Value, onlyIfInFlight: true); + var entry = TrackStub(db, id, onlyIfInFlight: true); if (entry is null) return; entry.Entity.FailureReason = reason; entry.Property(x => x.FailureReason).IsModified = true; diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorDriverOperationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorDriverOperationTests.cs index 538a95ed1..6d1e9ea9f 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorDriverOperationTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorDriverOperationTests.cs @@ -21,14 +21,88 @@ public sealed class AdminOperationsActorDriverOperationTests : ControlPlaneActor { private static readonly TimeSpan AckBudget = TimeSpan.FromSeconds(1); + private static readonly TimeSpan FastRetry = TimeSpan.FromMilliseconds(30); + private (IActorRef Actor, Akka.TestKit.TestProbe Router) Create(IDbContextFactory factory) { var router = CreateTestProbe("router"); var coordinator = CreateTestProbe("coord"); - var actor = Sys.ActorOf(AdminOperationsActor.Props(factory, coordinator.Ref, Enumerable.Empty(), meshRouter: router.Ref)); + var actor = Sys.ActorOf(AdminOperationsActor.Props(factory, coordinator.Ref, Enumerable.Empty(), meshRouter: router.Ref, + driverAuditRetryDelay: FastRetry)); return (actor, router); } + /// + /// lmxopcua#1051 (H-3 remainder): a TRANSIENT audit-write failure (ConfigDb briefly unreachable) is retried on a + /// backoff, so the ConfigEdit row is still recorded once the database answers — it used to be logged and lost. + /// + [Fact] + public void Transient_audit_failure_is_retried_until_the_row_is_recorded() + { + var inner = NewInMemoryDbFactory(); + var flaky = new FlakyAsyncFactory(inner, failures: 3, () => new InvalidOperationException("ConfigDb unreachable (simulated)")); + var (actor, _) = Create(flaky); + + actor.Tell(new RestartDriver("MAIN", "drv-9", "joe", Guid.NewGuid())); + ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken).Ok.ShouldBeTrue(); + + AwaitAssert(() => + { + flaky.Calls.ShouldBe(4); + using var db = inner.CreateDbContext(); + db.ConfigEdits.Single().EditedBy.ShouldBe("joe"); + }, duration: PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + } + + /// The retry is bounded: a ConfigDb that never answers costs attempts, then the record is logged and dropped. + [Fact] + public void Audit_retry_gives_up_after_the_attempt_cap() + { + var inner = NewInMemoryDbFactory(); + var flaky = new FlakyAsyncFactory(inner, failures: int.MaxValue, () => new InvalidOperationException("ConfigDb unreachable (simulated)")); + var (actor, _) = Create(flaky); + + actor.Tell(new ReconnectDriver("MAIN", "drv-9", "joe", Guid.NewGuid())); + ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken).Ok.ShouldBeTrue(); + + AwaitAssert(() => flaky.Calls.ShouldBe(AdminOperationsActor.MaxDriverAuditAttempts), + duration: PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + // Absence after the cap, with a positive control: well past several backoff periods, still exactly the cap. + ExpectNoMsg(TimeSpan.FromMilliseconds(30 * 64), TestContext.Current.CancellationToken); + flaky.Calls.ShouldBe(AdminOperationsActor.MaxDriverAuditAttempts); + } + + /// A write the database REJECTS (a constraint / truncation) fails identically every time: not retried. + [Fact] + public void Rejected_audit_write_is_not_retried() + { + var inner = NewInMemoryDbFactory(); + var flaky = new FlakyAsyncFactory(inner, failures: int.MaxValue, + () => new DbUpdateException("rejected", SqlExceptionFactory.Create(8152, "String or binary data would be truncated."))); + var (actor, _) = Create(flaky); + + actor.Tell(new RestartDriver("MAIN", "drv-9", "joe", Guid.NewGuid())); + ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken).Ok.ShouldBeTrue(); + + AwaitAssert(() => flaky.Calls.ShouldBe(1), duration: PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + ExpectNoMsg(TimeSpan.FromMilliseconds(30 * 16), TestContext.Current.CancellationToken); + flaky.Calls.ShouldBe(1); + } + + private sealed class FlakyAsyncFactory(IDbContextFactory inner, int failures, Func error) + : IDbContextFactory + { + private int _calls; + public int Calls => Volatile.Read(ref _calls); + public OtOpcUaConfigDbContext CreateDbContext() => inner.CreateDbContext(); + public Task CreateDbContextAsync(CancellationToken cancellationToken = default) + { + var call = Interlocked.Increment(ref _calls); + if (call <= failures) throw error(); + return Task.FromResult(inner.CreateDbContext()); + } + } + /// The audit write throws: the command still went out and the reply says so (success). [Theory] [InlineData(true)] diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorOffThreadWritesTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorOffThreadWritesTests.cs new file mode 100644 index 000000000..58b0d2a36 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorOffThreadWritesTests.cs @@ -0,0 +1,253 @@ +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; + +/// +/// 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 (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). +/// +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(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(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(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); + } + + /// + /// 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. + /// + [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 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 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(); + } + + /// + /// 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. + /// + private sealed class GatedDbFactory(IDbContextFactory inner) : IDbContextFactory + { + 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(); + } + + /// True exactly once: when an armed countdown reaches zero on this call. + 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; + } + } + } +}