Files
lmxopcua/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common/AlarmBatchWrite.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

112 lines
6.7 KiB
C#

using ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian;
namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common;
/// <summary>
/// The batched alarm-history write both SQL backends share: events go to the database in chunks of one statement each
/// (one round trip per chunk, not per event), and the per-event outcomes the store-and-forward drain needs are kept:
/// <list type="bullet">
/// <item>a chunk that succeeds is Ack for every event in it (each was inserted or already present — the writes are
/// insert-if-absent / deduplicated by event id);</item>
/// <item>a chunk failing with a KNOWN transient error (the caller's <c>isTransient</c>: the database is down or
/// busy) is RetryPlease for all its events — re-sending them one by one during an outage would only multiply
/// the round trips;</item>
/// <item>a chunk failing <see cref="HistorianWriteOutcome.PermanentFail"/>-class (a data error, or anything the
/// caller's classifier wants isolated) is re-sent ONE EVENT AT A TIME, so only the poison event dead-letters and
/// its siblings still Ack;</item>
/// <item>a chunk failing with an error that is neither (RetryPlease-class but not a known transient — an
/// 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. 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 <c>isTransient</c> 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);</item>
/// <item>a cancellation of the caller's token makes every event not yet decided RetryPlease (never a dead letter).</item>
/// </list>
/// </summary>
public static class AlarmBatchWrite
{
/// <summary>Writes the undecided events of a batch and returns one outcome per event.</summary>
/// <param name="outcomes">
/// One slot per batch event; a non-null slot is already decided (e.g. a pre-1970 time on QuestDB) and is not sent.
/// Filled in place; every slot is non-null on return.
/// </param>
/// <param name="chunkSize">Events per statement (at least 1).</param>
/// <param name="writeChunk">Writes the events at the given batch indexes in ONE statement; throws on failure.</param>
/// <param name="classify">Maps a write failure to the outcome it implies (see the summary for multi-event chunks).</param>
/// <param name="isTransient">
/// Whether a failure is a KNOWN outage-class error (connection / timeout / throttling). A multi-event chunk whose
/// RetryPlease-class failure is not one of these is isolated event by event.
/// </param>
/// <param name="onFailure">Optional diagnostic hook per failure (the exception and its classified outcome).</param>
/// <param name="ct">The drain's cancellation token.</param>
/// <returns>The filled outcomes.</returns>
public static async Task<HistorianWriteOutcome[]> RunAsync(
HistorianWriteOutcome?[] outcomes, int chunkSize,
Func<IReadOnlyList<int>, CancellationToken, Task> writeChunk,
Func<Exception, HistorianWriteOutcome> classify,
Func<Exception, bool> isTransient,
Action<Exception, HistorianWriteOutcome>? onFailure,
CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(outcomes);
ArgumentNullException.ThrowIfNull(writeChunk);
ArgumentNullException.ThrowIfNull(classify);
ArgumentNullException.ThrowIfNull(isTransient);
chunkSize = Math.Max(1, chunkSize);
var pending = new List<int>(outcomes.Length);
for (var i = 0; i < outcomes.Length; i++)
if (outcomes[i] is null) pending.Add(i);
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);
if (isolate && chunk.Count > 1)
{
// 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)
{
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;
}
var result = new HistorianWriteOutcome[outcomes.Length];
for (var i = 0; i < outcomes.Length; i++) result[i] = outcomes[i] ?? HistorianWriteOutcome.RetryPlease;
return result;
// Isolate = the failure is not a known outage: a PermanentFail, or a RetryPlease the caller cannot vouch for.
// Outage = a known outage-class error (or a shutdown): stop sending into it.
async Task<(HistorianWriteOutcome Outcome, bool Isolate, bool Outage)> TryAsync(IReadOnlyList<int> indexes)
{
if (ct.IsCancellationRequested) return (HistorianWriteOutcome.RetryPlease, false, true);
try
{
await writeChunk(indexes, ct).ConfigureAwait(false);
return (HistorianWriteOutcome.Ack, false, false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return (HistorianWriteOutcome.RetryPlease, false, true); // shutdown: never a dead letter
}
catch (Exception ex)
{
var o = classify(ex);
onFailure?.Invoke(ex, o);
var outage = o == HistorianWriteOutcome.RetryPlease && isTransient(ex);
return (o, o == HistorianWriteOutcome.PermanentFail || (o == HistorianWriteOutcome.RetryPlease && !outage), outage);
}
}
}
}