diff --git a/docs/Configuration.md b/docs/Configuration.md
index 95f6ffcd1..599fcdd54 100644
--- a/docs/Configuration.md
+++ b/docs/Configuration.md
@@ -307,6 +307,8 @@ h2c mesh settings do not opt this listener into cleartext.
**The listener is dedicated h2c and coexists with the LocalDb-sync listener.** A fused admin+driver node with **both** `ConfigServe:GrpcListenPort` and `LocalDb:SyncListenPort` set re-binds its existing HTTP surface exactly once and adds both dedicated HTTP/2-only ports on top — see the same Kestrel-takeover caveat under [`LocalDb`](#localdb-pair-local-config-cache--driver-role-only).
+**An HTTPS binding refuses host start (#980 / review 05 H-5).** The takeover cannot replay an HTTPS endpoint's certificate configuration (TLS is terminated upstream), so a node with any HTTPS URL/`HTTPS_PORTS` binding **and** any non-zero `LocalDb:SyncListenPort` / `ConfigServe:GrpcListenPort` / `Telemetry:GrpcListenPort` / `DataConnections:ListenPort` now fails to start with a message naming every requested port (`DedicatedListenerGuard`). It previously logged one Error, zeroed the ports and booted ready with no deploy/config/telemetry endpoints. Serve the UI/health surface over HTTP, or set the port(s) to 0.
+
**`RevisionHash == SHA-256(artifact bytes)` is load-bearing.** `ConfigComposer` computes the deployment's revision hash as the lowercase-hex SHA-256 of the exact artifact bytes, so the node verifies a fetch against the `RevisionHash` the dispatch already carries — no hash rides in the proto. If a future change makes the revision hash anything else, every fetch fails verification.
**`DeploymentArtifactService` is `AllowAnonymous` by design** — same reasoning as `NodeCommandService`/`CentralCommandService` above: the AdminUI cookie `FallbackPolicy` on an admin-role node would otherwise block a correctly-keyed fetch before `ConfigServeAuthInterceptor`'s verdict matters. See [`security.md` § Mesh gRPC ingress is `AllowAnonymous` by design](security.md#mesh-grpc-ingress-is-allowanonymous-by-design).
@@ -431,6 +433,8 @@ 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).
+
- **`EventId` gives cross-restart deduplication, and the DB enforces it.** Each row carries the
stable per-event `AuditEvent.EventId`, under a *filtered* unique index
(`UX_ConfigAuditLog_EventId`, `WHERE [EventId] IS NOT NULL` — so the nullable pre-v2 backfill rows
diff --git a/docs/Redundancy.md b/docs/Redundancy.md
index 529889204..d1bf5bc8c 100644
--- a/docs/Redundancy.md
+++ b/docs/Redundancy.md
@@ -472,9 +472,15 @@ two-node pair that choice means *any* crash of the oldest node is a full outage.
`sc.exe failure OtOpcUaHost … actions= restart/5000/restart/30000/restart/60000`; the docker-dev rig sets
`restart: unless-stopped`.
2. **The recovery watchdog** `ActorSystemTerminationWatchdog` (registered in `Program.cs` after `AddAkka`) —
- it watches `ActorSystem.WhenTerminated` and, on an unexpected self-down, calls
- `IHostApplicationLifetime.StopApplication()` so the process exits and the supervisor restarts it instead
- of idling forever with a dead actor system. Under `auto-down` the *survivor* no longer needs this
+ it watches `ActorSystem.WhenTerminated` and, on a termination outside host shutdown (auto-down, manual
+ failover `Leave`, endpoint step-down), flushes Serilog and **exits the process with code 1**
+ (`Environment.Exit`, on a dedicated thread) so the supervisor restarts it instead of idling forever with
+ a dead actor system. It deliberately does **not** call `StopApplication()` (#980 / review 05 H-1): under
+ `UseWindowsService` that is a *clean* service stop (`SERVICE_STOPPED`, exit 0), which `sc.exe failure`
+ recovery does not act on, so a node that left the cluster stayed stopped on Windows (docker's
+ `restart: unless-stopped` masked it). A graceful host stop (SCM stop, Ctrl-C) is still silent. The
+ real-SCM check (leave a node on a Windows pair, assert the service returns to `Running` within the first
+ recovery delay) is a live gate on `windev`. Under `auto-down` the *survivor* no longer needs this
(it is never the one downed); the **downed** node still does.
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
@@ -508,7 +514,7 @@ The mechanism is a graceful cluster **`Leave`** of the current Primary, never a
query to `RedundancyStateActor.SelectDriverPrimary`, pinned together by
`ManualFailoverServiceTests.Parity_with_SelectDriverPrimary` so the node acted on is exactly the node the
election names. The leaving node hands its singletons over through the cluster-leave phases,
-`CoordinatedShutdown` runs, `ActorSystemTerminationWatchdog` exits the process, the supervisor restarts it,
+`CoordinatedShutdown` runs, `ActorSystemTerminationWatchdog` exits the process (non-zero), the supervisor restarts it,
and it rejoins as the **youngest** member — so the survivor is now the oldest, becomes Primary, and
advertises `ServiceLevel` 250. OPC UA clients re-select.
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Audit/AuditWriterActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Audit/AuditWriterActor.cs
index 3f0aa914f..386f9de96 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Audit/AuditWriterActor.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Audit/AuditWriterActor.cs
@@ -14,6 +14,14 @@ namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Audit;
/// - elapses with a non-empty buffer.
/// - PreRestart / PostStop (supervisor swap or coordinated shutdown).
///
+/// A flush that fails because the database did not answer (connection loss, login timeout, deadlock — as
+/// opposed to the database rejecting specific rows) keeps the batch: the events go back into the buffer
+/// and the next timer tick retries them (#980 / review 05 H-2). The buffer is bounded by
+/// ; past that the OLDEST events are dropped, counted
+/// () and logged, so a long outage cannot grow memory without bound.
+/// While flushes are failing, the count-threshold trigger is suppressed (each attempt blocks the actor for a
+/// connect timeout) and only the timer retries.
+///
/// Dedup is two-layer: in-buffer (the below collapses
/// duplicate EventIds before flush) and at the database via the filtered unique index
/// UX_ConfigAuditLog_EventId (cross-restart safety — a retry of an already-flushed
@@ -30,9 +38,21 @@ public sealed class AuditWriterActor : ReceiveActor, IWithTimers, IAuditWriter
public const int FlushBatchSize = 500;
public static readonly TimeSpan FlushInterval = TimeSpan.FromSeconds(5);
+ /// Upper bound on events held in memory awaiting a successful save; past it the oldest are dropped.
+ public const int MaxBufferedEvents = 10_000;
+
private readonly IDbContextFactory _dbFactory;
private readonly ILoggingAdapter _log = Context.GetLogger();
- private readonly Dictionary _buffer = new();
+ // Insertion-ordered so the overflow policy can drop the OLDEST events first.
+ private readonly OrderedDictionary _buffer = new();
+ private bool _lastFlushFailed;
+ private long _overflowDropped;
+
+ /// Total events dropped (oldest first) because the retry buffer hit .
+ public long OverflowDroppedCount => Interlocked.Read(ref _overflowDropped);
+
+ /// Events currently buffered awaiting a successful save (diagnostic / test seam).
+ public int BufferedCount => _buffer.Count;
/// Gets or sets the timer scheduler for the actor.
public ITimerScheduler Timers { get; set; } = null!;
@@ -62,8 +82,9 @@ public sealed class AuditWriterActor : ReceiveActor, IWithTimers, IAuditWriter
/// seam. Best-effort and never throws: routes the event onto this
/// actor's mailbox via Tell (thread-safe from any caller) so it flows through the same
/// batching + dedup pipeline as in-cluster traffic, then returns immediately. The actual
- /// persistence happens asynchronously on the next flush; a write failure there is logged and
- /// the batch dropped (per the best-effort audit contract).
+ /// persistence happens asynchronously on the next flush; a transient database failure there
+ /// keeps the batch for retry (bounded — see ), while rows the database
+ /// rejects outright are dropped (per the best-effort audit contract).
///
/// The canonical audit event to persist.
/// Unused — enqueue is synchronous and non-blocking.
@@ -80,10 +101,30 @@ public sealed class AuditWriterActor : ReceiveActor, IWithTimers, IAuditWriter
// In-buffer dedup. Last write wins on duplicate EventId within the batch — events
// with the same EventId are by contract identical, so this is a no-op.
_buffer[evt.EventId] = evt;
- if (_buffer.Count >= FlushBatchSize) FlushBuffer();
+ TrimToCap();
+ // While the database is failing, only the timer retries: a threshold-triggered attempt per arriving
+ // event would block the actor for a connect timeout each time.
+ if (_buffer.Count >= FlushBatchSize && !_lastFlushFailed) FlushBuffer();
}
- private void FlushBuffer()
+ /// Drops the oldest events beyond , counting and logging them.
+ private void TrimToCap()
+ {
+ var overflow = _buffer.Count - MaxBufferedEvents;
+ if (overflow <= 0) return;
+
+ for (var i = 0; i < overflow; i++) _buffer.RemoveAt(0);
+ var before = Interlocked.Read(ref _overflowDropped);
+ var total = Interlocked.Add(ref _overflowDropped, overflow);
+ // Once per 1000 drops (and on the first), so a sustained outage does not log per event.
+ if (before == 0 || before / 1000 != total / 1000)
+ _log.Warning(
+ "AuditWriter retry buffer is full ({Max} events) because the ConfigDb is not accepting writes; " +
+ "dropped the oldest {Overflow} event(s) ({Total} dropped in total)",
+ MaxBufferedEvents, overflow, total);
+ }
+
+ private void FlushBuffer(bool final = false)
{
if (_buffer.Count == 0) return;
@@ -93,11 +134,28 @@ public sealed class AuditWriterActor : ReceiveActor, IWithTimers, IAuditWriter
try
{
var dropped = SaveBatch(snapshot);
+ _lastFlushFailed = false;
_log.Debug("AuditWriter flushed {Count} events ({Dropped} rejected rows dropped)", snapshot.Count - dropped, dropped);
}
catch (Exception ex)
{
- _log.Error(ex, "AuditWriter flush failed; {Count} events dropped", snapshot.Count);
+ _lastFlushFailed = true;
+ if (final)
+ {
+ // The actor is going away; there is no next tick. This is the one place events are lost.
+ _log.Error(ex, "AuditWriter flush failed while stopping; {Count} events dropped", snapshot.Count);
+ return;
+ }
+
+ // The database did not answer (or failed in a way that names no row): keep the batch. Events
+ // that arrived since the snapshot (none today — the actor is single-threaded — but cheap to be
+ // right about) stay after the older ones. The unique EventId index makes a retried batch safe.
+ var newer = _buffer.Values.ToList();
+ _buffer.Clear();
+ foreach (var evt in snapshot) _buffer[evt.EventId] = evt;
+ foreach (var evt in newer) _buffer[evt.EventId] = evt;
+ TrimToCap();
+ _log.Warning(ex, "AuditWriter flush failed; keeping {Count} events buffered for retry", _buffer.Count);
}
}
@@ -200,14 +258,14 @@ public sealed class AuditWriterActor : ReceiveActor, IWithTimers, IAuditWriter
///
protected override void PreRestart(Exception reason, object message)
{
- FlushBuffer();
+ FlushBuffer(final: true);
base.PreRestart(reason, message);
}
///
protected override void PostStop()
{
- FlushBuffer();
+ FlushBuffer(final: true);
base.PostStop();
}
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/ActorSystemTerminationWatchdog.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/ActorSystemTerminationWatchdog.cs
index 5ee383299..ecf941dfd 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/ActorSystemTerminationWatchdog.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/ActorSystemTerminationWatchdog.cs
@@ -15,8 +15,17 @@ namespace ZB.MOM.WW.OtOpcUa.Host;
/// This watchdog closes the gap where the terminates but the .NET
/// host process keeps running with a dead actor system (idling forever, never restarted). It watches
/// ; if the system terminates outside a normal host
-/// shutdown, it stops the application so the supervisor can restart the process. Mirrors the sister
-/// ScadaBridge project's proven pattern.
+/// shutdown, it ends the process as a failure (flush logs, exit code )
+/// so the supervisor can restart it. Mirrors the sister ScadaBridge project's proven pattern.
+///
+/// Why not StopApplication() (#980 / review 05 H-1). That is a graceful host stop;
+/// under UseWindowsService the host then reports SERVICE_STOPPED with exit code 0, and
+/// Windows SCM runs sc failure recovery only when the service process dies without reporting
+/// a clean stop (or, with sc failureflag, stops with a non-zero code). So a node that left the
+/// cluster (manual failover, endpoint step-down, auto-down after a pause) stopped for good and the pair
+/// ran on one node. Docker (restart: unless-stopped) restarts on any exit, which is why this never
+/// showed on the docker-dev rig. The exit is performed on a separate thread so it cannot deadlock the
+/// thread that completed the termination, and is injectable so the path is testable.
///
/// Registered after AddAkka so it starts after Akka's own hosted service has
/// built the system; the is resolved lazily in
@@ -30,20 +39,31 @@ public sealed class ActorSystemTerminationWatchdog : IHostedService
private readonly Func _actorSystemAccessor;
private readonly IHostApplicationLifetime _lifetime;
private readonly ILogger _logger;
+ private readonly Action _exitProcess;
+ private readonly Action _flushLogs;
private volatile bool _stopRequested;
+ /// Process exit code used when the actor system terminated outside host shutdown.
+ public const int FailureExitCode = 1;
+
/// Constructs the watchdog over a lazy accessor and the host lifetime.
/// Lazy accessor (resolved in , never at construction, so it can't race Akka startup).
/// Host application lifetime used to stop the process on an unexpected self-down.
/// Logger for the critical self-down diagnostic.
+ /// Ends the process with the given exit code; defaults to . Test seam.
+ /// Flushes the log pipeline before exit; defaults to Serilog.Log.CloseAndFlush. Test seam.
public ActorSystemTerminationWatchdog(
Func actorSystemAccessor,
IHostApplicationLifetime lifetime,
- ILogger logger)
+ ILogger logger,
+ Action? exitProcess = null,
+ Action? flushLogs = null)
{
_actorSystemAccessor = actorSystemAccessor;
_lifetime = lifetime;
_logger = logger;
+ _exitProcess = exitProcess ?? Environment.Exit;
+ _flushLogs = flushLogs ?? Serilog.Log.CloseAndFlush;
}
/// Wires the continuation that exits the host on an unexpected self-down.
@@ -60,10 +80,22 @@ public sealed class ActorSystemTerminationWatchdog : IHostedService
return;
_logger.LogCritical(
- "ActorSystem terminated outside host shutdown (SBR self-down / "
- + "run-coordinated-shutdown-when-down). Stopping the host so the service supervisor "
- + "restarts this node as a fresh incarnation (2-node keep-oldest exit-and-rejoin recovery).");
- _lifetime.StopApplication();
+ "ActorSystem terminated outside host shutdown (downed / left the cluster / "
+ + "run-coordinated-shutdown-when-down). Exiting the process with code {ExitCode} so the "
+ + "service supervisor (SCM recovery / docker restart) restarts this node as a fresh "
+ + "incarnation (exit-and-rejoin recovery).",
+ FailureExitCode);
+
+ // A dedicated thread: the exit must not run on (or wait for) the thread that completed the
+ // ActorSystem termination, and a failing flush must never prevent the exit.
+ var exit = new Thread(() =>
+ {
+ try { _flushLogs(); }
+ catch { /* the exit below is the point */ }
+ _exitProcess(FailureExitCode);
+ })
+ { IsBackground = true, Name = "otopcua-watchdog-exit" };
+ exit.Start();
},
TaskContinuationOptions.ExecuteSynchronously);
return Task.CompletedTask;
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DedicatedListenerGuard.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DedicatedListenerGuard.cs
new file mode 100644
index 000000000..b34738d47
--- /dev/null
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DedicatedListenerGuard.cs
@@ -0,0 +1,58 @@
+namespace ZB.MOM.WW.OtOpcUa.Host.Configuration;
+
+///
+/// Start-up guard for the dedicated h2c listeners (LocalDb sync, ConfigServe, telemetry, data
+/// connections). Taking over Kestrel for a dedicated listener means re-binding every existing endpoint
+/// explicitly, and an HTTPS endpoint's certificate configuration cannot be replayed (TLS is terminated
+/// upstream). #980 / review 05 H-5.
+///
+///
+/// A dedicated listener is only ever requested by an explicit non-zero port setting, and every consumer
+/// of those ports is load-bearing: without the telemetry/command listener a node can receive no deploy
+/// command, without ConfigServe no node can fetch config or ack. The option validators check the
+/// configured values, so they pass while the effective ports are zeroed — the node would boot,
+/// join its mesh and report ready with every mesh endpoint missing. So a contradictory configuration
+/// fails host start with a message naming every setting involved, instead of logging one Error and
+/// continuing.
+///
+public static class DedicatedListenerGuard
+{
+ ///
+ /// Throws when any dedicated listener is requested while an
+ /// existing HTTPS binding makes it impossible to bind.
+ ///
+ /// LocalDb:SyncListenPort effective value (0 = off).
+ /// ConfigServe:GrpcListenPort effective value (0 = off).
+ /// Telemetry:GrpcListenPort effective value (0 = off).
+ /// DataConnections:ListenPort effective value (0 = off).
+ /// The HTTP surface the host was asked to serve.
+ /// The raw configured URL list, for the message; may be null.
+ public static void ThrowIfHttpsBlocksDedicatedListeners(
+ int syncListenPort,
+ int configServeGrpcPort,
+ int telemetryListenPort,
+ int dataListenPort,
+ IReadOnlyList existingBindings,
+ string? configuredUrls)
+ {
+ ArgumentNullException.ThrowIfNull(existingBindings);
+ if (!existingBindings.Any(b => b.IsSecure))
+ return;
+
+ var requested = new List();
+ if (syncListenPort > 0) requested.Add($"LocalDb:SyncListenPort={syncListenPort}");
+ if (configServeGrpcPort > 0) requested.Add($"ConfigServe:GrpcListenPort={configServeGrpcPort}");
+ if (telemetryListenPort > 0) requested.Add($"Telemetry:GrpcListenPort={telemetryListenPort}");
+ if (dataListenPort > 0) requested.Add($"DataConnections:ListenPort={dataListenPort}");
+ if (requested.Count == 0)
+ return;
+
+ throw new InvalidOperationException(
+ "Dedicated h2c listener(s) are requested (" + string.Join(", ", requested) + ") but this host " +
+ $"serves HTTPS endpoint(s) ({configuredUrls ?? "ASPNETCORE_HTTPS_PORTS/HTTPS_PORTS"}). " +
+ "Binding a dedicated listener requires re-binding every existing endpoint explicitly, and the " +
+ "HTTPS certificate configuration cannot be replayed safely, so the node cannot start with the " +
+ "mesh endpoints it was configured to serve. Terminate TLS upstream (as the docker-dev rig does) " +
+ "and serve the UI/health surface over HTTP, or set the listed port(s) to 0 on this node.");
+ }
+}
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Program.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Program.cs
index fc88a0671..a4aa95f68 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Program.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Program.cs
@@ -745,27 +745,11 @@ if (syncListenPort > 0 || configServeGrpcPort > 0 || telemetryListenPort > 0 ||
// Re-binding an https endpoint would need its certificate configuration replayed too, which
// this host does not model (TLS is terminated at Traefik). Rather than silently serve it
- // without TLS — or drop it — refuse to take over Kestrel at all and leave the existing
- // surface exactly as it was. The operator gets a loud, actionable error instead of an
- // AdminUI that stopped answering. Disables BOTH dedicated ports (either would force the same
- // Kestrel takeover).
- if (existingBindings.Any(b => b.IsSecure))
- {
- if (dataListenPort > 0)
- throw new InvalidOperationException("The dedicated data listener cannot safely replay existing HTTPS URL bindings. Configure an HTTP UI/health binding and the dedicated data TLS certificate separately.");
- Log.Error(
- "A dedicated h2c listener is requested (LocalDb:SyncListenPort={SyncPort}, " +
- "ConfigServe:GrpcListenPort={ConfigServePort}, Telemetry:GrpcListenPort={TelemetryPort}) but this " +
- "host serves HTTPS endpoint(s) ({Urls}). " +
- "Binding a dedicated listener requires re-binding every existing endpoint explicitly, and the " +
- "HTTPS certificate configuration cannot be replayed safely. ALL dedicated listeners are DISABLED; " +
- "terminate TLS upstream (as the docker-dev rig does) or leave these features off on this node.",
- syncListenPort, configServeGrpcPort, telemetryListenPort, configuredUrls);
- syncListenPort = 0;
- configServeGrpcPort = 0;
- telemetryListenPort = 0;
- }
- else
+ // without TLS, drop it, or (the pre-#980 behaviour) boot with every mesh listener silently
+ // disabled and report ready — fail host start with an actionable error (review 05 H-5). The
+ // Program.cs wrapper turns the throw into a Fatal log + stderr FATAL + exit 1.
+ DedicatedListenerGuard.ThrowIfHttpsBlocksDedicatedListeners(
+ syncListenPort, configServeGrpcPort, telemetryListenPort, dataListenPort, existingBindings, configuredUrls);
{
// Capture locals so the ConfigureKestrel closure does not observe later reassignment.
var syncPortToBind = syncListenPort;
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AuditWriterActorRejectedRowTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AuditWriterActorRejectedRowTests.cs
index 86855b2c7..4ba586889 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AuditWriterActorRejectedRowTests.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AuditWriterActorRejectedRowTests.cs
@@ -108,7 +108,11 @@ public sealed class AuditWriterActorRejectedRowTests : ControlPlaneActorTestBase
foreach (var id in ids) persisted.ShouldContain(id);
}
- /// A failure that names no entry is a whole-batch failure, exactly as before.
+ ///
+ /// A failure that names no entry is a whole-batch failure: the batch is kept for retry (#980 H-2; see
+ /// ), so the ONLY loss left is the final flush at stop with the
+ /// database still down. Terminating ⇒ the retry loop does not spin.
+ ///
[Fact]
public void A_connection_level_failure_still_drops_the_batch_without_looping()
{
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AuditWriterActorRetryTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AuditWriterActorRetryTests.cs
new file mode 100644
index 000000000..751bc9a63
--- /dev/null
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AuditWriterActorRetryTests.cs
@@ -0,0 +1,128 @@
+using Akka.Actor;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Diagnostics;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Storage;
+using Shouldly;
+using Xunit;
+using ZB.MOM.WW.Audit;
+using ZB.MOM.WW.OtOpcUa.Configuration;
+using ZB.MOM.WW.OtOpcUa.ControlPlane.Audit;
+using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness;
+
+namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests;
+
+///
+/// #980 / review 05 H-2 — a flush that fails because the database did not answer used to clear the
+/// buffer first and drop the batch. The writer now keeps it (bounded, drop-oldest + counter) and the next
+/// tick retries; the unique EventId index makes a retried batch safe.
+///
+public sealed class AuditWriterActorRetryTests : ControlPlaneActorTestBase
+{
+ [Fact]
+ public void A_transient_connection_failure_keeps_the_batch_and_the_next_flush_persists_it()
+ {
+ var failing = new FailingSaves { Down = true };
+ var factory = new FailingDbFactory(Guid.NewGuid().ToString("N"), new InMemoryDatabaseRoot(), failing);
+ var actor = ActorOfAsTestActorRef(AuditWriterActor.Props(factory));
+
+ var ids = Enumerable.Range(0, 20).Select(_ => Guid.NewGuid()).ToList();
+ foreach (var id in ids) actor.Tell(NewEvent(id));
+
+ actor.Tell(AuditWriterActor.Flush.Instance); // outage: the save throws
+ actor.UnderlyingActor.BufferedCount.ShouldBe(20, "the failed batch must stay buffered, not be dropped");
+ failing.Attempts.ShouldBeGreaterThan(0, "positive control: the failure path really ran");
+ using (var during = factory.CreateDbContext(withFailure: false))
+ during.ConfigAuditLogs.Count().ShouldBe(0);
+
+ failing.Down = false;
+ actor.Tell(AuditWriterActor.Flush.Instance); // recovery
+ actor.UnderlyingActor.BufferedCount.ShouldBe(0);
+
+ using var db = factory.CreateDbContext(withFailure: false);
+ var persisted = db.ConfigAuditLogs.Select(r => r.EventId).ToList();
+ persisted.Count.ShouldBe(20, "no event may be lost across the outage");
+ foreach (var id in ids) persisted.ShouldContain(id);
+ actor.UnderlyingActor.OverflowDroppedCount.ShouldBe(0);
+ }
+
+ [Fact]
+ public void Events_arriving_during_an_outage_are_kept_and_persist_after_recovery()
+ {
+ var failing = new FailingSaves { Down = true };
+ var factory = new FailingDbFactory(Guid.NewGuid().ToString("N"), new InMemoryDatabaseRoot(), failing);
+ var actor = ActorOfAsTestActorRef(AuditWriterActor.Props(factory));
+
+ // Cross the count threshold so a threshold flush fires, fails, and the writer must NOT retry per event.
+ var ids = Enumerable.Range(0, AuditWriterActor.FlushBatchSize + 50).Select(_ => Guid.NewGuid()).ToList();
+ foreach (var id in ids) actor.Tell(NewEvent(id));
+
+ failing.Attempts.ShouldBe(1, "while the database is failing, arriving events must not each trigger a blocking flush attempt");
+ actor.UnderlyingActor.BufferedCount.ShouldBe(ids.Count);
+
+ failing.Down = false;
+ actor.Tell(AuditWriterActor.Flush.Instance);
+ using var db = factory.CreateDbContext(withFailure: false);
+ db.ConfigAuditLogs.Count().ShouldBe(ids.Count);
+ }
+
+ [Fact]
+ public void The_retry_buffer_is_bounded_dropping_the_oldest_and_counting_them()
+ {
+ var failing = new FailingSaves { Down = true };
+ var factory = new FailingDbFactory(Guid.NewGuid().ToString("N"), new InMemoryDatabaseRoot(), failing);
+ var actor = ActorOfAsTestActorRef(AuditWriterActor.Props(factory));
+
+ const int extra = 25;
+ var ids = Enumerable.Range(0, AuditWriterActor.MaxBufferedEvents + extra).Select(_ => Guid.NewGuid()).ToList();
+ foreach (var id in ids) actor.Tell(NewEvent(id));
+
+ actor.UnderlyingActor.BufferedCount.ShouldBe(AuditWriterActor.MaxBufferedEvents);
+ actor.UnderlyingActor.OverflowDroppedCount.ShouldBe(extra);
+
+ failing.Down = false;
+ actor.Tell(AuditWriterActor.Flush.Instance);
+ using var db = factory.CreateDbContext(withFailure: false);
+ var persisted = db.ConfigAuditLogs.Select(r => r.EventId).ToHashSet();
+ persisted.Count.ShouldBe(AuditWriterActor.MaxBufferedEvents);
+ // Drop-OLDEST: the first `extra` are gone, the newest survive.
+ foreach (var id in ids.Take(extra)) persisted.ShouldNotContain(id);
+ persisted.ShouldContain(ids[^1]);
+ persisted.ShouldContain(ids[extra]);
+ }
+
+ private static AuditEvent NewEvent(Guid eventId) => new()
+ {
+ EventId = eventId, Category = "Config", Action = "Edit", Actor = "joe",
+ OccurredAtUtc = DateTimeOffset.UtcNow, Outcome = AuditOutcome.Success,
+ DetailsJson = "{}", SourceNode = "node-a", CorrelationId = Guid.NewGuid(),
+ };
+
+ /// Throws a connection-level (entry-less) on every save while .
+ private sealed class FailingSaves : ISaveChangesInterceptor
+ {
+ private int _attempts;
+ public volatile bool Down;
+ public int Attempts => Volatile.Read(ref _attempts);
+
+ public InterceptionResult SavingChanges(DbContextEventData eventData, InterceptionResult result)
+ {
+ if (!Down) return result;
+ Interlocked.Increment(ref _attempts);
+ throw new DbUpdateException("connection lost (simulated)");
+ }
+ }
+
+ private sealed class FailingDbFactory(string dbName, InMemoryDatabaseRoot root, FailingSaves interceptor)
+ : IDbContextFactory
+ {
+ public OtOpcUaConfigDbContext CreateDbContext() => CreateDbContext(withFailure: true);
+
+ public OtOpcUaConfigDbContext CreateDbContext(bool withFailure)
+ {
+ var builder = new DbContextOptionsBuilder().UseInMemoryDatabase(dbName, root);
+ if (withFailure) builder.AddInterceptors(interceptor);
+ return new OtOpcUaConfigDbContext(builder.Options);
+ }
+ }
+}
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/ActorSystemTerminationWatchdogTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/ActorSystemTerminationWatchdogTests.cs
index f4fed6ce8..0f62bf356 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/ActorSystemTerminationWatchdogTests.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/ActorSystemTerminationWatchdogTests.cs
@@ -15,22 +15,47 @@ namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests;
[Trait("Category", "Unit")]
public sealed class ActorSystemTerminationWatchdogTests
{
- /// An unexpected ActorSystem termination stops the host so the supervisor restarts the node.
+ ///
+ /// An unexpected ActorSystem termination ends the process with a NON-ZERO exit code (#980 H-1):
+ /// a graceful StopApplication reports a clean service stop and SCM never restarts it.
+ ///
[Fact]
- public async Task Unexpected_termination_stops_the_application()
+ public async Task Unexpected_termination_exits_the_process_non_zero_after_flushing_logs()
{
var system = ActorSystem.Create("watchdog-unexpected");
var lifetime = new FakeHostApplicationLifetime();
- var watchdog = new ActorSystemTerminationWatchdog(
- () => system, lifetime, NullLogger.Instance);
+ var exits = new ExitRecorder();
+ var watchdog = Create(system, lifetime, exits);
await watchdog.StartAsync(CancellationToken.None);
// Simulate the SBR self-down: the ActorSystem terminates while the host is still running.
await system.Terminate();
- await WaitForAsync(() => lifetime.StopApplicationCalls > 0, TimeSpan.FromSeconds(5));
- lifetime.StopApplicationCalls.ShouldBe(1, "an out-of-band ActorSystem termination must stop the host once");
+ await WaitForAsync(() => exits.ExitCodes.Count > 0, TimeSpan.FromSeconds(5));
+ exits.ExitCodes.ShouldBe([ActorSystemTerminationWatchdog.FailureExitCode],
+ "an out-of-band ActorSystem termination must end the process once, non-zero");
+ ActorSystemTerminationWatchdog.FailureExitCode.ShouldNotBe(0);
+ exits.FlushCalls.ShouldBe(1, "logs are flushed before the process exits");
+ exits.FlushedBeforeExit.ShouldBeTrue();
+ lifetime.StopApplicationCalls.ShouldBe(0,
+ "StopApplication is a CLEAN stop (SERVICE_STOPPED, exit 0) and would defeat SCM recovery");
+ }
+
+ /// A throwing log flush must never prevent the exit.
+ [Fact]
+ public async Task A_failing_log_flush_still_exits_the_process()
+ {
+ var system = ActorSystem.Create("watchdog-flush-throws");
+ var lifetime = new FakeHostApplicationLifetime();
+ var exits = new ExitRecorder { FlushThrows = true };
+ var watchdog = Create(system, lifetime, exits);
+
+ await watchdog.StartAsync(CancellationToken.None);
+ await system.Terminate();
+
+ await WaitForAsync(() => exits.ExitCodes.Count > 0, TimeSpan.FromSeconds(5));
+ exits.ExitCodes.ShouldBe([ActorSystemTerminationWatchdog.FailureExitCode]);
}
/// A graceful host stop (StopAsync ran) leaves the termination continuation silent.
@@ -39,8 +64,8 @@ public sealed class ActorSystemTerminationWatchdogTests
{
var system = ActorSystem.Create("watchdog-graceful");
var lifetime = new FakeHostApplicationLifetime();
- var watchdog = new ActorSystemTerminationWatchdog(
- () => system, lifetime, NullLogger.Instance);
+ var exits = new ExitRecorder();
+ var watchdog = Create(system, lifetime, exits);
await watchdog.StartAsync(CancellationToken.None);
@@ -51,6 +76,7 @@ public sealed class ActorSystemTerminationWatchdogTests
// Give any continuation a chance to run, then assert it stayed silent.
await Task.Delay(500, TestContext.Current.CancellationToken);
lifetime.StopApplicationCalls.ShouldBe(0, "a graceful shutdown must not re-trigger StopApplication");
+ exits.ExitCodes.ShouldBeEmpty("a graceful shutdown must not exit the process as a failure");
}
/// Termination while the host is already stopping (ApplicationStopping fired) stays silent.
@@ -59,8 +85,8 @@ public sealed class ActorSystemTerminationWatchdogTests
{
var system = ActorSystem.Create("watchdog-already-stopping");
var lifetime = new FakeHostApplicationLifetime();
- var watchdog = new ActorSystemTerminationWatchdog(
- () => system, lifetime, NullLogger.Instance);
+ var exits = new ExitRecorder();
+ var watchdog = Create(system, lifetime, exits);
await watchdog.StartAsync(CancellationToken.None);
@@ -69,6 +95,36 @@ public sealed class ActorSystemTerminationWatchdogTests
await Task.Delay(500, TestContext.Current.CancellationToken);
lifetime.StopApplicationCalls.ShouldBe(0, "termination during an in-progress host shutdown must stay silent");
+ exits.ExitCodes.ShouldBeEmpty("termination during an in-progress host shutdown must not exit as a failure");
+ }
+
+ private static ActorSystemTerminationWatchdog Create(
+ ActorSystem system, IHostApplicationLifetime lifetime, ExitRecorder exits) =>
+ new(() => system, lifetime, NullLogger.Instance, exits.Exit, exits.Flush);
+
+ /// Records the exit + flush the watchdog performs instead of killing the test process.
+ private sealed class ExitRecorder
+ {
+ private readonly object _gate = new();
+ public List ExitCodes { get; } = [];
+ public int FlushCalls { get; private set; }
+ public bool FlushedBeforeExit { get; private set; }
+ public bool FlushThrows { get; init; }
+
+ public void Flush()
+ {
+ lock (_gate) FlushCalls++;
+ if (FlushThrows) throw new InvalidOperationException("sink down");
+ }
+
+ public void Exit(int code)
+ {
+ lock (_gate)
+ {
+ FlushedBeforeExit = FlushCalls > 0;
+ ExitCodes.Add(code);
+ }
+ }
}
private static async Task WaitForAsync(Func condition, TimeSpan timeout)
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/DedicatedListenerGuardTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/DedicatedListenerGuardTests.cs
new file mode 100644
index 000000000..14cebbdb4
--- /dev/null
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/DedicatedListenerGuardTests.cs
@@ -0,0 +1,64 @@
+using Shouldly;
+using Xunit;
+using ZB.MOM.WW.OtOpcUa.Host.Configuration;
+
+namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests;
+
+///
+/// #980 / review 05 H-5 — an HTTPS binding combined with a requested dedicated h2c listener used to log one
+/// Error, zero the ports and keep booting (ready, but with no deploy/config/telemetry endpoints). It must
+/// fail host start instead, naming every setting involved.
+///
+[Trait("Category", "Unit")]
+public sealed class DedicatedListenerGuardTests
+{
+ [Fact]
+ public void Https_with_a_requested_telemetry_listener_fails_start_naming_the_setting_and_the_urls()
+ {
+ var bindings = KestrelHttpBinding.Parse("https://+:443");
+ var ex = Should.Throw(() =>
+ DedicatedListenerGuard.ThrowIfHttpsBlocksDedicatedListeners(
+ syncListenPort: 0, configServeGrpcPort: 0, telemetryListenPort: 4056, dataListenPort: 0,
+ bindings, "https://+:443"));
+ ex.Message.ShouldContain("Telemetry:GrpcListenPort=4056");
+ ex.Message.ShouldContain("https://+:443");
+ }
+
+ [Fact]
+ public void Every_requested_listener_is_named_in_the_error()
+ {
+ var bindings = KestrelHttpBinding.Parse("http://localhost:5000;https://+:443");
+ var ex = Should.Throw(() =>
+ DedicatedListenerGuard.ThrowIfHttpsBlocksDedicatedListeners(
+ 4057, 4055, 4056, 0, bindings, "http://localhost:5000;https://+:443"));
+ ex.Message.ShouldContain("LocalDb:SyncListenPort=4057");
+ ex.Message.ShouldContain("ConfigServe:GrpcListenPort=4055");
+ ex.Message.ShouldContain("Telemetry:GrpcListenPort=4056");
+ }
+
+ [Fact]
+ public void An_https_port_list_binding_is_also_refused()
+ {
+ var bindings = KestrelHttpBinding.ParsePorts("443", isSecure: true);
+ Should.Throw(() =>
+ DedicatedListenerGuard.ThrowIfHttpsBlocksDedicatedListeners(0, 4055, 0, 0, bindings, null));
+ }
+
+ // Positive controls: the guard must not trip on configurations that are valid.
+
+ [Fact]
+ public void Https_with_no_dedicated_listener_requested_is_fine()
+ {
+ var bindings = KestrelHttpBinding.Parse("https://+:443");
+ Should.NotThrow(() =>
+ DedicatedListenerGuard.ThrowIfHttpsBlocksDedicatedListeners(0, 0, 0, 0, bindings, "https://+:443"));
+ }
+
+ [Fact]
+ public void Http_with_every_dedicated_listener_requested_is_fine()
+ {
+ var bindings = KestrelHttpBinding.Parse("http://+:8080");
+ Should.NotThrow(() =>
+ DedicatedListenerGuard.ThrowIfHttpsBlocksDedicatedListeners(4057, 4055, 4056, 4058, bindings, "http://+:8080"));
+ }
+}