Files
lmxopcua/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayAlarmWriterTransientClassificationTests.cs
T
Joseph Doherty 1c7e06502f fix(historian): #976 review — Gateway alarm writer isolates an unrecognised batch failure per event
#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.
2026-12-03 12:01:24 -05:00

195 lines
9.0 KiB
C#

using Grpc.Core;
using Microsoft.Extensions.Logging.Abstractions;
using Shouldly;
using Xunit;
using ZB.MOM.WW.HistorianGateway.Client;
using ZB.MOM.WW.HistorianGateway.Contracts.Grpc;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian;
namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests;
/// <summary>
/// G-8 (#976): a transient gateway condition must never dead-letter alarm history. The gateway answers a server-side
/// cancellation (shutdown / internal timeout) with <c>Cancelled</c> and an unmapped server fault with <c>Unknown</c>;
/// a dropped channel surfaces as a plain transport exception. Only codes that prove the EVENT is bad dead-letter.
/// </summary>
public sealed class GatewayAlarmWriterTransientClassificationTests
{
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 GatewayAlarmHistorianWriter Writer(FakeHistorianGatewayClient fake) =>
new(fake, NullLogger<GatewayAlarmHistorianWriter>.Instance);
/// <summary>The published client wraps every code it has no typed exception for in the base type, inner RpcException.</summary>
private static Exception Wrapped(StatusCode code) =>
new HistorianGatewayException(code.ToString(), new RpcException(new Status(code, code.ToString())));
public static TheoryData<StatusCode> TransientCodes =>
[
StatusCode.Cancelled, StatusCode.Unknown, StatusCode.DataLoss, StatusCode.Unavailable, StatusCode.DeadlineExceeded,
StatusCode.ResourceExhausted, StatusCode.Aborted, StatusCode.Internal,
];
/// <summary>The codes that are a known outage of the whole path: a batch failing with one is never isolated.</summary>
public static TheoryData<StatusCode> SystemicCodes =>
[
StatusCode.Cancelled, StatusCode.Unavailable, StatusCode.DeadlineExceeded, StatusCode.ResourceExhausted,
StatusCode.Aborted, StatusCode.Unauthenticated, StatusCode.PermissionDenied,
];
/// <summary>Retryable but NOT a known outage — may be one event's fault (#976 review): the chunk is isolated per event.</summary>
public static TheoryData<StatusCode> UnrecognisedCodes => [StatusCode.Unknown, StatusCode.DataLoss, StatusCode.Internal];
[Theory]
[MemberData(nameof(SystemicCodes))]
public async Task A_systemic_code_from_SendEvents_retries_every_event_and_fans_out_nothing(StatusCode code)
{
var fake = new FakeHistorianGatewayClient
{
SendEventsSource = (_, _) => Task.FromException<SendEventsReply>(Wrapped(code)),
};
using var writer = Writer(fake);
var outcomes = await writer.WriteBatchAsync(Enumerable.Range(0, 5).Select(Evt).ToList(), Ct);
outcomes.ShouldAllBe(o => o == HistorianWriteOutcome.RetryPlease);
fake.SendEventCallCount.ShouldBe(0, "a systemic fault must not be re-sent event by event");
}
[Theory]
[MemberData(nameof(TransientCodes))]
public async Task A_transient_code_from_SendEvent_retries_the_event(StatusCode code)
{
var fake = new FakeHistorianGatewayClient { SendEventThrows = Wrapped(code) }; // SendEvents unset ⇒ Unimplemented ⇒ singles
using var writer = Writer(fake);
var outcomes = await writer.WriteBatchAsync(Enumerable.Range(0, 3).Select(Evt).ToList(), Ct);
outcomes.ShouldAllBe(o => o == HistorianWriteOutcome.RetryPlease);
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<SendEventsReply>(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<Exception> TransportFaults =>
[
new IOException("connection reset"),
new HttpRequestException("no route to host"),
new ObjectDisposedException("GrpcChannel"),
new TaskCanceledException("an internal timeout — not the caller's token"),
new HistorianGatewayException("wrapped transport fault", new IOException("connection reset")),
new HistorianGatewayUnavailableException("down"),
];
/// <summary>Retryable, status-less and not a transport fault: isolated on the batch path (#976 review).</summary>
public static TheoryData<Exception> 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<SendEventsReply>(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)
{
var batchFake = new FakeHistorianGatewayClient { SendEventsSource = (_, _) => Task.FromException<SendEventsReply>(fault) };
using (var writer = Writer(batchFake))
{
(await writer.WriteBatchAsync(Enumerable.Range(0, 4).Select(Evt).ToList(), Ct))
.ShouldAllBe(o => o == HistorianWriteOutcome.RetryPlease);
batchFake.SendEventCallCount.ShouldBe(0);
}
var singleFake = new FakeHistorianGatewayClient { SendEventThrows = fault };
using (var writer = Writer(singleFake))
{
(await writer.WriteBatchAsync(Enumerable.Range(0, 2).Select(Evt).ToList(), Ct))
.ShouldAllBe(o => o == HistorianWriteOutcome.RetryPlease);
}
}
[Theory]
[InlineData(StatusCode.InvalidArgument)]
[InlineData(StatusCode.FailedPrecondition)]
[InlineData(StatusCode.OutOfRange)]
[InlineData(StatusCode.NotFound)]
[InlineData(StatusCode.AlreadyExists)]
public async Task Positive_control_a_code_that_proves_the_event_bad_still_dead_letters(StatusCode code)
{
var fake = new FakeHistorianGatewayClient { SendEventThrows = Wrapped(code) };
using var writer = Writer(fake);
(await writer.WriteBatchAsync([Evt(0)], Ct)).Single().ShouldBe(HistorianWriteOutcome.PermanentFail);
}
[Fact]
public async Task Positive_control_an_event_that_cannot_be_mapped_dead_letters_without_an_RPC_on_both_paths()
{
var poison = Evt(1) with { DeliveryId = Guid.Empty };
var batchFake = new FakeHistorianGatewayClient
{
SendEventsSource = (events, _) =>
{
var reply = new SendEventsReply();
foreach (var e in events) reply.Results.Add(new EventWriteResult { Id = e.Id, Success = true });
return Task.FromResult(reply);
},
};
using (var writer = Writer(batchFake))
{
(await writer.WriteBatchAsync([Evt(0), poison, Evt(2)], Ct)).ShouldBe(
[HistorianWriteOutcome.Ack, HistorianWriteOutcome.PermanentFail, HistorianWriteOutcome.Ack]);
batchFake.SendEventsCalls.Single().Count.ShouldBe(2);
}
var singleFake = new FakeHistorianGatewayClient(); // SendEvents ⇒ Unimplemented ⇒ singles
using (var writer = Writer(singleFake))
{
(await writer.WriteBatchAsync([Evt(0)], Ct)).Single().ShouldBe(HistorianWriteOutcome.Ack);
writer.BatchUnsupported.ShouldBeTrue("the single-send path is what the next write exercises");
(await writer.WriteBatchAsync([poison], Ct)).Single().ShouldBe(HistorianWriteOutcome.PermanentFail);
singleFake.SendEventCallCount.ShouldBe(1, "the unmappable event is never sent");
}
}
}