From 34527374ecca940764d4acd8d1a917c7d4a6a43c Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:40:50 -0500 Subject: [PATCH] fix(health): wall-clock-anchored report sequence, nack stale reports, drain standby counters (COMM-1, COMM-6, WP4 task 4.1) --- .../Component-HealthMonitoring.md | 3 + .../Services/ICentralHealthAggregator.cs | 7 +- .../Actors/CentralCommunicationActor.cs | 26 +++-- .../CentralHealthAggregator.cs | 8 +- .../CentralHealthReportLoop.cs | 21 ++-- .../HealthReportSender.cs | 57 +++++++--- .../HealthReportAckTests.cs | 28 +++++ .../CentralHealthAggregatorTests.cs | 11 ++ .../CentralHealthReportLoopTests.cs | 5 +- .../HealthReportSenderTests.cs | 100 ++++++++++++++++++ .../CentralHealthAuditBacklogProviderTests.cs | 2 +- .../Kpi/SiteHealthKpiSampleSourceTests.cs | 2 +- 12 files changed, 231 insertions(+), 39 deletions(-) diff --git a/docs/requirements/Component-HealthMonitoring.md b/docs/requirements/Component-HealthMonitoring.md index 03c728b7..88bd6180 100644 --- a/docs/requirements/Component-HealthMonitoring.md +++ b/docs/requirements/Component-HealthMonitoring.md @@ -48,6 +48,8 @@ Site clusters (metric collection and reporting). Central cluster (aggregation an - Sites send a **health report message** to central at a configurable interval (default: **30 seconds**). - Each report is a **flat snapshot** containing the current values of all monitored metrics, a **monotonic sequence number**, and the **report timestamp** from the site. Central replaces the previous state for that site only if the incoming sequence number is higher than the last received — this prevents stale reports (e.g., delayed in transit or from a pre-failover node) from overwriting newer state. + - **The sequence number is wall-clock anchored on every report** (COMM-1, 2026-12): each report takes `max(previous + 1, now as Unix-ms)`, so after a failover the newly active node's first report sorts above anything the old active node sent, however long either process has run. (The earlier scheme seeded Unix-ms once at process start and added 1 per report; for a pair started `g` ms apart it broke once the active node had sent more than `g` reports — ~42 h for a 5 s gap — after which every report from the new active node was rejected for days.) The same rule drives the central self-report (`$central`). + - **A rejected report is nacked, never silently dropped**: `ICentralHealthAggregator.ProcessReport` returns whether it applied the report, and the central communication actor acks the site with `Accepted=false` + an error on a stale rejection. The site's transport then throws, the per-interval counters are restored into the next report, and the drop is logged at the site. - Central tracks two **distinct** signals per site — do not conflate them: - **Liveness (online/offline)**: driven by the **last signal of any kind** (a full report *or* a transport heartbeat, the latter arriving every ~5s from any reachable site node). If central receives no signal within `OfflineTimeout` (default: **60 seconds**), the site is marked **offline**. Because heartbeats are frequent, this only fires on genuine total loss of contact — not during a single-node failover, when the surviving node keeps heartbeating. The synthetic *central* self-report site has no heartbeat source and uses the longer `CentralOfflineTimeout` (default: **3 minutes**) so a single missed self-report does not flap it offline. - **Metrics staleness**: an **online** site (heartbeats still arriving) that has produced no full **report** within `MetricsStaleTimeout` (default: **2 minutes**) is flagged **metrics stale**. This surfaces the failure mode where a site's report pipeline (`HealthReportSender`) has died but the node is otherwise reachable — previously such a site showed "online with frozen metrics forever". A site that has **never** delivered a report is anchored on its first-contact time (`FirstSeenAt`), so a report pipeline dead from first boot is also flagged after `MetricsStaleTimeout` (previously such a site showed online-with-no-metrics indefinitely). `MetricsStaleTimeout` must be positive and no shorter than the report interval. @@ -60,6 +62,7 @@ Script error rates and alarm evaluation error rates are calculated as **raw coun - The site maintains a counter for each metric that increments on every failure. - Each health report includes the count since the last report. The counter resets after each report is sent. +- A **standby** node does not send reports but still **drains** its interval counters on every report tick (COMM-6), so the first report after it becomes active covers one interval rather than its whole standby life (a node standby for weeks used to report every dead letter of that period as one 30 s spike). - Central displays these as "X errors in the last 30 seconds" (or whatever the configured interval is). - **Script errors** include all failures that prevent a script from completing successfully: unhandled exceptions, timeouts, recursion limit violations, and any other error condition. - **Alarm evaluation errors** include all failures during alarm condition evaluation. diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/ICentralHealthAggregator.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/ICentralHealthAggregator.cs index 31dd1684..e6596dda 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/ICentralHealthAggregator.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/ICentralHealthAggregator.cs @@ -12,7 +12,12 @@ public interface ICentralHealthAggregator /// Processes an incoming health report from a site and updates the aggregated state. /// /// The health report received from the site. - void ProcessReport(SiteHealthReport report); + /// + /// true when the report was applied; false when it was rejected as stale + /// (its sequence number is not above the last one applied for the site). The caller acks + /// the site with the result so a drop is never silent (COMM-1). + /// + bool ProcessReport(SiteHealthReport report); /// /// Bumps the last-seen timestamp for a site, keeping it marked online diff --git a/src/ZB.MOM.WW.ScadaBridge.Communication/Actors/CentralCommunicationActor.cs b/src/ZB.MOM.WW.ScadaBridge.Communication/Actors/CentralCommunicationActor.cs index 1ea0cb6a..b643fab9 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Communication/Actors/CentralCommunicationActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Communication/Actors/CentralCommunicationActor.cs @@ -142,7 +142,10 @@ public class CentralCommunicationActor : ReceiveActor // Health monitoring: heartbeats and health reports from sites Receive(HandleHeartbeat); Receive(HandleSiteHealthReport); - Receive(r => ProcessLocally(r.Report)); + // Block-bodied on purpose: ProcessLocally returns bool, and an expression lambda would + // bind Receive(Predicate), where false means "unhandled" — every stale replica + // (including this node's own self-delivered one) would then be logged as unhandled. + Receive(r => { ProcessLocally(r.Report); }); Receive(r => MarkHeartbeatLocally(r.Heartbeat)); Receive(_ => { /* DistributedPubSub subscribe confirmation */ }); @@ -331,7 +334,7 @@ public class CentralCommunicationActor : ReceiveActor /// private void HandleSiteHealthReport(SiteHealthReport report) { - ProcessLocally(report); + var accepted = ProcessLocally(report); try { @@ -349,7 +352,13 @@ public class CentralCommunicationActor : ReceiveActor // which arrives without an Ask sender) never dead-letters an ack. if (!Sender.IsNobody()) { - Sender.Tell(new SiteHealthReportAck(report.SiteId, report.SequenceNumber, Accepted: true)); + // The ack carries the aggregator's verdict (COMM-1): a report rejected as stale is + // nacked, so the site's transport throws, its per-interval counters are restored, and + // the drop is logged at the site instead of vanishing behind an "Accepted" ack. + Sender.Tell(accepted + ? new SiteHealthReportAck(report.SiteId, report.SequenceNumber, Accepted: true) + : new SiteHealthReportAck(report.SiteId, report.SequenceNumber, Accepted: false, + Error: "Rejected as stale: sequence number is not above the last report central applied for this site")); } } @@ -358,17 +367,16 @@ public class CentralCommunicationActor : ReceiveActor /// Used for both site-originated reports and peer-replicated ones — the /// aggregator is idempotent via sequence-number comparison. /// - private void ProcessLocally(SiteHealthReport report) + private bool ProcessLocally(SiteHealthReport report) { var aggregator = _serviceProvider.GetService(); if (aggregator != null) { - aggregator.ProcessReport(report); - } - else - { - _log.Warning("ICentralHealthAggregator not available, dropping health report from site {0}", report.SiteId); + return aggregator.ProcessReport(report); } + + _log.Warning("ICentralHealthAggregator not available, dropping health report from site {0}", report.SiteId); + return false; } // HandleConnectionStateChanged removed — no production diff --git a/src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/CentralHealthAggregator.cs b/src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/CentralHealthAggregator.cs index 765d558c..bd1d1292 100644 --- a/src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/CentralHealthAggregator.cs +++ b/src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/CentralHealthAggregator.cs @@ -34,7 +34,7 @@ public class CentralHealthAggregator : BackgroundService, ICentralHealthAggregat } /// - public void ProcessReport(SiteHealthReport report) + public bool ProcessReport(SiteHealthReport report) { var now = _timeProvider.GetUtcNow(); @@ -60,7 +60,7 @@ public class CentralHealthAggregator : BackgroundService, ICentralHealthAggregat { _logger.LogInformation( "Site {SiteId} registered with sequence #{Seq}", report.SiteId, report.SequenceNumber); - return; + return true; } // Lost the race — another thread registered first; retry as an update. @@ -72,7 +72,7 @@ public class CentralHealthAggregator : BackgroundService, ICentralHealthAggregat _logger.LogDebug( "Rejecting stale report from site {SiteId}: seq {Incoming} <= {Last}", report.SiteId, report.SequenceNumber, existing.LastSequenceNumber); - return; + return false; } var updated = existing with @@ -98,7 +98,7 @@ public class CentralHealthAggregator : BackgroundService, ICentralHealthAggregat _logger.LogInformation( "Site {SiteId} is back online (seq #{Seq})", report.SiteId, report.SequenceNumber); } - return; + return true; } // CAS lost — the entry changed under us; retry with the fresh value. diff --git a/src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/CentralHealthReportLoop.cs b/src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/CentralHealthReportLoop.cs index ac668e53..100fde17 100644 --- a/src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/CentralHealthReportLoop.cs +++ b/src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/CentralHealthReportLoop.cs @@ -44,12 +44,13 @@ public class CentralHealthReportLoop : BackgroundService private readonly HealthMonitoringOptions _options; private readonly ILogger _logger; - // Seeded with Unix-ms so reports from a node that has newly become active - // (oldest Up member) always sort after reports from any previously-active - // node for siteId="central". - // The clock is read through the injected TimeProvider so the seeding is - // deterministically testable. + // Advanced to max(previous + 1, now-ms) on every report (COMM-1, see + // HealthReportSender.NextSequenceNumber) so reports from a node that has newly become + // active (oldest Up member) always sort after reports from any previously-active node + // for siteId="central". The clock is read through the injected TimeProvider so the + // sequence is deterministically testable. private long _sequenceNumber; + private readonly TimeProvider _timeProvider; /// /// Initializes the central health report loop. @@ -73,7 +74,8 @@ public class CentralHealthReportLoop : BackgroundService _clusterNodeProvider = clusterNodeProvider; _options = options.Value; _logger = logger; - _sequenceNumber = (timeProvider ?? TimeProvider.System).GetUtcNow().ToUnixTimeMilliseconds(); + _timeProvider = timeProvider ?? TimeProvider.System; + _sequenceNumber = _timeProvider.GetUtcNow().ToUnixTimeMilliseconds(); } /// @@ -98,11 +100,16 @@ public class CentralHealthReportLoop : BackgroundService _collector.SetActiveNode(isPrimary); if (!isPrimary) + { + // Drain the per-interval counters on a standby tick (COMM-6) so a failover's + // first report covers one interval, not the node's whole standby life. + _collector.CollectReport(CentralSiteId); continue; + } _collector.SetClusterNodes(_clusterNodeProvider.GetClusterNodes()); - var seq = Interlocked.Increment(ref _sequenceNumber); + var seq = HealthReportSender.NextSequenceNumber(ref _sequenceNumber, _timeProvider); // CollectReport atomically read-and-resets // the per-interval error counters via Interlocked.Exchange. If diff --git a/src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/HealthReportSender.cs b/src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/HealthReportSender.cs index ee9356f5..3647d24f 100644 --- a/src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/HealthReportSender.cs +++ b/src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/HealthReportSender.cs @@ -9,12 +9,14 @@ namespace ZB.MOM.WW.ScadaBridge.HealthMonitoring; /// /// Periodically collects a SiteHealthReport and sends it to central via Akka remoting. -/// Sequence numbers are monotonic and reset on service restart. They are not -/// zero/one-based: the per-process counter is seeded with the current Unix epoch -/// (milliseconds) at construction so that, after a failover, reports from a -/// freshly-active node always sort after reports from any prior active node for the -/// same site — otherwise the central aggregator's sequence-number guard would -/// silently reject the new active's first reports as stale. +/// Sequence numbers are monotonic and not zero/one-based: every report takes +/// max(previous + 1, now as Unix-ms) (see ), so a +/// node that has just become active always sorts after anything the prior active node +/// sent — otherwise the central aggregator's sequence-number guard would reject the new +/// active's reports as stale. Seeding once at process construction and then adding 1 per +/// report (the pre-2026-12 shape) only worked while the two nodes' start gap in ms +/// exceeded the reports already sent (COMM-1): a pair started 5 s apart broke after +/// ~42 h of uptime. /// public class HealthReportSender : BackgroundService { @@ -26,13 +28,11 @@ public class HealthReportSender : BackgroundService private readonly StoreAndForwardStorage? _sfStorage; private readonly IClusterNodeProvider? _clusterNodeProvider; - // Seeded with Unix-ms at construction so reports from a freshly-active - // node always sort after reports from any prior active node for the same - // site. Without this seeding, failover would silently drop the new - // active's first reports because their per-process counter starts below - // the prior active's last sequence number. The clock is read through the - // injected TimeProvider so the seeding is deterministically testable. + // Advanced to max(previous + 1, now-ms) on every report (COMM-1) so a freshly-active + // node always sorts after the prior active node's last report. The clock is read through + // the injected TimeProvider so the sequence is deterministically testable. private long _sequenceNumber; + private readonly TimeProvider _timeProvider; /// Initializes the sender, seeds the monotonic sequence number from the current Unix timestamp. /// Site health metric collector supplying the report payload. @@ -60,7 +60,30 @@ public class HealthReportSender : BackgroundService _siteId = siteIdentityProvider.SiteId; _sfStorage = sfStorage; _clusterNodeProvider = clusterNodeProvider; - _sequenceNumber = (timeProvider ?? TimeProvider.System).GetUtcNow().ToUnixTimeMilliseconds(); + _timeProvider = timeProvider ?? TimeProvider.System; + _sequenceNumber = _timeProvider.GetUtcNow().ToUnixTimeMilliseconds(); + } + + /// + /// Advances the sequence number to max(previous + 1, now as Unix-ms) and returns it. + /// Wall-clock anchored on every call, so after a failover the new active node's first report + /// sorts above the old active's last one regardless of how long either process has run + /// (COMM-1); the previous + 1 floor keeps it strictly monotonic within the process even + /// if the clock steps backwards. + /// + /// The sequence field to advance. + /// The clock to anchor on. + /// The new sequence number. + internal static long NextSequenceNumber(ref long sequence, TimeProvider timeProvider) + { + while (true) + { + var previous = Interlocked.Read(ref sequence); + var nowMs = timeProvider.GetUtcNow().ToUnixTimeMilliseconds(); + var next = Math.Max(previous + 1, nowMs); + if (Interlocked.CompareExchange(ref sequence, next, previous) == previous) + return next; + } } /// @@ -83,8 +106,14 @@ public class HealthReportSender : BackgroundService { // Only the active node (running the DeploymentManager singleton) sends health reports. // The standby node has no instance/connection data and would overwrite the active's report. + // The standby still DRAINS its per-interval counters each tick (COMM-6): increments keep + // landing on a standby (dead letters, etc.), and without the drain weeks of them would + // be reported as one 30 s interval on the first report after a failover. if (!_collector.IsActiveNode) + { + _collector.CollectReport(_siteId); continue; + } if (_clusterNodeProvider != null) { @@ -147,7 +176,7 @@ public class HealthReportSender : BackgroundService } } - var seq = Interlocked.Increment(ref _sequenceNumber); + var seq = NextSequenceNumber(ref _sequenceNumber, _timeProvider); // CollectReport atomically read-and-resets // the per-interval error counters via Interlocked.Exchange. The diff --git a/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/HealthReportAckTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/HealthReportAckTests.cs index a67b4b18..a3028da7 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/HealthReportAckTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/HealthReportAckTests.cs @@ -51,6 +51,7 @@ public class HealthReportAckTests : TestKit var mockRepo = Substitute.For(); mockRepo.GetAllSitesAsync(Arg.Any()).Returns(new List()); var aggregator = Substitute.For(); + aggregator.ProcessReport(Arg.Any()).Returns(true); var services = new ServiceCollection(); services.AddScoped(_ => mockRepo); @@ -66,4 +67,31 @@ public class HealthReportAckTests : TestKit Assert.Equal(3, ack.SequenceNumber); AwaitAssert(() => aggregator.Received().ProcessReport(Arg.Is(r => r.SequenceNumber == 3))); } + + /// + /// COMM-1 regression: a report the aggregator rejects as stale is nacked (Accepted=false with an + /// error), so the site's transport throws and the drop is visible instead of being acked as accepted. + /// + [Fact] + public void CentralCommunicationActor_OnStaleReport_NacksWithError() + { + var mockRepo = Substitute.For(); + mockRepo.GetAllSitesAsync(Arg.Any()).Returns(new List()); + var aggregator = Substitute.For(); + aggregator.ProcessReport(Arg.Any()).Returns(false); + + var services = new ServiceCollection(); + services.AddScoped(_ => mockRepo); + services.AddSingleton(aggregator); + var sp = services.BuildServiceProvider(); + + var transport = Substitute.For(); + var actor = Sys.ActorOf(Props.Create(() => new CentralCommunicationActor(sp, transport))); + + actor.Tell(SampleReport(seq: 4)); + var ack = ExpectMsg(); + Assert.False(ack.Accepted); + Assert.Equal(4, ack.SequenceNumber); + Assert.False(string.IsNullOrEmpty(ack.Error)); + } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/CentralHealthAggregatorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/CentralHealthAggregatorTests.cs index f1f2387b..6fb95d4a 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/CentralHealthAggregatorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/CentralHealthAggregatorTests.cs @@ -113,6 +113,17 @@ public class CentralHealthAggregatorTests } /// Verifies that a report with a sequence number equal to the stored one is rejected. + /// COMM-1: ProcessReport reports its verdict so the caller can nack a dropped report. + [Fact] + public void ProcessReport_ReturnsFalseOnlyWhenRejectedAsStale() + { + Assert.True(_aggregator.ProcessReport(MakeReport("site-1", 5))); + Assert.True(_aggregator.ProcessReport(MakeReport("site-1", 6))); + Assert.False(_aggregator.ProcessReport(MakeReport("site-1", 6))); + Assert.False(_aggregator.ProcessReport(MakeReport("site-1", 2))); + Assert.Equal(6, _aggregator.GetSiteState("site-1")!.LastSequenceNumber); + } + [Fact] public void ProcessReport_RejectsEqualSequence() { diff --git a/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/CentralHealthReportLoopTests.cs b/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/CentralHealthReportLoopTests.cs index 5bfa2e04..3b7cce89 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/CentralHealthReportLoopTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/CentralHealthReportLoopTests.cs @@ -28,7 +28,7 @@ public class CentralHealthReportLoopTests /// Gets the reports passed to . public List Processed { get; } = []; /// - public void ProcessReport(SiteHealthReport report) => Processed.Add(report); + public bool ProcessReport(SiteHealthReport report) { Processed.Add(report); return true; } /// public void MarkHeartbeat(string siteId, DateTimeOffset receivedAt) { } /// @@ -262,7 +262,7 @@ public class CentralHealthReportLoopTests public List Processed { get; } = []; /// - public void ProcessReport(SiteHealthReport report) + public bool ProcessReport(SiteHealthReport report) { var n = Interlocked.Increment(ref _callCount); if (n == 1) @@ -270,6 +270,7 @@ public class CentralHealthReportLoopTests throw new InvalidOperationException("aggregator temporarily unavailable"); } Processed.Add(report); + return true; } /// diff --git a/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/HealthReportSenderTests.cs b/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/HealthReportSenderTests.cs index fae7155d..4f9bec17 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/HealthReportSenderTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/HealthReportSenderTests.cs @@ -478,4 +478,104 @@ public class HealthReportSenderTests Assert.Equal(fixedInstant.ToUnixTimeMilliseconds(), sender.CurrentSequenceNumber); } + + /// + /// COMM-1 regression: two site nodes started 5 s apart; the older one (A) is active and has + /// sent 6 000 reports (~50 h at 30 s). B becomes active. Under the old "seed at construction, + /// +1 per report" scheme B's first sequence (T_B + 1) sorted below A's last (T_A + 6000) and + /// central rejected every B report. With max(prev + 1, now-ms) B's first report sorts + /// above anything A ever sent. + /// + [Fact] + public void NextSequenceNumber_AfterFailover_SortsAboveLongRunningPeer() + { + var t0 = new DateTimeOffset(2026, 12, 1, 0, 0, 0, TimeSpan.Zero); + var clock = new TestTimeProvider(t0); + + long seqA = t0.ToUnixTimeMilliseconds(); + long seqB = t0.AddSeconds(5).ToUnixTimeMilliseconds(); + + long lastA = 0; + for (var i = 0; i < 6000; i++) + { + clock.Advance(TimeSpan.FromSeconds(30)); + lastA = HealthReportSender.NextSequenceNumber(ref seqA, clock); + } + + clock.Advance(TimeSpan.FromSeconds(30)); + var firstB = HealthReportSender.NextSequenceNumber(ref seqB, clock); + + Assert.True(firstB > lastA, $"B's first sequence {firstB} must sort above A's last {lastA}"); + // The old scheme would have produced T_B + 1, below A's T_A + 6000. + Assert.True(t0.AddSeconds(5).ToUnixTimeMilliseconds() + 1 < t0.ToUnixTimeMilliseconds() + 6000); + } + + /// COMM-1: the sequence stays strictly monotonic when the wall clock steps backwards. + [Fact] + public void NextSequenceNumber_ClockStepsBack_StillStrictlyIncreasing() + { + var t0 = new DateTimeOffset(2026, 12, 1, 0, 0, 0, TimeSpan.Zero); + var clock = new TestTimeProvider(t0); + long seq = t0.ToUnixTimeMilliseconds(); + + var a = HealthReportSender.NextSequenceNumber(ref seq, clock); + clock.Advance(TimeSpan.FromMinutes(-10)); + var b = HealthReportSender.NextSequenceNumber(ref seq, clock); + var c = HealthReportSender.NextSequenceNumber(ref seq, clock); + + Assert.True(b > a); + Assert.True(c > b); + } + + /// + /// COMM-6 regression: a standby node drains its per-interval counters every tick, so the first + /// report after it becomes active does not carry its whole standby life as one interval. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task StandbyTicks_DrainIntervalCounters_SoFirstActiveReportIsOneInterval() + { + var transport = new FakeTransport(); + var collector = new SiteHealthCollector(); + collector.SetActiveNode(false); + for (var i = 0; i < 4000; i++) collector.IncrementDeadLetter(); + collector.IncrementScriptError(); + + var sender = new HealthReportSender( + collector, + transport, + Options.Create(new HealthMonitoringOptions { ReportInterval = TimeSpan.FromMilliseconds(30) }), + NullLogger.Instance, + new FakeSiteIdentityProvider()); + + await sender.StartAsync(CancellationToken.None); + try + { + // Let several standby ticks run (30 ms interval), then promote the node. + await Task.Delay(300); + Assert.Empty(transport.SentReports); + + collector.SetActiveNode(true); + await WaitUntilAsync(() => transport.SentReports.Count > 0, TimeSpan.FromSeconds(5)); + } + finally + { + await sender.StopAsync(CancellationToken.None); + } + + var first = transport.SentReports[0]; + Assert.Equal(0, first.DeadLetterCount); + Assert.Equal(0, first.ScriptErrorCount); + } + + private static async Task WaitUntilAsync(Func condition, TimeSpan timeout) + { + var deadline = DateTime.UtcNow + timeout; + while (DateTime.UtcNow < deadline) + { + if (condition()) return; + await Task.Delay(20); + } + Assert.Fail("Condition not met within timeout"); + } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/Kpi/CentralHealthAuditBacklogProviderTests.cs b/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/Kpi/CentralHealthAuditBacklogProviderTests.cs index 30f5f69f..0deaf974 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/Kpi/CentralHealthAuditBacklogProviderTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/Kpi/CentralHealthAuditBacklogProviderTests.cs @@ -100,7 +100,7 @@ public class CentralHealthAuditBacklogProviderTests States.TryGetValue(siteId, out var state) ? state : null; /// - public void ProcessReport(SiteHealthReport report) => throw new NotSupportedException(); + public bool ProcessReport(SiteHealthReport report) => throw new NotSupportedException(); /// public void MarkHeartbeat(string siteId, DateTimeOffset receivedAt) => throw new NotSupportedException(); diff --git a/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/Kpi/SiteHealthKpiSampleSourceTests.cs b/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/Kpi/SiteHealthKpiSampleSourceTests.cs index 2792ec91..051b4121 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/Kpi/SiteHealthKpiSampleSourceTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.HealthMonitoring.Tests/Kpi/SiteHealthKpiSampleSourceTests.cs @@ -265,7 +265,7 @@ public class SiteHealthKpiSampleSourceTests States.TryGetValue(siteId, out var state) ? state : null; /// - public void ProcessReport(SiteHealthReport report) => + public bool ProcessReport(SiteHealthReport report) => throw new NotSupportedException(); ///