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/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);
+ }
}