fix(comm): key site liveness on central receive time; gRPC connect timeout + connect-phase deadline failover (COMM-4, COMM-5, WP4 task 4.4)

This commit is contained in:
Joseph Doherty
2026-12-03 09:52:54 -05:00
parent c1db7094eb
commit f02fe9d696
18 changed files with 350 additions and 38 deletions
@@ -65,10 +65,14 @@ public class CentralCommunicationActorTests : TestKit
var centralActor = Sys.ActorOf(
Props.Create(() => new CentralCommunicationActor(sp, transport)));
var timestamp = DateTimeOffset.UtcNow;
centralActor.Tell(new HeartbeatMessage("site1", "host1", true, timestamp));
// COMM-4: the site stamps its own (here: 30 min fast) clock, but liveness is keyed on
// central's receive time.
var siteStamp = DateTimeOffset.UtcNow.AddMinutes(30);
var before = DateTimeOffset.UtcNow;
centralActor.Tell(new HeartbeatMessage("site1", "host1", true, siteStamp));
AwaitAssert(() => aggregator.Received(1).MarkHeartbeat("site1", timestamp));
AwaitAssert(() => aggregator.Received(1).MarkHeartbeat("site1",
Arg.Is<DateTimeOffset>(t => t >= before && t <= DateTimeOffset.UtcNow)));
}
/// <summary>Verifies that a replicated heartbeat marks the local aggregator without being rebroadcast.</summary>
@@ -93,10 +97,13 @@ public class CentralCommunicationActorTests : TestKit
var centralActor = Sys.ActorOf(
Props.Create(() => new CentralCommunicationActor(sp, transport)));
var ts = DateTimeOffset.UtcNow;
centralActor.Tell(new SiteHeartbeatReplica(new HeartbeatMessage("site-1", "host-a", true, ts)));
var before = DateTimeOffset.UtcNow;
centralActor.Tell(new SiteHeartbeatReplica(
new HeartbeatMessage("site-1", "host-a", true, before.AddMinutes(-30))));
AwaitAssert(() => aggregator.Received(1).MarkHeartbeat("site-1", ts));
// Keyed on this node's receive time, not the site stamp (COMM-4).
AwaitAssert(() => aggregator.Received(1).MarkHeartbeat("site-1",
Arg.Is<DateTimeOffset>(t => t >= before && t <= DateTimeOffset.UtcNow)));
}
/// <summary>Verifies that a failure loading site addresses is logged rather than silently swallowed.</summary>
@@ -0,0 +1,168 @@
using Grpc.Core;
using Grpc.Net.Client;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.ScadaBridge.Communication.Grpc;
namespace ZB.MOM.WW.ScadaBridge.Communication.Tests.Grpc;
/// <summary>
/// COMM-5: a black-holed peer (SYNs silently dropped) must surface as a failover-worthy error
/// well inside a call deadline, not as a DeadlineExceeded that never moves the channel pair.
/// The live cases dial <c>192.0.2.1</c> (TEST-NET-1, never routed). On a host with a default
/// route the SYN is dropped (the black-hole shape); on a host without one the connect fails
/// fast with a socket error instead — every assertion here holds for either, since both are
/// failover-worthy.
/// </summary>
public sealed class GrpcConnectTimeoutTests
{
private const string BlackHole = "http://192.0.2.1:8083";
/// <summary>A <c>ConnectTimeout</c> firing on the subchannel is a provably-unsent connect failure.</summary>
[Fact]
public void SubchannelConnectTimeout_IsNeverSent()
{
var ex = new RpcException(new Status(StatusCode.Unavailable, GrpcRetrySafety.SubchannelConnectFailureDetail,
new TimeoutException("A connection could not be established within the configured ConnectTimeout.",
new OperationCanceledException())));
Assert.True(GrpcRetrySafety.WasNeverSent(ex));
Assert.True(GrpcRetrySafety.ProvablyNotApplied(ex));
}
/// <summary>The option defaults to 5 s and is validated positive.</summary>
[Fact]
public void GrpcConnectTimeout_DefaultsToFiveSeconds_AndMustBePositive()
{
Assert.Equal(TimeSpan.FromSeconds(5), new CommunicationOptions().GrpcConnectTimeout);
var result = new CommunicationOptionsValidator().Validate(null, new CommunicationOptions { GrpcConnectTimeout = TimeSpan.Zero });
Assert.True(result.Failed);
Assert.Contains("GrpcConnectTimeout", result.FailureMessage);
}
/// <summary>
/// With the connect timeout shorter than the deadline, a black-holed peer fails Unavailable
/// and provably unsent — so the pair fails over even for a mutation.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task BlackHoledPeer_WithConnectTimeout_FailsUnavailableAndNeverSent()
{
using var channel = GrpcChannel.ForAddress(BlackHole, new GrpcChannelOptions
{
HttpHandler = new SocketsHttpHandler { ConnectTimeout = TimeSpan.FromMilliseconds(500) },
});
var client = new SiteStreamService.SiteStreamServiceClient(channel);
var ex = await Assert.ThrowsAsync<RpcException>(() => client.PullAuditEventsAsync(
new PullAuditEventsRequest(), deadline: DateTime.UtcNow.AddSeconds(10)).ResponseAsync);
Assert.Equal(StatusCode.Unavailable, ex.StatusCode);
Assert.True(GrpcRetrySafety.WasNeverSent(ex), $"expected a never-sent connect failure, got: {ex.Status.DebugException}");
}
/// <summary>
/// With the deadline shorter than the connect timeout, the call ends DeadlineExceeded while the
/// channel is still connecting — recognised as a connect-phase deadline.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task BlackHoledPeer_DeadlineBeforeConnectTimeout_IsAConnectPhaseDeadline()
{
using var channel = GrpcChannel.ForAddress(BlackHole, new GrpcChannelOptions
{
HttpHandler = new SocketsHttpHandler { ConnectTimeout = TimeSpan.FromSeconds(30) },
});
var client = new SiteStreamService.SiteStreamServiceClient(channel);
var ex = await Assert.ThrowsAsync<RpcException>(() => client.PullAuditEventsAsync(
new PullAuditEventsRequest(), deadline: DateTime.UtcNow.AddMilliseconds(400)).ResponseAsync);
if (ex.StatusCode == StatusCode.DeadlineExceeded)
Assert.True(GrpcRetrySafety.IsConnectPhaseDeadline(ex, channel));
else
Assert.True(GrpcRetrySafety.WasNeverSent(ex), "no default route: the connect fails fast instead");
}
/// <summary>A deadline on a non-connecting state (a plain server-side deadline) is not connect-phase.</summary>
[Fact]
public void NonDeadlineStatuses_AreNotConnectPhaseDeadlines()
{
using var channel = GrpcChannel.ForAddress(BlackHole);
Assert.False(GrpcRetrySafety.IsConnectPhaseDeadline(
new RpcException(new Status(StatusCode.Unavailable, "x")), channel));
// A fresh channel that never attempted a connection is Idle, not connecting.
Assert.False(GrpcRetrySafety.IsConnectPhaseDeadline(
new RpcException(new Status(StatusCode.DeadlineExceeded, "")), channel));
}
/// <summary>
/// SitePairChannelProvider: a connect-phase DeadlineExceeded on node A moves the pair to node B
/// (before COMM-5 only Unavailable did, so a black-holed NodeA kept every command).
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task SitePair_ConnectPhaseDeadlineOnNodeA_FlipsToNodeB()
{
using var provider = new SitePairChannelProvider(
new NoKeyProvider(),
Options.Create(new CommunicationOptions()),
NullLogger<SitePairChannelProvider>.Instance,
handlerFactory: _ => new SocketsHttpHandler { ConnectTimeout = TimeSpan.FromSeconds(30) },
reachabilityProbe: (_, _) => Task.FromResult(false));
provider.UpdateSite("site-1", BlackHole, "http://localhost:15399");
var ex = await Assert.ThrowsAsync<RpcException>(() => provider.ExecuteAsync("site-1",
(channel, ct) => new SiteStreamService.SiteStreamServiceClient(channel)
.PullAuditEventsAsync(new PullAuditEventsRequest(), deadline: DateTime.UtcNow.AddMilliseconds(400),
cancellationToken: ct).ResponseAsync,
CancellationToken.None, retrySafe: false));
// Either shape moves the pair: a connect-phase deadline (black hole) or a fast connect
// failure (no default route).
Assert.True(ex.StatusCode is StatusCode.DeadlineExceeded or StatusCode.Unavailable or StatusCode.Aborted,
$"unexpected {ex.StatusCode}");
Assert.False(provider.IsOnPreferredNode("site-1"));
}
/// <summary>
/// GrpcCentralTransport: a heartbeat that times out against a black-holed central-a moves the
/// pair to central-b (before COMM-5 a quiet site whose only traffic is the heartbeat never left
/// a dead central-a and read Offline at central).
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task CentralTransport_HeartbeatConnectPhaseDeadline_FlipsToTheOtherCentral()
{
var options = new CommunicationOptions { HealthReportTimeout = TimeSpan.FromMilliseconds(400) };
using var provider = new CentralChannelProvider(
new[] { BlackHole, "http://localhost:15397" },
new NoKeyProvider(),
"site-1",
options,
NullLogger.Instance,
handlerFactory: _ => new SocketsHttpHandler { ConnectTimeout = TimeSpan.FromSeconds(30) },
backoffBase: TimeSpan.FromMinutes(10),
backoffCap: TimeSpan.FromMinutes(10));
var transport = new GrpcCentralTransport(provider, options, NullLogger<GrpcCentralTransport>.Instance);
transport.SendHeartbeat(
new ZB.MOM.WW.ScadaBridge.Commons.Messages.Health.HeartbeatMessage("site-1", "node-a", true, DateTimeOffset.UtcNow),
Akka.Actor.ActorRefs.Nobody);
var deadline = DateTime.UtcNow.AddSeconds(10);
while (provider.CurrentIndex == 0 && DateTime.UtcNow < deadline)
await Task.Delay(50);
Assert.Equal(1, provider.CurrentIndex);
}
private sealed class NoKeyProvider : ISitePskProvider
{
/// <inheritdoc />
public ValueTask<string> GetAsync(string siteId, CancellationToken ct) => new("k");
/// <inheritdoc />
public void Invalidate(string siteId) { }
}
}
@@ -932,13 +932,20 @@ public class SiteAlarmAggregatorActorTests : TestKit
/// this suite can demonstrate. The deadline is therefore a self-healing guard rather than
/// a fix for a measured production incident.
/// </para>
/// <para>
/// COMM-5 (2026-12) changed what the deadline does: it is now a stream ERROR (flip node,
/// spend a retry) rather than only a release of the in-flight guard, because a black-holed
/// node never resolves the attempt either, and reopening on the same node never left it. If
/// the stalled attempt was in fact a slow-headers stream on the active node, the flip lands on
/// the standby, which refuses at once (COMM-2), and the next error flips back.
/// </para>
/// </summary>
[Fact]
public void OpenAttemptThatNeverResolves_ReleasesTheInFlightGuard_SoTheTickCanReopen()
public void OpenAttemptThatNeverResolves_IsAStreamError_FlipsToTheOtherNode()
{
// 250 ms deadline; the reconcile timer is parked 10 minutes away so the ONLY tick is
// the one this test issues by hand.
var (actor, seed, sink, factory) = CreateActor(
// 250 ms deadline; the reconcile timer is parked 10 minutes away so nothing but the
// open deadline can move the stream.
var (_, seed, sink, factory) = CreateActor(
reconcileInterval: TimeSpan.FromMinutes(10),
autoConnect: false,
openAttemptTimeout: TimeSpan.FromMilliseconds(250));
@@ -947,18 +954,18 @@ public class SiteAlarmAggregatorActorTests : TestKit
AwaitCondition(() => factory.ClientFor(GrpcNodeA).Subs.Count == 1, TimeSpan.FromSeconds(3));
seed.CompleteNext();
// The stream never reports connected, never faults, never completes — the quiet-site
// header-timeout shape. Liveness is (correctly) false the whole time.
AssertHoldsFor(TimeSpan.FromMilliseconds(300),
(() => !sink.StreamLive, "a stream that never connected must never read as live"));
// The stream never reports connected, never faults, never completes — the black-holed
// node / header-timeout shape. Liveness is (correctly) false the whole time.
Assert.False(sink.StreamLive, "a stream that never connected must never read as live");
// Pre-fix this tick found _openInFlight still true and skipped the reopen, leaving
// node A on one subscription forever. Post-fix the deadline has released the flag.
actor.Tell(new RunReconcile());
AwaitCondition(() => factory.ClientFor(GrpcNodeA).Subs.Count == 2, TimeSpan.FromSeconds(5));
// COMM-5: the open deadline is a stream error — the aggregator flips to node B on its
// own (pre-fix it only released the in-flight guard and the next reconcile tick reopened
// on the SAME node, so a black-holed node A was never left).
AwaitCondition(() => factory.ClientFor(GrpcNodeB).Subs.Count == 1, TimeSpan.FromSeconds(5));
Assert.Single(factory.ClientFor(GrpcNodeA).Subs);
// And the reopen is a real one: its connect brings the feed up and earns a re-seed.
factory.ClientFor(GrpcNodeA).Subs[1].OnConnected!();
factory.ClientFor(GrpcNodeB).Subs[0].OnConnected!();
AwaitCondition(() => seed.CallCount == 2, TimeSpan.FromSeconds(3));
seed.CompleteNext();
AwaitCondition(() => sink.StreamLive, TimeSpan.FromSeconds(3));
@@ -57,7 +57,8 @@ public class SyntheticHeartbeatTests : TestKit
actor.Tell(new HeartbeatMessage("site-1", "node-a", IsActive: true, Timestamp: T0));
AwaitAssert(() => aggregator.Received(1).MarkHeartbeat("site-1", T0));
// Marked with central's receive time, not the site stamp T0 (COMM-4).
AwaitAssert(() => aggregator.Received(1).MarkHeartbeat("site-1", Arg.Is<DateTimeOffset>(t => t > T0)));
}
/// <summary>Verifies that a replicated synthetic heartbeat is also skipped.</summary>
@@ -353,6 +353,22 @@ public class CentralHealthAggregatorTests
Assert.True(_aggregator.GetSiteState("site-1")!.IsOnline);
}
/// <summary>
/// COMM-4 regression: a heartbeat stamped in central's future (a fast site clock) must not
/// extend the offline timeout by the skew — it is clamped to central's now.
/// </summary>
[Fact]
public void MarkHeartbeat_FutureStamp_DoesNotDelayOfflineDetection()
{
_aggregator.ProcessReport(MakeReport("site-1", 1));
_aggregator.MarkHeartbeat("site-1", _timeProvider.GetUtcNow().AddMinutes(30));
_timeProvider.Advance(TimeSpan.FromSeconds(61));
_aggregator.CheckForOfflineSites();
Assert.False(_aggregator.GetSiteState("site-1")!.IsOnline);
}
/// <summary>
/// Regression test: an offline-to-online transition must
/// be backed by a fresh LastHeartbeatAt. Previously MarkHeartbeat used