Merge historian follow-ups: QuestDB WaitAsync give-up seam + tests (#1072), stalled alarm S&F queue qualified by historian reachability (#1071), QuestDB fixture prefix registry + stale sweep, 134 leaked tables dropped (#1062)

This commit is contained in:
Joseph Doherty
2026-12-03 16:36:40 -05:00
13 changed files with 511 additions and 46 deletions
+9 -3
View File
@@ -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)
+1
View File
@@ -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`):
@@ -65,8 +65,15 @@ public sealed class NullAlarmHistorianSink : IAlarmHistorianSink
/// </param>
/// <param name="Stalled">
/// <c>true</c> 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; <paramref name="LastError"/> says which. Always <c>false</c> 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 <paramref name="HistorianUnreachable"/> instead). Always <c>false</c>
/// when no threshold is configured.
/// </param>
/// <param name="HistorianUnreachable">
/// <c>true</c> 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.
/// <see cref="Stalled"/> is then <c>false</c>. Always <c>false</c> for a writer that does not report reachability.
/// </param>
/// <param name="LastProgressUtc">UTC of the last time the queue made progress (a row delivered or dead-lettered) or was seen empty; <c>null</c> when not tracked (no drain yet, or not the drain owner).</param>
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);
/// <summary>Where the drain worker is in its state machine.</summary>
public enum HistorianDrainState
@@ -121,4 +129,29 @@ public interface IAlarmHistorianWriter
/// <returns>One <see cref="HistorianWriteOutcome"/> per event, in the same order as <paramref name="batch"/>.</returns>
Task<IReadOnlyList<HistorianWriteOutcome>> WriteBatchAsync(
IReadOnlyList<AlarmHistorianEvent> batch, CancellationToken cancellationToken);
/// <summary>
/// Whether this writer tracks <see cref="LastReachableUtc"/> (#1071). Default <c>false</c>: the sink cannot tell an
/// outage from a stuck queue and stall detection keeps its #1034 meaning.
/// </summary>
bool ReportsReachability => false;
/// <summary>
/// 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 <c>null</c> when none yet. Meaningful only when
/// <see cref="ReportsReachability"/>.
/// </summary>
DateTime? LastReachableUtc => null;
}
/// <summary>Cheap thread-safe "last time the historian answered" stamp a writer keeps for <see cref="IAlarmHistorianWriter.LastReachableUtc"/> (#1071).</summary>
public sealed class HistorianReachability
{
private long _ticks;
/// <summary>Records that the historian just answered.</summary>
public void Touch() => Interlocked.Exchange(ref _ticks, DateTime.UtcNow.Ticks);
/// <summary>The last answer time, or <c>null</c> when it has never answered.</summary>
public DateTime? LastUtc => Interlocked.Read(ref _ticks) is var t and > 0 ? new DateTime(t, DateTimeKind.Utc) : null;
}
@@ -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 <paramref name="now"/> (#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.
/// </summary>
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;
/// <summary>How recently the historian must have answered for it to count as reachable (#1071).</summary>
internal static readonly TimeSpan ReachabilityWindow = TimeSpan.FromMinutes(5);
/// <summary>
/// Classifies a no-progress queue (#1071): <c>Stalled</c> = the queue is stuck (historian reachable, or the writer cannot
/// say); <c>Outage</c> = the writer reports the historian unreachable, so the rows are merely held.
/// </summary>
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);
}
/// <summary>Logs a stall once on entering it (and once on leaving it); called after every drain tick.</summary>
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);
}
/// <summary>Operator action from Admin UI — retry every dead-lettered row. Non-cascading: they rejoin the regular queue + get a fresh backoff.</summary>
@@ -68,6 +68,20 @@ public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDispos
private readonly IHistorianGatewayClient _client;
private readonly ILogger<GatewayAlarmHistorianWriter> _logger;
private readonly HistorianReachability _reach = new();
/// <inheritdoc/>
public bool ReportsReachability => true;
/// <inheritdoc/>
public DateTime? LastReachableUtc => _reach.LastUtc;
// #1071: any gateway answer (success, or a failure that is not a systemic outage/transport fault) proves it reachable.
private void NoteAnswered(Exception ex)
{
if (!IsSystemicFailure(ex)) _reach.Touch();
}
/// <summary>Set once the gateway answers <c>SendEvents</c> with <c>Unimplemented</c>: single sends from then on.</summary>
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);
@@ -90,6 +90,14 @@ internal sealed class QuestDbAlarmHistorianWriter : IAlarmHistorianWriter
/// <summary>Events per INSERT: 12 bound parameters each.</summary>
internal const int ChunkRows = 500;
private readonly HistorianReachability _reach = new();
/// <inheritdoc/>
public bool ReportsReachability => true;
/// <inheritdoc/>
public DateTime? LastReachableUtc => _reach.LastUtc;
private long _statements;
/// <summary>INSERT statements sent so far (lifetime) — test/diagnostic.</summary>
@@ -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;
}
/// <summary>Classifies a write exception as retryable or a permanent dead-letter failure.</summary>
@@ -114,6 +114,41 @@ internal sealed class QuestDbWalVisibility
/// <returns>Whether polling can stop because the rows are visible.</returns>
internal static bool Reached(long writerTxn, long targetTxn) => writerTxn >= targetTxn;
/// <summary>One <c>wal_tables()</c> row: applied and sequenced transaction numbers + the suspended flag.</summary>
/// <param name="WriterTxn">Last applied transaction.</param>
/// <param name="SequencerTxn">Last sequenced (committed) transaction.</param>
/// <param name="Suspended">Whether the table's WAL apply is suspended.</param>
internal readonly record struct WalState(long WriterTxn, long SequencerTxn, bool Suspended);
/// <summary>Reads a table's <see cref="WalState"/>; null when it is not a WAL table (or has no row).</summary>
/// <param name="table">Table name.</param>
/// <param name="ct">Cancellation.</param>
internal delegate Task<WalState?> WalProbe(string table, CancellationToken ct);
private readonly WalProbe? _probeOverride;
private readonly Func<TimeSpan, CancellationToken, Task> _delay = static (d, ct) => Task.Delay(d, ct);
private readonly TimeProvider _time = TimeProvider.System;
/// <summary>
/// Test seam (#1072): a wait driven by a supplied <paramref name="probe"/> (no database), a <paramref name="delay"/>
/// and a <paramref name="time"/> so the timeout / suspended give-up paths can be forced deterministically.
/// </summary>
/// <param name="probe">Supplies the WAL state.</param>
/// <param name="timeout">Maximum wait.</param>
/// <param name="log">Logger.</param>
/// <param name="delay">Replacement for <see cref="Task.Delay(TimeSpan, CancellationToken)"/> (may advance <paramref name="time"/>).</param>
/// <param name="time">Clock the timeout is measured on.</param>
internal QuestDbWalVisibility(WalProbe probe, TimeSpan timeout, ILogger log,
Func<TimeSpan, CancellationToken, Task> delay, TimeProvider time)
{
_conn = null!;
_probeOverride = probe;
_timeout = timeout;
_log = log;
_delay = delay;
_time = time;
}
/// <summary>Waits until everything this caller inserted into <paramref name="table"/> is visible to queries.</summary>
/// <param name="table">Full table name written to.</param>
/// <param name="ct">Cancellation.</param>
@@ -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<bool> 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);
}
@@ -81,6 +81,14 @@ internal sealed class SqlServerAlarmHistorianWriter : IAlarmHistorianWriter
/// <summary>Events per statement: 11 parameters each, under SQL Server's 2,100-parameter limit.</summary>
internal const int ChunkRows = 150;
private readonly HistorianReachability _reach = new();
/// <inheritdoc/>
public bool ReportsReachability => true;
/// <inheritdoc/>
public DateTime? LastReachableUtc => _reach.LastUtc;
private long _statements;
/// <summary>Statements sent so far (lifetime) — test/diagnostic.</summary>
@@ -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;
}
/// <summary>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).</summary>
@@ -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);
@@ -207,4 +207,41 @@ public sealed partial class LocalDbStoreAndForwardSinkTests
on.GetStatus().QueueDepth.ShouldBe(0);
on.GetStatus().Stalled.ShouldBeFalse("nothing queued");
}
// ---------------------------------------------------------------------------------------------- #1071 outage vs stuck
/// <summary>A writer that answers RetryPlease for everything and reports (settable) historian reachability.</summary>
private sealed class ReachabilityWriter : IAlarmHistorianWriter
{
public DateTime? Reachable { get; set; }
public bool ReportsReachability => true;
public DateTime? LastReachableUtc => Reachable;
public Task<IReadOnlyList<HistorianWriteOutcome>> WriteBatchAsync(IReadOnlyList<AlarmHistorianEvent> batch, CancellationToken ct) =>
Task.FromResult<IReadOnlyList<HistorianWriteOutcome>>(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();
}
}
@@ -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;
/// <see cref="SkipReason"/> is set, nothing connects and every test calls <c>Assert.Skip</c>. Present ⇒ tests isolate
/// from each other with <see cref="UniquePrefix"/>; every prefix handed out is dropped on dispose (and a test may
/// drop its own early with <see cref="DropPrefixAsync"/>). Never touches a table outside those prefixes.
/// <para>
/// <b>Leak hygiene (#1062).</b> 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
/// <see cref="RegistryTable"/>, and at fixture start any <c>t&lt;12 hex&gt;_*</c> table whose prefix was registered
/// more than <see cref="StaleAfter"/> 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 <i>adopted</i> — registered now — so it is dropped one
/// <see cref="StaleAfter"/> later, never while a live run could still own it. Only tables whose name matches
/// <see cref="TestTableName"/> are ever touched.
/// </para>
/// </summary>
public sealed class QuestDbFixture : IAsyncLifetime
{
@@ -17,6 +28,20 @@ public sealed class QuestDbFixture : IAsyncLifetime
private readonly ConcurrentBag<string> _prefixes = new();
/// <summary>Records every prefix handed out and when (QuestDB has no table-creation time to age tables by).</summary>
public const string RegistryTable = "otopcua_test_prefix_registry";
/// <summary>How old a registered prefix must be before the start-of-fixture sweep drops its tables.</summary>
public static readonly TimeSpan StaleAfter = TimeSpan.FromDays(1);
/// <summary>The only table names the fixture ever drops: a <see cref="UniquePrefix"/> (<c>t</c> + 12 hex + <c>_</c>) then anything.</summary>
public static readonly Regex TestTableName = new("^t[0-9a-f]{12}_", RegexOptions.Compiled | RegexOptions.CultureInvariant);
/// <summary>The 14-character <see cref="UniquePrefix"/> a test table name starts with, or null when it is not a test table.</summary>
/// <param name="tableName">A table name.</param>
/// <returns>The prefix, or null.</returns>
public static string? TestPrefixOf(string tableName) => TestTableName.IsMatch(tableName) ? tableName[..14] : null;
/// <summary>Why tests must skip, or null when QuestDB is available.</summary>
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
/// <summary>Drops every table whose name starts with <paramref name="prefix"/> (found through <c>tables()</c>).</summary>
/// <param name="prefix">Table prefix.</param>
/// <returns>A task completing when they are gone.</returns>
/// <exception cref="AggregateException">Some tables could not be dropped after retries (the rest were still dropped).</exception>
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<Exception>();
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}");
}
}
/// <summary>
/// Start-of-fixture sweep (#1062): drops the tables of registered prefixes older than <see cref="StaleAfter"/> and
/// adopts (registers now) test-pattern tables nobody registered. Best effort — never fails the fixture.
/// </summary>
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<string, DateTime>(); // 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<string>();
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<string>();
var adopt = new HashSet<string>();
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}");
}
}
/// <inheritdoc/>
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);
}
/// <inheritdoc/>
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();
}
}
@@ -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>(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
Func<TState, Exception?, string> formatter) => Entries.Add((logLevel, formatter(state, exception)));
}
private static (long Count, int Gauge) Observe(string table, string reason, Func<Task> 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<long>((_, 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<TimeSpan>();
var probes = 0;
var wal = new QuestDbWalVisibility(
(_, _) => { probes++; return Task.FromResult<QuestDbWalVisibility.WalState?>(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<QuestDbWalVisibility.WalState?>(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<QuestDbWalVisibility.WalState?>(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);
}
}
@@ -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()
{