fix(historian): #993 gateway read refusals no longer degrade health, QuestDB reverse events read finds its cut by backward scan, time-weighted aggregator stops allocating per sample

G-9: a gateway-answered InvalidArgument/OutOfRange/NotFound/Unimplemented read is a connectivity observation (open, streak ends), not a failure; outages still degrade.
G-17: capped reverse/end-only QuestDB events reads find the n+1-th latest ts with an early-exit backward scan, then read ts >= cut ordered (ts DESC, event_id DESC).
G-18: Distribute takes a bridged/nonGood flag instead of per-sample delegates (O(buckets) allocation).
QuestDB integration fixture waits up to 60 s for WAL visibility (shared host is CPU-saturated; the 5 s production default made alarm-writer tests read back fewer rows).

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-12-03 10:24:50 -05:00
parent be5641fc06
commit dd1d02e25f
10 changed files with 410 additions and 19 deletions
@@ -39,6 +39,32 @@ internal static class GatewayErrorReasons
GatewayExceptionOf(ex)?.StatusCode == StatusCode.FailedPrecondition
&& string.Equals(ReasonOf(ex), HistorianGatewayErrorReasons.AggregateNotSupportedForTag, StringComparison.Ordinal);
/// <summary>
/// True when <paramref name="ex"/> is the gateway ANSWERING that the request itself is bad — status
/// <see cref="StatusCode.InvalidArgument"/>, <see cref="StatusCode.OutOfRange"/>, <see cref="StatusCode.NotFound"/> or
/// <see cref="StatusCode.Unimplemented"/> (a gateway older than the RPC). Such a failure proves the gateway is reachable
/// and must not degrade the health snapshot (G-9, #993). <see cref="StatusCode.FailedPrecondition"/> is deliberately NOT
/// listed: the gateway also passes historian-side rejections through it, which are backend faults. Transport statuses,
/// <c>Internal</c>, <c>Unknown</c>, auth statuses and non-RPC exceptions are not refusals.
/// </summary>
/// <param name="ex">A gateway call's exception.</param>
/// <returns>Whether it is a request-level refusal.</returns>
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)
@@ -1015,6 +1015,20 @@ public sealed class GatewayHistorianDataSource : IHistorianDataSource, IAsyncDis
/// </summary>
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.");
}
@@ -449,6 +449,18 @@ public sealed class QuestDbHistorianDataSource : IHistorianDataSource
HistorianReadCapabilities.Data | HistorianReadCapabilities.Events | HistorianReadCapabilities.ServerTimestamps;
/// <summary>
/// The backward-scan statement that finds the n+1-th latest event time of a reverse window (G-17, #993): <c>$1</c> =
/// exclusive lower bound, <c>$2</c> = inclusive upper bound, [<c>$3</c> = source,] then the row count.
/// </summary>
/// <param name="eventTable">The event table.</param>
/// <param name="withSource">Whether the statement filters on a source.</param>
/// <returns>The SQL text.</returns>
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);
@@ -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);
/// <summary>Counts <c>[from.t, toTicks)</c> as outage (Bad) time; no value, never marks a bucket invalid.</summary>
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
/// <summary>
/// Splits the linear segment <c>[from.t, toTicks)</c> (value <c>from.v → toValue</c>) 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. <paramref name="bridged"/> 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).
/// </summary>
private void Distribute(StoredSample from, long toTicks, double toValue, Action<long, double, long> 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;
}
}
}