diff --git a/docs/AlarmHistorian.md b/docs/AlarmHistorian.md
index 9432470c0..c6689d5d0 100644
--- a/docs/AlarmHistorian.md
+++ b/docs/AlarmHistorian.md
@@ -302,9 +302,15 @@ delivered or dead-lettered:
- gauge `otopcua.alarm_historian.queue.stalled` (1/0) plus `…queue.depth` / `…queue.dead_letter_depth`,
- the readiness check `alarm-historian`: **Degraded** (still 200, never Unhealthy).
-The sink cannot tell an outage from a retry-forever head (both look like "no Ack"), so it also fires
-on a long genuine outage; `LastError` says which. A node that is not the drain owner is never stalled
-and promotion restarts the clock.
+**Outage vs stuck (#1071).** A queue whose head is retry-forever rows and a long historian outage both look like
+"no Ack". The three writers (Gateway, SqlServer, QuestDB) therefore report `IAlarmHistorianWriter.LastReachableUtc` — the
+last write attempt the historian *answered* (success or a data-level refusal; a transport/outage failure such as gRPC
+`Unavailable`/deadline/auth, or a transient SQL fault, does not count). When no progress has been made for the threshold:
+the historian answered within the last 5 minutes ⇒ **`Stalled`** (a stuck head); it has not ⇒
+**`HistorianUnreachable`** (rows are merely held; `Stalled` stays false, the `queue.stalled` gauge reads 0, the
+Warning says "HELD by a historian outage", and the readiness check is still **Degraded** with an outage description).
+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.
### Durability bound (important)
diff --git a/infra/README.md b/infra/README.md
index 0315de8be..c4d5d6f28 100644
--- a/infra/README.md
+++ b/infra/README.md
@@ -66,6 +66,7 @@ Nuclear reset: `ssh dohertj2@10.100.0.35 'cd /opt/otopcua-mssql && docker compos
| Creds (dev) | QuestDB stock default `admin` / `quest` (throwaway fixture credential) |
| Env var | `HISTORIAN_QUESTDB_TEST_CONNECTION='Host=10.100.0.35;Port=8812;Username=admin;Password=quest;Database=qdb;ServerCompatibilityMode=NoTypeLoading'` |
| Used by | `Driver.Historian.QuestDb.IntegrationTests` (incl. the shared `Historian.Conformance` suite); absent env var ⇒ every test skips |
+| Table hygiene (#1062) | Every test table is `t<12 hex>_*`. `QuestDbFixture` drops each prefix on teardown (per-table retry, one failure never abandons the rest) and records each prefix in `otopcua_test_prefix_registry`; at start it drops `t<12 hex>_*` tables whose prefix was registered > 1 day ago and adopts unregistered ones (dropped a day later). Manual check: `curl -G http://10.100.0.35:19000/exec --data-urlencode 'query=select table_name from tables()'`. |
Deploy / update (the `/opt` dir was created with `sudo mkdir` + `chown dohertj2`):
diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian/IAlarmHistorianSink.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian/IAlarmHistorianSink.cs
index dec354379..01bd83512 100644
--- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian/IAlarmHistorianSink.cs
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian/IAlarmHistorianSink.cs
@@ -65,8 +65,15 @@ public sealed class NullAlarmHistorianSink : IAlarmHistorianSink
///
///
/// true when rows are queued on a node that owns the drain and nothing has been delivered or dead-lettered for the
-/// configured stall threshold (#1034). Fires on both a long historian outage and a queue head of rows that always answer
-/// retry; says which. Always false when no threshold is configured.
+/// configured stall threshold (#1034) while the historian is (or is not known to be not) reachable — a queue head of rows that
+/// always answer retry, or a writer that cannot report reachability (then it also fires on a long outage; #1071: a writer
+/// that reports reachability moves a pure outage to instead). Always false
+/// when no threshold is configured.
+///
+///
+/// true when the queue has made no progress for the stall threshold (#1071) but the writer reports the historian
+/// itself unreachable (no write has reached it recently) — an outage, not a stuck queue; the rows are simply held.
+/// is then false. Always false for a writer that does not report reachability.
///
/// UTC of the last time the queue made progress (a row delivered or dead-lettered) or was seen empty; null when not tracked (no drain yet, or not the drain owner).
public sealed record HistorianSinkStatus(
@@ -78,7 +85,8 @@ public sealed record HistorianSinkStatus(
HistorianDrainState DrainState,
long EvictedCount = 0,
bool Stalled = false,
- DateTime? LastProgressUtc = null);
+ DateTime? LastProgressUtc = null,
+ bool HistorianUnreachable = false);
/// Where the drain worker is in its state machine.
public enum HistorianDrainState
@@ -121,4 +129,29 @@ public interface IAlarmHistorianWriter
/// One per event, in the same order as .
Task> WriteBatchAsync(
IReadOnlyList batch, CancellationToken cancellationToken);
+
+ ///
+ /// Whether this writer tracks (#1071). Default false: the sink cannot tell an
+ /// outage from a stuck queue and stall detection keeps its #1034 meaning.
+ ///
+ bool ReportsReachability => false;
+
+ ///
+ /// UTC of the last write attempt that REACHED the historian (it answered — success or a data-level refusal; a
+ /// transport/outage failure does not count), or null when none yet. Meaningful only when
+ /// .
+ ///
+ DateTime? LastReachableUtc => null;
+}
+
+/// Cheap thread-safe "last time the historian answered" stamp a writer keeps for (#1071).
+public sealed class HistorianReachability
+{
+ private long _ticks;
+
+ /// Records that the historian just answered.
+ public void Touch() => Interlocked.Exchange(ref _ticks, DateTime.UtcNow.Ticks);
+
+ /// The last answer time, or null when it has never answered.
+ public DateTime? LastUtc => Interlocked.Read(ref _ticks) is var t and > 0 ? new DateTime(t, DateTimeKind.Utc) : null;
}
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 36b9fe83a..2d56f9964 100644
--- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian/LocalDbStoreAndForwardSink.cs
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian/LocalDbStoreAndForwardSink.cs
@@ -114,6 +114,7 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
// transition-only logging.
private DateTime? _progressUtc;
private bool _wasStalled;
+ private bool _wasOutage;
private long _queuedRowCount;
// Cached dead-letter depth (R05:7). GetStatus used to run a synchronous COUNT(*) table scan per
@@ -552,28 +553,54 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
/// Whether the queue is stalled at (#1034): rows are queued, this node owns the drain, and
/// nothing has left the queue for at least the threshold. Pure over the supplied state.
///
- private bool IsStalled(DateTime now, long queued, HistorianDrainState state, DateTime? progressUtc) =>
+ private bool IsNoProgress(DateTime now, long queued, HistorianDrainState state, DateTime? progressUtc) =>
_stallThreshold is { } threshold
&& queued > 0
&& state is not (HistorianDrainState.NotPrimary or HistorianDrainState.Disabled)
&& progressUtc is { } p
&& now - p >= threshold;
+ /// How recently the historian must have answered for it to count as reachable (#1071).
+ internal static readonly TimeSpan ReachabilityWindow = TimeSpan.FromMinutes(5);
+
+ ///
+ /// Classifies a no-progress queue (#1071): Stalled = the queue is stuck (historian reachable, or the writer cannot
+ /// say); Outage = the writer reports the historian unreachable, so the rows are merely held.
+ ///
+ private (bool Stalled, bool Outage) Classify(DateTime now, long queued, HistorianDrainState state, DateTime? progressUtc)
+ {
+ if (!IsNoProgress(now, queued, state, progressUtc)) return (false, false);
+ if (!_writer.ReportsReachability) return (true, false);
+ var reachable = _writer.LastReachableUtc is { } r && now - r < ReachabilityWindow;
+ return reachable ? (true, false) : (false, true);
+ }
+
/// Logs a stall once on entering it (and once on leaving it); called after every drain tick.
private void ObserveStall()
{
if (_stallThreshold is null) return;
var queued = Interlocked.Read(ref _queuedRowCount);
- bool stalled, changed;
+ bool stalled, changed, outage, outageChanged;
DateTime? progress;
string? lastError;
lock (_statusLock)
{
progress = _progressUtc;
lastError = _lastError;
- stalled = IsStalled(_clock(), queued, _drainState, progress);
+ (stalled, outage) = Classify(_clock(), queued, _drainState, progress);
changed = stalled != _wasStalled;
_wasStalled = stalled;
+ outageChanged = outage != _wasOutage;
+ _wasOutage = outage;
+ }
+ if (outageChanged)
+ {
+ if (outage)
+ _logger.Warning(
+ "Alarm historian queue HELD by a historian outage: {Queued} event(s) queued, none delivered since {Since:O} (threshold {Threshold}) and the historian has not answered a write recently; last error: {LastError}",
+ queued, progress, _stallThreshold, lastError ?? "(none)");
+ else if (!stalled)
+ _logger.Information("Alarm historian outage over or queue progressing (no longer held)");
}
if (!changed) return;
if (stalled)
@@ -645,7 +672,7 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
HistorianDrainState drainState;
long evicted;
DateTime? progress;
- bool stalled;
+ bool stalled, outage;
lock (_statusLock)
{
lastDrain = _lastDrainUtc;
@@ -654,7 +681,7 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
drainState = _drainState;
evicted = _evictedCount;
progress = _progressUtc;
- stalled = IsStalled(_clock(), queued, drainState, progress);
+ (stalled, outage) = Classify(_clock(), queued, drainState, progress);
}
return new HistorianSinkStatus(
@@ -666,7 +693,8 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
DrainState: drainState,
EvictedCount: evicted,
Stalled: stalled,
- LastProgressUtc: progress);
+ LastProgressUtc: progress,
+ HistorianUnreachable: outage);
}
/// Operator action from Admin UI — retry every dead-lettered row. Non-cascading: they rejoin the regular queue + get a fresh backoff.
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 d7c78438a..a0500893f 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
@@ -68,6 +68,20 @@ public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDispos
private readonly IHistorianGatewayClient _client;
private readonly ILogger _logger;
+ private readonly HistorianReachability _reach = new();
+
+ ///
+ public bool ReportsReachability => true;
+
+ ///
+ public DateTime? LastReachableUtc => _reach.LastUtc;
+
+ // #1071: any gateway answer (success, or a failure that is not a systemic outage/transport fault) proves it reachable.
+ private void NoteAnswered(Exception ex)
+ {
+ if (!IsSystemicFailure(ex)) _reach.Touch();
+ }
+
/// Set once the gateway answers SendEvents with Unimplemented: single sends from then on.
private volatile bool _batchUnsupported;
@@ -162,6 +176,7 @@ public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDispos
try
{
reply = await _client.SendEventsAsync(events, cancellationToken).ConfigureAwait(false);
+ _reach.Touch();
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
@@ -171,6 +186,7 @@ public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDispos
}
catch (Exception exception)
{
+ NoteAnswered(exception);
if (StatusOf(exception) == StatusCode.Unimplemented)
{
_batchUnsupported = true;
@@ -312,6 +328,7 @@ public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDispos
{
var ack = await _client.SendEventAsync(mapped, cancellationToken)
.ConfigureAwait(false);
+ _reach.Touch();
return MapAck(ack);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
@@ -323,6 +340,7 @@ public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDispos
}
catch (Exception exception)
{
+ NoteAnswered(exception);
// NEVER throw out of the writer — the drain worker expects a per-event outcome. Classify
// and log only the failure category (no event content, hostnames, or credentials).
var outcome = Classify(exception);
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 d8a74af5d..e67898363 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
@@ -90,6 +90,14 @@ internal sealed class QuestDbAlarmHistorianWriter : IAlarmHistorianWriter
/// Events per INSERT: 12 bound parameters each.
internal const int ChunkRows = 500;
+ private readonly HistorianReachability _reach = new();
+
+ ///
+ public bool ReportsReachability => true;
+
+ ///
+ public DateTime? LastReachableUtc => _reach.LastUtc;
+
private long _statements;
/// INSERT statements sent so far (lifetime) — test/diagnostic.
@@ -126,7 +134,19 @@ internal sealed class QuestDbAlarmHistorianWriter : IAlarmHistorianWriter
}
cmd.CommandText = sql.ToString();
Interlocked.Increment(ref _statements);
- await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
+ try
+ {
+ await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
+ _reach.Touch();
+ }
+ catch (PostgresException ex) when (NoteAnswered(ex)) { throw; }
+ }
+
+ // #1071: a server-side refusal (not a transport/transient fault) proves the historian answered.
+ private bool NoteAnswered(Exception ex)
+ {
+ if (!QuestDbConnection.IsTransient(ex)) _reach.Touch();
+ return false;
}
/// Classifies a write exception as retryable or a permanent dead-letter failure.
diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb/QuestDbWalVisibility.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb/QuestDbWalVisibility.cs
index d416d737f..ad24ce116 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb/QuestDbWalVisibility.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb/QuestDbWalVisibility.cs
@@ -114,6 +114,41 @@ internal sealed class QuestDbWalVisibility
/// Whether polling can stop because the rows are visible.
internal static bool Reached(long writerTxn, long targetTxn) => writerTxn >= targetTxn;
+ /// One wal_tables() row: applied and sequenced transaction numbers + the suspended flag.
+ /// Last applied transaction.
+ /// Last sequenced (committed) transaction.
+ /// Whether the table's WAL apply is suspended.
+ internal readonly record struct WalState(long WriterTxn, long SequencerTxn, bool Suspended);
+
+ /// Reads a table's ; null when it is not a WAL table (or has no row).
+ /// Table name.
+ /// Cancellation.
+ internal delegate Task WalProbe(string table, CancellationToken ct);
+
+ private readonly WalProbe? _probeOverride;
+ private readonly Func _delay = static (d, ct) => Task.Delay(d, ct);
+ private readonly TimeProvider _time = TimeProvider.System;
+
+ ///
+ /// Test seam (#1072): a wait driven by a supplied (no database), a
+ /// and a so the timeout / suspended give-up paths can be forced deterministically.
+ ///
+ /// Supplies the WAL state.
+ /// Maximum wait.
+ /// Logger.
+ /// Replacement for (may advance ).
+ /// Clock the timeout is measured on.
+ internal QuestDbWalVisibility(WalProbe probe, TimeSpan timeout, ILogger log,
+ Func delay, TimeProvider time)
+ {
+ _conn = null!;
+ _probeOverride = probe;
+ _timeout = timeout;
+ _log = log;
+ _delay = delay;
+ _time = time;
+ }
+
/// Waits until everything this caller inserted into is visible to queries.
/// Full table name written to.
/// Cancellation.
@@ -125,33 +160,35 @@ internal sealed class QuestDbWalVisibility
{
if (Disabled) return true;
Interlocked.Increment(ref _waits);
- var sw = Stopwatch.StartNew();
- var delay = FirstPollInterval;
- await using var conn = await _conn.OpenAsync(ct).ConfigureAwait(false);
+ if (_probeOverride is not null) return await WaitCoreAsync(table, _probeOverride, ct).ConfigureAwait(false);
- long target;
- await using (var cmd = _conn.CreateCommand(conn, "SELECT sequencerTxn FROM wal_tables() WHERE name = $1"))
+ await using var conn = await _conn.OpenAsync(ct).ConfigureAwait(false);
+ return await WaitCoreAsync(table, async (t, token) =>
{
- QuestDbConnection.BindText(cmd, table);
- var o = await cmd.ExecuteScalarAsync(ct).ConfigureAwait(false);
- if (o is null or DBNull) return true; // not a WAL table: writes are immediately visible
- target = Convert.ToInt64(o);
- }
+ await using var cmd = _conn.CreateCommand(conn,
+ "SELECT writerTxn, sequencerTxn, suspended FROM wal_tables() WHERE name = $1");
+ QuestDbConnection.BindText(cmd, t);
+ await using var r = await cmd.ExecuteReaderAsync(token).ConfigureAwait(false);
+ if (!await r.ReadAsync(token).ConfigureAwait(false)) return null;
+ return (WalState?)new WalState(r.GetInt64(0), r.GetInt64(1), r.GetBoolean(2));
+ }, ct).ConfigureAwait(false);
+ }
+
+ private async Task WaitCoreAsync(string table, WalProbe probe, CancellationToken ct)
+ {
+ var started = _time.GetTimestamp();
+ var delay = FirstPollInterval;
+
+ // The target is captured once, after the caller's INSERT: a concurrent writer can only raise it.
+ if (await probe(table, ct).ConfigureAwait(false) is not { } first) return true; // not a WAL table: immediately visible
+ var target = first.SequencerTxn;
while (true)
{
- long writer;
- bool suspended;
- await using (var cmd = _conn.CreateCommand(conn, "SELECT writerTxn, suspended FROM wal_tables() WHERE name = $1"))
- {
- QuestDbConnection.BindText(cmd, table);
- await using var r = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false);
- if (!await r.ReadAsync(ct).ConfigureAwait(false)) return true;
- writer = r.GetInt64(0);
- suspended = r.GetBoolean(1);
- }
+ if (await probe(table, ct).ConfigureAwait(false) is not { } state) return true;
+ var writer = state.WriterTxn;
if (Reached(writer, target)) return true;
- if (suspended)
+ if (state.Suspended)
{
Interlocked.Increment(ref _failures);
RecordFailure(table, "suspended");
@@ -159,7 +196,8 @@ internal sealed class QuestDbWalVisibility
table, writer, target);
return false;
}
- if (sw.Elapsed >= _timeout)
+ var elapsed = _time.GetElapsedTime(started);
+ if (elapsed >= _timeout)
{
Interlocked.Increment(ref _failures);
RecordFailure(table, "timeout");
@@ -167,9 +205,9 @@ internal sealed class QuestDbWalVisibility
table, _timeout.TotalMilliseconds, writer, target);
return false;
}
- var remaining = _timeout - sw.Elapsed;
+ var remaining = _timeout - elapsed;
// Never sleep past the timeout (and never a negative delay if it elapsed in between).
- await Task.Delay(remaining <= TimeSpan.Zero ? TimeSpan.Zero : delay < remaining ? delay : remaining, ct)
+ await _delay(remaining <= TimeSpan.Zero ? TimeSpan.Zero : delay < remaining ? delay : remaining, ct)
.ConfigureAwait(false);
delay = NextPollInterval(delay);
}
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 7645ed9f9..d00762432 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
@@ -81,6 +81,14 @@ internal sealed class SqlServerAlarmHistorianWriter : IAlarmHistorianWriter
/// Events per statement: 11 parameters each, under SQL Server's 2,100-parameter limit.
internal const int ChunkRows = 150;
+ private readonly HistorianReachability _reach = new();
+
+ ///
+ public bool ReportsReachability => true;
+
+ ///
+ public DateTime? LastReachableUtc => _reach.LastUtc;
+
private long _statements;
/// Statements sent so far (lifetime) — test/diagnostic.
@@ -130,11 +138,21 @@ internal sealed class SqlServerAlarmHistorianWriter : IAlarmHistorianWriter
}
Interlocked.Increment(ref _statements);
await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
+ _reach.Touch();
}
// Single-row statement: a duplicate-key error means the row IS there (a concurrent writer won).
catch (SqlException ex) when (indexes.Count == 1 && SqlHistorianConnection.IsDuplicateKey(ex))
{
+ _reach.Touch();
}
+ catch (SqlException ex) when (NoteAnswered(ex)) { throw; }
+ }
+
+ // #1071: a server-side refusal (not a transport/transient fault) proves the historian answered.
+ private bool NoteAnswered(Exception ex)
+ {
+ if (!SqlHistorianConnection.IsTransient(ex)) _reach.Touch();
+ return false;
}
/// Classifies a write failure. Only a data error SQL Server will reject forever dead-letters; anything unknown or non-SQL retries (never lose alarm history).
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Health/AlarmHistorianHealthCheck.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Health/AlarmHistorianHealthCheck.cs
index d91f7dfa4..10c2cf475 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Health/AlarmHistorianHealthCheck.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Health/AlarmHistorianHealthCheck.cs
@@ -29,10 +29,19 @@ public static class AlarmHistorianHealthDecision
if (status.LastProgressUtc is { } progress) data["lastProgressUtc"] = progress.ToString("O");
if (status.LastError is { } error) data["lastError"] = error;
+ // #1071: an outage (the writer reports the historian not answering) is held rows, not a stuck queue — still Degraded
+ // (alarm history is not reaching the historian) but named for what it is.
+ if (status.HistorianUnreachable)
+ return (HealthStatus.Degraded,
+ $"Alarm history queue held by a historian outage: {status.QueueDepth} event(s) queued, none delivered since "
+ + $"{status.LastProgressUtc:O}; the historian has not answered a write recently"
+ + (status.LastError is null ? "." : $" (last error: {status.LastError})."),
+ data);
+
return status.Stalled
? (HealthStatus.Degraded,
$"Alarm history queue stalled: {status.QueueDepth} event(s) queued, none delivered or dead-lettered since "
- + $"{status.LastProgressUtc:O}. The historian is unreachable or the queue head is rows that always answer retry"
+ + $"{status.LastProgressUtc:O}. The historian is reachable, so the queue head is rows that always answer retry (or the writer cannot report reachability)"
+ (status.LastError is null ? "." : $" (last error: {status.LastError})."),
data)
: (HealthStatus.Healthy, $"Alarm history queue draining ({status.QueueDepth} queued).", data);
diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian.Tests/LocalDbStoreAndForwardSinkRecoveryTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian.Tests/LocalDbStoreAndForwardSinkRecoveryTests.cs
index 74fc39580..40c488adc 100644
--- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian.Tests/LocalDbStoreAndForwardSinkRecoveryTests.cs
+++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian.Tests/LocalDbStoreAndForwardSinkRecoveryTests.cs
@@ -207,4 +207,41 @@ public sealed partial class LocalDbStoreAndForwardSinkTests
on.GetStatus().QueueDepth.ShouldBe(0);
on.GetStatus().Stalled.ShouldBeFalse("nothing queued");
}
+
+ // ---------------------------------------------------------------------------------------------- #1071 outage vs stuck
+
+ /// A writer that answers RetryPlease for everything and reports (settable) historian reachability.
+ private sealed class ReachabilityWriter : IAlarmHistorianWriter
+ {
+ public DateTime? Reachable { get; set; }
+ public bool ReportsReachability => true;
+ public DateTime? LastReachableUtc => Reachable;
+
+ public Task> WriteBatchAsync(IReadOnlyList batch, CancellationToken ct) =>
+ Task.FromResult>(batch.Select(_ => HistorianWriteOutcome.RetryPlease).ToArray());
+ }
+
+ [Fact]
+ public async Task A_long_outage_is_reported_unreachable_not_stalled_and_a_reachable_historian_with_no_progress_is_stalled()
+ {
+ var now = new DateTime(2026, 12, 3, 0, 0, 0, DateTimeKind.Utc);
+ var writer = new ReachabilityWriter { Reachable = now.AddMinutes(-1) };
+ using var sink = new LocalDbStoreAndForwardSink(Db, writer, _log, clock: () => now, stallThreshold: Stall);
+ await sink.EnqueueAsync(Event("held", now), CancellationToken.None);
+ await sink.DrainOnceAsync(CancellationToken.None);
+
+ // Outage: the historian last answered long ago.
+ now += Stall + TimeSpan.FromMinutes(5);
+ await sink.DrainOnceAsync(CancellationToken.None);
+ var outage = sink.GetStatus();
+ outage.Stalled.ShouldBeFalse("an outage is not a stuck queue");
+ outage.HistorianUnreachable.ShouldBeTrue();
+
+ // Positive control: the same no-progress queue, but the historian answered a moment ago (rows keep answering retry).
+ writer.Reachable = now.AddSeconds(-30);
+ await sink.DrainOnceAsync(CancellationToken.None);
+ var stuck = sink.GetStatus();
+ stuck.Stalled.ShouldBeTrue("reachable historian + no progress = stuck head");
+ stuck.HistorianUnreachable.ShouldBeFalse();
+ }
}
diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb.IntegrationTests/QuestDbFixture.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb.IntegrationTests/QuestDbFixture.cs
index 2bfbcf5ab..628ad1cfb 100644
--- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb.IntegrationTests/QuestDbFixture.cs
+++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb.IntegrationTests/QuestDbFixture.cs
@@ -1,4 +1,5 @@
using System.Collections.Concurrent;
+using System.Text.RegularExpressions;
using Npgsql;
using Xunit;
@@ -9,6 +10,16 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb.IntegrationTests;
/// is set, nothing connects and every test calls Assert.Skip. Present ⇒ tests isolate
/// from each other with ; every prefix handed out is dropped on dispose (and a test may
/// drop its own early with ). Never touches a table outside those prefixes.
+///
+/// Leak hygiene (#1062). Teardown never lets one failed drop abandon the remaining prefixes (each prefix and each
+/// table is dropped independently, with retries — a table QuestDB reports busy is retried), and a killed run (no teardown)
+/// is covered by a stale sweep: every handed-out prefix is recorded with its time in the
+/// , and at fixture start any t<12 hex>_* table whose prefix was registered
+/// more than ago is dropped. A matching table with no registry row (a leak from before the
+/// registry, or a concurrent run of an older build) is adopted — registered now — so it is dropped one
+/// later, never while a live run could still own it. Only tables whose name matches
+/// are ever touched.
+///
///
public sealed class QuestDbFixture : IAsyncLifetime
{
@@ -17,6 +28,20 @@ public sealed class QuestDbFixture : IAsyncLifetime
private readonly ConcurrentBag _prefixes = new();
+ /// Records every prefix handed out and when (QuestDB has no table-creation time to age tables by).
+ public const string RegistryTable = "otopcua_test_prefix_registry";
+
+ /// How old a registered prefix must be before the start-of-fixture sweep drops its tables.
+ public static readonly TimeSpan StaleAfter = TimeSpan.FromDays(1);
+
+ /// The only table names the fixture ever drops: a (t + 12 hex + _) then anything.
+ public static readonly Regex TestTableName = new("^t[0-9a-f]{12}_", RegexOptions.Compiled | RegexOptions.CultureInvariant);
+
+ /// The 14-character a test table name starts with, or null when it is not a test table.
+ /// A table name.
+ /// The prefix, or null.
+ public static string? TestPrefixOf(string tableName) => TestTableName.IsMatch(tableName) ? tableName[..14] : null;
+
/// Why tests must skip, or null when QuestDB is available.
public string? SkipReason { get; private set; }
@@ -35,6 +60,7 @@ public sealed class QuestDbFixture : IAsyncLifetime
{
var p = "t" + Guid.NewGuid().ToString("N")[..12] + "_";
_prefixes.Add(p);
+ if (SkipReason is null) Register(p); // so a killed run's tables can be aged out by the next start
return p;
}
@@ -77,6 +103,7 @@ public sealed class QuestDbFixture : IAsyncLifetime
/// Drops every table whose name starts with (found through tables()).
/// Table prefix.
/// A task completing when they are gone.
+ /// Some tables could not be dropped after retries (the rest were still dropped).
public async Task DropPrefixAsync(string prefix)
{
if (SkipReason is not null) return;
@@ -91,31 +118,139 @@ public sealed class QuestDbFixture : IAsyncLifetime
await using var r = await cmd.ExecuteReaderAsync().ConfigureAwait(false);
while (await r.ReadAsync().ConfigureAwait(false)) names.Add(r.GetString(0));
}
+ var failures = new List();
foreach (var n in names)
{
- await using var drop = conn.CreateCommand();
- drop.CommandText = $"DROP TABLE IF EXISTS {n}";
- await drop.ExecuteNonQueryAsync().ConfigureAwait(false);
+ // Independent per table, with retries: one busy/suspended table must not leave its siblings (or later prefixes) behind.
+ for (var attempt = 1; ; attempt++)
+ {
+ try
+ {
+ await using var drop = conn.CreateCommand();
+ drop.CommandText = $"DROP TABLE IF EXISTS {n}";
+ await drop.ExecuteNonQueryAsync().ConfigureAwait(false);
+ break;
+ }
+ catch (Exception) when (attempt < 5)
+ {
+ await Task.Delay(TimeSpan.FromMilliseconds(250 * attempt)).ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ failures.Add(new InvalidOperationException($"Could not drop {n}: {ex.Message}", ex));
+ break;
+ }
+ }
+ }
+ if (failures.Count > 0) throw new AggregateException(failures);
+ }
+
+ private void Register(string prefix)
+ {
+ try
+ {
+ using var ds = NpgsqlDataSource.Create(ConnectionString);
+ using var conn = ds.OpenConnection();
+ using var cmd = conn.CreateCommand();
+ cmd.CommandText = $"INSERT INTO {RegistryTable} (ts, prefix) VALUES (now(), $1)";
+ cmd.Parameters.Add(new NpgsqlParameter { NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Varchar, Value = prefix });
+ cmd.ExecuteNonQuery();
+ }
+ catch (Exception ex)
+ {
+ Console.Error.WriteLine($"QuestDbFixture: could not register prefix {prefix} for stale sweeping: {ex.Message}");
+ }
+ }
+
+ ///
+ /// Start-of-fixture sweep (#1062): drops the tables of registered prefixes older than and
+ /// adopts (registers now) test-pattern tables nobody registered. Best effort — never fails the fixture.
+ ///
+ private async Task SweepStaleAsync()
+ {
+ try
+ {
+ await using var ds = NpgsqlDataSource.Create(ConnectionString);
+ await using var conn = await ds.OpenConnectionAsync().ConfigureAwait(false);
+ await using (var create = conn.CreateCommand())
+ {
+ create.CommandText = $"CREATE TABLE IF NOT EXISTS {RegistryTable} (ts TIMESTAMP, prefix SYMBOL) TIMESTAMP(ts) PARTITION BY DAY WAL";
+ await create.ExecuteNonQueryAsync().ConfigureAwait(false);
+ }
+
+ var registered = new Dictionary(); // prefix -> latest registration
+ try
+ {
+ await using var read = conn.CreateCommand();
+ read.CommandText = $"SELECT prefix, max(ts) FROM {RegistryTable}";
+ await using var r = await read.ExecuteReaderAsync().ConfigureAwait(false);
+ while (await r.ReadAsync().ConfigureAwait(false)) registered[r.GetString(0)] = r.GetDateTime(1);
+ }
+ catch (Exception ex) { Console.Error.WriteLine($"QuestDbFixture: registry read failed: {ex.Message}"); }
+
+ var tables = new List();
+ await using (var list = conn.CreateCommand())
+ {
+ list.CommandText = "SELECT table_name FROM tables()";
+ await using var r = await list.ExecuteReaderAsync().ConfigureAwait(false);
+ while (await r.ReadAsync().ConfigureAwait(false)) tables.Add(r.GetString(0));
+ }
+
+ var cutoff = DateTime.UtcNow - StaleAfter;
+ var stale = new HashSet();
+ var adopt = new HashSet();
+ foreach (var t in tables)
+ {
+ if (TestPrefixOf(t) is not { } prefix) continue;
+ if (registered.TryGetValue(prefix, out var at)) { if (at < cutoff) stale.Add(prefix); }
+ else adopt.Add(prefix);
+ }
+
+ foreach (var prefix in adopt) Register(prefix);
+ foreach (var prefix in stale)
+ {
+ try { await DropPrefixAsync(prefix).ConfigureAwait(false); }
+ catch (Exception ex) { Console.Error.WriteLine($"QuestDbFixture: stale sweep of {prefix}: {ex.Message}"); }
+ }
+
+ try
+ {
+ await using var trim = conn.CreateCommand(); // keep the registry itself small
+ trim.CommandText = $"ALTER TABLE {RegistryTable} DROP PARTITION WHERE ts < dateadd('d', -30, now())";
+ await trim.ExecuteNonQueryAsync().ConfigureAwait(false);
+ }
+ catch { /* nothing old enough to drop, or not worth failing for */ }
+ }
+ catch (Exception ex)
+ {
+ Console.Error.WriteLine($"QuestDbFixture: stale sweep skipped: {ex.Message}");
}
}
///
- public ValueTask InitializeAsync()
+ public async ValueTask InitializeAsync()
{
var cs = Environment.GetEnvironmentVariable(ConnectionEnvVar);
if (string.IsNullOrWhiteSpace(cs))
+ {
SkipReason = $"{ConnectionEnvVar} is not set; QuestDB historian integration tests skipped.";
- else
- ConnectionString = cs;
- return ValueTask.CompletedTask;
+ return;
+ }
+ ConnectionString = cs;
+ await SweepStaleAsync().ConfigureAwait(false);
}
///
public async ValueTask DisposeAsync()
{
if (SkipReason is not null) return;
+ // Every prefix is attempted: a failure on one (reported, not thrown) never abandons the rest; leftovers are aged
+ // out by the next start's sweep.
foreach (var p in _prefixes.Distinct())
- await DropPrefixAsync(p).ConfigureAwait(false);
+ {
+ try { await DropPrefixAsync(p).ConfigureAwait(false); }
+ catch (Exception ex) { Console.Error.WriteLine($"QuestDbFixture: teardown of {p} incomplete: {ex.Message}"); }
+ }
NpgsqlConnection.ClearAllPools();
}
}
diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb.Tests/QuestDbWalVisibilityTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb.Tests/QuestDbWalVisibilityTests.cs
index 0f1dfa8f8..313450fb5 100644
--- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb.Tests/QuestDbWalVisibilityTests.cs
+++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb.Tests/QuestDbWalVisibilityTests.cs
@@ -1,4 +1,5 @@
using System.Diagnostics.Metrics;
+using Microsoft.Extensions.Logging;
using Shouldly;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using Xunit;
@@ -82,4 +83,115 @@ public sealed class QuestDbWalVisibilityTests
QuestDbWalVisibility.RecentFailureGauge(DateTime.UtcNow + QuestDbWalVisibility.RecentFailureWindow + TimeSpan.FromSeconds(5)).ShouldBe(0);
QuestDbWalVisibility.ResetRecentFailure();
}
+
+ // ---- #1072: forced give-up paths (no database; a probe delegate + a manual clock) ----
+
+ private sealed class ManualTime : TimeProvider
+ {
+ private long _ticks;
+ public override long TimestampFrequency => TimeSpan.TicksPerSecond;
+ public override long GetTimestamp() => Interlocked.Read(ref _ticks);
+ public void Advance(TimeSpan d) => Interlocked.Add(ref _ticks, d.Ticks);
+ }
+
+ private sealed class CapturingLogger : ILogger
+ {
+ public readonly List<(LogLevel Level, string Message)> Entries = new();
+ public IDisposable? BeginScope(TState state) where TState : notnull => null;
+ public bool IsEnabled(LogLevel logLevel) => true;
+ public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
+ Func formatter) => Entries.Add((logLevel, formatter(state, exception)));
+ }
+
+ private static (long Count, int Gauge) Observe(string table, string reason, Func act)
+ {
+ long count = 0;
+ using var listener = new MeterListener();
+ listener.InstrumentPublished = (inst, l) =>
+ {
+ if (inst.Meter.Name == OtOpcUaTelemetry.MeterName && inst.Name == QuestDbWalVisibility.FailuresCounterName)
+ l.EnableMeasurementEvents(inst);
+ };
+ listener.SetMeasurementEventCallback((_, value, tags, _) =>
+ {
+ string? t = null, r = null;
+ foreach (var tag in tags)
+ {
+ if (tag.Key == "table") t = (string?)tag.Value;
+ if (tag.Key == "reason") r = (string?)tag.Value;
+ }
+ if (t == table && r == reason) Interlocked.Add(ref count, value);
+ });
+ listener.Start();
+ act().GetAwaiter().GetResult();
+ return (Interlocked.Read(ref count), QuestDbWalVisibility.RecentFailureGauge(DateTime.UtcNow));
+ }
+
+ [Fact]
+ public void A_wait_that_never_catches_up_gives_up_at_the_timeout_with_a_warning_a_metric_and_the_health_gauge()
+ {
+ QuestDbWalVisibility.ResetRecentFailure();
+ var table = "t" + Guid.NewGuid().ToString("N")[..12] + "_sample";
+ var time = new ManualTime();
+ var log = new CapturingLogger();
+ var delays = new List();
+ var probes = 0;
+ var wal = new QuestDbWalVisibility(
+ (_, _) => { probes++; return Task.FromResult(new(writerTxn(), 10, false)); },
+ TimeSpan.FromMilliseconds(500), log,
+ (d, _) => { delays.Add(d); time.Advance(d); return Task.CompletedTask; }, time);
+ static long writerTxn() => 5; // never reaches the target of 10
+
+ bool result = true;
+ var (count, gauge) = Observe(table, "timeout", async () => result = await wal.WaitAsync(table, CancellationToken.None));
+
+ result.ShouldBeFalse();
+ wal.Failures.ShouldBe(1);
+ count.ShouldBe(1L, "the counter fires once with reason=timeout");
+ gauge.ShouldBe(1, "the recent-failure health gauge is raised");
+ log.Entries.ShouldContain(e => e.Level == LogLevel.Warning && e.Message.Contains("did not become visible") && e.Message.Contains(table));
+ delays.Sum(d => d.TotalMilliseconds).ShouldBe(500, "never sleeps past the timeout");
+ delays[0].ShouldBe(QuestDbWalVisibility.FirstPollInterval);
+ probes.ShouldBeGreaterThan(3);
+ QuestDbWalVisibility.ResetRecentFailure();
+ }
+
+ [Fact]
+ public void A_suspended_table_gives_up_at_once_without_sleeping_with_warning_metric_and_gauge()
+ {
+ QuestDbWalVisibility.ResetRecentFailure();
+ var table = "t" + Guid.NewGuid().ToString("N")[..12] + "_sample";
+ var log = new CapturingLogger();
+ var slept = false;
+ var wal = new QuestDbWalVisibility(
+ (_, _) => Task.FromResult(new(5, 10, true)),
+ TimeSpan.FromSeconds(30), log, (_, _) => { slept = true; return Task.CompletedTask; }, new ManualTime());
+
+ bool result = true;
+ var (count, gauge) = Observe(table, "suspended", async () => result = await wal.WaitAsync(table, CancellationToken.None));
+
+ result.ShouldBeFalse();
+ slept.ShouldBeFalse();
+ count.ShouldBe(1L);
+ gauge.ShouldBe(1);
+ log.Entries.ShouldContain(e => e.Level == LogLevel.Warning && e.Message.Contains("is suspended"));
+ QuestDbWalVisibility.ResetRecentFailure();
+ }
+
+ [Fact]
+ public async Task Positive_control_a_wait_that_catches_up_emits_nothing()
+ {
+ QuestDbWalVisibility.ResetRecentFailure();
+ var log = new CapturingLogger();
+ var time = new ManualTime();
+ var calls = 0;
+ var wal = new QuestDbWalVisibility(
+ (_, _) => Task.FromResult(new(++calls >= 4 ? 10 : 5, 10, false)),
+ TimeSpan.FromSeconds(1), log, (d, _) => { time.Advance(d); return Task.CompletedTask; }, time);
+
+ (await wal.WaitAsync("t_ok_sample", CancellationToken.None)).ShouldBeTrue();
+ wal.Failures.ShouldBe(0);
+ log.Entries.ShouldBeEmpty();
+ QuestDbWalVisibility.RecentFailureGauge(DateTime.UtcNow).ShouldBe(0);
+ }
}
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Health/AlarmHistorianHealthCheckTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Health/AlarmHistorianHealthCheckTests.cs
index 149ef2fc2..8ed2e7f06 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Health/AlarmHistorianHealthCheckTests.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Health/AlarmHistorianHealthCheckTests.cs
@@ -36,6 +36,16 @@ public sealed class AlarmHistorianHealthCheckTests
data["lastError"].ShouldBe("Historian unavailable");
}
+ [Fact]
+ public void An_outage_is_degraded_but_named_an_outage_not_a_stuck_queue()
+ {
+ var outage = Status(stalled: false, "Historian unavailable") with { HistorianUnreachable = true };
+ var (status, description, _) = AlarmHistorianHealthDecision.Evaluate(outage);
+ status.ShouldBe(HealthStatus.Degraded);
+ description.ShouldContain("outage");
+ description.ShouldNotContain("stalled");
+ }
+
[Fact]
public async Task The_check_maps_a_stalled_sink_to_Degraded()
{