Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Harness/SqlExceptionFactory.cs
T
Joseph Doherty ec3b835e4a fix(controlplane,runtime): #868 fourth review — SQL poison allowlist, memory-counted acks survive restart, adopted revisions unconfirmed
M1 IsPoison classified every SQL Server transient as poison:
   Microsoft.Data.SqlClient never sets DbException.IsTransient, so a deadlock
   (1205), timeout (-2 / Win32 258), dropped connection or AG failover was
   counted from memory and the node's row left Applying. Poison is now an
   ALLOWLIST: a DbUpdateException (not concurrency) carrying a SqlException
   whose number is 8152, 2628, 547, 515, 2627 or 2601. Everything else
   retries, bounded by the deadline deferral cap. IsPoison is public for tests.
   Acks counted only from memory (poison branch and the deferral cap) are kept
   in _memoryOnlyAcks and re-sent by PreRestart alongside _unpersisted, so a
   restart before the terminal write does not lose them.
M2 Revisions adopted without an outcome-reporting apply are unconfirmed, so a
   same-revision dispatch re-applies instead of short-circuiting a clean
   Applied over an empty address space: TryRecoverFromStale (restores only the
   revision marker) and RestoreApplied when the artifact read fails (null
   blob, LoadArtifactBlob swallows the error) or the restore throws.
L1 The re-drive comment documents the CreatedAtUtc recompute after a second
   restart / failover.
L2 _currentRevisionDegraded renamed _currentRevisionUnconfirmed; the stale
   TryBootFromCache remark corrected.
L3 docs/Redundancy.md: a Direct node running from cache that still cannot
   reach the ConfigDb acks a same-revision re-dispatch Failed
   (PartiallyFailed, not Sealed); Stale recovery and failed restores are
   unconfirmed too.

Test harness: SqlExceptionFactory builds real SqlExceptions (reflection on
SqlError / SqlErrorCollection / SqlException.CreateException);
ConstraintEnforcingDbFactory now throws DbUpdateException over SQL 2628
(over-length), 547 (poison) and 1205 (transient), plus FailNextContexts.

Tests (all fail on the previous code): poison allowlist theory (1205, 40613,
10054, 4060 not poison) + timeout/concurrency/providerless not poison; a
deadlocked ack write is retried and recorded; a memory-counted ack survives a
coordinator restart; Stale-recovered and failed-restore revisions re-apply on
re-dispatch.

Claude-Session: https://claude.ai/code/session_01GT67AD99zQQqpLCVm3p7xk
2026-11-11 13:31:49 -05:00

64 lines
3.0 KiB
C#

using System.ComponentModel;
using System.Reflection;
using Microsoft.Data.SqlClient;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness;
/// <summary>
/// Builds real <see cref="SqlException"/>s for tests. The type has no public constructor, so this goes through its
/// internal factory by reflection — the same objects SQL Server failures produce, carrying a real error number.
/// </summary>
public static class SqlExceptionFactory
{
private const BindingFlags NonPublic = BindingFlags.NonPublic | BindingFlags.Instance;
/// <summary>A <see cref="SqlException"/> with one error of the given number.</summary>
/// <param name="number">The SQL Server error number (e.g. 2628, 1205, -2).</param>
/// <param name="message">The error text.</param>
/// <param name="inner">An inner exception (e.g. a <see cref="Win32Exception"/> for a timeout).</param>
/// <returns>The exception.</returns>
public static SqlException Create(int number, string message, Exception? inner = null)
{
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" => message,
"server" => "test-sql",
"procedure" => string.Empty,
"exception" => inner,
"errorClass" => (byte)16,
_ => 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 == typeof(Exception) ? inner
: p.ParameterType.IsValueType ? Activator.CreateInstance(p.ParameterType) : null,
}).ToArray();
return (SqlException)create.Method.Invoke(null, createArgs)!;
}
/// <summary>A command timeout as SQL Server reports it: number -2 over a Win32 258 (WAIT_TIMEOUT).</summary>
/// <returns>The exception.</returns>
public static SqlException Timeout() =>
Create(-2, "Execution Timeout Expired.", new Win32Exception(258, "The wait operation timed out."));
}