diff --git a/docs/Historian.md b/docs/Historian.md
index fe6257ed6..caae26e29 100644
--- a/docs/Historian.md
+++ b/docs/Historian.md
@@ -1274,6 +1274,10 @@ says is complete carries no continuation point. `NumValuesPerNode == 0` stays un
is forward `[MinValue, EndTime)` everywhere.
- **Backends.** The server checks `IHistorianDataSource.SupportsReverseEvents`. SqlServer and QuestDB serve reverse natively
(`… > lo AND … <= hi ORDER BY time DESC, id DESC`, the `ReadEventsAsync(…, bool reverse, …)` overload) and report `true`.
+ QuestDB's capped reverse read (G-17, #993) first finds its cut with a backward scan that stops early
+ (`ReverseEventCutSql`: `ORDER BY ts DESC LIMIT n+1`), then reads `ts >= cut` ordered `(ts DESC, event_id DESC)` — the plain
+ `ORDER BY ts DESC, event_id DESC LIMIT n` planned as a forward scan of the whole window (no early exit), so "the latest 1,000
+ alarms" read every event row, again per continuation page; ties at the cut are still chosen by `event_id`.
**Gateway reports `false`** — the gateway streams ascending only and rejects `end < start` — and is never sent a reverse
read (Null reports `true` and answers empty either way, as for raw): since **#691.4** the server walks it back from bounded **forward** reads with the raw walk (#686/#689/#691:
page-sized ms-aligned segments filtered to `(segLo, segHi]`, a read the source flagged truncated is never answered from,
@@ -2160,6 +2164,14 @@ The read client reports `GetHealthSnapshot()` (query/failure counters, consecuti
`AutoCreateSchema=false`). A SQL connection outage on a read surfaces as `BadNoCommunication`; other SQL errors retain `BadHistoryOperationUnsupported` for **that node only**; a cancelled read
(deadline, client abort) is not counted as a backend fault.
+**Gateway: a request refusal is not an outage (G-9, #993).** On the Gateway backend a read the gateway *answered* with
+`InvalidArgument` / `OutOfRange` / `NotFound` / `Unimplemented` (`GatewayErrorReasons.IsRequestRefusal` — a bad window or tag name from the
+client; `FailedPrecondition` is NOT in the set, the gateway also passes historian-side rejections through it) proves the gateway is
+reachable: it is rethrown as before but is a connectivity observation only — `ProcessConnectionOpen`/`EventConnectionOpen` stay `true`, the
+consecutive-failure streak ends, and no failure counter moves (like the aggregate-not-supported and `MaxValuesCeiling` refusals). Transport
+statuses (`Unavailable`, `DeadlineExceeded`), `Internal`, `Unknown` and non-RPC exceptions still degrade health. A client polling HistoryRead
+with a bad argument used to hold `/hosts` at "connection closed" with a growing failure count against a healthy gateway.
+
### Retention (`RetentionDays`)
`hist.Sample`, `hist.SampleModified` and `hist.Event` grow without bound unless `ServerHistorian:SqlServer:RetentionDays` is set. QuestDB already has an
@@ -2528,6 +2540,12 @@ docker compose -f docker-dev/docker-compose.yml -f docker-dev/docker-compose.que
export HISTORIAN_QUESTDB_TEST_CONNECTION='Host=localhost;Port=18812;Username=admin;Password=quest;Database=qdb;ServerCompatibilityMode=NoTypeLoading'
```
+Tests wait for WAL visibility up to `QuestDbFixture.VisibilityTimeout` (60 s; env `HISTORIAN_QUESTDB_TEST_VISIBILITY_SECONDS`), not the
+production 5 s: the shared fixture's Docker host is routinely CPU-saturated (load average in the hundreds on 22 cores, 2026-12-03 — CI jobs,
+Ignition), QuestDB applies WAL commits late, `WaitAsync` gives up with only a Warning to a null logger, and a test then reads back FEWER rows
+than it wrote (the "0 rows on master" alarm-writer symptom, #993). Fixture state itself was clean (4 tables, none suspended, `sequencerTxn -
+writerTxn = 0`); it is load, not collision.
+
`admin` / `quest` is QuestDB's stock default — a throwaway fixture credential, not a secret. The fixture's compose file is
`tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb.IntegrationTests/Docker/docker-compose.yml` (label `project=lmxopcua`).
diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway/GatewayErrorReasons.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway/GatewayErrorReasons.cs
index d07975f00..ca1b85aa7 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway/GatewayErrorReasons.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway/GatewayErrorReasons.cs
@@ -39,6 +39,32 @@ internal static class GatewayErrorReasons
GatewayExceptionOf(ex)?.StatusCode == StatusCode.FailedPrecondition
&& string.Equals(ReasonOf(ex), HistorianGatewayErrorReasons.AggregateNotSupportedForTag, StringComparison.Ordinal);
+ ///
+ /// True when is the gateway ANSWERING that the request itself is bad — status
+ /// , , or
+ /// (a gateway older than the RPC). Such a failure proves the gateway is reachable
+ /// and must not degrade the health snapshot (G-9, #993). is deliberately NOT
+ /// listed: the gateway also passes historian-side rejections through it, which are backend faults. Transport statuses,
+ /// Internal, Unknown, auth statuses and non-RPC exceptions are not refusals.
+ ///
+ /// A gateway call's exception.
+ /// Whether it is a request-level refusal.
+ public static bool IsRequestRefusal(Exception ex)
+ {
+ for (var e = ex; e is not null; e = e.InnerException)
+ {
+ var code = e switch
+ {
+ HistorianGatewayException gw => (StatusCode?)gw.StatusCode,
+ RpcException rpc => rpc.StatusCode,
+ _ => null,
+ };
+ if (code is { } c)
+ return c is StatusCode.InvalidArgument or StatusCode.OutOfRange or StatusCode.NotFound or StatusCode.Unimplemented;
+ }
+ return false;
+ }
+
private static HistorianGatewayException? GatewayExceptionOf(Exception ex)
{
for (var e = ex; e is not null; e = e.InnerException)
diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway/GatewayHistorianDataSource.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway/GatewayHistorianDataSource.cs
index 8b47ba858..bbaa51b56 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway/GatewayHistorianDataSource.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway/GatewayHistorianDataSource.cs
@@ -1015,6 +1015,20 @@ public sealed class GatewayHistorianDataSource : IHistorianDataSource, IAsyncDis
///
private void RecordReadFailure(Exception ex)
{
+ if (GatewayErrorReasons.IsRequestRefusal(ex))
+ {
+ // G-9 (#993): the gateway ANSWERED — a bad window / tag name / unsupported call is the client's request, not a
+ // backend fault. It proves the gateway is reachable, so it is a connectivity observation only (like the
+ // aggregate-not-supported refusal it is not a counted query): no failure counters, the streak ends.
+ lock (_healthLock)
+ {
+ _lastObservationOpen = true;
+ _consecutiveFailures = 0;
+ }
+ _logger.LogDebug("Historian gateway refused a read request; not a health failure.");
+ return;
+ }
+
RecordOutcome(success: false, error: ex.Message);
_logger.LogDebug("Historian gateway read operation failed and was recorded as a health failure.");
}
diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb/QuestDbHistorianDataSource.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb/QuestDbHistorianDataSource.cs
index e97783d33..058e642f3 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb/QuestDbHistorianDataSource.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb/QuestDbHistorianDataSource.cs
@@ -449,6 +449,18 @@ public sealed class QuestDbHistorianDataSource : IHistorianDataSource
HistorianReadCapabilities.Data | HistorianReadCapabilities.Events | HistorianReadCapabilities.ServerTimestamps;
+ ///
+ /// The backward-scan statement that finds the n+1-th latest event time of a reverse window (G-17, #993): $1 =
+ /// exclusive lower bound, $2 = inclusive upper bound, [$3 = source,] then the row count.
+ ///
+ /// The event table.
+ /// Whether the statement filters on a source.
+ /// The SQL text.
+ internal static string ReverseEventCutSql(string eventTable, bool withSource) =>
+ $"SELECT ts FROM {eventTable} WHERE ts > $1 AND ts <= $2" +
+ (withSource ? " AND source = $3" : "") +
+ " ORDER BY ts DESC LIMIT " + (withSource ? "$4" : "$3");
+
// [start, end) by event time (a reversed window is swapped), ordered by (ts, event_id) ascending.
// maxEvents <= 0 or int.MaxValue => unbounded. Otherwise maxEvents + 1 rows are fetched; when the
// extra row arrives it is dropped and the continuation point is the UTF-8 of EventContinuation.Encode
@@ -475,16 +487,49 @@ public sealed class QuestDbHistorianDataSource : IHistorianDataSource
var end = QuestDbConnection.Round(endUtc);
var (lo, hi) = start <= end ? (start, end) : (end, start);
var bounded = maxEvents > 0 && maxEvents < int.MaxValue;
+
+ await using var conn = await _conn.OpenAsync(cancellationToken).ConfigureAwait(false);
+
+ // G-17 (#993): ORDER BY ts DESC, event_id DESC LIMIT n plans as a forward scan of the WHOLE window (Async Top K /
+ // full sort) - no early exit - so "the latest 1,000 alarms" read every event row, per page. Find the cut first with
+ // a backward scan that stops early (ts alone: the designated timestamp), then read ts >= cut, still ordered by
+ // (ts DESC, event_id DESC) so ties AT the cut are chosen by event_id exactly as before.
+ var reverseFrom = lo;
+ var reverseFromInclusive = false;
+ if (reverse && bounded)
+ {
+ await using var cut = _conn.CreateCommand(conn, ReverseEventCutSql(_conn.EventTable, sourceName is not null));
+ QuestDbConnection.BindTimestamp(cut, lo);
+ QuestDbConnection.BindTimestamp(cut, hi);
+ if (sourceName is not null) QuestDbConnection.BindText(cut, sourceName);
+ QuestDbConnection.BindLong(cut, (long)maxEvents + 1);
+ var seen = 0;
+ DateTime last = default;
+ await using (var cr = await cut.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false))
+ {
+ while (await cr.ReadAsync(cancellationToken).ConfigureAwait(false))
+ {
+ seen++;
+ last = QuestDbConnection.ReadUtc(cr, 0);
+ }
+ }
+ // Fewer than n + 1 events in the window: the whole window is the answer, nothing to cut.
+ if (seen == maxEvents + 1)
+ {
+ reverseFrom = last;
+ reverseFromInclusive = true;
+ }
+ }
+
var sql =
$"SELECT event_id, source, ts, received_utc, message, severity, alarm_type_name, alarm_name, alarm_id FROM {_conn.EventTable} " +
- (reverse ? "WHERE ts > $1 AND ts <= $2" : "WHERE ts >= $1 AND ts < $2") +
+ (reverse ? (reverseFromInclusive ? "WHERE ts >= $1 AND ts <= $2" : "WHERE ts > $1 AND ts <= $2") : "WHERE ts >= $1 AND ts < $2") +
(sourceName is null ? "" : " AND source = $3") +
(reverse ? " ORDER BY ts DESC, event_id DESC" : " ORDER BY ts ASC, event_id ASC") +
(bounded ? (sourceName is null ? " LIMIT $3" : " LIMIT $4") : "");
- await using var conn = await _conn.OpenAsync(cancellationToken).ConfigureAwait(false);
await using var cmd = _conn.CreateCommand(conn, sql);
- QuestDbConnection.BindTimestamp(cmd, lo);
+ QuestDbConnection.BindTimestamp(cmd, reverse ? reverseFrom : lo);
QuestDbConnection.BindTimestamp(cmd, hi);
if (sourceName is not null) QuestDbConnection.BindText(cmd, sourceName);
if (bounded) QuestDbConnection.BindLong(cmd, (long)maxEvents + 1);
diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common/TimeWeightedAggregator.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common/TimeWeightedAggregator.cs
index a474a8ffe..f1983b70e 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common/TimeWeightedAggregator.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common/TimeWeightedAggregator.cs
@@ -401,11 +401,7 @@ public sealed class TimeWeightedAggregator
private long FirstBucketAt(long t) => Math.Max(0, (t - _plan.OriginTicks) / _plan.IntervalTicks);
private void AddRaw(StoredSample from, long toTicks, double toValue) =>
- Distribute(from, toTicks, toValue, (i, area, ticks) =>
- {
- _rawArea[i] += area;
- _usableTicks[i] += ticks;
- });
+ Distribute(from, toTicks, toValue, bridged: false, nonGood: false);
/// Counts [from.t, toTicks) as outage (Bad) time; no value, never marks a bucket invalid.
private void AddBad(StoredSample from, long toTicks)
@@ -424,12 +420,7 @@ public sealed class TimeWeightedAggregator
}
private void AddBridged(StoredSample from, long toTicks, double toValue, bool nonGood) =>
- Distribute(from, toTicks, toValue, (i, area, ticks) =>
- {
- _bridgedArea[i] += area;
- _bridgedTicks[i] += ticks;
- if (nonGood) _bridgedNonGood[i] = true;
- });
+ Distribute(from, toTicks, toValue, bridged: true, nonGood);
// ------------------------------------------------------------------------------------------ PercentGood / PercentBad
@@ -488,9 +479,10 @@ public sealed class TimeWeightedAggregator
///
/// Splits the linear segment [from.t, toTicks) (value from.v → toValue) at the bucket edges, clipped to
/// the window, and hands each bucket its trapezoid area (value·ticks) and duration. A non-numeric start sample
- /// marks every bucket it touches invalid instead.
+ /// marks every bucket it touches invalid instead. selects the target arrays (bridged-across-a-
+ /// gap vs usable raw) — a flag, not a delegate, so a read over a million samples allocates nothing per sample (G-18).
///
- private void Distribute(StoredSample from, long toTicks, double toValue, Action add)
+ private void Distribute(StoredSample from, long toTicks, double toValue, bool bridged, bool nonGood)
{
var t0 = from.TimeUtc.Ticks;
var lo = Math.Max(t0, _start);
@@ -510,7 +502,18 @@ public sealed class TimeWeightedAggregator
var b = Math.Min(hi, BucketEnd(i));
if (a >= b) continue;
if (!numeric) { _invalid[i] = true; continue; }
- add(i, (ValueAt(a) + ValueAt(b)) / 2d * (b - a), b - a);
+ var area = (ValueAt(a) + ValueAt(b)) / 2d * (b - a);
+ if (bridged)
+ {
+ _bridgedArea[i] += area;
+ _bridgedTicks[i] += b - a;
+ if (nonGood) _bridgedNonGood[i] = true;
+ }
+ else
+ {
+ _rawArea[i] += area;
+ _usableTicks[i] += b - a;
+ }
}
}
diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayRawAggregateTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayRawAggregateTests.cs
index 2a390a46c..57858a2f0 100644
--- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayRawAggregateTests.cs
+++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayRawAggregateTests.cs
@@ -465,12 +465,14 @@ public sealed class GatewayRawAggregateTests
ds.ReadProcessedAsync("T", At(0), At(10), TimeSpan.Zero, HistoryAggregateType.Count, Ct));
ds.GetHealthSnapshot().TotalFailures.ShouldBe(0);
- // Any other InvalidArgument is still a backend fault.
+ // Any other InvalidArgument is rethrown, but it is a request-level REFUSAL (G-9, #993): the gateway answered, so
+ // it is no health failure either (a real outage still is — GatewayReadRefusalHealthTests).
var other = new RpcException(new Status(StatusCode.InvalidArgument, "start_time must be less than or equal to end_time."));
var ds2 = Source(new FakeHistorianGatewayClient { ThrowOnRead = new HistorianGatewayException(other.Status.Detail, other) });
await Should.ThrowAsync(() =>
ds2.ReadProcessedAsync("T", At(0), At(10), TimeSpan.Zero, HistoryAggregateType.Count, Ct));
- ds2.GetHealthSnapshot().TotalFailures.ShouldBe(1);
+ ds2.GetHealthSnapshot().TotalFailures.ShouldBe(0);
+ ds2.GetHealthSnapshot().ProcessConnectionOpen.ShouldBeTrue();
}
[Theory] // a window starting AT the epoch gets no 1 ms margin, so AVEVA's no-data row is stamped at the window start:
diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayReadRefusalHealthTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayReadRefusalHealthTests.cs
new file mode 100644
index 000000000..55faee6e2
--- /dev/null
+++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests/GatewayReadRefusalHealthTests.cs
@@ -0,0 +1,112 @@
+using Grpc.Core;
+using Microsoft.Extensions.Logging.Abstractions;
+using Shouldly;
+using Xunit;
+using ZB.MOM.WW.HistorianGateway.Client;
+using ZB.MOM.WW.HistorianGateway.Contracts.Grpc;
+using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
+
+namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Tests;
+
+///
+/// G-9 (review 2026-12-02, #993): a request-level refusal (the gateway ANSWERED "bad argument") must not mark the
+/// connection closed or bump the consecutive-failure count; a real outage still must. The health snapshot is the
+/// latest connectivity observation, and a refusal proves the gateway is reachable.
+///
+public sealed class GatewayReadRefusalHealthTests
+{
+ private static CancellationToken Ct => TestContext.Current.CancellationToken;
+ private static readonly DateTime T0 = new(2026, 12, 1, 8, 0, 0, DateTimeKind.Utc);
+
+ private static Exception Wrapped(StatusCode code) =>
+ new HistorianGatewayException(code.ToString(), new RpcException(new Status(code, code.ToString())));
+
+ private static GatewayHistorianDataSource Source(FakeHistorianGatewayClient fake) =>
+ new(fake, NullLogger.Instance);
+
+ public static TheoryData RefusalCodes =>
+ [StatusCode.InvalidArgument, StatusCode.OutOfRange, StatusCode.NotFound, StatusCode.Unimplemented];
+
+ public static TheoryData OutageCodes =>
+ [StatusCode.Unavailable, StatusCode.DeadlineExceeded];
+
+ private static async Task Read(GatewayHistorianDataSource ds, string kind)
+ {
+ switch (kind)
+ {
+ case "Raw": await ds.ReadRawAsync("T", T0, T0.AddHours(1), 10, Ct); break;
+ case "Events": await ds.ReadEventsAsync(null, T0, T0.AddHours(1), 10, Ct); break;
+ case "Processed":
+ await ds.ReadProcessedAsync("T", T0, T0.AddHours(1), TimeSpan.FromMinutes(10), HistoryAggregateType.Average, Ct); break;
+ case "AtTime": await ds.ReadAtTimeAsync("T", [T0], Ct); break;
+ }
+ }
+
+ [Theory]
+ [InlineData("Raw")]
+ [InlineData("Events")]
+ [InlineData("Processed")]
+ [InlineData("AtTime")]
+ public async Task A_refusal_keeps_the_connection_open_and_counts_no_consecutive_failure(string kind)
+ {
+ var fake = new FakeHistorianGatewayClient { RawSamples = [], Events = [] };
+ var ds = Source(fake);
+ await Read(ds, kind); // a good read: the connection is observed open
+ ds.GetHealthSnapshot().ProcessConnectionOpen.ShouldBeTrue();
+
+ fake.ThrowOnRead = Wrapped(StatusCode.InvalidArgument);
+ await Should.ThrowAsync(() => Read(ds, kind));
+
+ var h = ds.GetHealthSnapshot();
+ h.ProcessConnectionOpen.ShouldBeTrue("the gateway answered — a refusal is not an outage");
+ h.EventConnectionOpen.ShouldBeTrue();
+ h.ConsecutiveFailures.ShouldBe(0);
+ h.TotalFailures.ShouldBe(0);
+ }
+
+ [Theory]
+ [MemberData(nameof(RefusalCodes))]
+ public async Task Every_request_level_status_is_a_refusal(StatusCode code)
+ {
+ var fake = new FakeHistorianGatewayClient { RawSamples = [], ThrowOnRead = Wrapped(code) };
+ var ds = Source(fake);
+ // NotFound is the "tag missing" shape on some arms and is served as no-data; either way no health damage.
+ try { await ds.ReadRawAsync("T", T0, T0.AddHours(1), 10, Ct); } catch (Exception) { /* refusal rethrown */ }
+ var h = ds.GetHealthSnapshot();
+ h.ConsecutiveFailures.ShouldBe(0);
+ h.ProcessConnectionOpen.ShouldBeTrue();
+ }
+
+ [Theory]
+ [MemberData(nameof(OutageCodes))]
+ public async Task Positive_control_a_real_outage_still_degrades_health(StatusCode code)
+ {
+ var fake = new FakeHistorianGatewayClient { RawSamples = [] };
+ var ds = Source(fake);
+ await ds.ReadRawAsync("T", T0, T0.AddHours(1), 10, Ct);
+
+ fake.ThrowOnRead = Wrapped(code);
+ await Should.ThrowAsync(() => ds.ReadRawAsync("T", T0, T0.AddHours(1), 10, Ct));
+
+ var h = ds.GetHealthSnapshot();
+ h.ProcessConnectionOpen.ShouldBeFalse();
+ h.ConsecutiveFailures.ShouldBe(1);
+ h.TotalFailures.ShouldBe(1);
+ }
+
+ [Fact]
+ public async Task A_refusal_after_an_outage_proves_the_gateway_is_back_and_clears_the_streak()
+ {
+ var fake = new FakeHistorianGatewayClient { RawSamples = [], ThrowOnRead = Wrapped(StatusCode.Unavailable) };
+ var ds = Source(fake);
+ await Should.ThrowAsync(() => ds.ReadRawAsync("T", T0, T0.AddHours(1), 10, Ct));
+ ds.GetHealthSnapshot().ConsecutiveFailures.ShouldBe(1);
+
+ fake.ThrowOnRead = Wrapped(StatusCode.InvalidArgument);
+ await Should.ThrowAsync(() => ds.ReadRawAsync("T", T0, T0.AddHours(1), 10, Ct));
+
+ var h = ds.GetHealthSnapshot();
+ h.ProcessConnectionOpen.ShouldBeTrue();
+ h.ConsecutiveFailures.ShouldBe(0);
+ }
+}
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 4d9d0877d..2bfbcf5ab 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
@@ -59,8 +59,21 @@ public sealed class QuestDbFixture : IAsyncLifetime
TablePrefix = prefix,
RetentionDays = retentionDays,
AutoCreateSchema = autoCreate,
+ VisibilityTimeout = VisibilityTimeout,
};
+ ///
+ /// The read-your-writes wait the tests use. The production default (5 s) is too tight for the SHARED fixture: its docker
+ /// host is routinely CPU-saturated (load average in the hundreds on 22 cores, 2026-12-03), so QuestDB applies a WAL commit
+ /// late; WaitAsync then gives up silently (a Warning to a null logger) and the test reads back FEWER rows — the
+ /// "0 rows even on master" symptom (#993). Not a product defect: the timeout is the designed bound. Override with
+ /// HISTORIAN_QUESTDB_TEST_VISIBILITY_SECONDS.
+ ///
+ public static TimeSpan VisibilityTimeout { get; } =
+ int.TryParse(Environment.GetEnvironmentVariable("HISTORIAN_QUESTDB_TEST_VISIBILITY_SECONDS"), out var s) && s >= 0
+ ? TimeSpan.FromSeconds(s)
+ : TimeSpan.FromSeconds(60);
+
/// Drops every table whose name starts with (found through tables()).
/// Table prefix.
/// A task completing when they are gone.
diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb.IntegrationTests/ReverseEventsTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb.IntegrationTests/ReverseEventsTests.cs
new file mode 100644
index 000000000..c6f2fa388
--- /dev/null
+++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb.IntegrationTests/ReverseEventsTests.cs
@@ -0,0 +1,111 @@
+using System.Text;
+using Npgsql;
+using Shouldly;
+using Xunit;
+using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
+using ZB.MOM.WW.OtOpcUa.Driver.Historian.Conformance;
+using ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common;
+
+namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb.IntegrationTests;
+
+///
+/// G-17 (#993): a capped reverse / end-only events read finds its cut with a backward scan that stops early, then reads
+/// ts >= cut. The cut must never change the answer: ties AT the cut are still chosen by event_id descending.
+///
+[Collection(QuestDbCollection.Name)]
+public sealed class ReverseEventsTests(QuestDbFixture fx) : IAsyncLifetime
+{
+ private static readonly CancellationToken Ct = CancellationToken.None;
+ private QuestDbConformanceBackend _b = null!;
+
+ private static DateTime At(double s) => ConformanceData.At(s);
+
+ public async ValueTask InitializeAsync() => _b = await QuestDbConformanceBackend.CreateConcreteAsync(fx);
+
+ public async ValueTask DisposeAsync()
+ {
+ if (_b is not null) await _b.DisposeAsync();
+ }
+
+ /// Three events per second (ties), alternating between two sources; ids sort differently from insertion order.
+ private async Task> SeedAsync(int seconds)
+ {
+ await _b.Boot.EnsureAsync(Ct);
+ var rows = new List<(DateTime, string, string)>();
+ for (var s = 0; s < seconds; s++)
+ for (var k = 0; k < 3; k++)
+ rows.Add((_b.Round(At(s)), $"e{s:D3}-{(2 - k)}", (s + k) % 2 == 0 ? "srcA" : "srcB")); // inserted id-descending within a tie
+ foreach (var chunk in rows.Chunk(50))
+ {
+ var sql = new StringBuilder($"INSERT INTO {_b.Conn.EventTable} (ts, event_id, source, severity, message, received_utc) VALUES ");
+ for (var i = 0; i < chunk.Length; i++)
+ {
+ if (i > 0) sql.Append(", ");
+ var n = i * 3;
+ sql.Append($"(${n + 1}, ${n + 2}, ${n + 3}, 500, 'm', ${n + 1})");
+ }
+ await _b.ExecuteAsync(sql.ToString(), cmd =>
+ {
+ foreach (var (t, id, src) in chunk)
+ {
+ QuestDbConnection.BindTimestamp(cmd, t);
+ QuestDbConnection.BindText(cmd, id);
+ QuestDbConnection.BindText(cmd, src);
+ }
+ });
+ }
+ await _b.Wal.WaitAsync(_b.Conn.EventTable, Ct);
+ return rows;
+ }
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData("srcA")]
+ [InlineData("srcB")]
+ public async Task A_capped_reverse_read_equals_the_head_of_the_uncapped_one_for_every_cut_including_ties(string? source)
+ {
+ var rows = await SeedAsync(20);
+ var src = _b.CreateDataSource();
+ var expected = rows
+ .Where(r => source is null || r.Source == source)
+ .OrderByDescending(r => r.T).ThenByDescending(r => r.Id, StringComparer.Ordinal)
+ .Select(r => r.Id).ToList();
+
+ var start = At(100); // reversed window: (end, start]
+ var end = At(-1);
+ var all = await src.ReadEventsAsync(source, start, end, 0, reverse: true, Ct);
+ all.Events.Select(e => e.EventId).ShouldBe(expected);
+ all.ContinuationPoint.ShouldBeNull();
+
+ for (var n = 1; n <= expected.Count + 1; n++)
+ {
+ var page = await src.ReadEventsAsync(source, start, end, n, reverse: true, Ct);
+ page.Events.Select(e => e.EventId).ShouldBe(expected.Take(n), $"n = {n}");
+ if (n < expected.Count)
+ Encoding.UTF8.GetString(page.ContinuationPoint!).ShouldContain(expected[n], Case.Sensitive, $"n = {n}: the first event not returned");
+ else
+ page.ContinuationPoint.ShouldBeNull($"n = {n}");
+ }
+ }
+
+ [Fact]
+ public async Task The_cut_statement_is_a_backward_scan_not_a_forward_scan_of_the_window()
+ {
+ await SeedAsync(5);
+ foreach (var withSource in new[] { false, true })
+ {
+ var sql = "EXPLAIN " + QuestDbHistorianDataSource.ReverseEventCutSql(_b.Conn.EventTable, withSource);
+ await using var conn = await _b.Conn.OpenAsync(Ct);
+ await using var cmd = _b.Conn.CreateCommand(conn, sql);
+ QuestDbConnection.BindTimestamp(cmd, At(-1));
+ QuestDbConnection.BindTimestamp(cmd, At(100));
+ if (withSource) QuestDbConnection.BindText(cmd, "srcA");
+ QuestDbConnection.BindLong(cmd, 11);
+ var plan = new StringBuilder();
+ await using (var r = await cmd.ExecuteReaderAsync(Ct))
+ while (await r.ReadAsync(Ct)) plan.AppendLine(r.GetString(0));
+
+ plan.ToString().ShouldContain("backward", Case.Insensitive, $"withSource={withSource}:\n{plan}");
+ }
+ }
+}
diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common.Tests/TimeWeightedAggregatorTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common.Tests/TimeWeightedAggregatorTests.cs
index 6bb87e2d8..f8a09376a 100644
--- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common.Tests/TimeWeightedAggregatorTests.cs
+++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common.Tests/TimeWeightedAggregatorTests.cs
@@ -741,4 +741,51 @@ public sealed class TimeWeightedAggregatorTests
Should.Throw(() =>
new TimeWeightedAggregator(HistoryAggregateType.Average, BucketPlan.Create(At(0), At(10), TimeSpan.Zero)));
}
+ ///
+ /// G-18 (#993): the per-sample work (Distribute) used to allocate two delegates + a closure per usable sample (~160 B,
+ /// ~160 MB for a 1M-row read). Allocation must be O(buckets), not O(samples). Every sample kind that feeds the
+ /// distributor is exercised: usable raw segments, and segments bridged across a Bad sample.
+ ///
+ [Theory]
+ [InlineData(HistoryAggregateType.TimeAverage)]
+ [InlineData(HistoryAggregateType.TimeAverage2)]
+ [InlineData(HistoryAggregateType.Total)]
+ public void Evaluate_allocates_per_bucket_not_per_sample(HistoryAggregateType agg)
+ {
+ static StoredSample[] Series(int n)
+ {
+ var a = new StoredSample[n];
+ for (var i = 0; i < n; i++)
+ {
+ // every 7th sample is Bad so the bridged path runs too
+ var status = i % 7 == 3 ? 0x80000000u : 0u;
+ a[i] = new StoredSample(At(i), HistorianValue.FromDouble(i % 50), status);
+ }
+ return a;
+ }
+
+ const int Small = 1_000, Large = 100_000;
+ var small = Series(Small);
+ var large = Series(Large);
+ var smallPlan = BucketPlan.Create(At(0), At(Small), TimeSpan.FromSeconds(Small / 4d));
+ var largePlan = BucketPlan.Create(At(0), At(Large), TimeSpan.FromSeconds(Large / 4d));
+
+ TimeWeightedAggregator.Evaluate(agg, smallPlan, small, Now); // JIT warm-up
+ TimeWeightedAggregator.Evaluate(agg, largePlan, large, Now);
+
+ long Measure(BucketPlan plan, StoredSample[] data)
+ {
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ TimeWeightedAggregator.Evaluate(agg, plan, data, Now);
+ return GC.GetAllocatedBytesForCurrentThread() - before;
+ }
+
+ var smallBytes = Measure(smallPlan, small);
+ var largeBytes = Measure(largePlan, large);
+
+ // Same 4 buckets, 100x the samples: the extra 99,000 samples must cost (almost) nothing. The old per-sample
+ // allocation was >= 99,000 * 100 B ~ 10 MB; allow 64 KB for the 4-bucket result noise.
+ (largeBytes - smallBytes).ShouldBeLessThan(64 * 1024,
+ $"small={smallBytes} B, large={largeBytes} B — allocation must not scale with the sample count");
+ }
}