fix(health): wall-clock-anchored report sequence, nack stale reports, drain standby counters (COMM-1, COMM-6, WP4 task 4.1)
This commit is contained in:
@@ -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**).
|
- 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.
|
- 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:
|
- 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.
|
- **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.
|
- **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.
|
- 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.
|
- 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).
|
- 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.
|
- **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.
|
- **Alarm evaluation errors** include all failures during alarm condition evaluation.
|
||||||
|
|||||||
@@ -12,7 +12,12 @@ public interface ICentralHealthAggregator
|
|||||||
/// Processes an incoming health report from a site and updates the aggregated state.
|
/// Processes an incoming health report from a site and updates the aggregated state.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="report">The health report received from the site.</param>
|
/// <param name="report">The health report received from the site.</param>
|
||||||
void ProcessReport(SiteHealthReport report);
|
/// <returns>
|
||||||
|
/// <c>true</c> when the report was applied; <c>false</c> 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).
|
||||||
|
/// </returns>
|
||||||
|
bool ProcessReport(SiteHealthReport report);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Bumps the last-seen timestamp for a site, keeping it marked online
|
/// Bumps the last-seen timestamp for a site, keeping it marked online
|
||||||
|
|||||||
@@ -142,7 +142,10 @@ public class CentralCommunicationActor : ReceiveActor
|
|||||||
// Health monitoring: heartbeats and health reports from sites
|
// Health monitoring: heartbeats and health reports from sites
|
||||||
Receive<HeartbeatMessage>(HandleHeartbeat);
|
Receive<HeartbeatMessage>(HandleHeartbeat);
|
||||||
Receive<SiteHealthReport>(HandleSiteHealthReport);
|
Receive<SiteHealthReport>(HandleSiteHealthReport);
|
||||||
Receive<SiteHealthReportReplica>(r => ProcessLocally(r.Report));
|
// Block-bodied on purpose: ProcessLocally returns bool, and an expression lambda would
|
||||||
|
// bind Receive<T>(Predicate<T>), where false means "unhandled" — every stale replica
|
||||||
|
// (including this node's own self-delivered one) would then be logged as unhandled.
|
||||||
|
Receive<SiteHealthReportReplica>(r => { ProcessLocally(r.Report); });
|
||||||
Receive<SiteHeartbeatReplica>(r => MarkHeartbeatLocally(r.Heartbeat));
|
Receive<SiteHeartbeatReplica>(r => MarkHeartbeatLocally(r.Heartbeat));
|
||||||
Receive<SubscribeAck>(_ => { /* DistributedPubSub subscribe confirmation */ });
|
Receive<SubscribeAck>(_ => { /* DistributedPubSub subscribe confirmation */ });
|
||||||
|
|
||||||
@@ -331,7 +334,7 @@ public class CentralCommunicationActor : ReceiveActor
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
private void HandleSiteHealthReport(SiteHealthReport report)
|
private void HandleSiteHealthReport(SiteHealthReport report)
|
||||||
{
|
{
|
||||||
ProcessLocally(report);
|
var accepted = ProcessLocally(report);
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -349,7 +352,13 @@ public class CentralCommunicationActor : ReceiveActor
|
|||||||
// which arrives without an Ask sender) never dead-letters an ack.
|
// which arrives without an Ask sender) never dead-letters an ack.
|
||||||
if (!Sender.IsNobody())
|
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
|
/// Used for both site-originated reports and peer-replicated ones — the
|
||||||
/// aggregator is idempotent via sequence-number comparison.
|
/// aggregator is idempotent via sequence-number comparison.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private void ProcessLocally(SiteHealthReport report)
|
private bool ProcessLocally(SiteHealthReport report)
|
||||||
{
|
{
|
||||||
var aggregator = _serviceProvider.GetService<ICentralHealthAggregator>();
|
var aggregator = _serviceProvider.GetService<ICentralHealthAggregator>();
|
||||||
if (aggregator != null)
|
if (aggregator != null)
|
||||||
{
|
{
|
||||||
aggregator.ProcessReport(report);
|
return aggregator.ProcessReport(report);
|
||||||
}
|
}
|
||||||
else
|
|
||||||
{
|
|
||||||
_log.Warning("ICentralHealthAggregator not available, dropping health report from site {0}", report.SiteId);
|
_log.Warning("ICentralHealthAggregator not available, dropping health report from site {0}", report.SiteId);
|
||||||
}
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// HandleConnectionStateChanged removed — no production
|
// HandleConnectionStateChanged removed — no production
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ public class CentralHealthAggregator : BackgroundService, ICentralHealthAggregat
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public void ProcessReport(SiteHealthReport report)
|
public bool ProcessReport(SiteHealthReport report)
|
||||||
{
|
{
|
||||||
var now = _timeProvider.GetUtcNow();
|
var now = _timeProvider.GetUtcNow();
|
||||||
|
|
||||||
@@ -60,7 +60,7 @@ public class CentralHealthAggregator : BackgroundService, ICentralHealthAggregat
|
|||||||
{
|
{
|
||||||
_logger.LogInformation(
|
_logger.LogInformation(
|
||||||
"Site {SiteId} registered with sequence #{Seq}", report.SiteId, report.SequenceNumber);
|
"Site {SiteId} registered with sequence #{Seq}", report.SiteId, report.SequenceNumber);
|
||||||
return;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Lost the race — another thread registered first; retry as an update.
|
// Lost the race — another thread registered first; retry as an update.
|
||||||
@@ -72,7 +72,7 @@ public class CentralHealthAggregator : BackgroundService, ICentralHealthAggregat
|
|||||||
_logger.LogDebug(
|
_logger.LogDebug(
|
||||||
"Rejecting stale report from site {SiteId}: seq {Incoming} <= {Last}",
|
"Rejecting stale report from site {SiteId}: seq {Incoming} <= {Last}",
|
||||||
report.SiteId, report.SequenceNumber, existing.LastSequenceNumber);
|
report.SiteId, report.SequenceNumber, existing.LastSequenceNumber);
|
||||||
return;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
var updated = existing with
|
var updated = existing with
|
||||||
@@ -98,7 +98,7 @@ public class CentralHealthAggregator : BackgroundService, ICentralHealthAggregat
|
|||||||
_logger.LogInformation(
|
_logger.LogInformation(
|
||||||
"Site {SiteId} is back online (seq #{Seq})", report.SiteId, report.SequenceNumber);
|
"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.
|
// CAS lost — the entry changed under us; retry with the fresh value.
|
||||||
|
|||||||
@@ -44,12 +44,13 @@ public class CentralHealthReportLoop : BackgroundService
|
|||||||
private readonly HealthMonitoringOptions _options;
|
private readonly HealthMonitoringOptions _options;
|
||||||
private readonly ILogger<CentralHealthReportLoop> _logger;
|
private readonly ILogger<CentralHealthReportLoop> _logger;
|
||||||
|
|
||||||
// Seeded with Unix-ms so reports from a node that has newly become active
|
// Advanced to max(previous + 1, now-ms) on every report (COMM-1, see
|
||||||
// (oldest Up member) always sort after reports from any previously-active
|
// HealthReportSender.NextSequenceNumber) so reports from a node that has newly become
|
||||||
// node for siteId="central".
|
// active (oldest Up member) always sort after reports from any previously-active node
|
||||||
// The clock is read through the injected TimeProvider so the seeding is
|
// for siteId="central". The clock is read through the injected TimeProvider so the
|
||||||
// deterministically testable.
|
// sequence is deterministically testable.
|
||||||
private long _sequenceNumber;
|
private long _sequenceNumber;
|
||||||
|
private readonly TimeProvider _timeProvider;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Initializes the central health report loop.
|
/// Initializes the central health report loop.
|
||||||
@@ -73,7 +74,8 @@ public class CentralHealthReportLoop : BackgroundService
|
|||||||
_clusterNodeProvider = clusterNodeProvider;
|
_clusterNodeProvider = clusterNodeProvider;
|
||||||
_options = options.Value;
|
_options = options.Value;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
_sequenceNumber = (timeProvider ?? TimeProvider.System).GetUtcNow().ToUnixTimeMilliseconds();
|
_timeProvider = timeProvider ?? TimeProvider.System;
|
||||||
|
_sequenceNumber = _timeProvider.GetUtcNow().ToUnixTimeMilliseconds();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -98,11 +100,16 @@ public class CentralHealthReportLoop : BackgroundService
|
|||||||
_collector.SetActiveNode(isPrimary);
|
_collector.SetActiveNode(isPrimary);
|
||||||
|
|
||||||
if (!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;
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
_collector.SetClusterNodes(_clusterNodeProvider.GetClusterNodes());
|
_collector.SetClusterNodes(_clusterNodeProvider.GetClusterNodes());
|
||||||
|
|
||||||
var seq = Interlocked.Increment(ref _sequenceNumber);
|
var seq = HealthReportSender.NextSequenceNumber(ref _sequenceNumber, _timeProvider);
|
||||||
|
|
||||||
// CollectReport atomically read-and-resets
|
// CollectReport atomically read-and-resets
|
||||||
// the per-interval error counters via Interlocked.Exchange. If
|
// the per-interval error counters via Interlocked.Exchange. If
|
||||||
|
|||||||
@@ -9,12 +9,14 @@ namespace ZB.MOM.WW.ScadaBridge.HealthMonitoring;
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Periodically collects a SiteHealthReport and sends it to central via Akka remoting.
|
/// Periodically collects a SiteHealthReport and sends it to central via Akka remoting.
|
||||||
/// Sequence numbers are monotonic and reset on service restart. They are <b>not</b>
|
/// Sequence numbers are monotonic and <b>not</b> zero/one-based: every report takes
|
||||||
/// zero/one-based: the per-process counter is seeded with the current Unix epoch
|
/// <c>max(previous + 1, now as Unix-ms)</c> (see <see cref="NextSequenceNumber"/>), so a
|
||||||
/// (milliseconds) at construction so that, after a failover, reports from a
|
/// node that has just become active always sorts after anything the prior active node
|
||||||
/// freshly-active node always sort after reports from any prior active node for the
|
/// sent — otherwise the central aggregator's sequence-number guard would reject the new
|
||||||
/// same site — otherwise the central aggregator's sequence-number guard would
|
/// active's reports as stale. Seeding once at process construction and then adding 1 per
|
||||||
/// silently reject the new active's first reports as stale.
|
/// 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.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class HealthReportSender : BackgroundService
|
public class HealthReportSender : BackgroundService
|
||||||
{
|
{
|
||||||
@@ -26,13 +28,11 @@ public class HealthReportSender : BackgroundService
|
|||||||
private readonly StoreAndForwardStorage? _sfStorage;
|
private readonly StoreAndForwardStorage? _sfStorage;
|
||||||
private readonly IClusterNodeProvider? _clusterNodeProvider;
|
private readonly IClusterNodeProvider? _clusterNodeProvider;
|
||||||
|
|
||||||
// Seeded with Unix-ms at construction so reports from a freshly-active
|
// Advanced to max(previous + 1, now-ms) on every report (COMM-1) so a freshly-active
|
||||||
// node always sort after reports from any prior active node for the same
|
// node always sorts after the prior active node's last report. The clock is read through
|
||||||
// site. Without this seeding, failover would silently drop the new
|
// the injected TimeProvider so the sequence is deterministically testable.
|
||||||
// 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.
|
|
||||||
private long _sequenceNumber;
|
private long _sequenceNumber;
|
||||||
|
private readonly TimeProvider _timeProvider;
|
||||||
|
|
||||||
/// <summary>Initializes the sender, seeds the monotonic sequence number from the current Unix timestamp.</summary>
|
/// <summary>Initializes the sender, seeds the monotonic sequence number from the current Unix timestamp.</summary>
|
||||||
/// <param name="collector">Site health metric collector supplying the report payload.</param>
|
/// <param name="collector">Site health metric collector supplying the report payload.</param>
|
||||||
@@ -60,7 +60,30 @@ public class HealthReportSender : BackgroundService
|
|||||||
_siteId = siteIdentityProvider.SiteId;
|
_siteId = siteIdentityProvider.SiteId;
|
||||||
_sfStorage = sfStorage;
|
_sfStorage = sfStorage;
|
||||||
_clusterNodeProvider = clusterNodeProvider;
|
_clusterNodeProvider = clusterNodeProvider;
|
||||||
_sequenceNumber = (timeProvider ?? TimeProvider.System).GetUtcNow().ToUnixTimeMilliseconds();
|
_timeProvider = timeProvider ?? TimeProvider.System;
|
||||||
|
_sequenceNumber = _timeProvider.GetUtcNow().ToUnixTimeMilliseconds();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Advances the sequence number to <c>max(previous + 1, now as Unix-ms)</c> 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 <c>previous + 1</c> floor keeps it strictly monotonic within the process even
|
||||||
|
/// if the clock steps backwards.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="sequence">The sequence field to advance.</param>
|
||||||
|
/// <param name="timeProvider">The clock to anchor on.</param>
|
||||||
|
/// <returns>The new sequence number.</returns>
|
||||||
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -83,8 +106,14 @@ public class HealthReportSender : BackgroundService
|
|||||||
{
|
{
|
||||||
// Only the active node (running the DeploymentManager singleton) sends health reports.
|
// 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 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)
|
if (!_collector.IsActiveNode)
|
||||||
|
{
|
||||||
|
_collector.CollectReport(_siteId);
|
||||||
continue;
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
if (_clusterNodeProvider != null)
|
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
|
// CollectReport atomically read-and-resets
|
||||||
// the per-interval error counters via Interlocked.Exchange. The
|
// the per-interval error counters via Interlocked.Exchange. The
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ public class HealthReportAckTests : TestKit
|
|||||||
var mockRepo = Substitute.For<ISiteRepository>();
|
var mockRepo = Substitute.For<ISiteRepository>();
|
||||||
mockRepo.GetAllSitesAsync(Arg.Any<CancellationToken>()).Returns(new List<Site>());
|
mockRepo.GetAllSitesAsync(Arg.Any<CancellationToken>()).Returns(new List<Site>());
|
||||||
var aggregator = Substitute.For<ICentralHealthAggregator>();
|
var aggregator = Substitute.For<ICentralHealthAggregator>();
|
||||||
|
aggregator.ProcessReport(Arg.Any<SiteHealthReport>()).Returns(true);
|
||||||
|
|
||||||
var services = new ServiceCollection();
|
var services = new ServiceCollection();
|
||||||
services.AddScoped(_ => mockRepo);
|
services.AddScoped(_ => mockRepo);
|
||||||
@@ -66,4 +67,31 @@ public class HealthReportAckTests : TestKit
|
|||||||
Assert.Equal(3, ack.SequenceNumber);
|
Assert.Equal(3, ack.SequenceNumber);
|
||||||
AwaitAssert(() => aggregator.Received().ProcessReport(Arg.Is<SiteHealthReport>(r => r.SequenceNumber == 3)));
|
AwaitAssert(() => aggregator.Received().ProcessReport(Arg.Is<SiteHealthReport>(r => r.SequenceNumber == 3)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public void CentralCommunicationActor_OnStaleReport_NacksWithError()
|
||||||
|
{
|
||||||
|
var mockRepo = Substitute.For<ISiteRepository>();
|
||||||
|
mockRepo.GetAllSitesAsync(Arg.Any<CancellationToken>()).Returns(new List<Site>());
|
||||||
|
var aggregator = Substitute.For<ICentralHealthAggregator>();
|
||||||
|
aggregator.ProcessReport(Arg.Any<SiteHealthReport>()).Returns(false);
|
||||||
|
|
||||||
|
var services = new ServiceCollection();
|
||||||
|
services.AddScoped(_ => mockRepo);
|
||||||
|
services.AddSingleton(aggregator);
|
||||||
|
var sp = services.BuildServiceProvider();
|
||||||
|
|
||||||
|
var transport = Substitute.For<ISiteCommandTransport>();
|
||||||
|
var actor = Sys.ActorOf(Props.Create(() => new CentralCommunicationActor(sp, transport)));
|
||||||
|
|
||||||
|
actor.Tell(SampleReport(seq: 4));
|
||||||
|
var ack = ExpectMsg<SiteHealthReportAck>();
|
||||||
|
Assert.False(ack.Accepted);
|
||||||
|
Assert.Equal(4, ack.SequenceNumber);
|
||||||
|
Assert.False(string.IsNullOrEmpty(ack.Error));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -113,6 +113,17 @@ public class CentralHealthAggregatorTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that a report with a sequence number equal to the stored one is rejected.</summary>
|
/// <summary>Verifies that a report with a sequence number equal to the stored one is rejected.</summary>
|
||||||
|
/// <summary>COMM-1: ProcessReport reports its verdict so the caller can nack a dropped report.</summary>
|
||||||
|
[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]
|
[Fact]
|
||||||
public void ProcessReport_RejectsEqualSequence()
|
public void ProcessReport_RejectsEqualSequence()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ public class CentralHealthReportLoopTests
|
|||||||
/// <summary>Gets the reports passed to <see cref="ProcessReport"/>.</summary>
|
/// <summary>Gets the reports passed to <see cref="ProcessReport"/>.</summary>
|
||||||
public List<SiteHealthReport> Processed { get; } = [];
|
public List<SiteHealthReport> Processed { get; } = [];
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public void ProcessReport(SiteHealthReport report) => Processed.Add(report);
|
public bool ProcessReport(SiteHealthReport report) { Processed.Add(report); return true; }
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public void MarkHeartbeat(string siteId, DateTimeOffset receivedAt) { }
|
public void MarkHeartbeat(string siteId, DateTimeOffset receivedAt) { }
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
@@ -262,7 +262,7 @@ public class CentralHealthReportLoopTests
|
|||||||
public List<SiteHealthReport> Processed { get; } = [];
|
public List<SiteHealthReport> Processed { get; } = [];
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public void ProcessReport(SiteHealthReport report)
|
public bool ProcessReport(SiteHealthReport report)
|
||||||
{
|
{
|
||||||
var n = Interlocked.Increment(ref _callCount);
|
var n = Interlocked.Increment(ref _callCount);
|
||||||
if (n == 1)
|
if (n == 1)
|
||||||
@@ -270,6 +270,7 @@ public class CentralHealthReportLoopTests
|
|||||||
throw new InvalidOperationException("aggregator temporarily unavailable");
|
throw new InvalidOperationException("aggregator temporarily unavailable");
|
||||||
}
|
}
|
||||||
Processed.Add(report);
|
Processed.Add(report);
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
|
|||||||
@@ -478,4 +478,104 @@ public class HealthReportSenderTests
|
|||||||
|
|
||||||
Assert.Equal(fixedInstant.ToUnixTimeMilliseconds(), sender.CurrentSequenceNumber);
|
Assert.Equal(fixedInstant.ToUnixTimeMilliseconds(), sender.CurrentSequenceNumber);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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 <c>max(prev + 1, now-ms)</c> B's first report sorts
|
||||||
|
/// above anything A ever sent.
|
||||||
|
/// </summary>
|
||||||
|
[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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>COMM-1: the sequence stays strictly monotonic when the wall clock steps backwards.</summary>
|
||||||
|
[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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[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<HealthReportSender>.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<bool> 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");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -100,7 +100,7 @@ public class CentralHealthAuditBacklogProviderTests
|
|||||||
States.TryGetValue(siteId, out var state) ? state : null;
|
States.TryGetValue(siteId, out var state) ? state : null;
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public void ProcessReport(SiteHealthReport report) => throw new NotSupportedException();
|
public bool ProcessReport(SiteHealthReport report) => throw new NotSupportedException();
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public void MarkHeartbeat(string siteId, DateTimeOffset receivedAt) => throw new NotSupportedException();
|
public void MarkHeartbeat(string siteId, DateTimeOffset receivedAt) => throw new NotSupportedException();
|
||||||
|
|||||||
+1
-1
@@ -265,7 +265,7 @@ public class SiteHealthKpiSampleSourceTests
|
|||||||
States.TryGetValue(siteId, out var state) ? state : null;
|
States.TryGetValue(siteId, out var state) ? state : null;
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public void ProcessReport(SiteHealthReport report) =>
|
public bool ProcessReport(SiteHealthReport report) =>
|
||||||
throw new NotSupportedException();
|
throw new NotSupportedException();
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
|
|||||||
Reference in New Issue
Block a user