test(historian): #1072 QuestDB WAL visibility give-up paths are testable (probe/delay/clock seam) and covered: warning + counter + health gauge
This commit is contained in:
@@ -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);
|
||||
}
|
||||
|
||||
+112
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user