From 69f475392c706b949863d5d2297f1f8c9dde48d8 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 15:07:25 -0500 Subject: [PATCH 1/7] 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 --- docs/DriverLifecycle.md | 7 +- docs/Redundancy.md | 8 +- .../AdminOperations/AdminOperationsActor.cs | 97 ++++- .../Coordinators/ConfigPublishCoordinator.cs | 407 ++++++++++++------ ...dminOperationsActorDriverOperationTests.cs | 76 +++- ...gPublishCoordinatorOffThreadWritesTests.cs | 253 +++++++++++ 6 files changed, 707 insertions(+), 141 deletions(-) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorOffThreadWritesTests.cs 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; + } + } + } +} From 79235bf593947c8fceb33782b7f4146e4a5f2408 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 15:10:21 -0500 Subject: [PATCH 2/7] fix(resilience): #1052 every failed attempt counts toward ConsecutiveFailures, no-retry capabilities included; non-idempotent write telemetry on the caller's host Decided: an innermost recorder counts each attempt ending in a handled failure (not caller cancellation, not a refusal; the pipeline timeout stays counted once by OnTimeout). OnRetry only logs now. Write/AlarmAcknowledge/ Initialize failures used to never raise the /hosts count, and a retried call's last attempt was never counted. The ::non-idempotent write pipeline records failures + breaker under the caller's host (trackerHostName). Co-Authored-By: Claude --- docs/DriverLifecycle.md | 9 +- .../Resilience/CapabilityInvoker.cs | 4 +- .../DriverResiliencePipelineBuilder.cs | 55 +++++++++-- .../DriverResiliencePipelineBuilderTests.cs | 5 +- .../TerminalFailureTrackingTests.cs | 94 +++++++++++++++++++ 5 files changed, 156 insertions(+), 11 deletions(-) create mode 100644 tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/TerminalFailureTrackingTests.cs diff --git a/docs/DriverLifecycle.md b/docs/DriverLifecycle.md index 6064f68da..c0538c9a8 100644 --- a/docs/DriverLifecycle.md +++ b/docs/DriverLifecycle.md @@ -627,8 +627,13 @@ before touching it: snapshot could never self-correct — only the discarded pipeline's `OnClosed` stamps the close — so a deploy during an outage would otherwise strand a false OPEN chip forever. This was unreachable while breakers never opened; the Initialize wrap made it reachable. -- `ConsecutiveFailures` stays 0 during a connect outage that FAILS fast — the tracker counts retry - attempts, and Initialize has none. The breaker-OPEN chip is the operator signal. +- **`ConsecutiveFailures` counts every failed attempt (#1052, decided).** It used to be fed only by the retry + strategy's `OnRetry`, so a no-retry capability (Write, AlarmAcknowledge, Initialize) never raised it — a connect outage + that failed fast read 0 on `/hosts` — and a retried call's LAST attempt was never counted. An innermost recorder now + counts each attempt that ends in a handled failure (never a caller cancellation or a `DriverOperationRefusedException`; + the pipeline timeout is counted once by `OnTimeout`), and any success resets it. A Tier A Read that fails 4 attempts + now reads 4, not 3. The non-idempotent write pipeline (cached under `host::non-idempotent`) records its failures and + breaker on the CALLER's host, where its success already reset them — it used to show a phantom `::non-idempotent` row. - **The pipeline's own timeout is a failure (#999 / review K-6).** A call that outlasts its capability timeout (a blackholed device that never answers) used to reach the breaker as an `OperationCanceledException`, which both predicates excluded — every call burned the full timeout diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/CapabilityInvoker.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/CapabilityInvoker.cs index fd750c1c0..4b95ed985 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/CapabilityInvoker.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/CapabilityInvoker.cs @@ -136,7 +136,9 @@ public sealed class CapabilityInvoker : IDriverCapabilityInvoker // safe and removes the per-write allocation the previous once-per-call snapshot incurred. The // null-check-assign tolerates a benign first-call race (both threads build an equivalent record). var noRetryOptions = _noRetryWriteOptions ??= BuildNoRetryWriteOptions(); - var pipeline = _builder.GetOrCreate(_driverInstanceId, $"{hostName}::non-idempotent", DriverCapability.Write, noRetryOptions, _optionsGeneration); + // The pipeline is cached under "::non-idempotent", but its failures and breaker are the caller host's (#1052). + var pipeline = _builder.GetOrCreate(_driverInstanceId, $"{hostName}::non-idempotent", DriverCapability.Write, noRetryOptions, + _optionsGeneration, trackerHostName: hostName); // Record in-flight accounting on the CALLER's host (the "::non-idempotent" suffix is a // pipeline-cache key, not an operator-facing host) so Admin /hosts sees write depth too. _statusTracker?.RecordCallStart(_driverInstanceId, hostName); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResiliencePipelineBuilder.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResiliencePipelineBuilder.cs index d697a4430..d853155ab 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResiliencePipelineBuilder.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResiliencePipelineBuilder.cs @@ -23,6 +23,11 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Resilience; /// tracker failure. Before, both predicates excluded every : a hung /// device burned the full timeout on every call forever with the breaker closed and no failure on /hosts. /// +/// Every failed ATTEMPT is a tracker failure (#1052). An innermost recorder counts each attempt that ends in +/// a handled failure (not a caller cancellation, not a , not the pipeline +/// timeout — OnTimeout counts that one). It replaced the count in OnRetry, which a no-retry capability +/// (Write, AlarmAcknowledge, Initialize) never reaches and which skipped every retried call's last attempt. +/// /// Pipeline resolution is lock-free on the hot path: the inner /// caches a per key; /// first-call cost is one .Build. Thereafter reads are O(1). @@ -83,21 +88,28 @@ public sealed class DriverResiliencePipelineBuilder /// its OWN (old) generation — a key the new invoker's generation never reads. Defaults to 0 so /// every existing caller/test compiles unchanged. /// + /// + /// The host the pipeline's tracker telemetry is recorded under, when it differs from the cache key's + /// — the non-idempotent write pipeline is cached under host::non-idempotent + /// but its failures and breaker belong to host (#1052). Must be a function of : + /// it is not part of the cache key. Null = . + /// /// The cached or newly built resilience pipeline for the key. public ResiliencePipeline GetOrCreate( string driverInstanceId, string hostName, DriverCapability capability, DriverResilienceOptions options, - long optionsGeneration = 0) + long optionsGeneration = 0, + string? trackerHostName = null) { ArgumentNullException.ThrowIfNull(options); ArgumentException.ThrowIfNullOrWhiteSpace(hostName); var key = new PipelineKey(driverInstanceId, hostName, capability, optionsGeneration); return _pipelines.GetOrAdd(key, static (k, state) => Build( - k.DriverInstanceId, k.HostName, state.capability, state.options, state.timeProvider, state.tracker, state.logger), - (capability, options, timeProvider: _timeProvider, tracker: _statusTracker, logger: _logger)); + k.DriverInstanceId, state.trackerHost ?? k.HostName, state.capability, state.options, state.timeProvider, state.tracker, state.logger), + (capability, options, timeProvider: _timeProvider, tracker: _statusTracker, logger: _logger, trackerHost: trackerHostName)); } /// @@ -178,12 +190,12 @@ public sealed class DriverResiliencePipelineBuilder // left to retry with. It is still a breaker failure (below) and a tracker failure (OnTimeout). ShouldHandle = new PredicateBuilder().Handle(ex => ex is not OperationCanceledException and not DriverOperationRefusedException), }; - if (tracker is not null || logger is not null) + if (logger is not null) { + // The failed attempt itself is counted by the innermost AttemptFailureRecorder (#1052), not here. retryOptions.OnRetry = args => { - tracker?.RecordFailure(driverInstanceId, hostName, timeProvider.GetUtcNow().UtcDateTime); - logger?.LogWarning( + logger.LogWarning( "Driver resilience retry: instance={DriverInstanceId} host={HostName} capability={Capability} attempt={Attempt}: {Reason}", driverInstanceId, hostName, capability, args.AttemptNumber, args.Outcome.Exception?.Message ?? "unknown"); return default; @@ -238,9 +250,40 @@ public sealed class DriverResiliencePipelineBuilder builder.AddCircuitBreaker(breakerOptions); } + // #1052: innermost, so it sees every attempt — the retried ones, the last one, and the only one of a no-retry + // capability. ConsecutiveFailures is "failed attempts since the last success". + if (tracker is not null) + { + var recorder = new AttemptFailureRecorder(tracker, driverInstanceId, hostName, timeProvider); + builder.AddStrategy(_ => recorder, AttemptFailureRecorderOptions.Instance); + } + return builder.Build(); } + /// + /// Innermost pass-through that records a tracker failure for each attempt ending in a handled failure (#1052). A + /// cancellation is never counted here: the caller's is not a failure, and the pipeline's own timeout is counted by + /// OnTimeout. A refusal is not a failure of the target. + /// + private sealed class AttemptFailureRecorder( + DriverResilienceStatusTracker tracker, string driverInstanceId, string hostName, TimeProvider timeProvider) : ResilienceStrategy + { + protected override async ValueTask> ExecuteCore( + Func>> callback, ResilienceContext context, TState state) + { + var outcome = await callback(context, state).ConfigureAwait(context.ContinueOnCapturedContext); + if (outcome.Exception is not null and not OperationCanceledException and not DriverOperationRefusedException) + tracker.RecordFailure(driverInstanceId, hostName, timeProvider.GetUtcNow().UtcDateTime); + return outcome; + } + } + + private sealed class AttemptFailureRecorderOptions : ResilienceStrategyOptions + { + public static readonly AttemptFailureRecorderOptions Instance = new() { Name = "AttemptFailureRecorder" }; + } + /// The caller's token, recorded by before the timeout links its own. private static readonly ResiliencePropertyKey CallerTokenKey = new("otopcua.caller-token"); diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResiliencePipelineBuilderTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResiliencePipelineBuilderTests.cs index e5863b23f..d811d7b01 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResiliencePipelineBuilderTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResiliencePipelineBuilderTests.cs @@ -265,7 +265,7 @@ public sealed class DriverResiliencePipelineBuilderTests attempts.ShouldBeLessThanOrEqualTo(1); } - /// Verifies that the tracker records failure on every retry. + /// Verifies that the tracker records a failure for every failed attempt. [Fact] public async Task Tracker_RecordsFailure_OnEveryRetry() { @@ -283,7 +283,8 @@ public sealed class DriverResiliencePipelineBuilderTests var snap = tracker.TryGet("drv-trk", "host-x"); snap.ShouldNotBeNull(); var retryCount = TierAOptions.Resolve(DriverCapability.Read).RetryCount; - snap!.ConsecutiveFailures.ShouldBe(retryCount); + // #1052: every failed ATTEMPT counts, the final (un-retried) one included. + snap!.ConsecutiveFailures.ShouldBe(retryCount + 1); } /// Verifies that the tracker stamps the breaker open when it trips. diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/TerminalFailureTrackingTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/TerminalFailureTrackingTests.cs new file mode 100644 index 000000000..104cd26ff --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/TerminalFailureTrackingTests.cs @@ -0,0 +1,94 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Resilience; + +namespace ZB.MOM.WW.OtOpcUa.Core.Tests.Resilience; + +/// +/// lmxopcua#1052 (#999 follow-up, decided): ConsecutiveFailures counts FAILED ATTEMPTS, every one. It used to be +/// fed only by the retry strategy's OnRetry, so a capability with no retry (Write, AlarmAcknowledge, Initialize) +/// never raised the /hosts failure count however often it failed, and a retried call's last attempt was never counted +/// either. And a non-idempotent write's pipeline telemetry landed on a phantom host::non-idempotent row. +/// +[Trait("Category", "Unit")] +public sealed class TerminalFailureTrackingTests +{ + private static readonly DriverResilienceOptions TierA = new() { Tier = DriverTier.A }; + + [Theory] + [InlineData(DriverCapability.Write)] + [InlineData(DriverCapability.AlarmAcknowledge)] + [InlineData(DriverCapability.Initialize)] + public async Task A_no_retry_capability_failure_is_counted(DriverCapability capability) + { + var tracker = new DriverResilienceStatusTracker(); + var pipeline = new DriverResiliencePipelineBuilder(statusTracker: tracker).GetOrCreate("drv", "host-1", capability, TierA); + + for (var i = 1; i <= 2; i++) + { + await Should.ThrowAsync(async () => + await pipeline.ExecuteAsync(_ => throw new InvalidOperationException("device refused the socket"), + TestContext.Current.CancellationToken)); + tracker.TryGet("drv", "host-1")!.ConsecutiveFailures.ShouldBe(i, $"failure {i} of a {capability} with no retry"); + } + } + + [Fact] + public async Task Every_failed_attempt_of_a_retried_call_is_counted_including_the_last() + { + var tracker = new DriverResilienceStatusTracker(); + var pipeline = new DriverResiliencePipelineBuilder(statusTracker: tracker).GetOrCreate("drv", "host-1", DriverCapability.Read, TierA); + var attempts = 0; + + await Should.ThrowAsync(async () => + await pipeline.ExecuteAsync(_ => { attempts++; throw new InvalidOperationException("down"); }, + TestContext.Current.CancellationToken)); + + attempts.ShouldBe(TierA.Resolve(DriverCapability.Read).RetryCount + 1); + tracker.TryGet("drv", "host-1")!.ConsecutiveFailures.ShouldBe(attempts); + } + + [Fact] + public async Task A_refusal_is_not_a_failure() + { + var tracker = new DriverResilienceStatusTracker(); + var pipeline = new DriverResiliencePipelineBuilder(statusTracker: tracker).GetOrCreate("drv", "host-1", DriverCapability.Write, TierA); + + await Should.ThrowAsync(async () => + await pipeline.ExecuteAsync(_ => throw new DriverOperationRefusedException("not writable"), + TestContext.Current.CancellationToken)); + (tracker.TryGet("drv", "host-1")?.ConsecutiveFailures ?? 0).ShouldBe(0); + + // Positive control: a genuine failure on the same pipeline IS counted. + await Should.ThrowAsync(async () => + await pipeline.ExecuteAsync(_ => throw new InvalidOperationException("down"), TestContext.Current.CancellationToken)); + tracker.TryGet("drv", "host-1")!.ConsecutiveFailures.ShouldBe(1); + } + + /// + /// A non-idempotent write runs on a pipeline cached under host::non-idempotent; its failures and its breaker + /// belong to the CALLER's host, where its success already resets the counter. + /// + [Fact] + public async Task Non_idempotent_write_failures_land_on_the_callers_host() + { + var tracker = new DriverResilienceStatusTracker(); + var invoker = new CapabilityInvoker(new DriverResiliencePipelineBuilder(statusTracker: tracker), "drv", () => TierA, + statusTracker: tracker); + var threshold = TierA.Resolve(DriverCapability.Write).BreakerFailureThreshold; + + for (var i = 0; i < threshold; i++) + await Should.ThrowAsync(async () => + await invoker.ExecuteWriteAsync("host-1", isIdempotent: false, + _ => throw new InvalidOperationException("down"), TestContext.Current.CancellationToken)); + + var snap = tracker.TryGet("drv", "host-1")!; + snap.ConsecutiveFailures.ShouldBe(threshold); + snap.IsBreakerOpen.ShouldBeTrue("the write breaker opened, and it is this host's breaker"); + tracker.TryGet("drv", "host-1::non-idempotent").ShouldBeNull("no phantom host row"); + + await invoker.ExecuteWriteAsync("host-1", isIdempotent: true, _ => ValueTask.FromResult(0), TestContext.Current.CancellationToken); + tracker.TryGet("drv", "host-1")!.ConsecutiveFailures.ShouldBe(0, "a success on the same host resets it"); + } +} From 6b19f4add6ef01bb6475541cae8031f7ee91b016 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 15:20:02 -0500 Subject: [PATCH 3/7] feat(resilience): #1047 non-retrying AcquisitionSubscribe capability wraps SubscribeAcquisitionAsync (breaker + /hosts telemetry), OTOPCUA0001 suppression removed New DriverCapability.AcquisitionSubscribe (appended): RetryCount 0 in every tier and forced 0 by the parser, 30 s timeout (outlasts the actor's 10 s acquisition timeout), breaker 5 (Tier C none). PendingAcquisition.Start routes through the invoker keyed on the driver instance; an open breaker fails fast and the capacity reservation is released. Co-Authored-By: Claude --- docs/DriverLifecycle.md | 7 + .../DriverCapability.cs | 10 ++ .../Resilience/DriverResilienceOptions.cs | 6 + .../DriverResilienceOptionsParser.cs | 9 ++ .../Drivers/DriverInstanceActor.cs | 26 ++-- .../DriverResilienceOptionsParserTests.cs | 12 ++ .../DriverResilienceOptionsTests.cs | 16 ++ .../GrpcDataAcquisitionResilienceTests.cs | 146 ++++++++++++++++++ 8 files changed, 219 insertions(+), 13 deletions(-) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataAcquisitionResilienceTests.cs diff --git a/docs/DriverLifecycle.md b/docs/DriverLifecycle.md index c0538c9a8..6a0a83ca2 100644 --- a/docs/DriverLifecycle.md +++ b/docs/DriverLifecycle.md @@ -634,6 +634,13 @@ before touching it: the pipeline timeout is counted once by `OnTimeout`), and any success resets it. A Tier A Read that fails 4 attempts now reads 4, not 3. The non-idempotent write pipeline (cached under `host::non-idempotent`) records its failures and breaker on the CALLER's host, where its success already reset them — it used to show a phantom `::non-idempotent` row. +- **Acknowledged acquisition has its own capability, `AcquisitionSubscribe` (#1047).** gRPC-data acquisition + (`IAcknowledgedAcquisitionSource.SubscribeAcquisitionAsync`) used to call the source unwrapped (OTOPCUA0001 suppressed), + because the Subscribe pipeline retries and a retry would orphan a physical handle `PendingAcquisition` alone owns. It now runs + through the invoker on `AcquisitionSubscribe`: never retries (the parser forces 0), tier timeout 30 s — deliberately longer than + the actor's 10 s acquisition timeout, which stays the effective bound — breaker 5 (Tier C: none). Polly's timeout awaits the + call and passes a completed result through, so the handle contract is unchanged; an open breaker fails the acquisition fast + without calling the source and the reservation is released like any failure. Keyed on the driver instance. - **The pipeline's own timeout is a failure (#999 / review K-6).** A call that outlasts its capability timeout (a blackholed device that never answers) used to reach the breaker as an `OperationCanceledException`, which both predicates excluded — every call burned the full timeout diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DriverCapability.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DriverCapability.cs index 9ce94616e..da9315e42 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DriverCapability.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DriverCapability.cs @@ -47,4 +47,14 @@ public enum DriverCapability /// window, so a Read-sized threshold of 5 could never open on connect failures. /// Initialize, + + /// + /// — establishing an acknowledged gRPC-data + /// acquisition (lmxopcua#1047). Does NOT retry (the parser forces 0): a cancelled or superseded attempt can still + /// complete with a physical handle the runtime's pending acquisition alone owns, so a pipeline retry would orphan it. + /// The tier-default timeout (30 s) is deliberately longer than the runtime's own acquisition timeout (10 s by + /// default), which stays the effective bound; the pipeline adds the breaker and the /hosts telemetry. + /// Appended last so the existing members keep their numeric values. + /// + AcquisitionSubscribe, } diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResilienceOptions.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResilienceOptions.cs index 6a207da5c..0283bd770 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResilienceOptions.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResilienceOptions.cs @@ -86,6 +86,8 @@ public sealed record DriverResilienceOptions // timer fires every 10 s, so at most three init attempts fit one window; a threshold of 5 // could never open on connect failures. [DriverCapability.Initialize] = new(TimeoutSeconds: 5, RetryCount: 0, BreakerFailureThreshold: 2), + // #1047: never retries (a retry would orphan an acquisition handle); 30 s outlasts the runtime's 10 s acquisition timeout. + [DriverCapability.AcquisitionSubscribe] = new(TimeoutSeconds: 30, RetryCount: 0, BreakerFailureThreshold: 5), }, DriverTier.B => new Dictionary { @@ -98,6 +100,8 @@ public sealed record DriverResilienceOptions [DriverCapability.AlarmAcknowledge] = new(TimeoutSeconds: 8, RetryCount: 0, BreakerFailureThreshold: 5), // See the Tier A Initialize note: threshold 2 is cadence-reachability, not a tuning choice. [DriverCapability.Initialize] = new(TimeoutSeconds: 8, RetryCount: 0, BreakerFailureThreshold: 2), + // #1047: never retries (a retry would orphan an acquisition handle); 30 s outlasts the runtime's 10 s acquisition timeout. + [DriverCapability.AcquisitionSubscribe] = new(TimeoutSeconds: 30, RetryCount: 0, BreakerFailureThreshold: 5), }, DriverTier.C => new Dictionary { @@ -110,6 +114,8 @@ public sealed record DriverResilienceOptions [DriverCapability.AlarmAcknowledge] = new(TimeoutSeconds: 15, RetryCount: 0, BreakerFailureThreshold: 0), // Tier C stays breaker-less like every other Tier C capability (process-level supervision). [DriverCapability.Initialize] = new(TimeoutSeconds: 15, RetryCount: 0, BreakerFailureThreshold: 0), + // #1047: never retries (a retry would orphan an acquisition handle); 30 s outlasts the runtime's 10 s acquisition timeout. + [DriverCapability.AcquisitionSubscribe] = new(TimeoutSeconds: 30, RetryCount: 0, BreakerFailureThreshold: 0), }, _ => throw new ArgumentOutOfRangeException(nameof(tier), tier, $"No default policy table defined for tier {tier}."), }; diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResilienceOptionsParser.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResilienceOptionsParser.cs index f1ad841e7..ed69d2c09 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResilienceOptionsParser.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResilienceOptionsParser.cs @@ -200,6 +200,15 @@ public static class DriverResilienceOptionsParser retry = 0; } + // #1047: an acquisition attempt that is cancelled or superseded can still complete with a physical handle that + // only the runtime's pending acquisition may release; a pipeline retry would orphan it. + if (capability == DriverCapability.AcquisitionSubscribe && retry > 0) + { + AppendDiagnostic(ref diagnostic, + $"{capability} never retries (a retry would orphan an acquisition handle); retryCount override ignored."); + retry = 0; + } + var breaker = merged.BreakerFailureThreshold; if (breaker < ResiliencePolicyRanges.MinBreakerFailureThreshold) { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs index d1dc07942..eafdec723 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs @@ -2246,19 +2246,19 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers _finished.TrySetResult(true); } - // OTOPCUA0001 (#1001/S-11) is suppressed here ON PURPOSE, not overlooked. The stock Subscribe - // pipeline cannot wrap this call safely: it retries (3x on tiers A/B) and times out per attempt - // (5-8 s, shorter than the actor's 10 s acquisition timeout), but a SubscribeAcquisitionAsync - // attempt that is cancelled or superseded may still complete later with a physical handle, and - // the contract makes THIS class (PendingAcquisition) the sole owner of releasing it. A Polly - // retry/timeout would orphan those handles and desync the capacity reservation. Establishment - // is already bounded by the actor's own acquisition timeout + the _stop token. Follow-up: give - // the invoker a non-retrying acquisition capability so breaker/telemetry cover it too. + // #1047 (#1001/S-11 follow-up): wrapped on its OWN capability, AcquisitionSubscribe, which never retries + // (the parser forces 0) and whose 30 s tier timeout outlasts the actor's 10 s acquisition timeout. The stock + // Subscribe pipeline could not wrap this: it retries, and a SubscribeAcquisitionAsync attempt that is cancelled + // or superseded may still complete with a physical handle THIS class alone must release — a retry would orphan + // it. With no retry the pipeline is transparent to that contract (Polly's timeout awaits the call and passes a + // completed result through; only an OCE becomes TimeoutRejectedException, an ordinary failure here), and the + // breaker + /hosts telemetry now cover acquisition. An open breaker fails fast without calling the source, which + // ObserveAsync handles like any failure (reservation released). Keyed on the driver instance like a bulk Subscribe. internal void Start(IAcknowledgedAcquisitionSource source, AcquisitionSubscriptionRequest request, - Action callback) => _ = ObserveAsync(Task.Run(() => -#pragma warning disable OTOPCUA0001 - source.SubscribeAcquisitionAsync(request, callback, _stop.Token))); -#pragma warning restore OTOPCUA0001 + Action callback, IDriverCapabilityInvoker invoker, string hostKey) => _ = ObserveAsync(Task.Run(async () => + await invoker.ExecuteAsync(DriverCapability.AcquisitionSubscribe, hostKey, + async ct => await source.SubscribeAcquisitionAsync(request, callback, ct).ConfigureAwait(false), + _stop.Token).ConfigureAwait(false))); private async Task ObserveAsync(Task operation) { @@ -2418,7 +2418,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers else _sourcePublisher.TryPublish(ticket, item.Snapshot); } } - }); + }, _invoker, _driverInstanceId); started = true; var installed = await operation.Completion.WaitAsync(cts.Token); if (installed.Handle is null || installed.DesiredRevision != fence.Revision || diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResilienceOptionsParserTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResilienceOptionsParserTests.cs index 89a5a4d47..a77f6684d 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResilienceOptionsParserTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResilienceOptionsParserTests.cs @@ -371,6 +371,18 @@ public sealed class DriverResilienceOptionsParserTests diag.ShouldContain("Initialize never retries"); } + /// #1047: an AcquisitionSubscribe retryCount override is forced to 0 with a diagnostic. + [Fact] + public void AcquisitionSubscribeRetryOverride_IsForcedToZero_WithDiagnostic() + { + var options = DriverResilienceOptionsParser.ParseOrDefaults( + DriverTier.A, "{\"capabilityPolicies\":{\"AcquisitionSubscribe\":{\"retryCount\":3}}}", out var diag); + + options.Resolve(DriverCapability.AcquisitionSubscribe).RetryCount.ShouldBe(0); + diag.ShouldNotBeNull(); + diag.ShouldContain("AcquisitionSubscribe never retries"); + } + /// A Read (idempotent) retryCount override is still honored — the invariant is write-shaped only. [Fact] public void ReadRetryOverride_StillHonored() diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResilienceOptionsTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResilienceOptionsTests.cs index 94403874b..67660902b 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResilienceOptionsTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResilienceOptionsTests.cs @@ -93,6 +93,22 @@ public sealed class DriverResilienceOptionsTests defaults[DriverCapability.Initialize].RetryCount.ShouldBe(0); } + /// + /// #1047: acknowledged acquisition never retries (a retry would orphan a handle the runtime's pending acquisition + /// owns) and its timeout outlasts the runtime's 10 s acquisition timeout, which stays the effective bound. + /// + /// The driver tier to test. + [Theory] + [InlineData(DriverTier.A)] + [InlineData(DriverTier.B)] + [InlineData(DriverTier.C)] + public void AcquisitionSubscribe_NeverRetries_AndOutlastsTheRuntimeTimeout(DriverTier tier) + { + var policy = DriverResilienceOptions.GetTierDefaults(tier)[DriverCapability.AcquisitionSubscribe]; + policy.RetryCount.ShouldBe(0); + policy.TimeoutSeconds.ShouldBeGreaterThan(10); + } + /// /// The Initialize breaker threshold must be reachable at the reconnect cadence (R2-10 T10): /// the breaker samples over 30 s and the reconnect timer fires every 10 s, so at most THREE diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataAcquisitionResilienceTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataAcquisitionResilienceTests.cs new file mode 100644 index 000000000..be75bcfe6 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataAcquisitionResilienceTests.cs @@ -0,0 +1,146 @@ +using System.Collections.Concurrent; +using Akka.Actor; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; + +/// +/// lmxopcua#1047 (#1001 follow-up): acknowledged acquisition () runs through +/// the capability invoker on its own NON-retrying capability, , so +/// the breaker and the /hosts telemetry cover it. It used to call the source directly (OTOPCUA0001 suppressed): the +/// stock Subscribe pipeline retries, and a retry would orphan a physical handle the pending acquisition owns. +/// +[Trait("Feature", "GrpcData"), Trait("Category", "Unit")] +public sealed class GrpcDataAcquisitionResilienceTests : RuntimeActorTestBase +{ + [Fact] + public async Task Acquisition_routes_through_the_invoker_on_the_acquisition_capability() + { + var (hub, publisher, incarnation) = Setup(); + using (hub) + { + var invoker = new GateInvoker(failAcquisitions: 0); + var driver = new AcquisitionDriver(); + var actor = await SpawnConnectedAsync(driver, invoker, publisher, incarnation, capacity: 4); + + var ack = await actor.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 1, incarnation, true), + PresenceBudget, TestContext.Current.CancellationToken); + + ack.Succeeded.ShouldBeTrue(); + driver.Calls.ShouldBe(1, "the source ran from inside the invoker's call site"); + invoker.Calls.ShouldContain(c => c.Capability == DriverCapability.AcquisitionSubscribe && c.Host == driver.DriverInstanceId); + } + } + + /// + /// An OPEN breaker fails the acquisition fast without calling the source, and the capacity reservation is released + /// (capacity 1: the next demand, once the breaker lets it through, still gets the slot). + /// + [Fact] + public async Task A_fast_failed_acquisition_releases_its_capacity() + { + var (hub, publisher, incarnation) = Setup(); + using (hub) + { + var invoker = new GateInvoker(failAcquisitions: 1); + var driver = new AcquisitionDriver(); + var actor = await SpawnConnectedAsync(driver, invoker, publisher, incarnation, capacity: 1); + + var first = await actor.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 1, incarnation, true), + PresenceBudget, TestContext.Current.CancellationToken); + first.Succeeded.ShouldBeFalse(); + driver.Calls.ShouldBe(0, "a fast-failed call never reaches the source"); + + DriverInstanceActor.AcquisitionDemandApplied? second = null; + for (var i = 0; i < 40 && second is not { Succeeded: true }; i++) + { + second = await actor.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 2 + i, incarnation, true), + PresenceBudget, TestContext.Current.CancellationToken); + if (second is not { Succeeded: true }) await Task.Delay(25, TestContext.Current.CancellationToken); + } + second.ShouldNotBeNull().Succeeded.ShouldBeTrue("the failed attempt released the only capacity slot"); + driver.Calls.ShouldBe(1); + } + } + + private async Task SpawnConnectedAsync(AcquisitionDriver driver, IDriverCapabilityInvoker invoker, + SourceSamplePublisher publisher, long incarnation, int capacity) + { + var parent = CreateTestProbe(); + var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, invoker: invoker, clusterId: "cluster", + commsLossTimeout: TimeSpan.Zero, sourcePublisher: publisher, sourceIncarnation: incarnation, + acquisitionCapacity: new SubscriptionAcquisitionCapacity(capacity)), + TestContext.Current.CancellationToken); + actor.Tell(new DriverInstanceActor.InitializeRequested("{}")); + parent.ExpectMsg(m => m.Connected, PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + await Task.CompletedTask; + return actor; + } + + private static (PartitionedSampleHub Hub, SourceSamplePublisher Publisher, long Incarnation) Setup() + { + var hub = HubTest.Create(clock: new ManualTimeProvider()); + var publisher = new SourceSamplePublisher(hub, new("node-a", "serving-1", "Primary", 1, 1)); + var incarnation = publisher.RegisterDriverIncarnation("stub-driver-1"); + publisher.RegisterDriverShape("stub-driver-1", "tag", new(DataValueKind.Int32, null, -1)).ShouldBeTrue(); + publisher.EnsureDriverBinding("cluster", "stub-driver-1", "tag", incarnation).ShouldBeTrue(); + return (hub, publisher, incarnation); + } + + /// Records every routed call; the first failAcquisitions acquisition calls throw without invoking the call + /// site (an open breaker's BrokenCircuitException shape). + private sealed class GateInvoker(int failAcquisitions) : IDriverCapabilityInvoker + { + private int _acquisitionAttempts; + public ConcurrentQueue<(DriverCapability Capability, string Host)> Calls { get; } = new(); + + public ValueTask ExecuteAsync(DriverCapability capability, string hostName, + Func> callSite, CancellationToken cancellationToken) + { + Calls.Enqueue((capability, hostName)); + if (capability == DriverCapability.AcquisitionSubscribe && Interlocked.Increment(ref _acquisitionAttempts) <= failAcquisitions) + throw new InvalidOperationException("circuit open (simulated fast-fail)"); + return callSite(cancellationToken); + } + + public ValueTask ExecuteAsync(DriverCapability capability, string hostName, + Func callSite, CancellationToken cancellationToken) + { + Calls.Enqueue((capability, hostName)); + return callSite(cancellationToken); + } + + public ValueTask ExecuteWriteAsync(string hostName, bool isIdempotent, + Func> callSite, CancellationToken cancellationToken) + => callSite(cancellationToken); + } + + private sealed class AcquisitionDriver : StubDriver, ISubscribable, IAcknowledgedAcquisitionSource + { + private int _calls; + public int Calls => Volatile.Read(ref _calls); + public event EventHandler? OnDataChange { add { } remove { } } + public Task SubscribeAsync(IReadOnlyList refs, TimeSpan interval, CancellationToken ct) => + Task.FromResult(new Handle()); + public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct) => Task.CompletedTask; + public Task SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request, + Action callback, CancellationToken ct) + { + Interlocked.Increment(ref _calls); + return Task.FromResult(new AcquisitionSubscriptionResult(new Handle(), request.RequestedSamplingInterval, + request.DesiredRevision, request.ProducerIncarnation)); + } + private sealed class Handle : ISubscriptionHandle { public string DiagnosticId => "acq"; } + } +} From 2a8bac5bf5c5cb36c12f3347a00d7e516fa416ca Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 15:02:09 -0500 Subject: [PATCH 4/7] feat(audit,install): #1030 audit overflow drops exported as otopcua.audit.dropped; scripted SCM-restart-after-cluster-exit gate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - AuditWriterActor: every buffer-full drop is added to OtOpcUaTelemetry.AuditDropped (otopcua.audit.dropped{reason=buffer_full, actor}) — the count used to be readable only through the actor's own property. - scripts/install/tests/Test-ScmRestartAfterClusterExit.Windows.ps1: the windev manual gate of 2026-12-03 as a script (qfailure restart action; failover/command trigger => non-zero exit, 7031, Running under a new pid; Stop-Service stays stopped; optional kill control). Parse-checked with pwsh on macOS; must be run elevated on a Windows box hosting OtOpcUaHost. Co-Authored-By: Claude --- docs/Configuration.md | 2 +- docs/Redundancy.md | 9 + docs/ServiceHosting.md | 3 + ...est-ScmRestartAfterClusterExit.Windows.ps1 | 187 ++++++++++++++++++ .../Observability/OtOpcUaTelemetry.cs | 14 ++ .../Audit/AuditWriterActor.cs | 12 +- .../AuditWriterActorRetryTests.cs | 41 ++++ 7 files changed, 266 insertions(+), 2 deletions(-) create mode 100644 scripts/install/tests/Test-ScmRestartAfterClusterExit.Windows.ps1 diff --git a/docs/Configuration.md b/docs/Configuration.md index 99c1c6210..4cfe5c5d5 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -435,7 +435,7 @@ per cluster at `/clusters/{id}/audit`. It has no `appsettings` section — it is has a `ConfigDb` — but one schema property is worth recording here because it constrains how callers may write to it: -*Flush behaviour (#980 / review 05 H-2):* `AuditWriterActor` batches events and flushes every 5 s (or at 500). A flush that fails because the database did not answer **keeps** the batch and retries on the next tick; the buffer is bounded at 10 000 events (drop-oldest, with `OverflowDroppedCount` and a Warning). Rows the database rejects outright (e.g. a duplicate `EventId`) are still dropped individually. Events are lost only if the actor stops while the database is still down (logged at Error with the count). +*Flush behaviour (#980 / review 05 H-2):* `AuditWriterActor` batches events and flushes every 5 s (or at 500). A flush that fails because the database did not answer **keeps** the batch and retries on the next tick; the buffer is bounded at 10 000 events (drop-oldest, with `OverflowDroppedCount` and a Warning; since #1030 every drop is also exported as the meter counter `otopcua.audit.dropped{reason=buffer_full}` on the `ZB.MOM.WW.OtOpcUa` meter — alert on any non-zero rate, it means `ConfigAuditLog` is missing rows). Rows the database rejects outright (e.g. a duplicate `EventId`) are still dropped individually. Events are lost only if the actor stops while the database is still down (logged at Error with the count). - **`EventId` gives cross-restart deduplication, and the DB enforces it.** Each row carries the stable per-event `AuditEvent.EventId`, under a *filtered* unique index diff --git a/docs/Redundancy.md b/docs/Redundancy.md index af189f357..50f69a94f 100644 --- a/docs/Redundancy.md +++ b/docs/Redundancy.md @@ -504,6 +504,15 @@ two-node pair that choice means *any* crash of the oldest node is a full outage. that Akka's -1 is invisible to SCM recovery). Positive control: `sc stop` on the fixed build → clean `Stopped`, exit 0, no recovery. Under `auto-down` the *survivor* no longer needs this (it is never the one downed); the **downed** node still does. + + **Scripted form of that gate (#1030):** `scripts/install/tests/Test-ScmRestartAfterClusterExit.Windows.ps1`, run + elevated on the box hosting an installed `OtOpcUaHost` (the pair's current Primary for the default + `-Trigger Failover`, which pauses while the operator presses *Trigger failover* on the cluster redundancy page; + `-Trigger Command -TriggerCommand '…'` for an unattended trigger). It checks `sc.exe qfailure` has a restart action, + that the leave ends the process non-zero, logs **7031** and comes back `Running` under a new pid, and — as the + negative control — that `Stop-Service` stays `Stopped` with no 7031; `-KillControl` adds a hard-kill leg that + proves the SCM recovery config on its own. It never reconfigures the service and always leaves it running. Not + for the wonder boxes while remote access is on hold. 3. **Both peers listed in `SeedNodes`** on every node, **each node listing itself first**, so a restarted node can re-join via either peer and a node cold-starting while its peer is dead still forms the cluster. Without the self-first ordering it waits in `InitJoin` forever (auto-down removes the crash diff --git a/docs/ServiceHosting.md b/docs/ServiceHosting.md index 9c743f65a..159a2d4a2 100644 --- a/docs/ServiceHosting.md +++ b/docs/ServiceHosting.md @@ -186,6 +186,9 @@ steps inside the window (a `data\` backup) and the host start-up to `/health/rea - `scripts/install/Install-Services.ps1 -Roles admin,driver` — installs `OtOpcUaHost`. - `scripts/install/Install-ScriptWorkerIsolation.ps1` — the ScriptWorker identity, ACLs and firewall rule (above); only for `Scripting:Runner` ≠ `InProcess`. - `scripts/install/Invoke-OtOpcUaInstallSwap.ps1` — upgrade/rollback folder swap with the isolation `-Reapply` + `-Verify` gate built in (lmxopcua#901), scoped so only the swapped-in folder is handled while the service is stopped (lmxopcua#905, above). +- `scripts/install/tests/Test-ScmRestartAfterClusterExit.Windows.ps1` — elevated, on the node's own box: checks that a node + leaving its cluster (manual failover) is restarted by the `sc.exe failure` recovery `Install-Services.ps1` sets, and that a + clean `Stop-Service` is not (#980/#1030; `docs/Redundancy.md` §"Recovery still depends on supervision"). - `scripts/install/Uninstall-Services.ps1` — stops + removes the host service. (The historian backend is the external HistorianGateway — not installed/removed by these scripts.) ## Logging diff --git a/scripts/install/tests/Test-ScmRestartAfterClusterExit.Windows.ps1 b/scripts/install/tests/Test-ScmRestartAfterClusterExit.Windows.ps1 new file mode 100644 index 000000000..f45c3f50d --- /dev/null +++ b/scripts/install/tests/Test-ScmRestartAfterClusterExit.Windows.ps1 @@ -0,0 +1,187 @@ +<# +.SYNOPSIS + Windows-executed gate for lmxopcua#980 / #1030: an OtOpcUaHost node whose ActorSystem terminates because it LEFT or was + DOWNED from its cluster (manual failover, endpoint step-down, auto-down) must be RESTARTED by Windows SCM recovery + (sc.exe failure), while an operator `sc stop` must stay stopped. + +.DESCRIPTION + Background (docs/Redundancy.md "Recovery still depends on supervision"): ActorSystemTerminationWatchdog exits the process + with code 1 on an unexpected termination, so SCM sees the service process die WITHOUT reporting SERVICE_STOPPED, logs + System event 7031 ("terminated unexpectedly") and runs the configured recovery action. Before #980 the node ended in a + clean stop (SERVICE_STOPPED, win32 exit 0) and SCM never restarted it. This script is the scripted form of the manual + windev gate of 2026-12-03. + + It runs ON the Windows box that hosts the service under test, elevated, against an INSTALLED OtOpcUaHost + (scripts\install\Install-Services.ps1). It never installs, uninstalls or reconfigures anything; it stops/starts only the + named service and always leaves it Running (finally block). + + Legs (each prints PASS/FAIL lines; exit 0 = all passed, 1 = a check failed, 2 = cannot run here): + 1. Recovery config sc.exe qfailure lists at least one RESTART action (what Install-Services.ps1 sets). + 2. Cluster exit the trigger makes this node leave / be downed. Expected: the service process exits (exit code 1 + when readable), SCM logs 7031 for the service, and the service is Running again under a NEW pid + within the recovery delay + -TimeoutSeconds. + 3. Clean stop (unless -SkipStopControl) Stop-Service: the service reports Stopped, NO new 7031 is logged and it + is NOT restarted within the first recovery delay + 15 s; then the script starts it again. + 4. Kill control (only with -KillControl) Stop-Process -Force: a crash is restarted (7031/7034). This proves the + SCM recovery config, not the watchdog — use it to tell "recovery not configured" from "the + node did not exit non-zero" when leg 2 fails. + + Triggers (-Trigger): + Failover (default) the script pauses and asks the operator to press "Trigger failover" on the AdminUI cluster + redundancy page (/clusters/{id}/redundancy). Manual failover asks the driver PRIMARY to leave, so run this on + the box hosting the current Primary of a two-node pair. Needs an interactive console. + Command runs -TriggerCommand (a PowerShell script block, as text) that makes THIS node leave or be downed, e.g. a + local admin tool; the script does not interpret it. + + Do NOT run this on the wonder boxes (vd03 / vq03 / vq04) while remote access is on hold — it is meant for windev or a QA + pair, run locally by an operator. It restarts the node it targets: a two-node pair fails over once (and again for + -KillControl); a single-node cluster has an outage for each leg. + + Run once per PowerShell host if in doubt; it uses nothing host-specific: + + pwsh -NoProfile -File scripts\install\tests\Test-ScmRestartAfterClusterExit.Windows.ps1 + powershell -NoProfile -ExecutionPolicy Bypass -File scripts\install\tests\Test-ScmRestartAfterClusterExit.Windows.ps1 -KillControl + pwsh -NoProfile -File ...\Test-ScmRestartAfterClusterExit.Windows.ps1 -Trigger Command -TriggerCommand '