Merge historian follow-up (#1096): Gateway alarm writer counts only genuine gateway replies as answered (client-fabricated Internal/Unknown, proxy replies and status-less faults are not); BatchUnsupported seam replaces test reflection

This commit is contained in:
Joseph Doherty
2026-12-04 17:20:51 -05:00
3 changed files with 151 additions and 7 deletions
+5
View File
@@ -314,6 +314,11 @@ Warning says "HELD by a historian outage", and the readiness check is still **De
meter, next to `queue.stalled`) reads 1 only for the outage. The SqlServer writer counts a statement-level refusal as an
answer but NOT a login failure / refused connection / pool exhaustion (`SqlServerAlarmHistorianWriter.Answered`, via
`IsOutage` — it used `!IsTransient`, which counted those as reachable); QuestDB likewise excludes SQLSTATE class 08/28/53/57.
The Gateway writer (#1096, `GatewayAlarmHistorianWriter.IsGatewayAnswer`) counts a failure as an answer only when it carries a gRPC
status that is not a systemic code AND was not fabricated client-side: a status with a `Status.DebugException` (a connection
reset / HTTP/2 RST_STREAM surfaced as `Internal`/`Unknown`) or a Grpc.Net.Client detail such as `Bad gRPC response. HTTP status code: 5xx`
(a proxy) is not an answer; a genuine gateway `Internal` (historian rejection) / `Unknown` (throwing handler) is. A status-less
exception is never an answer. The `Unimplemented` batch probe still counts (it is a real gateway reply).
A writer that does not report reachability keeps the #1034 behaviour (stalled also fires on an outage; `LastError` says
which). A node that is not the drain owner is never stalled and promotion restarts the clock.
@@ -76,10 +76,42 @@ public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDispos
/// <inheritdoc/>
public DateTime? LastReachableUtc => _reach.LastUtc;
// #1071: any gateway answer (success, or a failure that is not a systemic outage/transport fault) proves it reachable.
// #1071/#1096: only a genuine gateway answer proves it reachable (see IsGatewayAnswer).
private void NoteAnswered(Exception ex)
{
if (!IsSystemicFailure(ex)) _reach.Touch();
if (IsGatewayAnswer(ex)) _reach.Touch();
}
// Grpc.Net.Client's own client-side status details (it fabricates these when no gateway status came back).
private static readonly string[] TransportDetailPrefixes =
[
"Bad gRPC response", "Error starting gRPC call", "Error reading next message", "Error sending message",
"Failed to deserialize response message", "Invalid content-type", "Error connecting to subchannel",
];
/// <summary>
/// Whether a failed call is evidence that the GATEWAY itself responded (#1096). Needs a gRPC status, and that status
/// must not be <see cref="IsSystemicFailure"/> (outage / auth / deadline), and must not have been fabricated on the
/// client side. The last matters for <c>Unknown</c>/<c>Internal</c> (and any code): the gateway genuinely returns
/// <c>Internal</c> for a historian-side rejection and ASP.NET Core returns <c>Unknown</c> for a throwing handler, but
/// Grpc.Net.Client ALSO reports <c>Internal</c>/<c>Unknown</c>/<c>Unimplemented</c> for a connection reset mid-call or
/// an HTTP/2 RST_STREAM (it attaches the transport exception as <c>Status.DebugException</c>) and for a non-gRPC reply
/// from a proxy ("Bad gRPC response. HTTP status code: 5xx"). A server-sent status has neither. A failure with no
/// gRPC status at all (a plain client/transport exception) is not an answer either.
/// </summary>
internal static bool IsGatewayAnswer(Exception exception)
{
if (IsSystemicFailure(exception)) return false;
for (Exception? e = exception; e is not null; e = e.InnerException)
{
if (e is not RpcException rpc) continue;
if (rpc.Status.DebugException is not null) return false;
var detail = rpc.Status.Detail ?? string.Empty;
foreach (var prefix in TransportDetailPrefixes)
if (detail.StartsWith(prefix, StringComparison.Ordinal)) return false;
return true;
}
return false;
}
/// <summary>Set once the gateway answers <c>SendEvents</c> with <c>Unimplemented</c>: single sends from then on.</summary>
@@ -100,8 +132,16 @@ public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDispos
/// <summary>The most single <c>SendEvent</c> RPCs one batch has in flight at once (the fallback path).</summary>
public const int MaxSendsInFlight = 8;
/// <summary>Whether the writer has fallen back to single sends for good (the gateway has no <c>SendEvents</c>) — diagnostic.</summary>
internal bool BatchUnsupported => _batchUnsupported;
/// <summary>
/// Whether the writer has fallen back to single sends for good (the gateway has no <c>SendEvents</c>). Internal setter
/// (#1096): lets tests start on the single-send path without the <c>Unimplemented</c> probe, which is itself a gateway
/// answer.
/// </summary>
internal bool BatchUnsupported
{
get => _batchUnsupported;
set => _batchUnsupported = value;
}
/// <inheritdoc />
public async Task<IReadOnlyList<HistorianWriteOutcome>> WriteBatchAsync(
@@ -28,9 +28,108 @@ public sealed class GatewayAlarmWriterReachabilityTests
/// Puts the writer on the single-send path WITHOUT the Unimplemented probe, which is itself a gateway answer and would
/// stamp reachability before the failure under test.
/// </summary>
private static void UseSingleSends(GatewayAlarmHistorianWriter w) =>
typeof(GatewayAlarmHistorianWriter).GetField("_batchUnsupported",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!.SetValue(w, true);
private static void UseSingleSends(GatewayAlarmHistorianWriter w) => w.BatchUnsupported = true;
private static Exception WrappedRpc(StatusCode code, string detail, Exception? debug = null) =>
new HistorianGatewayException(detail, new RpcException(new Status(code, detail, debug)));
// #1096: pin every status code. Server-sent codes with no client-side evidence:
[Theory]
[InlineData(StatusCode.InvalidArgument, true)]
[InlineData(StatusCode.FailedPrecondition, true)]
[InlineData(StatusCode.OutOfRange, true)]
[InlineData(StatusCode.NotFound, true)]
[InlineData(StatusCode.AlreadyExists, true)]
[InlineData(StatusCode.Unimplemented, true)]
[InlineData(StatusCode.Internal, true)]
[InlineData(StatusCode.Unknown, true)]
[InlineData(StatusCode.DataLoss, true)]
[InlineData(StatusCode.Unavailable, false)]
[InlineData(StatusCode.DeadlineExceeded, false)]
[InlineData(StatusCode.Cancelled, false)]
[InlineData(StatusCode.ResourceExhausted, false)]
[InlineData(StatusCode.Aborted, false)]
[InlineData(StatusCode.Unauthenticated, false)]
[InlineData(StatusCode.PermissionDenied, false)]
public void Every_server_sent_status_code_is_classified(StatusCode code, bool answered) =>
GatewayAlarmHistorianWriter.IsGatewayAnswer(Wrapped(code)).ShouldBe(answered);
[Theory]
[InlineData(StatusCode.Internal, "Bad gRPC response. HTTP status code: 500")]
[InlineData(StatusCode.Unknown, "Bad gRPC response. HTTP status code: 502")]
[InlineData(StatusCode.Unimplemented, "Bad gRPC response. HTTP status code: 404")]
[InlineData(StatusCode.Internal, "Error starting gRPC call. HttpRequestException: reset")]
[InlineData(StatusCode.Unknown, "Error reading next message. IOException: reset")]
public void A_client_fabricated_status_from_a_proxy_or_reset_is_not_an_answer(StatusCode code, string detail) =>
GatewayAlarmHistorianWriter.IsGatewayAnswer(WrappedRpc(code, detail)).ShouldBeFalse();
[Theory]
[InlineData(StatusCode.Internal)]
[InlineData(StatusCode.Unknown)]
public void A_status_carrying_a_transport_debug_exception_is_not_an_answer(StatusCode code) =>
GatewayAlarmHistorianWriter.IsGatewayAnswer(
WrappedRpc(code, "Received RST_STREAM with error code 2", new IOException("reset"))).ShouldBeFalse();
[Fact]
public void A_failure_with_no_grpc_status_is_not_an_answer()
{
GatewayAlarmHistorianWriter.IsGatewayAnswer(new InvalidOperationException("x")).ShouldBeFalse();
GatewayAlarmHistorianWriter.IsGatewayAnswer(new HistorianGatewayException("x")).ShouldBeFalse();
}
[Theory]
[InlineData(StatusCode.Internal)]
[InlineData(StatusCode.Unknown)]
public async Task A_genuine_gateway_Internal_or_Unknown_on_a_single_send_counts_as_answered(StatusCode code)
{
var fake = new FakeHistorianGatewayClient { SendEventThrows = Wrapped(code) };
using var w = Writer(fake);
UseSingleSends(w);
await w.WriteBatchAsync([Evt()], Ct);
w.LastReachableUtc.ShouldNotBeNull();
}
[Fact]
public async Task A_proxy_Internal_on_a_single_send_does_not_count_as_answered()
{
var fake = new FakeHistorianGatewayClient
{
SendEventThrows = WrappedRpc(StatusCode.Internal, "Bad gRPC response. HTTP status code: 500"),
};
using var w = Writer(fake);
UseSingleSends(w);
await w.WriteBatchAsync([Evt()], Ct);
w.LastReachableUtc.ShouldBeNull();
}
[Fact]
public async Task A_proxy_Unknown_on_SendEvents_does_not_count_as_answered()
{
var reset = WrappedRpc(StatusCode.Unknown, "Error starting gRPC call. HttpRequestException: reset");
var fake = new FakeHistorianGatewayClient
{
SendEventsSource = (_, _) => Task.FromException<SendEventsReply>(reset),
SendEventThrows = reset,
};
using var w = Writer(fake);
await w.WriteBatchAsync([Evt()], Ct);
w.LastReachableUtc.ShouldBeNull();
}
[Fact]
public async Task The_Unimplemented_batch_probe_counts_as_answered_and_flips_to_single_sends()
{
var fake = new FakeHistorianGatewayClient
{
SendEventsSource = (_, _) => Task.FromException<SendEventsReply>(Wrapped(StatusCode.Unimplemented)),
SendEventThrows = Wrapped(StatusCode.Unavailable), // the follow-up single send fails, so only the probe stamps
};
using var w = Writer(fake);
w.BatchUnsupported.ShouldBeFalse();
await w.WriteBatchAsync([Evt()], Ct);
w.BatchUnsupported.ShouldBeTrue();
w.LastReachableUtc.ShouldNotBeNull();
}
private static Exception Wrapped(StatusCode code) =>
new HistorianGatewayException(code.ToString(), new RpcException(new Status(code, code.ToString())));