diff --git a/.claude/rules/historian.md b/.claude/rules/historian.md
index 2de867160..348c7c302 100644
--- a/.claude/rules/historian.md
+++ b/.claude/rules/historian.md
@@ -81,7 +81,12 @@ Alarm events are written through `GatewayAlarmHistorianWriter` (gateway **`SendE
the durable **`LocalDbStoreAndForwardSink`** — `AlarmHistorian:Enabled=true` swaps the `NullAlarmHistorianSink`
default for the store-and-forward queue, which buffers into the node's consolidated LocalDb as the
replicated `alarm_sf_events` table (see the LocalDb section) and whose drain worker forwards batches to
-the gateway and uses per-event outcomes to decide retry vs. dead-letter (never throws). **Only the node
+the gateway and uses per-event outcomes to decide retry vs. dead-letter (never throws). ⚠️ **An outage never
+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
+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`,
`Capacity`, `DeadLetterRetentionDays`, `BatchSize`, `MaxAttempts`) — the downstream gateway connection
diff --git a/docs/AlarmHistorian.md b/docs/AlarmHistorian.md
index 8a19fd869..72cc14d19 100644
--- a/docs/AlarmHistorian.md
+++ b/docs/AlarmHistorian.md
@@ -59,7 +59,9 @@ unless noted.
- **`HistorianWriteOutcome`** — per-event drain result: `Ack` (persisted,
remove from queue), `RetryPlease` (transient failure — leave queued, retry
after backoff), `PermanentFail` (malformed/unrecoverable — move to
- dead-letter).
+ dead-letter). Writers return `PermanentFail` only when the failure proves the
+ EVENT bad; anything that could be an outage is `RetryPlease` (#976 — see
+ "Outages never dead-letter" below).
- **`HistorianSinkStatus`** — diagnostic snapshot surfaced to the AdminUI and
`/healthz`: `QueueDepth`, `DeadLetterDepth`, `LastDrainUtc`, `LastSuccessUtc`,
`LastError`, `DrainState`, and `EvictedCount`.
@@ -192,10 +194,11 @@ lifetime belong to LocalDb; the sink no longer manages either.
each outcome is applied in one transaction: `Ack` deletes the row (the delete
replicates as a tombstone, so the peer drops its copy and a promoted standby
cannot re-send it), `PermanentFail` flips its `dead_lettered` flag,
- `RetryPlease` bumps its attempt
- count and leaves it queued. A row whose `AttemptCount` has reached the configured
- **`MaxAttempts`** cap (default 10) is dead-lettered automatically on the next drain
- tick rather than retried — this breaks infinite retry loops for poison events whose
+ `RetryPlease` leaves it queued — and, **only on a drain where at least one event was
+ `Ack`'d** (the historian is demonstrably accepting writes), bumps its attempt count.
+ A row whose `AttemptCount` has reached the configured
+ **`MaxAttempts`** cap (default 10) is dead-lettered automatically on the next such drain
+ rather than retried — this breaks infinite retry loops for poison events whose
payload the historian will always reject (e.g. a malformed alarm record that triggers
a permanent SDK error on every attempt). The dead-lettered row remains inspectable
via `RetryDeadLettered()` for the configured retention window.
@@ -209,6 +212,38 @@ BackingOff`; a clean batch resets it. The async-void timer callback is fully
guarded: a fault is logged and recorded into `GetStatus()` rather than lost as
an unobserved task exception.
+### Outages never dead-letter (#976)
+
+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
+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
+after that, with no automatic retry. Now:
+
+- A drain with **no `Ack`** is treated as an outage: `RetryPlease` rows are left
+ exactly as they were (no attempt counted, nothing dead-lettered), the backoff climbs
+ to its 60 s cap, `DrainState = BackingOff` and `LastError` reads "Historian
+ 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.
+- 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.
+- 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`.
+
### Durability bound (important)
**The durability guarantee is bounded by `capacity` (default 1,000,000 rows).**
diff --git a/docs/Historian.md b/docs/Historian.md
index d447e17e7..fe6257ed6 100644
--- a/docs/Historian.md
+++ b/docs/Historian.md
@@ -431,6 +431,12 @@ because the outbox's `RemoveAsync` truncates the FIFO head *through* the acked i
entries could silently drop older, unwritten entries belonging to another. That much is deliberate and
unchanged.
+**Through, and no further (#976 G-7).** The recorder's append loop runs concurrently with the drain, and an append
+enqueues a record before it indexes it. Acking the newest indexed entry used to truncate to the log's live tail — past a
+value enqueued in that window, which was then silently never historized (and gone after a restart). The truncation point
+is now the acked record's own end (the address the drain's peek scanned past it), and a peek returns only indexed
+records, so every value it hands the drain can be acked.
+
What was wrong is what happened when a tag failed **permanently**: the head never advanced, so every
**healthy** tag in the batch was re-submitted to the historian on every drain pass, indefinitely —
duplicate samples at identical timestamps, and an outbox that never truncated (observed live at 8.3 MB
@@ -1717,6 +1723,10 @@ with the first HistoryUpdate after it.
Outcomes: `Ack` on insert or already-present (including a concurrent writer winning a 2627/2601 race); `RetryPlease` on
transient SQL errors (connection, timeout, deadlock 1205 …), bootstrap failures, cancellation and any unclassified error;
`PermanentFail` (dead-letter) only for data errors SQL will reject forever (truncation 2628/8152, conversion, null, range, constraint).
+ A multi-event chunk failing with an error that is neither a recognised data error nor a known transient (#976) is also
+ re-sent event by event, so an unrecognised poison event no longer retries its chunk-mates with it; the store-and-forward
+ sink counts a `RetryPlease` against `MaxAttempts` only on a drain where something was `Ack`'d, so an outage never
+ dead-letters (`docs/AlarmHistorian.md` §"Outages never dead-letter").
`SourceName` is the event's `EquipmentPath`; `Severity` is the numeric Part 9 value (Low 200, Medium 500, High 700, Critical 900).
- **Tag names** are `nvarchar(400)`, and a longer name is **refused, never truncated** (a truncating parameter would resolve
it onto whichever tag owns its first 400 characters): `EnsureTags` fails it individually, the live-value writer returns
diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian/LocalDbStoreAndForwardSink.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian/LocalDbStoreAndForwardSink.cs
index 6d239f752..081b1456f 100644
--- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian/LocalDbStoreAndForwardSink.cs
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian/LocalDbStoreAndForwardSink.cs
@@ -42,6 +42,21 @@ namespace ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian;
/// rows flip the dead_lettered flag
/// on the individual row; neighbors in the batch still retry on their own cadence.
///
+///
+/// An outage never dead-letters (lmxopcua#976 G-16/K-2). Every production writer answers a
+/// systemic failure — historian / gateway down, auth blip, failed schema bootstrap — with
+/// for every event, so a RetryPlease alone cannot tell
+/// an outage from a poison row. A RetryPlease therefore counts against MaxAttempts only on a
+/// drain that proves the historian is accepting writes: at least one event of the same drain was
+/// 'd. (A is not
+/// that evidence — writers decide some without contacting anything, e.g. a pre-1970 time on QuestDB.)
+/// A drain with no Ack is an outage: it backs off down the capped ladder, still dead-letters its
+/// PermanentFail rows, and leaves every RetryPlease row untouched — before this rule an outage
+/// longer than ~6.5 minutes dead-lettered the oldest queued alarm history, 100 rows every 10
+/// minutes after that. The cost: a batch made up ENTIRELY of rows
+/// that always answer RetryPlease is indistinguishable from an outage and is retried (at the 60 s cap)
+/// rather than dead-lettered; it is visible as a non-draining queue with LastError set.
+///
///
public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposable
{
@@ -51,7 +66,10 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
/// Default window dead-lettered rows are retained for before the sweeper purges them.
public static readonly TimeSpan DefaultDeadLetterRetention = TimeSpan.FromDays(30);
- /// Default max delivery attempts before a perpetually-retrying (poison) row is dead-lettered.
+ ///
+ /// Default max delivery attempts before a perpetually-retrying (poison) row is dead-lettered. Only attempts made
+ /// on a drain that proved the historian reachable count — an outage never consumes them (#976).
+ ///
public const int DefaultMaxAttempts = 10;
private static readonly TimeSpan[] BackoffLadder =
@@ -422,8 +440,15 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
return;
}
+ // #976 G-16/K-2: a RetryPlease is evidence against its row only when the same drain shows the historian
+ // accepting writes (some event Ack'd). A drain with no Ack is an outage — or a writer that refused events
+ // without contacting anything (a pre-1970 time, an unmappable event) — and RetryPlease rows are left exactly
+ // as they were: no attempt counted, nothing dead-lettered. PermanentFail rows dead-letter either way.
+ var historianReachable = outcomes.Any(o => o == HistorianWriteOutcome.Ack);
+
int rowsLeavingQueue = 0;
int rowsDeadLettered = 0;
+ int retriesDeferred = 0;
await using (var tx = await _db.BeginTransactionAsync(ct).ConfigureAwait(false))
{
for (var i = 0; i < outcomes.Count; i++)
@@ -450,9 +475,15 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
// attempt count is the count BEFORE this attempt; +1 accounts for the
// bump this drain represents. At the cap, dead-letter instead of
// bumping — and count it as leaving the live queue like PermanentFail.
- if (liveRows[i].AttemptCount + 1 >= _maxAttempts)
+ // Counted only on a drain that proved the historian reachable (#976):
+ // during an outage the row is left untouched.
+ if (!historianReachable)
{
- await DeadLetterRowAsync(tx, id, $"max attempts ({_maxAttempts}) exceeded", ct).ConfigureAwait(false);
+ retriesDeferred++;
+ }
+ else if (liveRows[i].AttemptCount + 1 >= _maxAttempts)
+ {
+ await DeadLetterRowAsync(tx, id, $"max attempts ({_maxAttempts}) exceeded while the historian accepted other events", ct).ConfigureAwait(false);
rowsLeavingQueue++;
rowsDeadLettered++;
}
@@ -474,9 +505,13 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
Interlocked.Add(ref _deadLetterRowCount, rowsDeadLettered);
var acks = outcomes.Count(o => o == HistorianWriteOutcome.Ack);
+ string? outageMsg = retriesDeferred > 0
+ ? $"Historian unavailable: {retriesDeferred} event(s) deferred with no write accepted (outage retries never count toward MaxAttempts)"
+ : null;
lock (_statusLock)
{
if (acks > 0) _lastSuccessUtc = _clock();
+ if (outageMsg is not null) _lastError = outageMsg;
if (outcomes.Any(o => o == HistorianWriteOutcome.RetryPlease))
_drainState = HistorianDrainState.BackingOff;
@@ -484,6 +519,8 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
_drainState = HistorianDrainState.Idle;
}
+ if (outageMsg is not null) _logger.Debug("{Msg}", outageMsg);
+
if (outcomes.Any(o => o == HistorianWriteOutcome.RetryPlease))
BumpBackoff();
else
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 6e590e10d..bd5d461ff 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
@@ -39,17 +39,19 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway;
/// call.
///
///
-/// Outcome mapping. Success (or store-forward-queued) ack ⇒ .
-/// Transient gRPC codes (Unavailable, DeadlineExceeded, ResourceExhausted,
-/// Aborted, Internal) and the auth codes (Unauthenticated,
-/// PermissionDenied) ⇒ — an auth fix
-/// re-enables the batch, so an auth blip never dead-letters. Permanent codes
-/// (InvalidArgument, FailedPrecondition, OutOfRange, Unimplemented) ⇒
-/// (dead-letter poison — mirrors the Wonderware
-/// PerEventStatus==2 boundary). The typed client exceptions are classified by type, or by
-/// the they wrap; any other or unclassifiable error defaults to
-/// so the drain worker cannot loop a poison
-/// event forever.
+/// Outcome mapping (lmxopcua#976 G-8). Success (or store-forward-queued) ack ⇒
+/// . Only the gRPC codes that prove the EVENT itself is bad
+/// (InvalidArgument, FailedPrecondition, OutOfRange, NotFound, AlreadyExists,
+/// Unimplemented) — and an event that cannot even be mapped to the wire — are
+/// (dead-letter poison). EVERYTHING else is
+/// : the transient codes, the auth codes (an auth fix re-enables
+/// the batch), Cancelled (the gateway's answer to a server-side cancellation — shutdown, internal timeout),
+/// Unknown (an unmapped server fault), DataLoss, any code not listed, and every non-RPC exception
+/// (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).
///
///
public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDisposable
@@ -134,17 +136,15 @@ public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDispos
var indexes = new List(count);
for (var i = offset; i < offset + count; i++)
{
- try
+ if (TryMap(batch[i], out var mapped))
{
- events.Add(AlarmEventMapper.ToHistorianEvent(batch[i]));
+ events.Add(mapped);
indexes.Add(i);
}
- catch (Exception exception)
+ else
{
- // An event that cannot even be mapped is poison: classified exactly as a single send would classify it.
- outcomes[i] = Classify(exception);
- _logger.LogWarning("Alarm event could not be mapped for SendEvents ({Exception}); dead-lettering it.",
- exception.GetType().Name);
+ // An event that cannot even be mapped is poison: no gateway can ever accept it.
+ outcomes[i] = HistorianWriteOutcome.PermanentFail;
}
}
if (events.Count == 0) return true;
@@ -241,11 +241,29 @@ public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDispos
return null;
}
- private async Task SendOneAsync(AlarmHistorianEvent evt, CancellationToken cancellationToken)
+ /// Maps an event to the wire; a mapping failure is poison (logged, never thrown).
+ private bool TryMap(AlarmHistorianEvent evt, out HistorianEvent mapped)
{
try
{
- var ack = await _client.SendEventAsync(AlarmEventMapper.ToHistorianEvent(evt), cancellationToken)
+ mapped = AlarmEventMapper.ToHistorianEvent(evt);
+ return true;
+ }
+ catch (Exception exception)
+ {
+ _logger.LogWarning("Alarm event could not be mapped to a gateway event ({Exception}); dead-lettering it.",
+ exception.GetType().Name);
+ mapped = null!;
+ return false;
+ }
+ }
+
+ private async Task SendOneAsync(AlarmHistorianEvent evt, CancellationToken cancellationToken)
+ {
+ if (!TryMap(evt, out var mapped)) return HistorianWriteOutcome.PermanentFail;
+ try
+ {
+ var ack = await _client.SendEventAsync(mapped, cancellationToken)
.ConfigureAwait(false);
return MapAck(ack);
}
@@ -283,37 +301,28 @@ public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDispos
private static HistorianWriteOutcome MapAck(WriteAck ack) =>
ack.Success || ack.Queued ? HistorianWriteOutcome.Ack : HistorianWriteOutcome.RetryPlease;
- private static HistorianWriteOutcome Classify(Exception exception) => exception switch
- {
- // Published client's typed hierarchy (production reality). Unavailable + both auth kinds retry.
- HistorianGatewayUnavailableException => HistorianWriteOutcome.RetryPlease,
- HistorianGatewayAuthenticationException => HistorianWriteOutcome.RetryPlease,
- HistorianGatewayAuthorizationException => HistorianWriteOutcome.RetryPlease,
- // A base client exception wrapping a permanent/transient RpcException → classify by inner status.
- HistorianGatewayException { InnerException: RpcException inner } => ClassifyStatus(inner.StatusCode),
- // Defensive raw RpcException path (the seam type signature permits it).
- RpcException rpc => ClassifyStatus(rpc.StatusCode),
- // Anything else (incl. a bare base client exception we cannot classify) → dead-letter to avoid
- // an infinite drain loop on a poison event.
- _ => HistorianWriteOutcome.PermanentFail,
- };
+ ///
+ /// Classifies a gateway failure. A failure carrying a gRPC status (the typed client exceptions, the base client
+ /// exception wrapping an , or a raw one) is classified by that status; anything without
+ /// one is a transport-level fault and retries. Never dead-letter on what might be an outage (lmxopcua#976 G-8).
+ ///
+ private static HistorianWriteOutcome Classify(Exception exception) =>
+ StatusOf(exception) is { } code ? ClassifyStatus(code) : HistorianWriteOutcome.RetryPlease;
+ ///
+ /// Only the codes that prove the EVENT is bad dead-letter; every other code — transient, auth, Cancelled
+ /// (server-side cancellation), Unknown (unmapped server fault), DataLoss, and any code this list does
+ /// not name — retries.
+ ///
private static HistorianWriteOutcome ClassifyStatus(StatusCode code) => code switch
{
- StatusCode.Unavailable
- or StatusCode.DeadlineExceeded
- or StatusCode.ResourceExhausted
- or StatusCode.Aborted
- or StatusCode.Internal
- // An auth fix re-enables the whole batch — never dead-letter on an auth blip.
- or StatusCode.Unauthenticated
- or StatusCode.PermissionDenied => HistorianWriteOutcome.RetryPlease,
StatusCode.InvalidArgument
or StatusCode.FailedPrecondition
or StatusCode.OutOfRange
+ or StatusCode.NotFound
+ or StatusCode.AlreadyExists
or StatusCode.Unimplemented => HistorianWriteOutcome.PermanentFail,
- // Unknown/unclassified gRPC code → dead-letter to avoid an infinite drain loop.
- _ => HistorianWriteOutcome.PermanentFail,
+ _ => HistorianWriteOutcome.RetryPlease,
};
///
diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway/Recorder/FasterLogHistorizationOutbox.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway/Recorder/FasterLogHistorizationOutbox.cs
index bc97933b5..97a3ae42b 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway/Recorder/FasterLogHistorizationOutbox.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway/Recorder/FasterLogHistorizationOutbox.cs
@@ -16,7 +16,10 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Recorder;
/// policy: when an append would exceed capacity, the head is advanced past the oldest
/// entry (truncate + commit) and is incremented. Assumes serialized
/// appends (the recorder actor processes messages sequentially); the lock protects the in-memory
-/// index, and FasterLog itself tolerates concurrent enqueue/scan.
+/// index, and FasterLog itself tolerates concurrent enqueue/scan. Appends DO run concurrently
+/// with the drain's peek/remove, and an append enqueues before it indexes, so neither side may
+/// reason from the live tail: a peek returns only indexed records, and a remove truncates to
+/// the acked record's own end, never past it (G-7, lmxopcua#976).
///
public sealed class FasterLogHistorizationOutbox : IHistorizationOutbox
{
@@ -42,6 +45,11 @@ public sealed class FasterLogHistorizationOutbox : IHistorizationOutbox
private readonly LinkedList _live = new();
private readonly Dictionary> _index = new();
private long _nextScanAddress; // authoritative logical head; peeks scan from here
+ // The last record the most recent peek returned: its start address and the scan's `next` address after it (the
+ // record's end, a valid truncation point). RemoveAsync of the NEWEST indexed entry truncates to that end — never to
+ // the live tail, which may already hold an append that is enqueued but not yet indexed (G-7, #976).
+ private long _lastPeekedStart = -1;
+ private long _lastPeekedEnd;
private long _droppedCount;
private long _unreadableCount;
@@ -149,6 +157,8 @@ public sealed class FasterLogHistorizationOutbox : IHistorizationOutbox
HistorizationOutboxEntry entry = entries[i];
byte[] payload = HistorizationOutboxEntrySerializer.Serialize(entry);
long start = await _log.EnqueueAsync(payload, ct).ConfigureAwait(false);
+ if (AfterEnqueueForTests is { } parked)
+ await parked().ConfigureAwait(false);
lock (_state)
{
_index[entry.Id] = _live.AddLast(new LiveEntry(entry.Id, start));
@@ -183,7 +193,7 @@ public sealed class FasterLogHistorizationOutbox : IHistorizationOutbox
while (_capacity > 0 && _live.Count > _capacity)
{
LinkedListNode oldest = _live.First!;
- truncateTo = oldest.Next?.Value.Start ?? _log.TailAddress;
+ truncateTo = oldest.Next?.Value.Start ?? EndOfRecordAt(oldest.Value.Start);
_index.Remove(oldest.Value.Id);
_live.RemoveFirst();
_droppedCount++;
@@ -216,29 +226,47 @@ public sealed class FasterLogHistorizationOutbox : IHistorizationOutbox
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(max);
- long from, tail;
+ long from, tail, lastIndexed;
lock (_state)
{
from = _nextScanAddress;
tail = _log.TailAddress;
+ // Only INDEXED records are returned (G-7, #976): a record past the newest indexed one belongs to an append that
+ // has enqueued but not yet indexed it. Returning it would make its id un-ackable (RemoveAsync no-ops on an
+ // unknown id) and the whole batch would be re-sent; it is peeked on the next pass, once indexed.
+ lastIndexed = _live.Last?.Value.Start ?? -1;
}
var batch = new List(Math.Min(max, 64));
List<(long Address, long Next, bool LeadsBatch)>? unreadable = null;
- using (FasterLogScanIterator iter = _log.Scan(from, tail, recover: false))
+ long lastStart = -1, lastEnd = 0;
+ if (lastIndexed >= from)
{
+ using FasterLogScanIterator iter = _log.Scan(from, tail, recover: false);
while (batch.Count < max && iter.GetNext(out byte[] bytes, out int len, out long address, out long next))
{
+ if (address > lastIndexed)
+ break;
ScanStepForTests?.Invoke();
if (HistorizationOutboxEntrySerializer.TryDeserialize(bytes.AsSpan(0, len), out HistorizationOutboxEntry? entry))
{
batch.Add(entry);
+ (lastStart, lastEnd) = (address, next);
continue;
}
(unreadable ??= []).Add((address, next, batch.Count == 0));
}
}
+ if (lastStart >= 0)
+ {
+ lock (_state)
+ {
+ _lastPeekedStart = lastStart;
+ _lastPeekedEnd = lastEnd;
+ }
+ }
+
long? droppedHeadTo = null;
if (unreadable is not null)
{
@@ -286,6 +314,9 @@ public sealed class FasterLogHistorizationOutbox : IHistorizationOutbox
return batch;
}
+ /// Test seam: awaited after each append's enqueue returns and BEFORE it is indexed (the G-7 window).
+ internal Func? AfterEnqueueForTests { get; set; }
+
/// Test seam: invoked once per record the peek scans, OUTSIDE the state lock.
internal Action? ScanStepForTests { get; set; }
@@ -298,7 +329,9 @@ public sealed class FasterLogHistorizationOutbox : IHistorizationOutbox
if (!_index.TryGetValue(id, out LinkedListNode? node))
return; // unknown / already removed -> defensive no-op
- truncateTo = node.Next?.Value.Start ?? _log.TailAddress;
+ // Never the live tail (G-7, #976): an append may have enqueued past the newest indexed entry and not yet indexed
+ // it, and truncating to the tail would silently discard that value.
+ truncateTo = node.Next?.Value.Start ?? EndOfRecordAt(node.Value.Start);
// FIFO ack: remove the target plus any older entries still ahead of it.
while (_live.First is { } first)
{
@@ -316,6 +349,18 @@ public sealed class FasterLogHistorizationOutbox : IHistorizationOutbox
await _log.CommitAsync(ct).ConfigureAwait(false); // make the head advance durable
}
+ // The address just past the record starting at `start` — a valid truncation point that covers that record and nothing
+ // after it. Caller holds _state. The newest indexed entry is normally the last record the drain peeked, whose end the
+ // peek recorded; otherwise a one-record scan finds it. If even that fails, the record's own start is returned: the
+ // target then stays in the log and may be re-delivered (a duplicate), never lost.
+ private long EndOfRecordAt(long start)
+ {
+ if (start == _lastPeekedStart)
+ return _lastPeekedEnd;
+ using FasterLogScanIterator iter = _log.Scan(start, _log.TailAddress, recover: false);
+ return iter.GetNext(out _, out _, out long address, out long next) && address == start ? next : start;
+ }
+
///
public ValueTask CountAsync(CancellationToken ct)
{
diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb/QuestDbAlarmHistorianWriter.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb/QuestDbAlarmHistorianWriter.cs
index e61eb1346..d8a74af5d 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb/QuestDbAlarmHistorianWriter.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb/QuestDbAlarmHistorianWriter.cs
@@ -75,6 +75,7 @@ internal sealed class QuestDbAlarmHistorianWriter : IAlarmHistorianWriter
var outcomes2 = await AlarmBatchWrite.RunAsync(slots, ChunkRows,
(indexes, ct) => InsertChunkAsync(batch, indexes, ct),
Classify,
+ QuestDbConnection.IsTransient,
(ex, outcome) => _log.LogWarning("QuestDB alarm event write failed ({Exception}); outcome {Outcome}.", ex.GetType().Name, outcome),
cancellationToken).ConfigureAwait(false);
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 448caf183..346aa6386 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
@@ -8,12 +8,17 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common;
///
/// - 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);
-/// - a chunk failing -class (transient: the database is down or
+///
- a chunk failing with a KNOWN transient error (the caller's isTransient: 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;
/// - a chunk failing -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;
+/// - 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;
/// - a cancellation of the caller's token makes every event not yet decided RetryPlease (never a dead letter).
///
///
@@ -27,6 +32,10 @@ public static class AlarmBatchWrite
/// Events per statement (at least 1).
/// Writes the events at the given batch indexes in ONE statement; throws on failure.
/// Maps a write failure to the outcome it implies (see the summary for multi-event chunks).
+ ///
+ /// 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.
+ ///
/// Optional diagnostic hook per failure (the exception and its classified outcome).
/// The drain's cancellation token.
/// The filled outcomes.
@@ -34,12 +43,14 @@ public static class AlarmBatchWrite
HistorianWriteOutcome?[] outcomes, int chunkSize,
Func, CancellationToken, Task> writeChunk,
Func classify,
+ Func isTransient,
Action? onFailure,
CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(outcomes);
ArgumentNullException.ThrowIfNull(writeChunk);
ArgumentNullException.ThrowIfNull(classify);
+ ArgumentNullException.ThrowIfNull(isTransient);
chunkSize = Math.Max(1, chunkSize);
var pending = new List(outcomes.Length);
@@ -49,12 +60,12 @@ 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 = await TryAsync(chunk).ConfigureAwait(false);
- if (outcome == HistorianWriteOutcome.PermanentFail && chunk.Count > 1)
+ 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.
foreach (var index in chunk)
- outcomes[index] = await TryAsync([index]).ConfigureAwait(false);
+ outcomes[index] = (await TryAsync([index]).ConfigureAwait(false)).Outcome;
continue;
}
foreach (var index in chunk) outcomes[index] ??= outcome;
@@ -64,23 +75,24 @@ public static class AlarmBatchWrite
for (var i = 0; i < outcomes.Length; i++) result[i] = outcomes[i] ?? HistorianWriteOutcome.RetryPlease;
return result;
- async Task TryAsync(IReadOnlyList indexes)
+ // 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)
{
- if (ct.IsCancellationRequested) return HistorianWriteOutcome.RetryPlease;
+ if (ct.IsCancellationRequested) return (HistorianWriteOutcome.RetryPlease, false);
try
{
await writeChunk(indexes, ct).ConfigureAwait(false);
- return HistorianWriteOutcome.Ack;
+ return (HistorianWriteOutcome.Ack, false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
- return HistorianWriteOutcome.RetryPlease; // shutdown: never a dead letter
+ return (HistorianWriteOutcome.RetryPlease, false); // shutdown: never a dead letter
}
catch (Exception ex)
{
var o = classify(ex);
onFailure?.Invoke(ex, o);
- return o;
+ return (o, o == HistorianWriteOutcome.PermanentFail || (o == HistorianWriteOutcome.RetryPlease && !isTransient(ex)));
}
}
}
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 583194388..914cb3a83 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,6 +71,7 @@ internal sealed class SqlServerAlarmHistorianWriter : IAlarmHistorianWriter
var written = await AlarmBatchWrite.RunAsync(slots, ChunkRows,
(indexes, ct) => WriteChunkAsync(batch, ids, indexes, ct),
ClassifyChunk,
+ SqlHistorianConnection.IsTransient,
(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/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian.Tests/LocalDbStoreAndForwardSinkTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian.Tests/LocalDbStoreAndForwardSinkTests.cs
index 97d686796..8f5701631 100644
--- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian.Tests/LocalDbStoreAndForwardSinkTests.cs
+++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian.Tests/LocalDbStoreAndForwardSinkTests.cs
@@ -420,32 +420,176 @@ public sealed class LocalDbStoreAndForwardSinkTests : IDisposable
///
/// Regression for finding 002: a permanently-malformed (poison) event that the
/// writer can only ever map to
- /// must NOT retry forever. After maxAttempts retry-please drains the row
- /// is dead-lettered so the queue head can never stall on it indefinitely.
+ /// must NOT retry forever. After maxAttempts retry-please drains in which the
+ /// historian proved reachable (its neighbours Ack'd) the row is dead-lettered, so the
+ /// queue head can never stall on it indefinitely.
///
[Fact]
public async Task RetryPlease_dead_letters_row_after_MaxAttempts()
{
- var writer = new FakeWriter { DefaultOutcome = HistorianWriteOutcome.RetryPlease };
- using var sink = new LocalDbStoreAndForwardSink(
- Db, writer, _log, maxAttempts: 3);
+ var writer = new OutageWriter();
+ writer.RetryForever.Add("poison");
+ using var sink = new LocalDbStoreAndForwardSink(Db, writer, _log, maxAttempts: 3);
+ var clock = new DateTime(2026, 7, 21, 0, 0, 0, DateTimeKind.Utc);
- await sink.EnqueueAsync(Event("poison"), CancellationToken.None);
+ await sink.EnqueueAsync(Event("poison", clock), CancellationToken.None);
- // Drain 1 + 2: still retrying — the row stays queued, not yet dead-lettered.
- await sink.DrainOnceAsync(CancellationToken.None);
- sink.GetStatus().QueueDepth.ShouldBe(1, "after 1 attempt the row is still queued");
- sink.GetStatus().DeadLetterDepth.ShouldBe(0, "not yet dead-lettered after 1 attempt");
+ // Each drain carries one healthy neighbour that Acks — the evidence the historian is reachable.
+ for (var attempt = 1; attempt <= 2; attempt++)
+ {
+ await sink.EnqueueAsync(Event($"healthy-{attempt}", clock.AddSeconds(attempt)), CancellationToken.None);
+ await sink.DrainOnceAsync(CancellationToken.None);
+ sink.GetStatus().QueueDepth.ShouldBe(1, $"after {attempt} counted attempt(s) the poison row is still queued");
+ sink.GetStatus().DeadLetterDepth.ShouldBe(0, $"not yet dead-lettered after {attempt} attempt(s)");
+ }
- await sink.DrainOnceAsync(CancellationToken.None);
- sink.GetStatus().QueueDepth.ShouldBe(1, "after 2 attempts the row is still queued");
- sink.GetStatus().DeadLetterDepth.ShouldBe(0, "not yet dead-lettered after 2 attempts");
-
- // Drain 3: the 3rd attempt hits the cap — dead-letter it.
+ // Drain 3: the 3rd counted attempt hits the cap — dead-letter it.
+ await sink.EnqueueAsync(Event("healthy-3", clock.AddSeconds(3)), CancellationToken.None);
await sink.DrainOnceAsync(CancellationToken.None);
var status = sink.GetStatus();
status.QueueDepth.ShouldBe(0, "row left the live queue once max attempts exceeded");
status.DeadLetterDepth.ShouldBe(1, "poison row dead-lettered at the max-attempts cap");
+ writer.Written.ShouldBe(["healthy-1", "healthy-2", "healthy-3"]);
+ }
+
+ ///
+ /// G-16 / K-2 (#976): an outage longer than the attempt cap's backoff span (~6.5 min) used to
+ /// dead-letter queued alarm history, because every writer answers an outage with
+ /// and every RetryPlease counted against
+ /// MaxAttempts. A drain in which NOTHING was Ack'd is an outage: it backs off,
+ /// capped, and counts nothing. Simulated hours of outage (fake clock advanced by the sink's own
+ /// backoff) with alarms still arriving, then reconnect: zero dead letters, every event written
+ /// once, in enqueue order.
+ ///
+ [Fact]
+ public async Task A_long_historian_outage_dead_letters_nothing_and_reconnect_drains_everything_in_order()
+ {
+ var now = new DateTime(2026, 7, 21, 0, 0, 0, DateTimeKind.Utc);
+ var writer = new OutageWriter { Down = true };
+ using var sink = new LocalDbStoreAndForwardSink(Db, writer, _log, batchSize: 10, maxAttempts: 10, clock: () => now);
+ var expected = new List();
+ var start = now;
+
+ async Task EnqueueAsync(string id)
+ {
+ now = now.AddMilliseconds(1);
+ await sink.EnqueueAsync(Event(id, now), CancellationToken.None);
+ expected.Add(id);
+ }
+
+ for (var i = 0; i < 25; i++) await EnqueueAsync($"pre-{i:D3}");
+
+ // 20× the attempt cap of drain cycles, the clock advancing by the backoff the sink chose each time.
+ for (var cycle = 0; cycle < 200; cycle++)
+ {
+ if (cycle % 20 == 0) await EnqueueAsync($"during-{cycle:D3}");
+ await sink.DrainOnceAsync(CancellationToken.None);
+ sink.GetStatus().DrainState.ShouldBe(HistorianDrainState.BackingOff);
+ now += sink.CurrentBackoff;
+ }
+
+ (now - start).ShouldBeGreaterThan(TimeSpan.FromHours(3), "the simulated outage far outlasts the old ~6.5 min cap");
+ sink.CurrentBackoff.ShouldBe(TimeSpan.FromSeconds(60), "outage retries back off, capped");
+ sink.GetStatus().DeadLetterDepth.ShouldBe(0, "an outage is not a poison event");
+ sink.GetStatus().QueueDepth.ShouldBe(expected.Count);
+ sink.GetStatus().LastError.ShouldNotBeNull("an outage is visible on the status while it lasts");
+ writer.Written.ShouldBeEmpty();
+
+ // Reconnect.
+ writer.Down = false;
+ for (var i = 0; i < 10 && sink.GetStatus().QueueDepth > 0; i++)
+ {
+ await sink.DrainOnceAsync(CancellationToken.None);
+ now += TimeSpan.FromSeconds(5);
+ }
+
+ writer.Written.ShouldBe(expected, "every queued event delivered once, in enqueue order");
+ sink.GetStatus().QueueDepth.ShouldBe(0);
+ sink.GetStatus().DeadLetterDepth.ShouldBe(0);
+ sink.CurrentBackoff.ShouldBe(TimeSpan.FromSeconds(1), "a clean drain resets the backoff");
+ sink.GetStatus().LastError.ShouldBeNull();
+ }
+
+ ///
+ /// Positive control for the outage test: the outage rule must not blunt dead-lettering. A genuinely
+ /// permanent failure still dead-letters at once — even on a drain where nothing else got through — and a
+ /// RetryPlease-forever poison row still dead-letters after MaxAttempts drains that proved the
+ /// historian reachable. The outage drains it sat through never counted, so it gets its full budget and
+ /// no more.
+ ///
+ [Fact]
+ public async Task After_an_outage_a_permanent_failure_still_dead_letters_and_a_poison_row_gets_exactly_its_budget()
+ {
+ var now = new DateTime(2026, 7, 21, 0, 0, 0, DateTimeKind.Utc);
+ var writer = new OutageWriter { Down = true };
+ writer.Permanent.Add("permanent");
+ writer.RetryForever.Add("poison");
+ using var sink = new LocalDbStoreAndForwardSink(Db, writer, _log, batchSize: 10, maxAttempts: 4, clock: () => now);
+
+ now = now.AddMilliseconds(1); await sink.EnqueueAsync(Event("poison", now), CancellationToken.None);
+ for (var cycle = 0; cycle < 50; cycle++)
+ {
+ await sink.DrainOnceAsync(CancellationToken.None);
+ now += sink.CurrentBackoff;
+ }
+ sink.GetStatus().DeadLetterDepth.ShouldBe(0, "nothing counts during the outage");
+
+ // A writer-decided permanent refusal (no historian contact — e.g. QuestDB's pre-1970 time) during the outage:
+ // it dead-letters, and it is NOT evidence the historian is up, so the poison row is still not counted.
+ writer.PermanentEvenWhenDown = true;
+ now = now.AddMilliseconds(1); await sink.EnqueueAsync(Event("permanent", now), CancellationToken.None);
+ for (var cycle = 0; cycle < 10; cycle++)
+ {
+ await sink.DrainOnceAsync(CancellationToken.None);
+ now += sink.CurrentBackoff;
+ }
+ sink.GetStatus().DeadLetterDepth.ShouldBe(1, "a PermanentFail dead-letters even on a drain with no Ack");
+ sink.GetStatus().QueueDepth.ShouldBe(1, "…and the poison row was not charged for it");
+
+ writer.Down = false;
+ for (var attempt = 1; attempt <= 4; attempt++)
+ {
+ now = now.AddMilliseconds(1);
+ await sink.EnqueueAsync(Event($"healthy-{attempt}", now), CancellationToken.None);
+ await sink.DrainOnceAsync(CancellationToken.None);
+ if (attempt < 4)
+ sink.GetStatus().QueueDepth.ShouldBe(1, $"the poison row survives {attempt} counted attempt(s)");
+ }
+
+ sink.GetStatus().QueueDepth.ShouldBe(0);
+ sink.GetStatus().DeadLetterDepth.ShouldBe(2, "the poison row dead-letters on its 4th counted attempt, not before");
+ writer.Written.ShouldBe(["healthy-1", "healthy-2", "healthy-3", "healthy-4"]);
+ }
+
+ ///
+ /// A historian that is either down (every event RetryPlease — what every production writer answers to an
+ /// outage) or up (Ack, except the named poison events). Records what it accepted, in order.
+ ///
+ private sealed class OutageWriter : IAlarmHistorianWriter
+ {
+ public bool Down { get; set; }
+ public bool PermanentEvenWhenDown { get; set; }
+ public HashSet Permanent { get; } = [];
+ public HashSet RetryForever { get; } = [];
+ public List Written { get; } = [];
+
+ public Task> WriteBatchAsync(
+ IReadOnlyList batch, CancellationToken ct)
+ {
+ var outcomes = new HistorianWriteOutcome[batch.Count];
+ for (var i = 0; i < batch.Count; i++)
+ {
+ var id = batch[i].AlarmId;
+ if (Permanent.Contains(id) && (!Down || PermanentEvenWhenDown)) outcomes[i] = HistorianWriteOutcome.PermanentFail;
+ else if (Down || RetryForever.Contains(id)) outcomes[i] = HistorianWriteOutcome.RetryPlease;
+ else
+ {
+ outcomes[i] = HistorianWriteOutcome.Ack;
+ Written.Add(id);
+ }
+ }
+ return Task.FromResult>(outcomes);
+ }
}
/// Verifies that NullAlarmHistorianSink reports disabled status.
diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayAlarmHistorianWriterTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayAlarmHistorianWriterTests.cs
index 0e159179b..0d37ee3d7 100644
--- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayAlarmHistorianWriterTests.cs
+++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayAlarmHistorianWriterTests.cs
@@ -127,9 +127,10 @@ public sealed class GatewayAlarmHistorianWriterTests
}
[Fact]
- public async Task Bare_base_typed_exception_is_PermanentFail()
+ public async Task Bare_base_typed_exception_is_RetryPlease()
{
- // No classifiable inner status → default to PermanentFail to avoid infinite drain loops.
+ // No gRPC status ⇒ nothing proves the event bad ⇒ retry (#976 G-8; it used to dead-letter). A poison event is still
+ // bounded by the sink, which counts the retry whenever the same drain shows the historian reachable.
var fake = new FakeHistorianGatewayClient
{
SendEventThrows = new HistorianGatewayException("unclassifiable"),
@@ -137,7 +138,7 @@ public sealed class GatewayAlarmHistorianWriterTests
var outcomes = await Writer(fake).WriteBatchAsync(new[] { Evt("A") }, TestContext.Current.CancellationToken);
- Assert.Equal(HistorianWriteOutcome.PermanentFail, outcomes[0]);
+ Assert.Equal(HistorianWriteOutcome.RetryPlease, outcomes[0]);
}
// ---- Defensive raw RpcException path --------------------------------------------------------
@@ -192,13 +193,13 @@ public sealed class GatewayAlarmHistorianWriterTests
}
[Fact]
- public async Task Unknown_exception_is_PermanentFail()
+ public async Task Unknown_exception_is_RetryPlease()
{
var fake = new FakeHistorianGatewayClient { SendEventThrows = new InvalidOperationException("boom") };
var outcomes = await Writer(fake).WriteBatchAsync(new[] { Evt("A") }, TestContext.Current.CancellationToken);
- Assert.Equal(HistorianWriteOutcome.PermanentFail, outcomes[0]);
+ Assert.Equal(HistorianWriteOutcome.RetryPlease, outcomes[0]);
}
[Fact]
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
new file mode 100644
index 000000000..7fbacdb4b
--- /dev/null
+++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayAlarmWriterTransientClassificationTests.cs
@@ -0,0 +1,141 @@
+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;
+
+///
+/// G-8 (#976): a transient gateway condition must never dead-letter alarm history. The gateway answers a server-side
+/// cancellation (shutdown / internal timeout) with Cancelled and an unmapped server fault with Unknown;
+/// a dropped channel surfaces as a plain transport exception. Only codes that prove the EVENT is bad dead-letter.
+///
+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.Instance);
+
+ /// The published client wraps every code it has no typed exception for in the base type, inner RpcException.
+ private static Exception Wrapped(StatusCode code) =>
+ new HistorianGatewayException(code.ToString(), new RpcException(new Status(code, code.ToString())));
+
+ public static TheoryData TransientCodes =>
+ [
+ StatusCode.Cancelled, StatusCode.Unknown, StatusCode.DataLoss, StatusCode.Unavailable, StatusCode.DeadlineExceeded,
+ StatusCode.ResourceExhausted, StatusCode.Aborted, StatusCode.Internal,
+ ];
+
+ [Theory]
+ [MemberData(nameof(TransientCodes))]
+ public async Task A_transient_code_from_SendEvents_retries_every_event_and_fans_out_nothing(StatusCode code)
+ {
+ var fake = new FakeHistorianGatewayClient
+ {
+ SendEventsSource = (_, _) => Task.FromException(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);
+ }
+
+ 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 InvalidOperationException("unexpected"),
+ ];
+
+ [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(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");
+ }
+ }
+}
diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/Recorder/FasterLogHistorizationOutboxTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/Recorder/FasterLogHistorizationOutboxTests.cs
index e6826aa2a..346299d69 100644
--- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/Recorder/FasterLogHistorizationOutboxTests.cs
+++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/Recorder/FasterLogHistorizationOutboxTests.cs
@@ -306,6 +306,77 @@ public sealed class FasterLogHistorizationOutboxTests : IDisposable
Assert.Equal(0, o.DroppedCount);
}
+ [Fact]
+ public async Task An_ack_racing_an_unindexed_append_never_truncates_that_append()
+ {
+ // G-7 (#976): the append loop and the drain run concurrently. An append advances the log tail in EnqueueAsync and
+ // indexes the entry only afterwards; an ack of the LAST indexed entry inside that gap used to truncate to the live
+ // tail — past the new, un-indexed record — so that value was silently never historized (and gone after restart).
+ var ct = TestContext.Current.CancellationToken;
+ var dir = NewTempDir();
+ var a = E("A", 1);
+ var b = E("B", 2);
+ {
+ using var o = new FasterLogHistorizationOutbox(dir, HistorizationCommitMode.PerEntry);
+ await o.AppendAsync(a, ct);
+ Assert.Equal(new[] { "A" }, (await o.PeekBatchAsync(10, ct)).Select(e => e.Tag));
+
+ var parked = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ o.AfterEnqueueForTests = async () =>
+ {
+ parked.TrySetResult();
+ await release.Task;
+ };
+ var append = Task.Run(async () => await o.AppendAsync(b, CancellationToken.None), ct);
+ await parked.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
+
+ await o.RemoveAsync(a.Id, ct); // the drain acks A while B is enqueued but not yet indexed
+
+ o.AfterEnqueueForTests = null;
+ release.SetResult();
+ await append.WaitAsync(TimeSpan.FromSeconds(10), ct);
+
+ Assert.Equal(1, await o.CountAsync(ct));
+ Assert.Equal(new[] { b.Id }, (await o.PeekBatchAsync(10, ct)).Select(e => e.Id));
+ }
+
+ // ...and the truncation that was made durable did not take B with it.
+ using var reopened = new FasterLogHistorizationOutbox(dir, HistorizationCommitMode.PerEntry);
+ Assert.Equal(new[] { b.Id }, (await reopened.PeekBatchAsync(10, ct)).Select(e => e.Id));
+ }
+
+ [Fact]
+ public async Task A_peek_returns_only_indexed_entries_so_every_peeked_entry_can_be_acked()
+ {
+ // The companion window: a peek that scans to the live tail returns a record whose append has not indexed it yet;
+ // the drain's RemoveAsync of that (last) id is then a no-op, so the whole batch is re-sent next pass.
+ var ct = TestContext.Current.CancellationToken;
+ using var o = new FasterLogHistorizationOutbox(NewTempDir(), HistorizationCommitMode.Periodic, commitIntervalMs: 10);
+ var a = E("A", 1);
+ await o.AppendAsync(a, ct);
+
+ var parked = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ o.AfterEnqueueForTests = async () =>
+ {
+ parked.TrySetResult();
+ await release.Task;
+ };
+ var append = Task.Run(async () => await o.AppendAsync(E("B", 2), CancellationToken.None), ct);
+ await parked.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
+ await Task.Delay(200, ct); // let the periodic commit make B scannable
+
+ var batch = await o.PeekBatchAsync(10, ct);
+
+ o.AfterEnqueueForTests = null;
+ release.SetResult();
+ await append.WaitAsync(TimeSpan.FromSeconds(10), ct);
+ Assert.Equal(new[] { a.Id }, batch.Select(e => e.Id));
+ // Positive control: once indexed, B is peeked.
+ Assert.Equal(new[] { "A", "B" }, (await o.PeekBatchAsync(10, ct)).Select(e => e.Tag));
+ }
+
[Fact]
public async Task Remove_unknown_id_is_noop()
{
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 cd6c18c93..d29362645 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
@@ -13,10 +13,13 @@ public sealed class AlarmBatchWriteTests
{
private sealed class PoisonException : Exception;
private sealed class OutageException : Exception;
+ private sealed class UnrecognisedException : Exception;
private static HistorianWriteOutcome Classify(Exception ex) =>
ex is PoisonException ? HistorianWriteOutcome.PermanentFail : HistorianWriteOutcome.RetryPlease;
+ private static bool IsTransient(Exception ex) => ex is OutageException;
+
private static HistorianWriteOutcome?[] Undecided(int n) => new HistorianWriteOutcome?[n];
[Fact]
@@ -24,7 +27,7 @@ public sealed class AlarmBatchWriteTests
{
var statements = new List();
var r = await AlarmBatchWrite.RunAsync(Undecided(25), 10,
- (ix, _) => { statements.Add(ix.ToArray()); return Task.CompletedTask; }, Classify, null, CancellationToken.None);
+ (ix, _) => { statements.Add(ix.ToArray()); return Task.CompletedTask; }, Classify, IsTransient, null, CancellationToken.None);
r.ShouldAllBe(o => o == HistorianWriteOutcome.Ack);
statements.Select(s => s.Length).ShouldBe([10, 10, 5]);
@@ -40,7 +43,7 @@ public sealed class AlarmBatchWriteTests
statements++;
if (ix.Contains(3)) throw new PoisonException();
return Task.CompletedTask;
- }, Classify, null, CancellationToken.None);
+ }, Classify, IsTransient, null, CancellationToken.None);
r.ShouldBe([HistorianWriteOutcome.Ack, HistorianWriteOutcome.Ack, HistorianWriteOutcome.Ack,
HistorianWriteOutcome.PermanentFail, HistorianWriteOutcome.Ack, HistorianWriteOutcome.Ack]);
@@ -52,7 +55,7 @@ public sealed class AlarmBatchWriteTests
{
var statements = 0;
var r = await AlarmBatchWrite.RunAsync(Undecided(6), 10,
- (_, _) => { statements++; throw new OutageException(); }, Classify, null, CancellationToken.None);
+ (_, _) => { statements++; throw new OutageException(); }, Classify, IsTransient, null, CancellationToken.None);
r.ShouldAllBe(o => o == HistorianWriteOutcome.RetryPlease);
statements.ShouldBe(1);
@@ -65,7 +68,7 @@ public sealed class AlarmBatchWriteTests
var outcomes = Undecided(4);
outcomes[1] = HistorianWriteOutcome.PermanentFail; // e.g. a pre-1970 time on QuestDB
var r = await AlarmBatchWrite.RunAsync(outcomes, 10,
- (ix, _) => { sent.AddRange(ix); return Task.CompletedTask; }, Classify, null, CancellationToken.None);
+ (ix, _) => { sent.AddRange(ix); return Task.CompletedTask; }, Classify, IsTransient, null, CancellationToken.None);
r.ShouldBe([HistorianWriteOutcome.Ack, HistorianWriteOutcome.PermanentFail, HistorianWriteOutcome.Ack, HistorianWriteOutcome.Ack]);
sent.ShouldBe([0, 2, 3]);
@@ -79,7 +82,7 @@ public sealed class AlarmBatchWriteTests
{
if (ix.Contains(2)) { cts.Cancel(); ct.ThrowIfCancellationRequested(); }
return Task.CompletedTask;
- }, Classify, null, cts.Token);
+ }, Classify, IsTransient, null, cts.Token);
r.ShouldBe([HistorianWriteOutcome.Ack, HistorianWriteOutcome.Ack,
HistorianWriteOutcome.RetryPlease, HistorianWriteOutcome.RetryPlease, HistorianWriteOutcome.RetryPlease]);
@@ -94,9 +97,40 @@ public sealed class AlarmBatchWriteTests
if (ix.Count > 1) throw new PoisonException();
if (ix[0] == 1) { cts.Cancel(); ct.ThrowIfCancellationRequested(); }
return Task.CompletedTask;
- }, Classify, null, cts.Token);
+ }, Classify, IsTransient, null, cts.Token);
r.ShouldBe([HistorianWriteOutcome.Ack, HistorianWriteOutcome.RetryPlease, HistorianWriteOutcome.RetryPlease,
HistorianWriteOutcome.RetryPlease]);
}
+
+ [Fact]
+ public async Task An_unrecognised_chunk_failure_is_isolated_so_its_siblings_still_Ack()
+ {
+ // G-16 secondary effect (#976): an error the classifier does not recognise is RetryPlease — not proven permanent —
+ // but it is not a known outage either. Retrying the whole chunk tied every sibling to the poison event; isolating it
+ // lets the siblings land, and the store-and-forward sink (which counts a RetryPlease only when the same drain shows
+ // the historian reachable) dead-letters the poison event alone once it keeps failing.
+ var statements = 0;
+ var r = await AlarmBatchWrite.RunAsync(Undecided(3), 10, (ix, _) =>
+ {
+ statements++;
+ if (ix.Contains(1)) throw new UnrecognisedException();
+ return Task.CompletedTask;
+ }, Classify, IsTransient, null, CancellationToken.None);
+
+ r.ShouldBe([HistorianWriteOutcome.Ack, HistorianWriteOutcome.RetryPlease, HistorianWriteOutcome.Ack]);
+ statements.ShouldBe(1 + 3, "the failed chunk, then one statement per event");
+ }
+
+ [Fact]
+ public async Task A_known_outage_is_never_isolated_even_though_an_unrecognised_failure_is()
+ {
+ // Control for the test above: isolation keys on "not a KNOWN transient", not on RetryPlease.
+ var statements = 0;
+ var r = await AlarmBatchWrite.RunAsync(Undecided(3), 10,
+ (_, _) => { statements++; throw new OutageException(); }, Classify, IsTransient, null, CancellationToken.None);
+
+ r.ShouldAllBe(o => o == HistorianWriteOutcome.RetryPlease);
+ statements.ShouldBe(1);
+ }
}