feat(historian): #1007 one-time revival of 'max attempts' dead letters; #1034 stalled alarm S&F queue detection (status, log, gauge, Degraded health)

#1007: LocalDbStoreAndForwardSink.ReviveMaxAttemptsDeadLetters requeues only rows whose last_error is exactly the pre-#976 'max attempts (N) exceeded' (idempotent, replicates through LocalDb); driven by AlarmHistorian:ReviveMaxAttemptsDeadLetters for one restart. Runbook in docs/AlarmHistorian.md.
#1034: AlarmHistorian:StallThresholdHours (default 2, 0 disables) -> HistorianSinkStatus.Stalled/LastProgressUtc, transition logs, otopcua.alarm_historian.queue.* gauges, Degraded 'alarm-historian' readiness check.
Both touch the same sink/options/registration files, hence one commit.
This commit is contained in:
Joseph Doherty
2026-12-03 15:04:03 -05:00
parent bd973f2ea7
commit 0ef9a31b28
13 changed files with 629 additions and 10 deletions
@@ -0,0 +1,60 @@
using Microsoft.Extensions.Diagnostics.HealthChecks;
using ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian;
namespace ZB.MOM.WW.OtOpcUa.Host.Health;
/// <summary>
/// Pure decision for the alarm store-and-forward probe (#1034), factored out of <see cref="AlarmHistorianHealthCheck"/>
/// so it is table-testable. <b>Never Unhealthy:</b> a stuck alarm-history queue does not stop the node serving driver data
/// (and on a redundant pair failing readiness would shift ServiceLevel to a peer that shares the same queue and the same
/// historian), so a stall is Degraded — still 200, but visible.
/// </summary>
public static class AlarmHistorianHealthDecision
{
/// <summary>Maps the sink's status to a health status.</summary>
/// <param name="status">The sink status, or <c>null</c> when no durable sink is registered (alarm history disabled).</param>
/// <returns>The status, a description and the queue figures.</returns>
public static (HealthStatus Status, string Description, IReadOnlyDictionary<string, object> Data) Evaluate(HistorianSinkStatus? status)
{
if (status is null)
return (HealthStatus.Healthy, "Alarm history store-and-forward is not enabled.", new Dictionary<string, object>());
var data = new Dictionary<string, object>
{
["queueDepth"] = status.QueueDepth,
["deadLetterDepth"] = status.DeadLetterDepth,
["evictedCount"] = status.EvictedCount,
["drainState"] = status.DrainState.ToString(),
};
if (status.LastProgressUtc is { } progress) data["lastProgressUtc"] = progress.ToString("O");
if (status.LastError is { } error) data["lastError"] = error;
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.LastError is null ? "." : $" (last error: {status.LastError})."),
data)
: (HealthStatus.Healthy, $"Alarm history queue draining ({status.QueueDepth} queued).", data);
}
}
/// <summary>Readiness-tier check (Degraded at worst) over the alarm store-and-forward queue's stall state (#1034).</summary>
/// <param name="sink">The registered alarm sink, or <c>null</c> when none is.</param>
public sealed class AlarmHistorianHealthCheck(IAlarmHistorianSink? sink) : IHealthCheck
{
/// <summary>The check's registration name.</summary>
public const string Name = "alarm-historian";
/// <inheritdoc />
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
HistorianSinkStatus? status;
try { status = sink?.GetStatus(); }
catch (ObjectDisposedException) { status = null; } // shutting down
var (health, description, data) = AlarmHistorianHealthDecision.Evaluate(status);
return Task.FromResult(health == HealthStatus.Healthy
? HealthCheckResult.Healthy(description, data)
: HealthCheckResult.Degraded(description, data: data));
}
}
@@ -73,6 +73,15 @@ public static class HealthEndpoints
sp => new ScriptRunnerHealthCheck(sp.GetService<ScriptRunnerSelection>()),
failureStatus: null,
tags: new[] { ZbHealthTags.Ready }));
// #1034: alarm store-and-forward queue stalled (rows queued, none delivered or dead-lettered for
// AlarmHistorian:StallThresholdHours). Ready tier, Degraded at worst (still 200): a stuck alarm-history
// queue must not take the node out of rotation. Healthy when alarm history is not enabled.
checks.Add(new HealthCheckRegistration(
AlarmHistorianHealthCheck.Name,
sp => new AlarmHistorianHealthCheck(sp.GetService<ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian.IAlarmHistorianSink>()),
failureStatus: null,
tags: new[] { ZbHealthTags.Ready }));
}
// configdb probe is admin-only (per-cluster mesh Phase 4). A driver-only node gets its config
@@ -0,0 +1,48 @@
using System.Diagnostics.Metrics;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Historian;
/// <summary>
/// Observable gauges over the alarm store-and-forward queue (#1034), hung off the central
/// <see cref="OtOpcUaTelemetry.Meter"/>. They read the sink's cached <see cref="HistorianSinkStatus"/> (no storage scan,
/// no actor Ask), so a scrape is cheap and never blocks the metrics thread.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><c>otopcua.alarm_historian.queue.stalled</c> — 1 when rows are queued on the draining node and none has been
/// delivered or dead-lettered for <c>AlarmHistorian:StallThresholdHours</c>; else 0. Alert on it.</item>
/// <item><c>otopcua.alarm_historian.queue.depth</c> / <c>.dead_letter_depth</c> — rows waiting / dead-lettered.</item>
/// </list>
/// </remarks>
public static class AlarmHistorianMetrics
{
/// <summary>Gauge name: 1 while the queue is stalled.</summary>
public const string StalledGaugeName = "otopcua.alarm_historian.queue.stalled";
private static volatile IAlarmHistorianSink? _sink;
static AlarmHistorianMetrics()
{
OtOpcUaTelemetry.Meter.CreateObservableGauge(
StalledGaugeName, () => Status()?.Stalled == true ? 1 : 0, unit: "{state}",
description: "1 when alarm events are queued on the draining node and none was delivered or dead-lettered for AlarmHistorian:StallThresholdHours (a long outage or retry-forever rows at the queue head).");
OtOpcUaTelemetry.Meter.CreateObservableGauge(
"otopcua.alarm_historian.queue.depth", () => Status()?.QueueDepth ?? 0L, unit: "{event}",
description: "Alarm events waiting in the store-and-forward queue.");
OtOpcUaTelemetry.Meter.CreateObservableGauge(
"otopcua.alarm_historian.queue.dead_letter_depth", () => Status()?.DeadLetterDepth ?? 0L, unit: "{event}",
description: "Alarm events dead-lettered in the store-and-forward queue (retained until the retention window expires).");
}
/// <summary>Points the gauges at <paramref name="sink"/> (the process's alarm sink). Re-binding replaces it.</summary>
/// <param name="sink">The alarm sink whose status the gauges report.</param>
public static void Bind(IAlarmHistorianSink sink) => _sink = sink ?? throw new ArgumentNullException(nameof(sink));
private static HistorianSinkStatus? Status()
{
try { return _sink?.GetStatus(); }
catch (ObjectDisposedException) { return null; } // a disposed sink (shutdown) reports nothing
}
}
@@ -41,6 +41,25 @@ public sealed class AlarmHistorianOptions
/// Defaults to 10 (matches <c>LocalDbStoreAndForwardSink</c>'s <c>DefaultMaxAttempts</c>).</summary>
public int MaxAttempts { get; init; } = LocalDbStoreAndForwardSink.DefaultMaxAttempts;
/// <summary>
/// Hours of no progress (nothing delivered or dead-lettered while rows are queued on the draining node) after which the
/// queue is reported stalled (#1034): a Warning log, the <c>otopcua.alarm_historian.queue.stalled</c> gauge and a
/// Degraded <c>alarm-historian</c> readiness check. Defaults to 2; <c>0</c> disables. Fires on a long historian outage
/// as well as on a queue head of retry-forever rows — read <c>LastError</c> to tell which.
/// </summary>
public double StallThresholdHours { get; init; } = 2;
/// <summary>
/// One-time recovery (#1007): when <c>true</c>, every host start requeues the rows the pre-#976 sink dead-lettered with
/// the bare "max attempts (N) exceeded" reason during an outage (<c>LocalDbStoreAndForwardSink.ReviveMaxAttemptsDeadLetters</c>).
/// Idempotent — safe to leave on, but intended to be turned on for one restart and then removed.
/// Defaults to <c>false</c>. See <c>docs/AlarmHistorian.md</c>.
/// </summary>
public bool ReviveMaxAttemptsDeadLetters { get; init; }
/// <summary>The stall threshold as a <see cref="TimeSpan"/>, or <c>null</c> when disabled (<see cref="StallThresholdHours"/> &lt;= 0).</summary>
public TimeSpan? StallThreshold => StallThresholdHours > 0 ? TimeSpan.FromHours(StallThresholdHours) : null;
/// <summary>Returns operator-facing misconfiguration warnings for an <c>Enabled</c> historian
/// (empty when disabled or correctly configured). Pure — the registration logs each entry.</summary>
/// <returns>Zero or more human-readable warning messages.</returns>
@@ -56,6 +75,8 @@ public sealed class AlarmHistorianOptions
warnings.Add($"AlarmHistorian:DeadLetterRetentionDays is {DeadLetterRetentionDays} — must be > 0; dead-lettered rows would be purged on every drain tick.");
if (MaxAttempts <= 0)
warnings.Add($"AlarmHistorian:MaxAttempts is {MaxAttempts} — must be > 0; the sink constructor will throw at startup.");
if (StallThresholdHours < 0)
warnings.Add($"AlarmHistorian:StallThresholdHours is {StallThresholdHours} — negative; stall detection is disabled (use 0 to disable explicitly).");
return warnings;
}
}
@@ -229,7 +229,17 @@ public static class ServiceCollectionExtensions
capacity: opts.Capacity,
deadLetterRetention: TimeSpan.FromDays(opts.DeadLetterRetentionDays),
maxAttempts: opts.MaxAttempts,
drainGate: () => !replicated || roleView.ShouldDrainAlarmHistory);
drainGate: () => !replicated || roleView.ShouldDrainAlarmHistory,
stallThreshold: opts.StallThreshold);
if (opts.ReviveMaxAttemptsDeadLetters)
{
var revived = sink.ReviveMaxAttemptsDeadLetters();
Serilog.Log.Logger.ForContext<LocalDbStoreAndForwardSink>().Warning(
"AlarmHistorian:ReviveMaxAttemptsDeadLetters is on: requeued {Revived} alarm event(s) the pre-#976 'max attempts' cap dead-lettered. "
+ "This is a one-time recovery — remove the setting once it reports 0",
revived);
}
AlarmHistorianMetrics.Bind(sink);
sink.StartDrainLoop(TimeSpan.FromSeconds(opts.DrainIntervalSeconds));
return sink;
});