diff --git a/docs/AlarmHistorian.md b/docs/AlarmHistorian.md index 0ac4c9446..9432470c0 100644 --- a/docs/AlarmHistorian.md +++ b/docs/AlarmHistorian.md @@ -265,8 +265,46 @@ after that, with no automatic retry. Now: dead-lettered. It shows as a queue that does not drain while `LastError` reports the deferral. - Rows dead-lettered as `max attempts (N) exceeded` before #976 may be outage - casualties; `RetryDeadLettered()` revives them. Rows dead-lettered by a post-#976 node - read `… exceeded while the historian accepted other events`. + casualties; see "Reviving rows the old cap dead-lettered (#1007)" below. Rows + dead-lettered by a post-#976 node read `… exceeded while the historian accepted other events`. + +### Reviving rows the old cap dead-lettered (#1007) + +A node that ran a pre-#976 build through a historian outage holds dead-lettered rows whose +`last_error` is exactly `max attempts (N) exceeded` — outage casualties, not poison. They stay +dead for the retention window (default 30 days, then they are purged and unrecoverable), so do +this soon after upgrading. One-time, idempotent, safe: + +1. Upgrade to a #976+ build (the revived rows must meet the new outage-aware rule). +2. Set `AlarmHistorian__ReviveMaxAttemptsDeadLetters=true` and restart the node (do the Primary, + or both nodes of a pair — the second finds nothing left). +3. Read the Warning `requeued N alarm event(s) the pre-#976 'max attempts' cap dead-lettered` + (N = 0 means nothing to do). The rows rejoin the queue with `attempt_count = 0` and drain in + their original enqueue order. The revival goes through LocalDb, so it replicates to the peer. +4. Remove the setting. Leaving it on is harmless (it re-runs and revives 0 each boot). + +It touches **only** the exact old reason (`last_error GLOB 'max attempts (*) exceeded'`): +`PermanentFail`, corrupt-payload and post-#976 poison dead letters are untouched (use +`RetryDeadLettered()` for those). A revived row that is genuinely poison dead-letters again under +the current rule with the new-style reason, so it cannot loop. Dead letters are visible as +`DeadLetterDepth` before/after. Delivery is at-least-once, so a casualty the historian had in fact +stored is simply re-written. + +### Stalled-queue detection (#1034) + +A queue whose head is rows that always answer `RetryPlease` (or a long outage) does not drain, and +nothing dead-letters it. `AlarmHistorian:StallThresholdHours` (default `2`, `0` disables) reports +the queue **stalled** once rows have been queued on the draining node for that long with no row +delivered or dead-lettered: + +- `HistorianSinkStatus.Stalled` / `LastProgressUtc` (AdminUI `/alarms/historian`, actor status), +- one Warning on entering the state and one Information on leaving it, +- gauge `otopcua.alarm_historian.queue.stalled` (1/0) plus `…queue.depth` / `…queue.dead_letter_depth`, +- the readiness check `alarm-historian`: **Degraded** (still 200, never Unhealthy). + +The sink cannot tell an outage from a retry-forever head (both look like "no Ack"), so it also fires +on a long genuine outage; `LastError` says which. A node that is not the drain owner is never stalled +and promotion restarts the clock. ### Durability bound (important) @@ -352,6 +390,8 @@ node's consolidated `LocalDb:Path` database (see | `Capacity` | long | `1000000` | Max queued rows before the sink evicts the oldest (data-loss signal via `EvictedCount`). | | `DeadLetterRetentionDays` | int | `30` | Days to retain dead-lettered rows before purge. | | `MaxAttempts` | int | `10` | Maximum delivery attempts before a poison (perpetually-retrying) row is dead-lettered automatically. Must be > 0. | +| `StallThresholdHours` | double | `2` | Hours of no queue progress (rows queued, none delivered/dead-lettered, on the draining node) before the queue is reported stalled (#1034). `0` disables. | +| `ReviveMaxAttemptsDeadLetters` | bool | `false` | One-time recovery (#1007): requeue rows the pre-#976 cap dead-lettered as `max attempts (N) exceeded`. Idempotent; remove after one restart. | > The downstream gateway connection lives in `ServerHistorian` (`Endpoint` + env `ServerHistorian__ApiKey`, > `UseTls`, `CaCertificatePath`); alarm-history `ReadEvents` additionally requires the gateway running diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian/IAlarmHistorianSink.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian/IAlarmHistorianSink.cs index 72287399d..dec354379 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian/IAlarmHistorianSink.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian/IAlarmHistorianSink.cs @@ -63,6 +63,12 @@ public sealed class NullAlarmHistorianSink : IAlarmHistorianSink /// its configured capacity. Non-zero values indicate that accepted alarm events /// were dropped before reaching the historian — operator attention required. /// +/// +/// true when rows are queued on a node that owns the drain and nothing has been delivered or dead-lettered for the +/// configured stall threshold (#1034). Fires on both a long historian outage and a queue head of rows that always answer +/// retry; says which. Always false when no threshold is configured. +/// +/// UTC of the last time the queue made progress (a row delivered or dead-lettered) or was seen empty; null when not tracked (no drain yet, or not the drain owner). public sealed record HistorianSinkStatus( long QueueDepth, long DeadLetterDepth, @@ -70,7 +76,9 @@ public sealed record HistorianSinkStatus( DateTime? LastSuccessUtc, string? LastError, HistorianDrainState DrainState, - long EvictedCount = 0); + long EvictedCount = 0, + bool Stalled = false, + DateTime? LastProgressUtc = null); /// Where the drain worker is in its state machine. public enum HistorianDrainState diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian/LocalDbStoreAndForwardSink.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian/LocalDbStoreAndForwardSink.cs index 081b1456f..36b9fe83a 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian/LocalDbStoreAndForwardSink.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian/LocalDbStoreAndForwardSink.cs @@ -90,6 +90,7 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl private readonly int _maxAttempts; private readonly Func _clock; private readonly Func _drainGate; + private readonly TimeSpan? _stallThreshold; private readonly SemaphoreSlim _drainGateLock = new(1, 1); private Timer? _drainTimer; @@ -108,6 +109,11 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl // Tracks the last gate decision so a denial is logged on the transition rather than on every // tick. Null until the first drain runs. private bool? _lastGateDecision; + // Stall detection (#1034). _progressUtc = the last time the queue made progress (a row Ack'd or dead-lettered) or was + // seen empty; null = not tracking (never drained yet, or this node is not the drain owner). _wasStalled drives the + // transition-only logging. + private DateTime? _progressUtc; + private bool _wasStalled; private long _queuedRowCount; // Cached dead-letter depth (R05:7). GetStatus used to run a synchronous COUNT(*) table scan per @@ -148,6 +154,10 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl /// most one node, because the queue replicates — see the class remarks. The default /// (null ⇒ always drain) is the correct single-node and test posture. /// + /// + /// When set (and positive), turns true once rows have been queued on a + /// draining node for this long with no row Ack'd or dead-lettered (#1034). null (the default) disables it. + /// public LocalDbStoreAndForwardSink( ILocalDb db, IAlarmHistorianWriter writer, @@ -157,7 +167,8 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl TimeSpan? deadLetterRetention = null, int maxAttempts = DefaultMaxAttempts, Func? clock = null, - Func? drainGate = null) + Func? drainGate = null, + TimeSpan? stallThreshold = null) { _db = db ?? throw new ArgumentNullException(nameof(db)); _writer = writer ?? throw new ArgumentNullException(nameof(writer)); @@ -168,6 +179,7 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl _maxAttempts = maxAttempts > 0 ? maxAttempts : throw new ArgumentOutOfRangeException(nameof(maxAttempts)); _clock = clock ?? (() => DateTime.UtcNow); _drainGate = drainGate ?? (static () => true); + _stallThreshold = stallThreshold is { } st && st > TimeSpan.Zero ? st : null; _queuedRowCount = ProbeRowCount(deadLettered: false); _deadLetterRowCount = ProbeRowCount(deadLettered: true); @@ -357,7 +369,7 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl { if (!EvaluateDrainGate()) { - lock (_statusLock) { _drainState = HistorianDrainState.NotPrimary; } + lock (_statusLock) { _drainState = HistorianDrainState.NotPrimary; _progressUtc = null; } return; } @@ -371,9 +383,10 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl var batch = await ReadBatchAsync(ct).ConfigureAwait(false); if (batch.Count == 0) { - lock (_statusLock) { _drainState = HistorianDrainState.Idle; } + lock (_statusLock) { _drainState = HistorianDrainState.Idle; _progressUtc = _clock(); } return; } + lock (_statusLock) { _progressUtc ??= _clock(); } // A null/un-deserializable payload can never succeed — dead-letter it // immediately for its own id so it cannot stall the queue head, and @@ -392,6 +405,7 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl } Interlocked.Add(ref _queuedRowCount, -corruptIds.Count); Interlocked.Add(ref _deadLetterRowCount, corruptIds.Count); + lock (_statusLock) { _progressUtc = _clock(); } _logger.Warning( "Dead-lettered {Count} historian queue row(s) with un-deserializable payload", corruptIds.Count); @@ -511,6 +525,7 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl lock (_statusLock) { if (acks > 0) _lastSuccessUtc = _clock(); + if (rowsLeavingQueue > 0) _progressUtc = _clock(); if (outageMsg is not null) _lastError = outageMsg; if (outcomes.Any(o => o == HistorianWriteOutcome.RetryPlease)) @@ -528,10 +543,48 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl } finally { - _drainGateLock.Release(); + try { ObserveStall(); } + finally { _drainGateLock.Release(); } } } + /// + /// Whether the queue is stalled at (#1034): rows are queued, this node owns the drain, and + /// nothing has left the queue for at least the threshold. Pure over the supplied state. + /// + private bool IsStalled(DateTime now, long queued, HistorianDrainState state, DateTime? progressUtc) => + _stallThreshold is { } threshold + && queued > 0 + && state is not (HistorianDrainState.NotPrimary or HistorianDrainState.Disabled) + && progressUtc is { } p + && now - p >= threshold; + + /// Logs a stall once on entering it (and once on leaving it); called after every drain tick. + private void ObserveStall() + { + if (_stallThreshold is null) return; + var queued = Interlocked.Read(ref _queuedRowCount); + bool stalled, changed; + DateTime? progress; + string? lastError; + lock (_statusLock) + { + progress = _progressUtc; + lastError = _lastError; + stalled = IsStalled(_clock(), queued, _drainState, progress); + changed = stalled != _wasStalled; + _wasStalled = stalled; + } + if (!changed) return; + if (stalled) + _logger.Warning( + "Alarm historian queue STALLED: {Queued} event(s) queued and none delivered or dead-lettered since {Since:O} (threshold {Threshold}). " + + "Either the historian has been unreachable that long or the head of the queue is rows that always answer retry; last error: {LastError}", + queued, progress, _stallThreshold, lastError ?? "(none)"); + else + _logger.Information("Alarm historian queue is making progress again (no longer stalled)"); + } + /// /// Consults the injected gate, logging only when the decision changes. /// @@ -591,6 +644,8 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl string? lastError; HistorianDrainState drainState; long evicted; + DateTime? progress; + bool stalled; lock (_statusLock) { lastDrain = _lastDrainUtc; @@ -598,6 +653,8 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl lastError = _lastError; drainState = _drainState; evicted = _evictedCount; + progress = _progressUtc; + stalled = IsStalled(_clock(), queued, drainState, progress); } return new HistorianSinkStatus( @@ -607,7 +664,9 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl LastSuccessUtc: lastSuccess, LastError: lastError, DrainState: drainState, - EvictedCount: evicted); + EvictedCount: evicted, + Stalled: stalled, + LastProgressUtc: progress); } /// Operator action from Admin UI — retry every dead-lettered row. Non-cascading: they rejoin the regular queue + get a fresh backoff. @@ -632,6 +691,44 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl return revived; } + /// + /// One-time recovery (#1007): requeues the rows the PRE-#976 sink dead-lettered with the bare + /// "max attempts (N) exceeded" reason — during a historian outage, when that cap counted every retry — so they + /// are delivered after all. Idempotent and safe to run on every boot. + /// + /// + /// + /// Matches ONLY last_error of exactly the old form (max attempts (*) exceeded, nothing after it). The + /// current rule's reason carries a suffix (… while the historian accepted other events), so a genuine poison + /// row, a PermanentFail row and a corrupt-payload row are never touched — use + /// for those. A revived row gets attempt_count = 0 and no error, and is + /// delivered in its original enqueue order. A revived row that is in fact poison dead-letters again under the + /// current rule with the new-style reason, so it cannot be revived a second time. Rows past + /// DeadLetterRetentionDays were already purged and cannot be recovered. + /// + /// + /// Runs through the LocalDb connection so the revival replicates to the pair peer (the capture triggers). + /// Running it on both nodes is harmless: the second finds nothing left to revive. + /// + /// + /// The number of rows revived. + public int ReviveMaxAttemptsDeadLetters() + { + if (_disposed) throw new ObjectDisposedException(nameof(LocalDbStoreAndForwardSink)); + using var conn = _db.CreateConnection(); + using var cmd = conn.CreateCommand(); + cmd.CommandText = + "UPDATE alarm_sf_events SET dead_lettered = 0, attempt_count = 0, last_error = NULL " + + "WHERE dead_lettered = 1 AND last_error GLOB 'max attempts (*) exceeded'"; + var revived = cmd.ExecuteNonQuery(); + if (revived > 0) + { + Interlocked.Add(ref _queuedRowCount, revived); + Interlocked.Add(ref _deadLetterRowCount, -revived); + } + return revived; + } + /// /// One queued row paired with its deserialized event. is /// null when the row's payload_json is corrupt or un-deserializable — diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Health/AlarmHistorianHealthCheck.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Health/AlarmHistorianHealthCheck.cs new file mode 100644 index 000000000..d91f7dfa4 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Health/AlarmHistorianHealthCheck.cs @@ -0,0 +1,60 @@ +using Microsoft.Extensions.Diagnostics.HealthChecks; +using ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian; + +namespace ZB.MOM.WW.OtOpcUa.Host.Health; + +/// +/// Pure decision for the alarm store-and-forward probe (#1034), factored out of +/// so it is table-testable. Never Unhealthy: 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. +/// +public static class AlarmHistorianHealthDecision +{ + /// Maps the sink's status to a health status. + /// The sink status, or null when no durable sink is registered (alarm history disabled). + /// The status, a description and the queue figures. + public static (HealthStatus Status, string Description, IReadOnlyDictionary Data) Evaluate(HistorianSinkStatus? status) + { + if (status is null) + return (HealthStatus.Healthy, "Alarm history store-and-forward is not enabled.", new Dictionary()); + + var data = new Dictionary + { + ["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); + } +} + +/// Readiness-tier check (Degraded at worst) over the alarm store-and-forward queue's stall state (#1034). +/// The registered alarm sink, or null when none is. +public sealed class AlarmHistorianHealthCheck(IAlarmHistorianSink? sink) : IHealthCheck +{ + /// The check's registration name. + public const string Name = "alarm-historian"; + + /// + public Task 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)); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Health/HealthEndpoints.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Health/HealthEndpoints.cs index 9e3995ec9..c36efbe95 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Health/HealthEndpoints.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Health/HealthEndpoints.cs @@ -73,6 +73,15 @@ public static class HealthEndpoints sp => new ScriptRunnerHealthCheck(sp.GetService()), 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()), + failureStatus: null, + tags: new[] { ZbHealthTags.Ready })); } // configdb probe is admin-only (per-cluster mesh Phase 4). A driver-only node gets its config diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/AlarmHistorianMetrics.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/AlarmHistorianMetrics.cs new file mode 100644 index 000000000..73cb08299 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/AlarmHistorianMetrics.cs @@ -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; + +/// +/// Observable gauges over the alarm store-and-forward queue (#1034), hung off the central +/// . They read the sink's cached (no storage scan, +/// no actor Ask), so a scrape is cheap and never blocks the metrics thread. +/// +/// +/// +/// otopcua.alarm_historian.queue.stalled — 1 when rows are queued on the draining node and none has been +/// delivered or dead-lettered for AlarmHistorian:StallThresholdHours; else 0. Alert on it. +/// otopcua.alarm_historian.queue.depth / .dead_letter_depth — rows waiting / dead-lettered. +/// +/// +public static class AlarmHistorianMetrics +{ + /// Gauge name: 1 while the queue is stalled. + 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)."); + } + + /// Points the gauges at (the process's alarm sink). Re-binding replaces it. + /// The alarm sink whose status the gauges report. + 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 + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/AlarmHistorianOptions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/AlarmHistorianOptions.cs index 9d7ed4a75..18a14734a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/AlarmHistorianOptions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/AlarmHistorianOptions.cs @@ -41,6 +41,25 @@ public sealed class AlarmHistorianOptions /// Defaults to 10 (matches LocalDbStoreAndForwardSink's DefaultMaxAttempts). public int MaxAttempts { get; init; } = LocalDbStoreAndForwardSink.DefaultMaxAttempts; + /// + /// 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 otopcua.alarm_historian.queue.stalled gauge and a + /// Degraded alarm-historian readiness check. Defaults to 2; 0 disables. Fires on a long historian outage + /// as well as on a queue head of retry-forever rows — read LastError to tell which. + /// + public double StallThresholdHours { get; init; } = 2; + + /// + /// One-time recovery (#1007): when true, every host start requeues the rows the pre-#976 sink dead-lettered with + /// the bare "max attempts (N) exceeded" reason during an outage (LocalDbStoreAndForwardSink.ReviveMaxAttemptsDeadLetters). + /// Idempotent — safe to leave on, but intended to be turned on for one restart and then removed. + /// Defaults to false. See docs/AlarmHistorian.md. + /// + public bool ReviveMaxAttemptsDeadLetters { get; init; } + + /// The stall threshold as a , or null when disabled ( <= 0). + public TimeSpan? StallThreshold => StallThresholdHours > 0 ? TimeSpan.FromHours(StallThresholdHours) : null; + /// Returns operator-facing misconfiguration warnings for an Enabled historian /// (empty when disabled or correctly configured). Pure — the registration logs each entry. /// Zero or more human-readable warning messages. @@ -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; } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ServiceCollectionExtensions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ServiceCollectionExtensions.cs index 10e6ca045..7d6f1a1e7 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ServiceCollectionExtensions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ServiceCollectionExtensions.cs @@ -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().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; }); diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian.Tests/LocalDbStoreAndForwardSinkRecoveryTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian.Tests/LocalDbStoreAndForwardSinkRecoveryTests.cs new file mode 100644 index 000000000..74fc39580 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian.Tests/LocalDbStoreAndForwardSinkRecoveryTests.cs @@ -0,0 +1,210 @@ +using Shouldly; +using Xunit; + +namespace ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian.Tests; + +/// +/// #1007 (one-time revival of rows the pre-#976 "max attempts" cap dead-lettered during an outage) and #1034 +/// (a queue that stops making progress is reported as stalled). +/// +public sealed partial class LocalDbStoreAndForwardSinkTests +{ + private const string OldCapReason = "max attempts (10) exceeded"; + + private async Task SetDeadLetterAsync(string alarmId, string? lastError, int attempts = 10) + { + // Rewrites a row exactly as the pre-#976 sink left it (dead-lettered with the old reason). + var n = await Db.ExecuteAsync( + "UPDATE alarm_sf_events SET dead_lettered = 1, attempt_count = @A, last_error = @E, last_attempt_utc = @T WHERE alarm_id = @Id", + new { A = attempts, E = lastError, T = DateTime.UtcNow.ToString("O"), Id = alarmId }, + TestContext.Current.CancellationToken); + n.ShouldBe(1); + } + + /// The revival touches ONLY rows the old cap dead-lettered; genuine dead letters stay dead. + [Fact] + public async Task Revive_requeues_only_rows_the_old_max_attempts_cap_dead_lettered() + { + var writer = new FakeWriter(); + using var sink = new LocalDbStoreAndForwardSink(Db, writer, _log); + var t = DateTime.UtcNow; + foreach (var id in new[] { "old-cap-1", "old-cap-2", "permanent", "poison", "corrupt", "live" }) + await sink.EnqueueAsync(Event(id, t = t.AddSeconds(1)), CancellationToken.None); + + await SetDeadLetterAsync("old-cap-1", OldCapReason); + await SetDeadLetterAsync("old-cap-2", "max attempts (3) exceeded"); // a different MaxAttempts is still the old cap + await SetDeadLetterAsync("permanent", "permanent fail at 2026-12-01T00:00:00.0000000Z", 1); + await SetDeadLetterAsync("poison", "max attempts (10) exceeded while the historian accepted other events"); // the #976 rule: a REAL poison row + await SetDeadLetterAsync("corrupt", "corrupt payload at 2026-12-01T00:00:00.0000000Z", 1); + await sink.DebugResyncCountersAsync(CancellationToken.None); + sink.GetStatus().DeadLetterDepth.ShouldBe(5); + + var revived = sink.ReviveMaxAttemptsDeadLetters(); + + revived.ShouldBe(2); + var status = sink.GetStatus(); + status.DeadLetterDepth.ShouldBe(3, "permanent / poison / corrupt rows stay dead-lettered"); + status.QueueDepth.ShouldBe(3, "the live row plus the two revived rows"); + + var rows = await Db.QueryAsync("SELECT alarm_id, dead_lettered, attempt_count, last_error FROM alarm_sf_events ORDER BY alarm_id", + r => (Id: r.GetString(0), Dead: r.GetInt64(1), Attempts: r.GetInt64(2), Err: r.IsDBNull(3) ? null : r.GetString(3)), + null, TestContext.Current.CancellationToken); + rows.Single(r => r.Id == "old-cap-1").ShouldBe(("old-cap-1", 0L, 0L, null)); + rows.Single(r => r.Id == "old-cap-2").ShouldBe(("old-cap-2", 0L, 0L, null)); + rows.Single(r => r.Id == "permanent").Dead.ShouldBe(1); + rows.Single(r => r.Id == "poison").Dead.ShouldBe(1); + rows.Single(r => r.Id == "corrupt").Dead.ShouldBe(1); + } + + /// Running it again (or on every boot) finds nothing: a revived row has no old-cap reason left. + [Fact] + public async Task Revive_is_idempotent_and_revived_rows_are_delivered_in_enqueue_order() + { + var writer = new FakeWriter(); + using var sink = new LocalDbStoreAndForwardSink(Db, writer, _log); + var t = DateTime.UtcNow; + await sink.EnqueueAsync(Event("a", t.AddSeconds(1)), CancellationToken.None); + await sink.EnqueueAsync(Event("b", t.AddSeconds(2)), CancellationToken.None); + await SetDeadLetterAsync("a", OldCapReason); + await SetDeadLetterAsync("b", OldCapReason); + await sink.DebugResyncCountersAsync(CancellationToken.None); + + sink.ReviveMaxAttemptsDeadLetters().ShouldBe(2); + sink.ReviveMaxAttemptsDeadLetters().ShouldBe(0, "second run is a no-op"); + sink.GetStatus().QueueDepth.ShouldBe(2); + + await sink.DrainOnceAsync(TestContext.Current.CancellationToken); + + writer.Batches.Single().Select(e => e.AlarmId).ShouldBe(["a", "b"]); + sink.GetStatus().QueueDepth.ShouldBe(0); + sink.GetStatus().DeadLetterDepth.ShouldBe(0); + sink.ReviveMaxAttemptsDeadLetters().ShouldBe(0, "delivered rows are gone"); + } + + /// + /// A revived row that is genuinely poison goes back to dead-letter under the NEW rule (so the one-time revival + /// cannot loop): it needs MaxAttempts drains in which the historian proved reachable, and gets a new-style reason. + /// + [Fact] + public async Task A_revived_poison_row_dead_letters_again_with_the_new_reason_and_is_then_not_revived() + { + var writer = new OutageWriter(); + writer.RetryForever.Add("poison"); + using var sink = new LocalDbStoreAndForwardSink(Db, writer, _log, maxAttempts: 2); + var t = DateTime.UtcNow; + await sink.EnqueueAsync(Event("poison", t.AddSeconds(1)), CancellationToken.None); + await SetDeadLetterAsync("poison", OldCapReason, 2); + await sink.DebugResyncCountersAsync(CancellationToken.None); + sink.ReviveMaxAttemptsDeadLetters().ShouldBe(1); + + for (var i = 0; i < 2; i++) + { + await sink.EnqueueAsync(Event($"healthy-{i}", t.AddSeconds(10 + i)), CancellationToken.None); + await sink.DrainOnceAsync(CancellationToken.None); + } + + sink.GetStatus().DeadLetterDepth.ShouldBe(1); + sink.ReviveMaxAttemptsDeadLetters().ShouldBe(0, "the new-rule reason is not the old cap's"); + } + + // ---------------------------------------------------------------------------------------------- #1034 stalled queue + + private static readonly TimeSpan Stall = TimeSpan.FromHours(2); + + /// No progress for the threshold while rows are queued and this node is draining ⇒ Stalled; recovery clears it. + [Fact] + public async Task A_queue_with_no_progress_for_the_threshold_is_reported_stalled_and_recovers_on_the_first_ack() + { + var now = new DateTime(2026, 12, 3, 0, 0, 0, DateTimeKind.Utc); + var writer = new OutageWriter(); + writer.RetryForever.Add("stuck"); + using var sink = new LocalDbStoreAndForwardSink(Db, writer, _log, clock: () => now, stallThreshold: Stall); + await sink.EnqueueAsync(Event("stuck", now), CancellationToken.None); + + await sink.DrainOnceAsync(CancellationToken.None); + sink.GetStatus().Stalled.ShouldBeFalse("first drain only starts the clock"); + + now += Stall - TimeSpan.FromMinutes(1); + await sink.DrainOnceAsync(CancellationToken.None); + sink.GetStatus().Stalled.ShouldBeFalse("just under the threshold"); + + now += TimeSpan.FromMinutes(2); + await sink.DrainOnceAsync(CancellationToken.None); + var stalled = sink.GetStatus(); + stalled.Stalled.ShouldBeTrue(); + stalled.QueueDepth.ShouldBe(1); + stalled.LastProgressUtc.ShouldBe(new DateTime(2026, 12, 3, 0, 0, 0, DateTimeKind.Utc)); + + writer.RetryForever.Clear(); + await sink.DrainOnceAsync(CancellationToken.None); + sink.GetStatus().Stalled.ShouldBeFalse("the row was delivered"); + } + + /// Positive control: a queue that keeps draining (some Ack every drain) is never stalled, however old it gets. + [Fact] + public async Task A_queue_that_keeps_acking_is_never_stalled_even_with_a_retry_forever_row_at_its_head() + { + var now = new DateTime(2026, 12, 3, 0, 0, 0, DateTimeKind.Utc); + var writer = new OutageWriter(); + writer.RetryForever.Add("stuck"); + using var sink = new LocalDbStoreAndForwardSink(Db, writer, _log, clock: () => now, maxAttempts: 100_000, stallThreshold: Stall); + await sink.EnqueueAsync(Event("stuck", now), CancellationToken.None); + + for (var i = 0; i < 10; i++) + { + now += TimeSpan.FromHours(1); + await sink.EnqueueAsync(Event($"ok-{i}", now), CancellationToken.None); + await sink.DrainOnceAsync(CancellationToken.None); + sink.GetStatus().Stalled.ShouldBeFalse($"cycle {i}: the historian is accepting events"); + } + } + + /// A Secondary (gate closed) is not draining on purpose: never Stalled, and promotion restarts the clock. + [Fact] + public async Task A_node_that_is_not_the_drain_owner_is_never_stalled_and_promotion_restarts_the_clock() + { + var now = new DateTime(2026, 12, 3, 0, 0, 0, DateTimeKind.Utc); + var open = false; + var writer = new OutageWriter { Down = true }; + using var sink = new LocalDbStoreAndForwardSink(Db, writer, _log, clock: () => now, stallThreshold: Stall, drainGate: () => open); + await sink.EnqueueAsync(Event("a", now), CancellationToken.None); + + now += TimeSpan.FromHours(10); + await sink.DrainOnceAsync(CancellationToken.None); + sink.GetStatus().DrainState.ShouldBe(HistorianDrainState.NotPrimary); + sink.GetStatus().Stalled.ShouldBeFalse(); + + open = true; // promoted + await sink.DrainOnceAsync(CancellationToken.None); + sink.GetStatus().Stalled.ShouldBeFalse("the clock starts at promotion, not at enqueue"); + now += Stall + TimeSpan.FromMinutes(1); + await sink.DrainOnceAsync(CancellationToken.None); + sink.GetStatus().Stalled.ShouldBeTrue(); + } + + /// An empty queue is never stalled, and the feature is off unless a threshold is configured. + [Fact] + public async Task Stall_detection_is_off_without_a_threshold_and_an_empty_queue_is_never_stalled() + { + var now = new DateTime(2026, 12, 3, 0, 0, 0, DateTimeKind.Utc); + var down = new OutageWriter { Down = true }; + using (var off = new LocalDbStoreAndForwardSink(Db, down, _log, clock: () => now)) + { + await off.EnqueueAsync(Event("a", now), CancellationToken.None); + await off.DrainOnceAsync(CancellationToken.None); + now += TimeSpan.FromDays(2); + await off.DrainOnceAsync(CancellationToken.None); + off.GetStatus().Stalled.ShouldBeFalse("no threshold configured"); + down.Down = false; + await off.DrainOnceAsync(CancellationToken.None); + off.GetStatus().QueueDepth.ShouldBe(0); + } + + using var on = new LocalDbStoreAndForwardSink(Db, down, _log, clock: () => now, stallThreshold: Stall); + await on.DrainOnceAsync(CancellationToken.None); + now += TimeSpan.FromDays(2); + await on.DrainOnceAsync(CancellationToken.None); + on.GetStatus().QueueDepth.ShouldBe(0); + on.GetStatus().Stalled.ShouldBeFalse("nothing queued"); + } +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian.Tests/LocalDbStoreAndForwardSinkTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian.Tests/LocalDbStoreAndForwardSinkTests.cs index 8f5701631..1f3b4a6ba 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian.Tests/LocalDbStoreAndForwardSinkTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian.Tests/LocalDbStoreAndForwardSinkTests.cs @@ -17,7 +17,7 @@ namespace ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian.Tests; /// capacity eviction, and retention-based dead-letter purge. /// [Trait("Category", "Unit")] -public sealed class LocalDbStoreAndForwardSinkTests : IDisposable +public sealed partial class LocalDbStoreAndForwardSinkTests : IDisposable { private readonly string _dbPath; private readonly ILogger _log; diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Health/AlarmHistorianHealthCheckTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Health/AlarmHistorianHealthCheckTests.cs new file mode 100644 index 000000000..149ef2fc2 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Health/AlarmHistorianHealthCheckTests.cs @@ -0,0 +1,55 @@ +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian; +using ZB.MOM.WW.OtOpcUa.Host.Health; + +namespace ZB.MOM.WW.OtOpcUa.Host.Tests.Health; + +/// #1034: a stalled alarm store-and-forward queue is Degraded (still ready/200), never Unhealthy. +public sealed class AlarmHistorianHealthCheckTests +{ + private static HistorianSinkStatus Status(bool stalled, string? lastError = null) => new( + QueueDepth: 12, DeadLetterDepth: 1, LastDrainUtc: null, LastSuccessUtc: null, LastError: lastError, + DrainState: HistorianDrainState.BackingOff, Stalled: stalled, + LastProgressUtc: new DateTime(2026, 12, 3, 0, 0, 0, DateTimeKind.Utc)); + + [Fact] + public void No_sink_is_healthy() => + AlarmHistorianHealthDecision.Evaluate(null).Status.ShouldBe(HealthStatus.Healthy); + + [Fact] + public void A_draining_queue_is_healthy_and_reports_its_figures() + { + var (status, _, data) = AlarmHistorianHealthDecision.Evaluate(Status(stalled: false)); + status.ShouldBe(HealthStatus.Healthy); + data["queueDepth"].ShouldBe(12L); + } + + [Fact] + public void A_stalled_queue_is_degraded_never_unhealthy_and_carries_the_last_error() + { + var (status, description, data) = AlarmHistorianHealthDecision.Evaluate(Status(stalled: true, "Historian unavailable")); + status.ShouldBe(HealthStatus.Degraded); + description.ShouldContain("stalled"); + description.ShouldContain("Historian unavailable"); + data["lastError"].ShouldBe("Historian unavailable"); + } + + [Fact] + public async Task The_check_maps_a_stalled_sink_to_Degraded() + { + var result = await new AlarmHistorianHealthCheck(new FixedSink(Status(stalled: true))) + .CheckHealthAsync(new HealthCheckContext(), TestContext.Current.CancellationToken); + result.Status.ShouldBe(HealthStatus.Degraded); + + (await new AlarmHistorianHealthCheck(null).CheckHealthAsync(new HealthCheckContext(), TestContext.Current.CancellationToken)) + .Status.ShouldBe(HealthStatus.Healthy); + } + + private sealed class FixedSink(HistorianSinkStatus status) : IAlarmHistorianSink + { + public Task EnqueueAsync(AlarmHistorianEvent evt, CancellationToken cancellationToken) => Task.CompletedTask; + public HistorianSinkStatus GetStatus() => status; + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Historian/AlarmHistorianMetricsTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Historian/AlarmHistorianMetricsTests.cs new file mode 100644 index 000000000..c04109c2a --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Historian/AlarmHistorianMetricsTests.cs @@ -0,0 +1,60 @@ +using System.Diagnostics.Metrics; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.Observability; +using ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian; +using ZB.MOM.WW.OtOpcUa.Runtime.Historian; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Historian; + +/// #1034: the alarm-queue stall gauge and the options that drive it. +[Collection("AlarmHistorianMetricsBinding")] // the sink gauges bind process-wide state +public sealed class AlarmHistorianMetricsTests +{ + [Fact] + public void The_stalled_gauge_reads_1_for_a_stalled_sink_and_0_once_it_recovers() + { + var sink = new SwitchSink(); + AlarmHistorianMetrics.Bind(sink); + + Observe().ShouldBe(0); + sink.Stalled = true; + Observe().ShouldBe(1); + sink.Stalled = false; + Observe().ShouldBe(0); + } + + private static int Observe() + { + var seen = new List(); + using var listener = new MeterListener + { + InstrumentPublished = (inst, l) => + { + if (ReferenceEquals(inst.Meter, OtOpcUaTelemetry.Meter) && inst.Name == AlarmHistorianMetrics.StalledGaugeName) + l.EnableMeasurementEvents(inst); + }, + }; + listener.SetMeasurementEventCallback((inst, v, _, _) => { if (inst.Name == AlarmHistorianMetrics.StalledGaugeName) seen.Add(v); }); + listener.Start(); + listener.RecordObservableInstruments(); + return seen.Single(); + } + + [Fact] + public void Options_default_to_a_two_hour_stall_threshold_and_no_revival_and_zero_disables() + { + var o = new AlarmHistorianOptions(); + o.StallThreshold.ShouldBe(TimeSpan.FromHours(2)); + o.ReviveMaxAttemptsDeadLetters.ShouldBeFalse(); + new AlarmHistorianOptions { StallThresholdHours = 0 }.StallThreshold.ShouldBeNull(); + new AlarmHistorianOptions { StallThresholdHours = 0.5 }.StallThreshold.ShouldBe(TimeSpan.FromMinutes(30)); + } + + private sealed class SwitchSink : IAlarmHistorianSink + { + public volatile bool Stalled; + public Task EnqueueAsync(AlarmHistorianEvent evt, CancellationToken cancellationToken) => Task.CompletedTask; + public HistorianSinkStatus GetStatus() => new(1, 0, null, null, null, HistorianDrainState.BackingOff, Stalled: Stalled); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Historian/AlarmHistorianRegistrationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Historian/AlarmHistorianRegistrationTests.cs index 6b806a176..4d08bf70a 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Historian/AlarmHistorianRegistrationTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Historian/AlarmHistorianRegistrationTests.cs @@ -17,6 +17,7 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Historian; /// default survives; when it is enabled a real wins /// (last-registration-wins over the TryAddSingleton Null default). /// +[Collection("AlarmHistorianMetricsBinding")] // the sink gauges bind process-wide state public sealed class AlarmHistorianRegistrationTests { /// A no-op writer the factory hands the sink; never actually invoked in these tests.