From 645a8b92099ae9c01fcff0872d5af69b31a447a9 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 11:53:42 -0500 Subject: [PATCH 1/2] =?UTF-8?q?fix(host):=20#980=20review=20=E2=80=94=20te?= =?UTF-8?q?rmination=20watchdog=20exits=20on=20a=20cluster=20leave/down=20?= =?UTF-8?q?under=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; + } + } + } +} From 1c7e06502fc6f1d8751ccb095598fff923ec6564 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 12:01:24 -0500 Subject: [PATCH 2/2] =?UTF-8?q?fix(historian):=20#976=20review=20=E2=80=94?= =?UTF-8?q?=20Gateway=20alarm=20writer=20isolates=20an=20unrecognised=20ba?= =?UTF-8?q?tch=20failure=20per=20event?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #976 made StatusCode.Unknown (the gateway's handler threw) and non-RPC non-transport exceptions RetryPlease. On the SendEvents path a RetryPlease marked the whole chunk and every later chunk RetryPlease; with no Ack the sink treats the drain as an outage and counts nothing, so ONE such event at the queue head stalled all Gateway alarm history until the 1,000,000-row capacity evicted it silently. The SQL writers already isolate unrecognised failures (AlarmBatchWrite); the Gateway writer had no equivalent. Gateway: a RetryPlease failure that is not a known outage (IsSystemicFailure: Unavailable, DeadlineExceeded, Cancelled, ResourceExhausted, Aborted, auth codes, typed Unavailable/auth client exceptions, or a socket/IO/HTTP/disposed/timeout/cancellation cause) re-sends the chunk singly at once: siblings Ack, the culprit keeps RetryPlease and dead-letters via MaxAttempts. If no single Acks it is treated as systemic (later chunks not sent) — bounded to one chunk of singles per drain. SQL (LOW): AlarmBatchWrite stops isolating at the first single that fails with a known outage error; the SQL Server alarm writer passes the wider SqlHistorianConnection.IsOutage (login failed 18456/18452, unreachable/refused 2/40/53/64/121/10061/10065/-1, severity >= 20, pool timeout) — IsTransient is unchanged for its retry callers. Fixes the false claim in docs/AlarmHistorian.md. Tests: GatewayAlarmPoisonDrainTests (real LocalDb sink + real writer: poison at the queue head ⇒ siblings Ack on the first drain, poison dead-letters via MaxAttempts; positive control: Unavailable outage ⇒ no single sends, nothing dead-lettered), writer-level isolation + bounded fan-out tests, AlarmBatchWrite early-stop + no-stop-on-adjacent-poison control, SqlOutageClassificationTests. --- .claude/rules/historian.md | 4 +- docs/AlarmHistorian.md | 44 ++++-- .../GatewayAlarmHistorianWriter.cs | 65 ++++++-- .../AlarmBatchWrite.cs | 30 ++-- .../SqlHistorianConnection.cs | 28 ++++ .../SqlServerAlarmHistorianWriter.cs | 2 +- .../GatewayAlarmPoisonDrainTests.cs | 143 ++++++++++++++++++ .../GatewayAlarmWriterBatchTests.cs | 30 ++++ ...AlarmWriterTransientClassificationTests.cs | 59 +++++++- .../AlarmBatchWriteTests.cs | 34 +++++ .../SqlOutageClassificationTests.cs | 89 +++++++++++ 11 files changed, 495 insertions(+), 33 deletions(-) create mode 100644 tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayAlarmPoisonDrainTests.cs create mode 100644 tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer.Tests/SqlOutageClassificationTests.cs diff --git a/.claude/rules/historian.md b/.claude/rules/historian.md index 867a2f9ed..5493863f4 100644 --- a/.claude/rules/historian.md +++ b/.claude/rules/historian.md @@ -86,7 +86,9 @@ the gateway and uses per-event outcomes to decide retry vs. dead-letter (never t dead-letters (#976):** a `RetryPlease` counts toward `MaxAttempts` only on a drain where some event was `Ack`'d, and the writers return `PermanentFail` only for failures that prove the EVENT bad (Gateway: `InvalidArgument`/`FailedPrecondition`/ `OutOfRange`/`NotFound`/`AlreadyExists`/`Unimplemented` + unmappable events — `Cancelled`, `Unknown`, unlisted codes and -non-RPC exceptions retry; SQL: recognised data errors, with unrecognised chunk failures isolated per event) — don't +non-RPC exceptions retry; SQL: recognised data errors) — and BOTH isolate an unrecognised batch failure per event (Gateway +`SendEvents` failing `Unknown`/`Internal`/`DataLoss`/unlisted/non-transport ⇒ single sends; only known-outage codes and transport +faults retry the batch whole), else one such event at the queue head Acks nothing and stalls the whole queue (#976 review) — don't reintroduce a dead-letter default "to avoid an infinite loop". **Only the node holding the Primary role drains** (a gated node reports `HistorianDrainState.NotPrimary`). The `AlarmHistorian` section carries only the `Enabled` gate + the queue knobs (`DrainIntervalSeconds`, diff --git a/docs/AlarmHistorian.md b/docs/AlarmHistorian.md index 72cc14d19..0ac4c9446 100644 --- a/docs/AlarmHistorian.md +++ b/docs/AlarmHistorian.md @@ -216,7 +216,7 @@ an unobserved task exception. Every production writer answers a systemic failure — historian, HistorianGateway or database down, an auth blip, a failed schema bootstrap, a gateway restart answering -`Cancelled`/`Unknown`, a dropped channel — with `RetryPlease` for every event of the +`Cancelled`, a dropped channel — with `RetryPlease` for every event of the batch. Until #976 the sink counted each of those against `MaxAttempts`, so an outage longer than ~6.5 minutes (1 + 2 + 5 + 15 + 60 s, then 60 s per drain, 10 attempts) dead-lettered the oldest 100 queued alarm events, and another 100 every ~10 minutes @@ -228,18 +228,42 @@ after that, with no automatic retry. Now: unavailable: N event(s) deferred …". `PermanentFail` rows still dead-letter. When the historian returns, the queue drains in `enqueued_at_utc` order. - `MaxAttempts` therefore bounds only a row that keeps failing **while its neighbours - land** — the finding-002 poison case it exists for. + land** — the finding-002 poison case it exists for. That only works if the writer lets + the neighbours land, i.e. isolates an event it cannot classify instead of retrying its + whole batch with it — which both writers now do (below). - Writers: `GatewayAlarmHistorianWriter` dead-letters only `InvalidArgument`, `FailedPrecondition`, `OutOfRange`, `NotFound`, `AlreadyExists`, `Unimplemented` (on a single send) and events that cannot be mapped to the wire; every other gRPC code and - every non-RPC exception retries (the default used to be dead-letter). The SQL writers - dead-letter only recognised data errors, and `AlarmBatchWrite` re-sends a multi-event - chunk **event by event** when it fails with an error that is neither a recognised data - error nor a known transient, so one unrecognised poison event cannot hold its - chunk-mates (they `Ack`, which is what lets the sink count the poison row's attempts). -- Residual: a batch made up **entirely** of rows that always answer `RetryPlease` looks - like an outage and is retried at the 60 s cap rather than dead-lettered. It shows as a - queue that does not drain while `LastError` reports the deferral. + every non-RPC exception retries (the default used to be dead-letter). On the batch + (`SendEvents`) path a retryable failure is split two ways (#976 review): + - a **known outage** — `Unavailable`, `DeadlineExceeded`, `Cancelled`, + `ResourceExhausted`, `Aborted`, `Unauthenticated`, `PermissionDenied`, or a + status-less transport fault (socket / I/O / HTTP, a disposed channel, a timeout) — + retries the chunk and every later chunk without sending more; + - anything else — `Unknown` (the gateway's handler threw, e.g. on one bad event), + `Internal`, `DataLoss`, an unlisted code, a non-transport exception — **re-sends the + chunk event by event**, so the siblings `Ack` and only the culprit keeps + `RetryPlease` (and dead-letters via `MaxAttempts` on those Ack'd drains). If not one + single send `Ack`s, it was not the event: later chunks retry as for an outage, so such + an outage costs at most one chunk of single sends per drain. Before this, the gateway + writer retried the whole batch on `Unknown`, the drain saw no `Ack`, and one such + event at the queue head stalled **all** Gateway alarm history until capacity eviction + dropped it silently. (The earlier version of this section said the writer behaved like + the SQL writers here; it did not.) + + The SQL writers dead-letter only recognised data errors, and `AlarmBatchWrite` + re-sends a multi-event chunk **event by event** when it fails with an error that is + neither a recognised data error nor a known outage, so one unrecognised poison event + cannot hold its chunk-mates. The isolation stops at the first single that fails with a + known outage error (the rest of the chunk retries), and the SQL Server writer's outage + set (`SqlHistorianConnection.IsOutage`) adds login failures (18456/18452), server + unreachable / refusing connections (2, 40, 53, 64, 121, 10061, 10065, -1), fatal + severity ≥ 20 and an exhausted connection pool to the retry-transient numbers — so an + outage of that kind costs one round trip per chunk, not one per event. +- Residual: a batch (Gateway: an isolated chunk) made up **entirely** of rows that always + answer `RetryPlease` looks like an outage and is retried at the 60 s cap rather than + dead-lettered. It shows as a queue that does not drain while `LastError` reports the + deferral. - Rows dead-lettered as `max attempts (N) exceeded` before #976 may be outage casualties; `RetryDeadLettered()` revives them. Rows dead-lettered by a post-#976 node read `… exceeded while the historian accepted other events`. diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway/GatewayAlarmHistorianWriter.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway/GatewayAlarmHistorianWriter.cs index bd5d461ff..d7c78438a 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway/GatewayAlarmHistorianWriter.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway/GatewayAlarmHistorianWriter.cs @@ -24,10 +24,17 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway; /// was not committed, so the re-send cannot duplicate it. A whole-call failure: /// /// -/// transient / systemic (Unavailable, auth, back-pressure, deadline, cancellation) ⇒ that call's and -/// every later call's events are , nothing more is sent (every -/// later call would hit it too). Events before the fault may already be committed, so the retry can duplicate -/// them — SendEvent is at-least-once too; +/// a KNOWN outage (: Unavailable, auth, back-pressure, deadline, +/// Cancelled, Aborted, or a status-less transport fault) ⇒ that call's and every later call's +/// events are , nothing more is sent (every later call would hit it +/// too). Events before the fault may already be committed, so the retry can duplicate them — SendEvent is +/// at-least-once too; +/// any other retryable failure (Unknown — the gateway's handler threw — Internal, +/// DataLoss, unlisted codes, a non-transport exception) ⇒ the chunk is re-sent event by event at once +/// (#976 review), because it may be one event's fault: its siblings Ack and the culprit keeps its RetryPlease, +/// which the sink counts toward MaxAttempts on that Ack'd drain and dead-letters alone. If NO single send +/// Acks, it was not the event: later chunks are RetryPlease as for an outage (so such an outage costs at most one +/// chunk of single sends per drain); /// Unimplemented (a gateway older than the RPC) ⇒ the writer stops trying batches for its lifetime and /// sends every event individually; /// any other refusal (InvalidArgument — a poison event or an over-limit batch, nothing sent — and the @@ -50,8 +57,10 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway; /// (a dropped channel's / , a disposed channel, a /// client exception with no inner status, an internal timeout's ). The /// default used to be PermanentFail, which dead-lettered a whole drained batch on a gateway restart. A poison event -/// the classifier cannot recognise is still bounded: the store-and-forward sink counts a RetryPlease against -/// MaxAttempts whenever the same drain proves the historian reachable (another event Ack'd). +/// the classifier cannot recognise is still bounded: the batch path isolates it (above), and the store-and-forward +/// sink counts a RetryPlease against MaxAttempts whenever the same drain proves the historian reachable +/// (another event Ack'd). Residual: a first chunk in which EVERY event fails that way Acks nothing and stops the +/// batch, so that drain is indistinguishable from an outage and is not counted. /// /// public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDisposable @@ -172,9 +181,24 @@ public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDispos } if (Classify(exception) == HistorianWriteOutcome.RetryPlease) { - _logger.LogDebug("Alarm SendEvents transiently failed ({Exception}); the batch will retry.", exception.GetType().Name); - foreach (var i in indexes) outcomes[i] = HistorianWriteOutcome.RetryPlease; - return false; + if (IsSystemicFailure(exception)) + { + _logger.LogDebug("Alarm SendEvents transiently failed ({Exception}); the batch will retry.", exception.GetType().Name); + foreach (var i in indexes) outcomes[i] = HistorianWriteOutcome.RetryPlease; + return false; + } + + // #976 review: a RetryPlease the writer cannot vouch for as an outage (Unknown — the gateway handler threw — + // Internal, DataLoss, an unlisted code, a non-transport client exception) may be ONE event's fault. Retrying + // the whole chunk tied every sibling to it, and the sink counts a RetryPlease only on a drain with an Ack, so + // one such event at the queue head stalled all Gateway alarm history until capacity eviction. Re-send the + // chunk's events singly NOW: the siblings Ack, the culprit keeps its RetryPlease and the sink dead-letters it + // alone via MaxAttempts. If not one single Acks it was not the event — treat it as systemic after all. + _logger.LogDebug( + "Alarm SendEvents failed with an unrecognised error ({Exception}); isolating the chunk's {Count} event(s).", + exception.GetType().Name, indexes.Count); + await SendSinglesAsync(batch, indexes, outcomes, cancellationToken).ConfigureAwait(false); + return indexes.Any(i => outcomes[i] == HistorianWriteOutcome.Ack); } // Refused up front (a poison event, an over-limit batch, …): nothing was sent — send them one by one so a poison // event dead-letters alone and its siblings still land. @@ -241,6 +265,29 @@ public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDispos return null; } + /// + /// Whether a RetryPlease-class failure is a KNOWN outage of the whole gateway path (so re-sending event by event would + /// only multiply the round trips): the transient / back-pressure / auth / deadline / server-cancellation codes, and a + /// status-less failure whose chain holds a transport fault (socket, I/O, HTTP, a disposed channel, a timeout or an + /// internal cancellation). Everything else — Unknown, Internal, DataLoss, unlisted codes, a + /// client exception with no status and no transport cause, any other exception — is unrecognised and gets the chunk + /// isolated per event. + /// + internal static bool IsSystemicFailure(Exception exception) + { + if (StatusOf(exception) is { } code) + return code is StatusCode.Unavailable or StatusCode.DeadlineExceeded or StatusCode.Cancelled + or StatusCode.ResourceExhausted or StatusCode.Aborted or StatusCode.Unauthenticated + or StatusCode.PermissionDenied; + for (Exception? e = exception; e is not null; e = e.InnerException) + if (e is HistorianGatewayUnavailableException or HistorianGatewayAuthenticationException + or HistorianGatewayAuthorizationException + or IOException or System.Net.Sockets.SocketException or HttpRequestException or ObjectDisposedException + or OperationCanceledException or TimeoutException) + return true; + return false; + } + /// Maps an event to the wire; a mapping failure is poison (logged, never thrown). private bool TryMap(AlarmHistorianEvent evt, out HistorianEvent mapped) { diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common/AlarmBatchWrite.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common/AlarmBatchWrite.cs index 346aa6386..3260284d1 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common/AlarmBatchWrite.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common/AlarmBatchWrite.cs @@ -18,7 +18,10 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common; /// unrecognised error, lmxopcua#976 G-16) is ALSO re-sent one event at a time: retrying the whole chunk tied /// every sibling to one poison event, and since the store-and-forward sink counts a RetryPlease only when the /// same drain proves the historian reachable, a chunk that never lands would otherwise pin the queue head. The -/// poison event keeps its RetryPlease and the sink dead-letters it alone once its siblings keep landing; +/// poison event keeps its RetryPlease and the sink dead-letters it alone once its siblings keep landing. Isolation +/// stops at the first single that fails with a KNOWN transient error (the outage began, or the chunk failure +/// was one the caller's isTransient missed): the chunk's remaining events are RetryPlease, so an outage +/// costs at most one extra round trip per chunk rather than one per event (#976 review); /// a cancellation of the caller's token makes every event not yet decided RetryPlease (never a dead letter). /// /// @@ -60,12 +63,19 @@ public static class AlarmBatchWrite for (var start = 0; start < pending.Count; start += chunkSize) { var chunk = pending.GetRange(start, Math.Min(chunkSize, pending.Count - start)); - var (outcome, isolate) = await TryAsync(chunk).ConfigureAwait(false); + var (outcome, isolate, _) = await TryAsync(chunk).ConfigureAwait(false); if (isolate && chunk.Count > 1) { - // Isolate the poison event: one statement per event, so the siblings still land. + // Isolate the poison event: one statement per event, so the siblings still land. A single that fails with a + // KNOWN outage error ends the isolation: the rest of the chunk is RetryPlease rather than a round trip each + // into the same outage (#976 review). foreach (var index in chunk) - outcomes[index] = (await TryAsync([index]).ConfigureAwait(false)).Outcome; + { + var single = await TryAsync([index]).ConfigureAwait(false); + outcomes[index] = single.Outcome; + if (single.Outage) break; + } + foreach (var index in chunk) outcomes[index] ??= HistorianWriteOutcome.RetryPlease; continue; } foreach (var index in chunk) outcomes[index] ??= outcome; @@ -76,23 +86,25 @@ public static class AlarmBatchWrite return result; // Isolate = the failure is not a known outage: a PermanentFail, or a RetryPlease the caller cannot vouch for. - async Task<(HistorianWriteOutcome Outcome, bool Isolate)> TryAsync(IReadOnlyList indexes) + // Outage = a known outage-class error (or a shutdown): stop sending into it. + async Task<(HistorianWriteOutcome Outcome, bool Isolate, bool Outage)> TryAsync(IReadOnlyList indexes) { - if (ct.IsCancellationRequested) return (HistorianWriteOutcome.RetryPlease, false); + if (ct.IsCancellationRequested) return (HistorianWriteOutcome.RetryPlease, false, true); try { await writeChunk(indexes, ct).ConfigureAwait(false); - return (HistorianWriteOutcome.Ack, false); + return (HistorianWriteOutcome.Ack, false, false); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { - return (HistorianWriteOutcome.RetryPlease, false); // shutdown: never a dead letter + return (HistorianWriteOutcome.RetryPlease, false, true); // shutdown: never a dead letter } catch (Exception ex) { var o = classify(ex); onFailure?.Invoke(ex, o); - return (o, o == HistorianWriteOutcome.PermanentFail || (o == HistorianWriteOutcome.RetryPlease && !isTransient(ex))); + var outage = o == HistorianWriteOutcome.RetryPlease && isTransient(ex); + return (o, o == HistorianWriteOutcome.PermanentFail || (o == HistorianWriteOutcome.RetryPlease && !outage), outage); } } } diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer/SqlHistorianConnection.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer/SqlHistorianConnection.cs index 74a585429..f634d02eb 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer/SqlHistorianConnection.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer/SqlHistorianConnection.cs @@ -122,6 +122,34 @@ internal sealed class SqlHistorianConnection return Array.IndexOf(TransientNumbers, sql.Number) >= 0; } + /// + /// Connection-level failures that affect every statement alike — login failed (18456/18452), the server not found / + /// unreachable / refusing connections (2, 40, 53, 64, 121, 10061, 10065, -1), a fatal error that closes the connection + /// (severity ≥ 20), and an exhausted connection pool — none of which can be one event's fault. Not "transient" for a + /// retry loop (a bad password never heals by retrying), so leaves them out. + /// + private static readonly int[] OutageNumbers = [18456, 18452, 2, 40, 53, 64, 121, 10061, 10065, -1]; + + /// + /// plus the connection-level failures in : what the alarm batch + /// write treats as an outage, so a chunk failing with one is retried whole rather than re-sent one statement per + /// event (#976 review — a login failure used to cost 150 round trips per chunk). + /// + /// Exception from a SQL call. + /// Whether the failure is an outage of the whole connection path. + public static bool IsOutage(Exception ex) + { + if (IsTransient(ex)) return true; + // SqlClient's pool timeout: "Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool." + if (ex is InvalidOperationException ioe && ioe.Message.Contains("connection from the pool", StringComparison.OrdinalIgnoreCase)) + return true; + if (ex is not SqlException sql) return false; + if (sql.Class >= 20) return true; + foreach (SqlError e in sql.Errors) + if (e.Class >= 20 || Array.IndexOf(OutageNumbers, e.Number) >= 0) return true; + return Array.IndexOf(OutageNumbers, sql.Number) >= 0; + } + /// True when is a unique-key violation (2627/2601): "already present". /// Exception from a SQL call. /// Whether it is a duplicate-key error. diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer/SqlServerAlarmHistorianWriter.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer/SqlServerAlarmHistorianWriter.cs index 914cb3a83..7645ed9f9 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer/SqlServerAlarmHistorianWriter.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer/SqlServerAlarmHistorianWriter.cs @@ -71,7 +71,7 @@ internal sealed class SqlServerAlarmHistorianWriter : IAlarmHistorianWriter var written = await AlarmBatchWrite.RunAsync(slots, ChunkRows, (indexes, ct) => WriteChunkAsync(batch, ids, indexes, ct), ClassifyChunk, - SqlHistorianConnection.IsTransient, + SqlHistorianConnection.IsOutage, (ex, outcome) => _log.LogWarning("SQL alarm event write failed ({Exception}); outcome {Outcome}.", ex.GetType().Name, outcome), cancellationToken).ConfigureAwait(false); for (var i = 0; i < batch.Count; i++) outcomes[i] = written[representative[ids[i]]]; diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayAlarmPoisonDrainTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayAlarmPoisonDrainTests.cs new file mode 100644 index 000000000..03a40098b --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayAlarmPoisonDrainTests.cs @@ -0,0 +1,143 @@ +using Grpc.Core; +using Microsoft.Data.Sqlite; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Serilog; +using Shouldly; +using Xunit; +using ZB.MOM.WW.HistorianGateway.Client; +using ZB.MOM.WW.HistorianGateway.Contracts.Grpc; +using ZB.MOM.WW.LocalDb; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian; + +namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests; + +/// +/// #976 review, end to end: the real draining through the real +/// . A RetryPlease-class failure the writer cannot recognise (Unknown — +/// the gateway's handler threw on one event) used to fail the whole SendEvents call RetryPlease with no Ack, which the +/// sink treats as an outage: the poison event at the queue head stalled ALL Gateway alarm history, forever. +/// +public sealed class GatewayAlarmPoisonDrainTests : IDisposable +{ + private const int MaxAttempts = 3; + private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"otopcua-gw-poison-{Guid.NewGuid():N}.sqlite"); + private ServiceProvider? _provider; + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private static AlarmHistorianEvent Evt(int i) => new( + $"alarm-{i}", "Area/Pump", "N", "LimitAlarm", AlarmSeverity.High, "Activated", $"m{i}", "u", null, + new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(i)); + + private static int MessageIndex(HistorianEvent e) => int.Parse(e.Properties["Message"][1..]); + + private static RpcException Status(StatusCode code) => new(new Status(code, code.ToString())); + + private ILocalDb NewDb() + { + var configuration = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary { ["LocalDb:Path"] = _dbPath }) + .Build(); + _provider = new ServiceCollection() + .AddZbLocalDb(configuration, db => + { + using var connection = db.CreateConnection(); + AlarmSfSchema.Apply(connection); + db.RegisterReplicated(AlarmSfSchema.EventsTable); + }) + .BuildServiceProvider(); + return _provider.GetRequiredService(); + } + + private async Task<(LocalDbStoreAndForwardSink Sink, GatewayAlarmHistorianWriter Writer)> NewSinkAsync( + FakeHistorianGatewayClient fake, int events) + { + var writer = new GatewayAlarmHistorianWriter(fake, NullLogger.Instance); + var sink = new LocalDbStoreAndForwardSink(NewDb(), writer, new LoggerConfiguration().CreateLogger(), + batchSize: 100, maxAttempts: MaxAttempts); + for (var i = 0; i < events; i++) await sink.EnqueueAsync(Evt(i), Ct); + return (sink, writer); + } + + [Fact] + public async Task A_poison_event_at_the_queue_head_no_longer_stalls_the_rest_and_eventually_dead_letters() + { + const int poison = 0; // the queue HEAD — the shape that stalled everything + var delivered = new HashSet(); + var fake = new FakeHistorianGatewayClient + { + SendEventsSource = (events, _) => + { + if (events.Any(e => MessageIndex(e) == poison)) + return Task.FromException( + new HistorianGatewayException("Exception was thrown by handler.", Status(StatusCode.Unknown))); + var reply = new SendEventsReply(); + foreach (var e in events) + { + lock (delivered) delivered.Add(MessageIndex(e)); + reply.Results.Add(new EventWriteResult { Id = e.Id, Success = true }); + } + return Task.FromResult(reply); + }, + SendEventSource = (e, _) => + { + if (MessageIndex(e) == poison) return Task.FromException(Status(StatusCode.Unknown)); + lock (delivered) delivered.Add(MessageIndex(e)); + return Task.FromResult(new WriteAck { Success = true }); + }, + }; + var (sink, writer) = await NewSinkAsync(fake, events: 5); + using var _ = sink; + using var __ = writer; + + await sink.DrainOnceAsync(Ct); + + delivered.ShouldBe([1, 2, 3, 4], ignoreOrder: true, "the siblings land on the FIRST drain"); + sink.GetStatus().QueueDepth.ShouldBe(1, "only the poison event is left"); + sink.GetStatus().DeadLetterDepth.ShouldBe(0, "an unrecognised failure is never dead-lettered directly"); + + // The poison event keeps failing while the historian accepts new events: it dead-letters via MaxAttempts. + for (var i = 0; i < MaxAttempts && sink.GetStatus().DeadLetterDepth == 0; i++) + { + await sink.EnqueueAsync(Evt(100 + i), Ct); + await sink.DrainOnceAsync(Ct); + } + + sink.GetStatus().DeadLetterDepth.ShouldBe(1, "the poison event leaves the queue on its own"); + sink.GetStatus().QueueDepth.ShouldBe(0); + } + + [Fact] + public async Task Positive_control_a_real_Unavailable_outage_isolates_nothing_and_dead_letters_nothing() + { + var fake = new FakeHistorianGatewayClient + { + SendEventsSource = (_, _) => Task.FromException( + new HistorianGatewayUnavailableException("down", Status(StatusCode.Unavailable))), + SendEventThrows = new HistorianGatewayUnavailableException("down", Status(StatusCode.Unavailable)), + }; + var (sink, writer) = await NewSinkAsync(fake, events: 5); + using var _ = sink; + using var __ = writer; + + for (var i = 0; i < MaxAttempts * 3; i++) await sink.DrainOnceAsync(Ct); + + fake.SendEventCallCount.ShouldBe(0, "a known outage is never re-sent event by event"); + sink.GetStatus().QueueDepth.ShouldBe(5); + sink.GetStatus().DeadLetterDepth.ShouldBe(0, "an outage never dead-letters, however long it lasts"); + } + + /// Cleans up the temp database. + public void Dispose() + { + _provider?.Dispose(); + SqliteConnection.ClearAllPools(); + foreach (var path in new[] { _dbPath, $"{_dbPath}-wal", $"{_dbPath}-shm" }) + { + try { if (File.Exists(path)) File.Delete(path); } catch { /* best effort */ } + } + } +} diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayAlarmWriterBatchTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayAlarmWriterBatchTests.cs index df8b99bd2..23dcb9d8f 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayAlarmWriterBatchTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayAlarmWriterBatchTests.cs @@ -108,6 +108,36 @@ public sealed class GatewayAlarmWriterBatchTests writer.BatchUnsupported.ShouldBeFalse("a refused batch is not an older gateway — the next drain batches again"); } + /// + /// #976 review: the gateway's handler throws on one event ⇒ the whole SendEvents call fails Unknown. That is + /// not a known outage, so the chunk is isolated: every sibling Acks, only the culprit keeps RetryPlease, and the next + /// chunk still goes out as a batch. + /// + [Fact] + public async Task An_Unknown_batch_failure_is_isolated_so_the_siblings_of_the_culprit_Ack() + { + const int poison = 3; + var size = GatewayAlarmHistorianWriter.MaxEventsPerBatch; + var fake = new FakeHistorianGatewayClient + { + SendEventsSource = (events, _) => events.Any(e => MessageIndex(e) == poison) + ? Task.FromException(new HistorianGatewayException("Exception was thrown by handler.", + new RpcException(new Status(StatusCode.Unknown, "Exception was thrown by handler.")))) + : Task.FromResult(AllOk(events)), + SendEventSource = (e, _) => MessageIndex(e) == poison + ? Task.FromException(new RpcException(new Status(StatusCode.Unknown, "Exception was thrown by handler."))) + : Task.FromResult(new WriteAck { Success = true }), + }; + using var writer = new GatewayAlarmHistorianWriter(fake, NullLogger.Instance); + + var outcomes = await writer.WriteBatchAsync(Enumerable.Range(0, size + 4).Select(Evt).ToList(), Ct); + + outcomes[poison].ShouldBe(HistorianWriteOutcome.RetryPlease, "unrecognised ⇒ never dead-lettered directly"); + outcomes.Where((_, i) => i != poison).ShouldAllBe(o => o == HistorianWriteOutcome.Ack); + fake.SendEventsCalls.Select(c => c.Count).ShouldBe([size, 4], "the next chunk is still batched"); + fake.SendEventCallCount.ShouldBe(size, "only the failing chunk fans out"); + } + [Fact] public async Task A_systemic_fault_retries_the_rest_and_sends_nothing_more() { diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayAlarmWriterTransientClassificationTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayAlarmWriterTransientClassificationTests.cs index 7fbacdb4b..f635f2cff 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayAlarmWriterTransientClassificationTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayAlarmWriterTransientClassificationTests.cs @@ -35,9 +35,19 @@ public sealed class GatewayAlarmWriterTransientClassificationTests StatusCode.ResourceExhausted, StatusCode.Aborted, StatusCode.Internal, ]; + /// The codes that are a known outage of the whole path: a batch failing with one is never isolated. + public static TheoryData SystemicCodes => + [ + StatusCode.Cancelled, StatusCode.Unavailable, StatusCode.DeadlineExceeded, StatusCode.ResourceExhausted, + StatusCode.Aborted, StatusCode.Unauthenticated, StatusCode.PermissionDenied, + ]; + + /// Retryable but NOT a known outage — may be one event's fault (#976 review): the chunk is isolated per event. + public static TheoryData UnrecognisedCodes => [StatusCode.Unknown, StatusCode.DataLoss, StatusCode.Internal]; + [Theory] - [MemberData(nameof(TransientCodes))] - public async Task A_transient_code_from_SendEvents_retries_every_event_and_fans_out_nothing(StatusCode code) + [MemberData(nameof(SystemicCodes))] + public async Task A_systemic_code_from_SendEvents_retries_every_event_and_fans_out_nothing(StatusCode code) { var fake = new FakeHistorianGatewayClient { @@ -64,16 +74,59 @@ public sealed class GatewayAlarmWriterTransientClassificationTests fake.SendEventCallCount.ShouldBe(3); } + [Theory] + [MemberData(nameof(UnrecognisedCodes))] + public async Task An_unrecognised_code_that_every_single_send_repeats_retries_all_and_stops_after_one_chunk(StatusCode code) + { + // An outage of a kind the writer cannot recognise: the batch AND every single send fail the same way. + var fake = new FakeHistorianGatewayClient + { + SendEventsSource = (_, _) => Task.FromException(Wrapped(code)), + SendEventThrows = Wrapped(code), + }; + using var writer = Writer(fake); + var size = GatewayAlarmHistorianWriter.MaxEventsPerBatch; + + var outcomes = await writer.WriteBatchAsync(Enumerable.Range(0, size + 5).Select(Evt).ToList(), Ct); + + outcomes.ShouldAllBe(o => o == HistorianWriteOutcome.RetryPlease, "nothing dead-letters on what may be an outage"); + fake.SendEventsCalls.Count.ShouldBe(1, "no single Ack'd, so it was not one event: the next chunk is not sent"); + fake.SendEventCallCount.ShouldBe(size, "the fan-out is bounded to the one isolated chunk"); + } + public static TheoryData TransportFaults => [ new IOException("connection reset"), new HttpRequestException("no route to host"), new ObjectDisposedException("GrpcChannel"), - new HistorianGatewayException("no inner status"), new TaskCanceledException("an internal timeout — not the caller's token"), + new HistorianGatewayException("wrapped transport fault", new IOException("connection reset")), + new HistorianGatewayUnavailableException("down"), + ]; + + /// Retryable, status-less and not a transport fault: isolated on the batch path (#976 review). + public static TheoryData UnrecognisedFaults => + [ + new HistorianGatewayException("no inner status"), new InvalidOperationException("unexpected"), ]; + [Theory] + [MemberData(nameof(UnrecognisedFaults))] + public async Task An_unrecognised_non_RPC_fault_retries_and_is_isolated_on_the_batch_path(Exception fault) + { + var fake = new FakeHistorianGatewayClient + { + SendEventsSource = (_, _) => Task.FromException(fault), + SendEventThrows = fault, + }; + using var writer = Writer(fake); + + (await writer.WriteBatchAsync(Enumerable.Range(0, 4).Select(Evt).ToList(), Ct)) + .ShouldAllBe(o => o == HistorianWriteOutcome.RetryPlease); + fake.SendEventCallCount.ShouldBe(4); + } + [Theory] [MemberData(nameof(TransportFaults))] public async Task A_non_RPC_transport_fault_retries_on_both_paths(Exception fault) diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common.Tests/AlarmBatchWriteTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common.Tests/AlarmBatchWriteTests.cs index d29362645..145fb4adf 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common.Tests/AlarmBatchWriteTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common.Tests/AlarmBatchWriteTests.cs @@ -61,6 +61,40 @@ public sealed class AlarmBatchWriteTests statements.ShouldBe(1); } + /// + /// #976 review: an unrecognised chunk failure is isolated, but once a single send hits a KNOWN outage the rest of the + /// chunk is RetryPlease — an outage the chunk-level classifier missed must not cost one round trip per event. + /// + [Fact] + public async Task Isolation_stops_at_the_first_single_that_hits_a_known_outage() + { + var statements = 0; + var r = await AlarmBatchWrite.RunAsync(Undecided(150), 150, (ix, _) => + { + statements++; + if (ix.Count > 1) throw new UnrecognisedException(); + if (ix[0] == 0) return Task.CompletedTask; + throw new OutageException(); + }, Classify, IsTransient, null, CancellationToken.None); + + r[0].ShouldBe(HistorianWriteOutcome.Ack); + r.Skip(1).ShouldAllBe(o => o == HistorianWriteOutcome.RetryPlease); + statements.ShouldBe(1 + 2, "the chunk, the Ack'd single, the single that met the outage — then stop"); + } + + [Fact] + public async Task Positive_control_isolation_continues_past_unrecognised_single_failures() + { + var r = await AlarmBatchWrite.RunAsync(Undecided(5), 10, (ix, _) => + { + if (ix.Count > 1 || ix[0] is 1 or 2) throw new UnrecognisedException(); + return Task.CompletedTask; + }, Classify, IsTransient, null, CancellationToken.None); + + r.ShouldBe([HistorianWriteOutcome.Ack, HistorianWriteOutcome.RetryPlease, HistorianWriteOutcome.RetryPlease, + HistorianWriteOutcome.Ack, HistorianWriteOutcome.Ack], "two adjacent poison events never stop the isolation"); + } + [Fact] public async Task Pre_decided_slots_are_kept_and_never_sent() { diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer.Tests/SqlOutageClassificationTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer.Tests/SqlOutageClassificationTests.cs new file mode 100644 index 000000000..fdb8f46da --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer.Tests/SqlOutageClassificationTests.cs @@ -0,0 +1,89 @@ +using System.Reflection; +using Microsoft.Data.SqlClient; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian; + +namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer.Tests; + +/// +/// #976 review: the alarm batch write isolates an unrecognised chunk failure event by event, so a connection-level +/// failure it does NOT recognise as an outage (login failed, server unreachable, pool exhausted) cost one round trip +/// per event — 150 per chunk. is the wider predicate the alarm writer +/// hands AlarmBatchWrite; is unchanged for its retry callers. +/// +public sealed class SqlOutageClassificationTests +{ + [Theory] + [InlineData(18456)] // login failed + [InlineData(18452)] // login from an untrusted domain + [InlineData(53)] // network path not found + [InlineData(40)] // could not open a connection + [InlineData(2)] // server not found / not accessible + [InlineData(10061)] // connection refused + public void Connection_level_errors_are_an_outage_but_not_a_retry_transient(int number) + { + var ex = SqlError(number, errorClass: 14); + SqlHistorianConnection.IsOutage(ex).ShouldBeTrue(); + SqlHistorianConnection.IsTransient(ex).ShouldBeFalse("IsTransient's retry callers keep their meaning"); + SqlServerAlarmHistorianWriter.Classify(ex).ShouldBe(HistorianWriteOutcome.RetryPlease, "never a dead letter"); + } + + [Fact] + public void A_fatal_severity_error_is_an_outage() => + SqlHistorianConnection.IsOutage(SqlError(9999, errorClass: 20)).ShouldBeTrue(); + + [Fact] + public void An_exhausted_connection_pool_is_an_outage() => + SqlHistorianConnection.IsOutage(new InvalidOperationException( + "Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.")) + .ShouldBeTrue(); + + [Theory] + [InlineData(8152)] // string or binary data would be truncated — a data error (poison) + [InlineData(50000)] // an unrecognised user error + public void Positive_control_statement_level_errors_are_not_an_outage(int number) => + SqlHistorianConnection.IsOutage(SqlError(number, errorClass: 16)).ShouldBeFalse(); + + [Fact] + public void Positive_control_an_unrelated_InvalidOperationException_is_not_an_outage() => + SqlHistorianConnection.IsOutage(new InvalidOperationException("unexpected")).ShouldBeFalse(); + + private const BindingFlags NonPublic = BindingFlags.NonPublic | BindingFlags.Instance; + + /// A real (internal factory, by reflection) with one error. + private static SqlException SqlError(int number, byte errorClass) + { + var errorCtor = typeof(SqlError).GetConstructors(NonPublic).OrderByDescending(c => c.GetParameters().Length).First(); + var args = errorCtor.GetParameters().Select(p => p.Name switch + { + "infoNumber" => (object?)number, + "errorMessage" => $"error {number}", + "server" => "test-sql", + "procedure" => string.Empty, + "exception" => null, + "errorClass" => errorClass, + _ => p.ParameterType == typeof(string) ? string.Empty + : p.ParameterType.IsValueType ? Activator.CreateInstance(p.ParameterType) : null, + }).ToArray(); + var error = (SqlError)errorCtor.Invoke(args); + + var collection = (SqlErrorCollection)Activator.CreateInstance(typeof(SqlErrorCollection), nonPublic: true)!; + typeof(SqlErrorCollection).GetMethod("Add", NonPublic)!.Invoke(collection, [error]); + + var create = typeof(SqlException).GetMethods(BindingFlags.NonPublic | BindingFlags.Static) + .Where(m => m.Name == "CreateException") + .Select(m => (Method: m, Params: m.GetParameters())) + .Where(x => x.Params.Length >= 2 && x.Params[0].ParameterType == typeof(SqlErrorCollection) + && x.Params[1].ParameterType == typeof(string)) + .OrderBy(x => x.Params.Length) + .First(); + var createArgs = create.Params.Select((p, i) => i switch + { + 0 => collection, + 1 => (object?)"16.0.0", + _ => p.ParameterType.IsValueType ? Activator.CreateInstance(p.ParameterType) : null, + }).ToArray(); + return (SqlException)create.Method.Invoke(null, createArgs)!; + } +}