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:
Joseph Doherty
2026-12-03 09:40:50 -05:00
parent f7e4f5b4ed
commit 34527374ec
12 changed files with 231 additions and 39 deletions
@@ -12,7 +12,12 @@ public interface ICentralHealthAggregator
/// Processes an incoming health report from a site and updates the aggregated state.
/// </summary>
/// <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>
/// 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
Receive<HeartbeatMessage>(HandleHeartbeat);
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<SubscribeAck>(_ => { /* DistributedPubSub subscribe confirmation */ });
@@ -331,7 +334,7 @@ public class CentralCommunicationActor : ReceiveActor
/// </summary>
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.
/// </summary>
private void ProcessLocally(SiteHealthReport report)
private bool ProcessLocally(SiteHealthReport report)
{
var aggregator = _serviceProvider.GetService<ICentralHealthAggregator>();
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
@@ -34,7 +34,7 @@ public class CentralHealthAggregator : BackgroundService, ICentralHealthAggregat
}
/// <inheritdoc />
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.
@@ -44,12 +44,13 @@ public class CentralHealthReportLoop : BackgroundService
private readonly HealthMonitoringOptions _options;
private readonly ILogger<CentralHealthReportLoop> _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;
/// <summary>
/// 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();
}
/// <summary>
@@ -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
@@ -9,12 +9,14 @@ namespace ZB.MOM.WW.ScadaBridge.HealthMonitoring;
/// <summary>
/// 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>
/// 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 <b>not</b> zero/one-based: every report takes
/// <c>max(previous + 1, now as Unix-ms)</c> (see <see cref="NextSequenceNumber"/>), 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.
/// </summary>
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;
/// <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>
@@ -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();
}
/// <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>
@@ -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