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
@@ -271,11 +271,17 @@ Three layers of dead-client detection prevent orphan streams on site nodes:
Keepalive settings are configurable via `CommunicationOptions`:
- `GrpcKeepAlivePingDelay`: 15 seconds (default)
- `GrpcKeepAlivePingTimeout`: 10 seconds (default)
- `GrpcConnectTimeout`: 5 seconds (default, validated positive) — `SocketsHttpHandler.ConnectTimeout` on every cross-cluster channel (central→site command pair, site→central control pair, site stream clients). See *Black-holed peers* below.
- `GrpcMaxStreamLifetime`: 4 hours (default)
- `GrpcMaxConcurrentStreams`: 100 (default)
- `GrpcStreamBatchMaxEvents`: 100 (default) — see Event Batching above
- `GrpcStreamBatchWindow`: 25 ms (default) — see Event Batching above
**Black-holed peers (COMM-5, 2026-12).** A peer whose host silently drops SYNs (powered off behind a router, firewall drop, WAN black hole) used to hold every connect for the OS TCP timeout (~21 s on Windows, ~2 min on Linux), so calls with shorter deadlines ended `DeadlineExceeded` — which neither channel pair failed over on — and a dead node kept every command. Three changes close it:
- `GrpcConnectTimeout` (5 s) makes the connect fail as `Unavailable` ("Error connecting to subchannel.", `TimeoutException` cause) well inside every call deadline. That shape is also recognised by `GrpcRetrySafety.WasNeverSent`, so even a mutation fails over within the call — the request provably never left the client.
- A `DeadlineExceeded` that expires while the channel is still `Connecting`/`TransientFailure` (`GrpcRetrySafety.IsConnectPhaseDeadline`) moves the pair: `SitePairChannelProvider` flips NodeA↔NodeB, `GrpcCentralTransport` flips central-a↔central-b (heartbeat included, so a quiet site leaves a dead central). The deadline is spent, so the call itself is not retried; a deadline on a connected (`Ready`) channel is a slow peer and moves nothing.
- The Alarm Summary aggregator's stream **open deadline** is now a stream error (flip node, spend a retry) rather than only a release of the in-flight guard; before, the next reconcile tick reopened on the same black-holed node indefinitely.
### 6a. Debug Snapshot (Central → Site)
- **Pattern**: Request/Response (one-shot, no subscription).
- Central sends a `DebugSnapshotRequest` (identified by instance unique name) to the site.
@@ -51,7 +51,7 @@ Site clusters (metric collection and reporting). Central cluster (aggregation an
- **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.
- **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). Both are stamped with **central's receive time** — never the site-stamped heartbeat timestamp (COMM-4): the offline check compares against central's clock, so a site clock running X fast used to stretch the timeout to 60 s + X. `MarkHeartbeat` also clamps any future-dated value to central's now. 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.
- **Online recovery**: when central receives a health report from a site that was marked offline, the site is automatically marked **online** and the metrics-stale flag cleared (a fresh report proves the pipeline is alive); a heartbeat alone also restores **online** but leaves the metrics-stale flag untouched. No manual acknowledgment required.
- **Status-transition timestamp**: each online↔offline flip stamps `LastStatusChangeAt`, so the UI can answer "since when has this site been offline/online" rather than only "is it offline now". Report/heartbeat traffic that leaves the status unchanged does not move it.
@@ -34,7 +34,10 @@ public interface ICentralHealthAggregator
/// shown as "unknown" during the failover window.
/// </summary>
/// <param name="siteId">The string identifier of the site that sent the heartbeat.</param>
/// <param name="receivedAt">The UTC timestamp when the heartbeat was received.</param>
/// <param name="receivedAt">
/// The UTC time CENTRAL received the heartbeat (its own clock — never the site-stamped
/// timestamp, COMM-4). A value in the aggregator's future is clamped to its current time.
/// </param>
void MarkHeartbeat(string siteId, DateTimeOffset receivedAt);
/// <summary>Returns a snapshot of all currently tracked site health states.</summary>
@@ -323,8 +323,12 @@ public class CentralCommunicationActor : ReceiveActor
return;
}
// Liveness is keyed on CENTRAL's receive time (COMM-4), never the site-stamped
// heartbeat.Timestamp: the offline check compares against central's clock, so a site
// clock running X ahead used to stretch the 60 s offline timeout to 60 s + X (a site
// without NTP, 30 min fast, read Online for ~31 min after its link dropped).
var aggregator = _serviceProvider.GetService<ICentralHealthAggregator>();
aggregator?.MarkHeartbeat(heartbeat.SiteId, heartbeat.Timestamp);
aggregator?.MarkHeartbeat(heartbeat.SiteId, DateTimeOffset.UtcNow);
}
/// <summary>
@@ -420,8 +420,18 @@ public sealed class SiteAlarmAggregatorActor : ReceiveActor, IWithTimers
_openInFlight = false;
_log.Warning(
"Site-alarm gRPC stream open for {0} did not report connected, error or completion within {1}; " +
"releasing the in-flight guard so the next reconcile tick can reopen",
"treating it as a stream error (flip node, count a retry)",
_siteIdentifier, _openAttemptTimeout);
// COMM-5: an attempt that never resolves is a failed attempt — the node did not
// accept the subscription. Treat it like a stream error so the aggregator flips to
// the other node and spends retry budget; before, it only released the guard and
// the next reconcile tick reopened on the SAME node (bumping the generation, so the
// cancelled attempt's eventual connect error was discarded as stale) — a black-holed
// NodeA was never left. Cancel the stalled attempt first so its late callbacks are
// silent (a cancelled attempt reports neither error nor completion).
_grpcCts?.Cancel();
HandleGrpcError();
});
// Coalesced-publish tick: one publish for a batch of dirtying deltas (N6).
@@ -134,6 +134,17 @@ public class CommunicationOptions
/// <summary>gRPC keepalive ping timeout — stream is considered dead if no response within this period.</summary>
public TimeSpan GrpcKeepAlivePingTimeout { get; set; } = TimeSpan.FromSeconds(10);
/// <summary>
/// TCP connect timeout (<c>SocketsHttpHandler.ConnectTimeout</c>) for every cross-cluster gRPC
/// channel — the central→site command pair, the site→central control pair and the site stream
/// clients (COMM-5). Without it a peer whose host silently drops SYNs (powered off behind a
/// router, firewall drop, WAN black hole) held the connect for the OS TCP timeout (~21 s on
/// Windows, ~2 min on Linux), so calls with shorter deadlines ended <c>DeadlineExceeded</c> and
/// never failed over. With it the connect fails as <c>Unavailable</c> well inside every call
/// deadline. Default 5 s.
/// </summary>
public TimeSpan GrpcConnectTimeout { get; set; } = TimeSpan.FromSeconds(5);
/// <summary>Maximum lifetime for a single gRPC stream before the server forces re-establishment.</summary>
public TimeSpan GrpcMaxStreamLifetime { get; set; } = TimeSpan.FromHours(4);
@@ -64,6 +64,8 @@ public sealed class CommunicationOptionsValidator : OptionsValidatorBase<Communi
builder.RequireThat(options.GrpcKeepAlivePingTimeout > TimeSpan.Zero,
$"ScadaBridge:Communication:GrpcKeepAlivePingTimeout must be a positive duration (was {options.GrpcKeepAlivePingTimeout}).");
builder.RequireThat(options.GrpcConnectTimeout > TimeSpan.Zero,
$"ScadaBridge:Communication:GrpcConnectTimeout must be a positive duration (was {options.GrpcConnectTimeout}).");
builder.RequireThat(options.GrpcMaxStreamLifetime > TimeSpan.Zero,
$"ScadaBridge:Communication:GrpcMaxStreamLifetime must be a positive duration (was {options.GrpcMaxStreamLifetime}).");
@@ -114,6 +114,7 @@ public sealed class CentralChannelProvider : IDisposable
{
KeepAlivePingDelay = options.GrpcKeepAlivePingDelay,
KeepAlivePingTimeout = options.GrpcKeepAlivePingTimeout,
ConnectTimeout = options.GrpcConnectTimeout,
KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always,
EnableMultipleHttp2Connections = true,
},
@@ -151,6 +152,18 @@ public sealed class CentralChannelProvider : IDisposable
return (idx, _clients[idx]);
}
/// <summary>
/// True when <paramref name="error"/> is a <see cref="StatusCode.DeadlineExceeded"/> that expired
/// while the endpoint at <paramref name="index"/> was still not accepting a connection
/// (COMM-5) — see <see cref="GrpcRetrySafety.IsConnectPhaseDeadline"/>.
/// </summary>
/// <param name="error">The RPC failure.</param>
/// <param name="index">The endpoint index the failed call used.</param>
/// <returns><c>true</c> for a connect-phase deadline.</returns>
public bool IsConnectPhaseDeadline(RpcException error, int index)
=> index >= 0 && index < _channels.Length
&& GrpcRetrySafety.IsConnectPhaseDeadline(error, _channels[index]);
/// <summary>
/// Reports that the endpoint at <paramref name="failedIndex"/> refused a connection (an
/// <see cref="StatusCode.Unavailable"/> / connect failure). If it is still the current endpoint
@@ -141,10 +141,12 @@ public sealed class GrpcCentralTransport : ICentralTransport
using var call = client.HeartbeatAsync(dto, options);
await call.ResponseAsync.ConfigureAwait(false);
}
catch (RpcException ex) when (IsConnectFailure(ex))
catch (RpcException ex) when (IsConnectFailure(ex) || _channels.IsConnectPhaseDeadline(ex, index))
{
// Nudge the pair so the next call tries the peer, but never fault: a heartbeat
// failure must not surface on the site's heartbeat timer path.
// failure must not surface on the site's heartbeat timer path. A connect-phase
// deadline (COMM-5: black-holed central node) counts too — otherwise a quiet site
// whose only traffic is the heartbeat never leaves a dead central-a.
_channels.ReportUnavailable(index);
_logger.LogDebug(ex, "Heartbeat to central endpoint {Endpoint} was unavailable.", CurrentEndpointSafe());
}
@@ -213,6 +215,13 @@ public sealed class GrpcCentralTransport : ICentralTransport
replyTo.Tell(new AkkaStatus.Failure(ex));
}
catch (RpcException ex) when (_channels.IsConnectPhaseDeadline(ex, index))
{
// COMM-5: the deadline expired before the endpoint accepted a connection. Move the
// pair so the next call tries the peer; the deadline is spent, so no retry here.
_channels.ReportUnavailable(index);
replyTo.Tell(new AkkaStatus.Failure(ex));
}
catch (Exception ex)
{
// DeadlineExceeded / Internal / PermissionDenied / a PSK-resolution throw — do NOT
@@ -1,6 +1,7 @@
using System.Net.Http;
using System.Net.Sockets;
using Grpc.Core;
using Grpc.Net.Client;
namespace ZB.MOM.WW.ScadaBridge.Communication.Grpc;
@@ -31,11 +32,12 @@ public static class GrpcRetrySafety
/// <summary>
/// True only when the client failed while OPENING a connection, so the request provably never
/// left this process (ScadaBridge#136 — the first command to a stopped node of a site pair).
/// Two shapes qualify, both <see cref="StatusCode.Unavailable"/> with a
/// <see cref="SocketException"/> in the debug-exception chain:
/// Two shapes qualify, both <see cref="StatusCode.Unavailable"/>:
/// <list type="bullet">
/// <item>Grpc.Net.Client's subchannel connect failure (<see cref="SubchannelConnectFailureDetail"/>):
/// the balancer never handed the call a connection, whatever the socket error.</item>
/// <item>Grpc.Net.Client's subchannel connect failure (<see cref="SubchannelConnectFailureDetail"/>)
/// with a <see cref="SocketException"/> or a <see cref="TimeoutException"/> (the
/// <c>SocketsHttpHandler.ConnectTimeout</c> firing on a black-holed peer — COMM-5) in the
/// debug-exception chain: the balancer never handed the call a connection.</item>
/// <item>An <see cref="HttpRequestException"/> classified as a name-resolution or connection
/// error whose socket error can only arise before a connection exists (refused, host not
/// found, DNS try-again / no-data).</item>
@@ -54,10 +56,18 @@ public static class GrpcRetrySafety
HttpRequestException? http = null;
SocketException? socket = null;
TimeoutException? connectTimeout = null;
for (var e = error.Status.DebugException; e is not null; e = e.InnerException)
{
http ??= e as HttpRequestException;
socket ??= e as SocketException;
connectTimeout ??= e as TimeoutException;
}
if (http is null)
{
return (socket is not null || connectTimeout is not null)
&& string.Equals(error.Status.Detail, SubchannelConnectFailureDetail, StringComparison.Ordinal);
}
if (socket is null)
@@ -65,16 +75,41 @@ public static class GrpcRetrySafety
return false;
}
if (http is null)
{
return string.Equals(error.Status.Detail, SubchannelConnectFailureDetail, StringComparison.Ordinal);
}
return http.HttpRequestError is HttpRequestError.NameResolutionError or HttpRequestError.ConnectionError
&& socket.SocketErrorCode is SocketError.ConnectionRefused or SocketError.HostNotFound
or SocketError.TryAgain or SocketError.NoData;
}
/// <summary>
/// True when a <see cref="StatusCode.DeadlineExceeded"/> ended the call while
/// <paramref name="channel"/> was still trying to connect (state <c>Connecting</c> or
/// <c>TransientFailure</c>), i.e. the peer never accepted a connection (COMM-5). That is a
/// reason to move the channel pair to the other node; it is NOT proof the request was unsent
/// for replay purposes, and the spent deadline leaves nothing to retry with anyway. A
/// deadline on a connected (<c>Ready</c>) channel is a slow peer and returns false, as does a
/// channel that does not expose a connectivity state.
/// </summary>
/// <param name="error">The RPC failure to inspect.</param>
/// <param name="channel">The channel the call ran on.</param>
/// <returns><c>true</c> for a deadline that expired in the connect phase.</returns>
public static bool IsConnectPhaseDeadline(RpcException error, GrpcChannel channel)
{
if (error.StatusCode != StatusCode.DeadlineExceeded)
{
return false;
}
try
{
return channel.State is ConnectivityState.Connecting or ConnectivityState.TransientFailure;
}
catch (InvalidOperationException)
{
// Channel built without the subchannel balancer (a custom test handler): unknown.
return false;
}
}
/// <summary>
/// True when a mutation may be replayed on the peer node: the server rejected it before
/// dispatch (<see cref="WasNotDispatched"/>), or the client never sent it (<see cref="WasNeverSent"/>).
@@ -322,6 +322,17 @@ public sealed class SitePairChannelProvider : IDisposable
if (primaryIsA) ConfirmFailback(pair);
return result;
}
catch (RpcException ex) when (secondary is not null && GrpcRetrySafety.IsConnectPhaseDeadline(ex, primary))
{
// COMM-5: the deadline expired while the node was still not accepting a connection
// (black-holed host, deadline shorter than the connect timeout). Move the pair so the
// next call goes to the other node; the spent deadline leaves nothing to retry with.
FlipTo(pair, toIsA: !primaryIsA);
_logger.LogWarning(
"Site {TargetSiteId} node {FromNode} did not accept a connection before the call deadline; next calls go to node {ToNode}",
siteId, primaryIsA ? "A" : "B", primaryIsA ? "B" : "A");
throw;
}
catch (RpcException ex) when (ex.StatusCode == StatusCode.Unavailable)
{
if (secondary is not null) FlipTo(pair, toIsA: !primaryIsA);
@@ -586,6 +597,7 @@ public sealed class SitePairChannelProvider : IDisposable
{
KeepAlivePingDelay = _options.GrpcKeepAlivePingDelay,
KeepAlivePingTimeout = _options.GrpcKeepAlivePingTimeout,
ConnectTimeout = _options.GrpcConnectTimeout,
KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always,
EnableMultipleHttp2Connections = true
}
@@ -92,7 +92,8 @@ public class SiteStreamGrpcClient : IAsyncDisposable, IDisposable
{
KeepAlivePingDelay = options.GrpcKeepAlivePingDelay,
KeepAlivePingTimeout = options.GrpcKeepAlivePingTimeout,
KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always
KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always,
ConnectTimeout = options.GrpcConnectTimeout
}
}.WithMessageLimits().WithSiteCredentials(pskProvider, siteIdentifier, endpoint));
_client = new SiteStreamService.SiteStreamServiceClient(_channel);
@@ -108,6 +108,14 @@ public class CentralHealthAggregator : BackgroundService, ICentralHealthAggregat
/// <inheritdoc />
public void MarkHeartbeat(string siteId, DateTimeOffset receivedAt)
{
// Never let a heartbeat stamp land in central's future (COMM-4): the offline check
// measures `now - LastHeartbeatAt` on central's clock, so a future stamp silently
// extends the offline timeout by the skew. Callers pass central's receive time; this
// clamp keeps a skewed caller from reintroducing the drift.
var clampNow = _timeProvider.GetUtcNow();
if (receivedAt > clampNow)
receivedAt = clampNow;
while (true)
{
if (!_siteStates.TryGetValue(siteId, out var existing))
@@ -151,8 +159,7 @@ public class CentralHealthAggregator : BackgroundService, ICentralHealthAggregat
DateTimeOffset newHeartbeat;
if (!existing.IsOnline)
{
var now = _timeProvider.GetUtcNow();
newHeartbeat = receivedAt > now ? receivedAt : now;
newHeartbeat = _timeProvider.GetUtcNow();
}
else
{
@@ -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