From 645a8b92099ae9c01fcff0872d5af69b31a447a9 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 11:53:42 -0500 Subject: [PATCH] =?UTF-8?q?fix(host):=20#980=20review=20=E2=80=94=20termin?= =?UTF-8?q?ation=20watchdog=20exits=20on=20a=20cluster=20leave/down=20unde?= =?UTF-8?q?r=20Akka.Hosting?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The first #980 fix stayed quiet whenever ApplicationStopping was already cancelled. Akka.Hosting 1.5.62's AkkaHostedService hooks WhenTerminated earlier and, for ClusterLeavingReason / ClusterDowningReason, sets Environment.ExitCode = -1 and calls StopApplication() BEFORE the watchdog's continuation — so manual failover, endpoint step-down and auto-down all still ended in a graceful stop (SERVICE_STOPPED, win32 exit 0 — SCM reads ServiceBase.ExitCode, not the -1) that Windows SCM never restarts. "Expected" is now decided from signals Akka.Hosting never produces: a host stop requested while the ActorSystem still runs (SCM stop / Ctrl-C / GracefulClusterLeaveService), the watchdog's own StopAsync before termination, or CoordinatedShutdown reason ClrExitReason. Everything else exits 1. After an unexpected termination the watchdog's StopAsync holds host shutdown until the exit is issued, so the service host cannot report SERVICE_STOPPED first. Registration moved to AddOtOpcUaTerminationWatchdog (shared with tests). Tests: TerminationWatchdogAkkaHostingTests — real AddAkka host + production cluster bootstrap + GracefulClusterLeave: Leave(self)/Down(self) => exit 1 (both fail on the old logic); host StopAsync and StopApplication-while-running => no exit. Live gate on windev SCM passed (7031 + restart; old logic => Stopped, exit -1, no recovery; sc stop => clean stop). --- docs/Redundancy.md | 30 ++- .../ActorSystemTerminationWatchdog.cs | 191 +++++++++++++---- src/Server/ZB.MOM.WW.OtOpcUa.Host/Program.cs | 16 +- .../ActorSystemTerminationWatchdogTests.cs | 61 ++++++ .../TerminationWatchdogAkkaHostingTests.cs | 202 ++++++++++++++++++ 5 files changed, 451 insertions(+), 49 deletions(-) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/TerminationWatchdogAkkaHostingTests.cs diff --git a/docs/Redundancy.md b/docs/Redundancy.md index 9ed502e1a..ae15892e3 100644 --- a/docs/Redundancy.md +++ b/docs/Redundancy.md @@ -478,10 +478,32 @@ two-node pair that choice means *any* crash of the oldest node is a full outage. 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. + `restart: unless-stopped` masked it). A graceful host stop (SCM stop, Ctrl-C) is still silent. + + **How "graceful" is decided (#980 review).** *Not* from "is the host already stopping": Akka.Hosting's + `AkkaHostedService` hooks `WhenTerminated` first and, for a `ClusterLeavingReason` / `ClusterDowningReason` + shutdown, sets `Environment.ExitCode = -1` and calls `StopApplication()` **before** the watchdog's + continuation runs — so the first #980 fix saw every leave/down as "already stopping" and stayed quiet, and + the node still ended in a clean stop. (The -1 does not help: SCM is told `ServiceBase.ExitCode`, which the + generic host leaves at 0, in `SERVICE_STOPPED`; recovery never runs.) The watchdog now treats a termination + as expected only when (a) the host asked to stop **while the ActorSystem was still running** (SCM + stop / Ctrl-C / `GracefulClusterLeaveService` — Akka.Hosting's hook only calls `StopApplication` after + termination, so it can never set this), (b) its own `StopAsync` ran, or (c) `CoordinatedShutdown`'s reason is + `ClrExitReason` (what both `GracefulClusterLeaveService` and Akka.Hosting's `StopAsync` run). Anything else — + `ClusterLeavingReason`, `ClusterDowningReason`, `ActorSystemTerminateReason`, no reason — exits 1. Once it has + decided to exit, its `StopAsync` holds the host's shutdown (bounded by `ShutdownTimeout`) until the exit is + issued, so the service host cannot report `SERVICE_STOPPED` first. Pinned by + `TerminationWatchdogAkkaHostingTests` (real `AddAkka` host + clustering, `Cluster.Leave`/`Down` of self ⇒ + exit 1; host `StopAsync` / `StopApplication`-while-running ⇒ no exit). + + **Real-SCM live gate (windev, 2026-12-03): PASSED.** A throwaway service (`AddWindowsService` + `AddAkka` + clustering + `GracefulClusterLeaveService` + this watchdog, `sc failure … actions= restart/3000`) that + `Leave`s its own cluster: the fixed watchdog exited 1 → SCM event **7031** "terminated unexpectedly … Restart + the service" → back to `Running` 3 s later. Control with the pre-review logic: watchdog quiet, host returned + with process exit code **-1**, service **Stopped, no 7031, never restarted** (confirms both the defect and + 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. 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/src/Server/ZB.MOM.WW.OtOpcUa.Host/ActorSystemTerminationWatchdog.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/ActorSystemTerminationWatchdog.cs index ecf941dfd..b15de5f61 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/ActorSystemTerminationWatchdog.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/ActorSystemTerminationWatchdog.cs @@ -1,4 +1,5 @@ using Akka.Actor; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; @@ -29,10 +30,22 @@ namespace ZB.MOM.WW.OtOpcUa.Host; /// /// Registered after AddAkka so it starts after Akka's own hosted service has /// built the system; the is resolved lazily in -/// (never at construction) so it can't race Akka startup. A graceful host stop is distinguished from -/// an unexpected SBR self-down via plus -/// , so normal shutdown never logs a false -/// alarm or double-triggers . +/// (never at construction) so it can't race Akka startup. +/// +/// Deciding "expected" (#980 review). NOT from ApplicationStopping at termination +/// time: Akka.Hosting 1.5.x's AkkaHostedService registers its own WhenTerminated hook +/// earlier, and for a ClusterLeavingReason/ClusterDowningReason shutdown it sets +/// Environment.ExitCode = -1 and calls StopApplication() BEFORE this watchdog's +/// continuation runs — so the host always looked "already stopping" and every leave/down ended in a +/// graceful stop (SERVICE_STOPPED with win32 exit 0 — ServiceBase.ExitCode, not +/// Environment.ExitCode, is what SCM is told, so the -1 never triggers recovery). The signals +/// used instead are ones Akka.Hosting never produces: a host stop requested while the system was still +/// running (SCM stop, Ctrl-C, ), this service's own +/// , or a reason of +/// (what every host-initiated stop runs). See +/// . On an unexpected termination also holds +/// the host's shutdown until the exit is issued, so the service host cannot report SERVICE_STOPPED +/// first. /// public sealed class ActorSystemTerminationWatchdog : IHostedService { @@ -41,7 +54,11 @@ public sealed class ActorSystemTerminationWatchdog : IHostedService private readonly ILogger _logger; private readonly Action _exitProcess; private readonly Action _flushLogs; + private readonly TaskCompletionSource _exitIssued = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource _verdict = new(TaskCreationOptions.RunContinuationsAsynchronously); // true = exiting + private volatile ActorSystem? _system; private volatile bool _stopRequested; + private volatile bool _hostStopRequestedWhileRunning; /// Process exit code used when the actor system terminated outside host shutdown. public const int FailureExitCode = 1; @@ -66,47 +83,149 @@ public sealed class ActorSystemTerminationWatchdog : IHostedService _flushLogs = flushLogs ?? Serilog.Log.CloseAndFlush; } - /// Wires the continuation that exits the host on an unexpected self-down. - /// Unused; the watchdog only registers a continuation. + /// + /// Wires the expected-stop signal and the continuation that + /// exits the process on an unexpected termination. + /// + /// Unused; the watchdog only registers callbacks. /// A completed task. public Task StartAsync(CancellationToken cancellationToken) { var system = _actorSystemAccessor(); + _system = system; + + // A host stop requested while the ActorSystem is still RUNNING is an operator/supervisor stop + // (SCM stop, Ctrl-C/SIGTERM, GracefulClusterLeaveService.StoppingAsync): expected. Akka.Hosting's + // own termination hook calls StopApplication only AFTER the system has terminated, so it can + // never set this — which is exactly why "ApplicationStopping is cancelled" was not a usable signal + // (#980 review: the hook always ran first, so every leave/down looked like an expected stop). + _lifetime.ApplicationStopping.Register(() => + { + if (!system.WhenTerminated.IsCompleted) + _hostStopRequestedWhileRunning = true; + }); + system.WhenTerminated.ContinueWith( - _ => - { - // Expected shutdown: our StopAsync ran, or the host is already stopping. Stay quiet. - if (_stopRequested || _lifetime.ApplicationStopping.IsCancellationRequested) - return; - - _logger.LogCritical( - "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(); - }, + _ => OnTerminated(system), TaskContinuationOptions.ExecuteSynchronously); return Task.CompletedTask; } - /// Marks a graceful shutdown so the termination continuation stays silent and does not re-trigger stop. - /// Unused. - /// A completed task. - public Task StopAsync(CancellationToken cancellationToken) + /// + /// Classifies an termination. Expected (stay quiet) when the host asked to + /// stop while the system was still running, or when ran for + /// — the reason both + /// and Akka.Hosting's own StopAsync use for a host + /// stop. Everything else — ClusterLeavingReason (manual failover, endpoint step-down), + /// ClusterDowningReason (auto-down / SBR), ActorSystemTerminateReason, an unknown or + /// absent reason — is unexpected: the node must exit non-zero so the supervisor restarts it. + /// + /// The , or null when none ran. + /// Whether the host asked to stop before the system terminated. + /// when the termination is part of a normal host shutdown. + public static bool IsExpectedTermination(CoordinatedShutdown.Reason? shutdownReason, bool hostStopRequested) => + hostStopRequested || shutdownReason is CoordinatedShutdown.ClrExitReason; + + private void OnTerminated(ActorSystem system) { - _stopRequested = true; - return Task.CompletedTask; + CoordinatedShutdown.Reason? reason = null; + try + { + reason = CoordinatedShutdown.Get(system).ShutdownReason; + } + catch (Exception ex) + { + // Unreadable reason ⇒ treat as unexpected: a needless restart beats a node that never returns. + _logger.LogDebug(ex, "Could not read the CoordinatedShutdown reason after ActorSystem termination."); + } + + if (IsExpectedTermination(reason, _stopRequested || _hostStopRequestedWhileRunning)) + { + _logger.LogInformation( + "ActorSystem terminated as part of a host shutdown (reason {Reason}); no restart requested.", + reason?.GetType().Name ?? "none"); + _verdict.TrySetResult(false); + return; + } + + _verdict.TrySetResult(true); + _logger.LogCritical( + "ActorSystem terminated outside host shutdown (reason {Reason}: 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).", + reason?.GetType().Name ?? "none", + 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 */ } + try { _exitProcess(FailureExitCode); } + finally { _exitIssued.TrySetResult(); } + }) + { IsBackground = true, Name = "otopcua-watchdog-exit" }; + exit.Start(); + } + + /// + /// Before termination: marks a graceful shutdown so the later termination stays silent. After an + /// unexpected termination: holds the host shutdown until the failure exit is issued: Akka.Hosting's + /// hook has called StopApplication, and if the host finished stopping first the Windows service + /// host would report SERVICE_STOPPED (win32 exit code 0) and SCM would never restart the node. + /// + /// The host's shutdown token; bounds the wait. + /// A task that completes when the stop may proceed. + public async Task StopAsync(CancellationToken cancellationToken) + { + var system = _system; + if (system is null) + return; // never started + + // Only a stop that arrives while the system still runs marks the termination as expected. A stop that + // arrives after it terminated is the host reacting to Akka.Hosting's StopApplication — and may even + // beat this watchdog's own continuation, so it must not flip that continuation's verdict. + if (!system.WhenTerminated.IsCompleted) + { + _stopRequested = true; + return; + } + + try + { + if (await _verdict.Task.WaitAsync(cancellationToken).ConfigureAwait(false)) + await _exitIssued.Task.WaitAsync(cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + // Shutdown timeout: let the host finish rather than hang it. + } + } +} + +/// Registration for — shared by Program.cs and its tests. +public static class ActorSystemTerminationWatchdogRegistration +{ + /// + /// Registers . Call it after AddAkka so it starts after + /// Akka's hosted service has built the (resolved lazily, in StartAsync). + /// + /// The service collection. + /// Test seam; defaults to . + /// Test seam; defaults to Serilog.Log.CloseAndFlush. + /// The same collection. + public static IServiceCollection AddOtOpcUaTerminationWatchdog( + this IServiceCollection services, Action? exitProcess = null, Action? flushLogs = null) + { + ArgumentNullException.ThrowIfNull(services); + services.AddHostedService(sp => new ActorSystemTerminationWatchdog( + () => sp.GetRequiredService(), + sp.GetRequiredService(), + sp.GetRequiredService>(), + exitProcess, + flushLogs)); + return services; } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Program.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Program.cs index 612cf4edc..bbab08c15 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Program.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Program.cs @@ -566,8 +566,9 @@ builder.Services.AddAkka("otopcua", (ab, sp) => // (WebApplication starts the server last), and Kestrel drains open requests for up to ShutdownTimeout, // so without this the peer's long-lived LocalDb sync stream held the Primary role for ~30 s on every // planned stop. Its StoppingAsync runs before ANY hosted service's StopAsync. Registered BEFORE the -// watchdog below only for readability — it raises ApplicationStopping itself, which is what keeps the -// watchdog quiet, so it does not depend on lifecycle-callback order. +// watchdog below only for readability — it raises ApplicationStopping while the ActorSystem is still +// running and runs CoordinatedShutdown with ClrExitReason, either of which keeps the watchdog quiet, so +// it does not depend on lifecycle-callback order. builder.Services.AddOtOpcUaGracefulClusterLeave(); // Simultaneous-cold-start split-brain guard (dark switch Cluster:BootstrapGuard:Enabled, default off). @@ -582,13 +583,10 @@ builder.Services.AddHostedService(sp => new ClusterBootstrapCoordinator( // Down-if-alone recovery watchdog. Registered AFTER AddAkka so it starts after Akka's own // hosted service has built the ActorSystem; it resolves the system lazily (never at construction) so -// it can't race startup. On an unexpected SBR self-down it stops the host so the service supervisor -// (sc.exe failure / docker restart: unless-stopped) restarts this node — the 2-node keep-oldest -// exit-and-rejoin recovery path. -builder.Services.AddHostedService(sp => new ActorSystemTerminationWatchdog( - () => sp.GetRequiredService(), - sp.GetRequiredService(), - sp.GetRequiredService>())); +// it can't race startup. When the ActorSystem terminates for anything but a host stop (cluster leave from +// manual failover / endpoint step-down, auto-down) it exits the process with code 1 so the service +// supervisor (sc.exe failure / docker restart: unless-stopped) restarts this node (#980). +builder.Services.AddOtOpcUaTerminationWatchdog(); if (hasAdmin) { 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 0f62bf356..217562806 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/ActorSystemTerminationWatchdogTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/ActorSystemTerminationWatchdogTests.cs @@ -98,6 +98,67 @@ public sealed class ActorSystemTerminationWatchdogTests exits.ExitCodes.ShouldBeEmpty("termination during an in-progress host shutdown must not exit as a failure"); } + /// + /// #980 review: Akka.Hosting's termination hook (registered earlier) calls StopApplication AFTER + /// the system terminated and BEFORE the watchdog's continuation. That stop must not read as "expected". + /// + [Fact] + public async Task Stop_requested_by_a_termination_hook_after_termination_still_exits() + { + var system = ActorSystem.Create("watchdog-hosting-hook-order"); + var lifetime = new FakeHostApplicationLifetime(); + var exits = new ExitRecorder(); + + // Mimic AkkaHostedService.TerminationHook: registered first, runs first. + _ = system.WhenTerminated.ContinueWith(_ => lifetime.TriggerStopping(), TaskContinuationOptions.ExecuteSynchronously); + 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 host stop that arrives AFTER an unexpected termination (the host reacting to Akka.Hosting's + /// StopApplication) neither cancels the exit nor completes before it is issued — otherwise the Windows + /// service host could report SERVICE_STOPPED first. + /// + [Fact] + public async Task Stop_after_unexpected_termination_waits_for_the_exit() + { + var system = ActorSystem.Create("watchdog-stop-after-termination"); + var lifetime = new FakeHostApplicationLifetime(); + var exits = new ExitRecorder(); + var exitGate = new ManualResetEventSlim(false); + var watchdog = new ActorSystemTerminationWatchdog( + () => system, lifetime, NullLogger.Instance, + code => { exitGate.Wait(TimeSpan.FromSeconds(10)); exits.Exit(code); }, exits.Flush); + await watchdog.StartAsync(CancellationToken.None); + + await system.Terminate(); + var stop = watchdog.StopAsync(CancellationToken.None); + + await Task.Delay(300, TestContext.Current.CancellationToken); + stop.IsCompleted.ShouldBeFalse("host shutdown must be held until the failure exit is issued"); + exitGate.Set(); + await stop.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + exits.ExitCodes.ShouldBe([ActorSystemTerminationWatchdog.FailureExitCode]); + } + + /// The expected/unexpected verdict by CoordinatedShutdown reason. + [Fact] + public void Only_a_host_stop_or_ClrExitReason_is_expected() + { + ActorSystemTerminationWatchdog.IsExpectedTermination(CoordinatedShutdown.ClrExitReason.Instance, false).ShouldBeTrue(); + ActorSystemTerminationWatchdog.IsExpectedTermination(CoordinatedShutdown.ClusterLeavingReason.Instance, true).ShouldBeTrue(); + ActorSystemTerminationWatchdog.IsExpectedTermination(CoordinatedShutdown.ClusterLeavingReason.Instance, false).ShouldBeFalse(); + ActorSystemTerminationWatchdog.IsExpectedTermination(CoordinatedShutdown.ClusterDowningReason.Instance, false).ShouldBeFalse(); + ActorSystemTerminationWatchdog.IsExpectedTermination(CoordinatedShutdown.ActorSystemTerminateReason.Instance, false).ShouldBeFalse(); + ActorSystemTerminationWatchdog.IsExpectedTermination(null, false).ShouldBeFalse(); + } + private static ActorSystemTerminationWatchdog Create( ActorSystem system, IHostApplicationLifetime lifetime, ExitRecorder exits) => new(() => system, lifetime, NullLogger.Instance, exits.Exit, exits.Flush); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/TerminationWatchdogAkkaHostingTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/TerminationWatchdogAkkaHostingTests.cs new file mode 100644 index 000000000..0928d1c1a --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/TerminationWatchdogAkkaHostingTests.cs @@ -0,0 +1,202 @@ +using System.Net; +using System.Net.Sockets; +using Akka.Actor; +using Akka.Cluster; +using Akka.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Options; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Cluster; +using ZB.MOM.WW.OtOpcUa.Host; + +namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests; + +/// +/// #980 review: the termination watchdog under a REAL Akka.Hosting host with clustering, wired exactly as +/// Program.cs does (production cluster bootstrap, , the +/// watchdog registration). +/// +/// +/// uses a bare , which has no +/// Akka.Hosting termination hook — and that hook is the whole bug: for a cluster leave/down +/// AkkaHostedService sets Environment.ExitCode = -1 and calls StopApplication() +/// BEFORE the watchdog's continuation runs, so a watchdog keyed on "the host is already stopping" stayed +/// quiet for every manual failover, endpoint step-down and auto-down, and the node stopped gracefully +/// (SERVICE_STOPPED, exit 0) where SCM never restarts it. These tests fail on that version. +/// + +public sealed class TerminationWatchdogAkkaHostingTests +{ + private static readonly TimeSpan ExitWait = TimeSpan.FromSeconds(30); + + /// + /// Cluster.Leave(self) — what manual failover (ManualFailoverService) and the endpoint + /// step-down actor do — must end the process non-zero, not in a graceful host stop. + /// + [Fact] + public async Task Cluster_leave_of_self_exits_the_process_non_zero() + { + var exits = new ExitRecorder(); + using var host = await StartNodeAsync(exits); + + var cluster = Akka.Cluster.Cluster.Get(host.Services.GetRequiredService()); + cluster.Leave(cluster.SelfAddress); + + (await exits.WaitForExitAsync(ExitWait)).ShouldBeTrue( + "a cluster leave the host did not initiate must exit the process so SCM restarts it"); + exits.Codes.ShouldBe([ActorSystemTerminationWatchdog.FailureExitCode]); + CoordinatedShutdown.Get(host.Services.GetRequiredService()).ShutdownReason + .ShouldBeOfType(); + + await StopQuietlyAsync(host); + } + + /// Cluster.Down(self) — the auto-down / SBR shape — must also exit non-zero. + [Fact] + public async Task Cluster_down_of_self_exits_the_process_non_zero() + { + var exits = new ExitRecorder(); + using var host = await StartNodeAsync(exits); + + var cluster = Akka.Cluster.Cluster.Get(host.Services.GetRequiredService()); + cluster.Down(cluster.SelfAddress); + + (await exits.WaitForExitAsync(ExitWait)).ShouldBeTrue("a self-down must exit the process non-zero"); + exits.Codes.ShouldBe([ActorSystemTerminationWatchdog.FailureExitCode]); + + await StopQuietlyAsync(host); + } + + /// + /// Positive control: a host-initiated stop (what SCM stop / Ctrl-C reach via IHost.StopAsync) + /// leaves the cluster through and must stay exit-free. + /// + [Fact] + public async Task Host_initiated_stop_stays_exit_free() + { + var exits = new ExitRecorder(); + var host = await StartNodeAsync(exits); + var system = host.Services.GetRequiredService(); + + await host.StopAsync(TestContext.Current.CancellationToken); + await system.WhenTerminated.WaitAsync(ExitWait, TestContext.Current.CancellationToken); + + (await exits.WaitForExitAsync(TimeSpan.FromSeconds(2))).ShouldBeFalse( + "a host-initiated stop is a planned stop, not a crash"); + host.Dispose(); + } + + /// + /// Positive control: an SCM-style stop (StopApplication while the system still runs — what + /// WindowsServiceLifetime.OnStop does) followed by the host's own stop stays exit-free, even + /// without (Akka.Hosting's StopAsync runs ClrExitReason). + /// + [Fact] + public async Task Stop_application_while_running_stays_exit_free_without_graceful_leave() + { + var exits = new ExitRecorder(); + var host = await StartNodeAsync(exits, withGracefulLeave: false); + var system = host.Services.GetRequiredService(); + + host.Services.GetRequiredService().StopApplication(); + await host.StopAsync(TestContext.Current.CancellationToken); + await system.WhenTerminated.WaitAsync(ExitWait, TestContext.Current.CancellationToken); + + (await exits.WaitForExitAsync(TimeSpan.FromSeconds(2))).ShouldBeFalse( + "a supervisor-requested stop is a planned stop, not a crash"); + host.Dispose(); + } + + private static async Task StartNodeAsync(ExitRecorder exits, bool withGracefulLeave = true) + { + var systemName = "wd980"; + var port = FreePort(); + var self = $"akka.tcp://{systemName}@127.0.0.1:{port}"; + var options = new AkkaClusterOptions + { + SystemName = systemName, + Hostname = "127.0.0.1", + PublicHostname = "127.0.0.1", + Port = port, + Roles = ["admin", "driver"], + SeedNodes = [self], + }; + + var builder = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(); + builder.ConfigureServices(services => + { + services.AddSingleton>(Options.Create(options)); + services.AddAkka(systemName, (ab, sp) => ab.WithOtOpcUaClusterBootstrap(sp)); + // Same order as Program.cs: both after AddAkka. + if (withGracefulLeave) + services.AddOtOpcUaGracefulClusterLeave(); + services.AddOtOpcUaTerminationWatchdog(exits.Exit, () => { }); + }); + + var host = builder.Build(); + await host.StartAsync(TestContext.Current.CancellationToken); + + var cluster = Akka.Cluster.Cluster.Get(host.Services.GetRequiredService()); + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(30); + while (cluster.SelfMember.Status != MemberStatus.Up && DateTime.UtcNow < deadline) + await Task.Delay(100, TestContext.Current.CancellationToken); + cluster.SelfMember.Status.ShouldBe(MemberStatus.Up, "the single-node cluster must form before the test acts"); + return host; + } + + private static async Task StopQuietlyAsync(IHost host) + { + try + { + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + await host.StopAsync(cts.Token); + } + catch (OperationCanceledException) + { + // The host may already be stopping on Akka.Hosting's StopApplication; nothing to assert here. + } + } + + private static int FreePort() + { + var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + listener.Stop(); + return port; + } + + /// Records the watchdog's exit instead of ending the test process. + private sealed class ExitRecorder + { + private readonly TaskCompletionSource _exited = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly object _gate = new(); + private readonly List _codes = []; + + public IReadOnlyList Codes + { + get { lock (_gate) return _codes.ToArray(); } + } + + public void Exit(int code) + { + lock (_gate) _codes.Add(code); + _exited.TrySetResult(); + } + + public async Task WaitForExitAsync(TimeSpan timeout) + { + try + { + await _exited.Task.WaitAsync(timeout); + return true; + } + catch (TimeoutException) + { + return false; + } + } + } +}