fix(comm): fold post-snapshot debug events into the snapshot and fail fast on a snapshot-request failure (COMM-3, COMM-7, WP4 task 4.3)

This commit is contained in:
Joseph Doherty
2026-12-03 09:47:29 -05:00
parent 8a4b466a03
commit c1db7094eb
4 changed files with 278 additions and 7 deletions
@@ -441,6 +441,7 @@ Disconnect is detected at the **transport layer**, never via an application-leve
- **In-flight command/control messages (gRPC call + deadline)**: When a connection drops while a request is in flight (e.g., a deployment sent but no response received), the gRPC call fails or hits its deadline and the caller receives a failure. There is **no automatic retry or buffering at central** — the engineer sees the failure in the UI and re-initiates the action. This is consistent with the design principle that central does not buffer messages. An in-progress deployment whose round-trip exceeds the timeout (default 120 s at `CommunicationService.DeployInstanceAsync`) surfaces as `DeploymentStatus.Failed` to the caller.
- **Debug streams (gRPC)**: Any gRPC stream interruption is detected by the HTTP/2 keepalive PING (~25 s) and triggers reconnection logic in the `DebugStreamBridgeActor`. The bridge actor attempts to reconnect to the other site node endpoint (NodeB if NodeA failed, or vice versa), with up to 3 retries and 5-second backoff. If all retries fail, the consumer is notified via `OnStreamTerminated` and the bridge actor is stopped. Events during the reconnection gap are lost (acceptable for real-time debug view). On successful reconnection, the consumer can request a fresh snapshot to re-sync state.
- **Debug View snapshot hand-over (COMM-3/COMM-7, 2026-12).** The bridge actor buffers stream events until the snapshot arrives and flushes that gap-window buffer right after it; `DebugStreamService.StartStreamAsync` now **holds** every event that follows the snapshot until it hands the snapshot back, folds them into it (newer-or-equal timestamp per entity wins, unseen entities appended) and only then passes later events through to `onEvent`. Before this the gap-window events reached the consumer before the caller had applied the snapshot, so the SignalR hub sent `OnAttributeChanged` ahead of `OnSnapshot` and a client that replaces its state from the snapshot regressed to the older value. A fail-fast `Status.Failure` from the command transport for the snapshot request (no gRPC channel for the site, an immediate RPC error) now fails the start at once with that cause and tears the session down, instead of waiting out the 30 s snapshot timeout.
- **Only the active site node serves streams (COMM-2, 2026-12).** The site stream hub is node-local — Instance Actors, and therefore every attribute/alarm event, exist only on the active node (oldest Up member of the `site-{SiteId}` role, `ActiveNodeEvaluator.SelfIsOldestUp`). `SiteStreamGrpcServer` therefore refuses `SubscribeInstance`/`SubscribeSite` with **`Unavailable`** on a node that is not active, and a watchdog (2 s) ends every open stream with **`Unavailable`** once the node loses the active role. Both consumers treat `Unavailable` as a stream error and flip NodeA↔NodeB, so after a failover — and in the steady state after any NodeA restart, where NodeA rejoins as standby — the Alarm Summary aggregator and Debug View land on the node that produces events. Before this a subscription to a healthy standby succeeded (headers flushed, keepalives passed) and never delivered an event; nothing errored, so the consumer never flipped and `IsLive` stayed true. The ending deliberately uses an error status, not OK: a graceful completion does not flip the node (below). The reconciliation/trace pulls on the same service are not gated — they read node-local stores and must answer on either node.
- **Graceful end of stream is NOT a fault, but it IS a reconnect trigger.** When the site's `GrpcMaxStreamLifetime` (4 h) elapses — and on a graceful site shutdown — the server ends the RPC with status **OK**, so the client's read loop simply finishes with no exception. `SiteStreamGrpcClient` reports that through a dedicated `onCompleted` callback, distinct from `onError`, and both consuming actors treat it as a reconnect trigger that **does not spend (or refund) the error-retry budget** and does **not** flip the node — the peer that closed cleanly is healthy. `SiteAlarmAggregatorActor` marks the stream down and lets the periodic reconcile tick reopen it (which also re-seeds); `DebugStreamBridgeActor` reopens on the same endpoint after `ReconnectDelay`. Both stamp the stream generation on the callback so a completion racing out of an already-replaced stream is ignored, and both observe the subscription `Task` itself so a fault escaping the subscribe call can never go unobserved. Without the `onCompleted` leg an OK completion was invisible to the reconnect logic and the stream stayed silently dead until the central process restarted.
@@ -291,6 +291,37 @@ public class DebugStreamBridgeActor : ReceiveActor, IWithTimers
_snapshotDelivered = true;
});
// Fail-fast reply from the command transport (COMM-7). GrpcSiteTransport answers a
// send it cannot complete (no channel for the site, an immediate RPC error) with
// Status.Failure to the reply target — this actor, for the snapshot request. Before
// the snapshot that is the end of the session: fail it now with the real cause instead
// of waiting out the 30 s snapshot deadline and reporting a generic timeout. After the
// snapshot (e.g. a failed unsubscribe) it is informational only.
Receive<Status.Failure>(failure =>
{
if (_stopped) return;
if (_snapshotDelivered)
{
_log.Debug("Ignoring command-plane failure for {0} after the snapshot: {1}",
_instanceUniqueName, failure.Cause?.Message);
return;
}
_log.Warning("Debug snapshot request for {0} on site {1} failed: {2}",
_instanceUniqueName, _siteIdentifier, failure.Cause?.Message);
Timers.Cancel(SnapshotTimerKey);
CleanupGrpc();
SendUnsubscribe();
_stopped = true;
_preSnapshotBuffer.Clear();
// Hand the cause to DebugStreamService (it intercepts this marker and fails the
// pending StartStreamAsync with it) before the generic termination callback.
_onEvent(new DebugSnapshotRequestFailed(
failure.Cause ?? new InvalidOperationException("The debug snapshot request failed.")));
_onTerminated();
Context.Stop(Self);
});
// Hard snapshot deadline. Nothing else ends a session stuck in the
// buffering phase: the site's reply was lost, so no gRPC error fires, the stream
// keeps delivering events, and stream traffic does not renew the orphan net (which
@@ -577,7 +608,7 @@ public class DebugStreamBridgeActor : ReceiveActor, IWithTimers
/// key via <see cref="string.Concat"/> (e.g. two entries with null AttributePath
/// would otherwise share a key with any entry whose AttributePath is the empty string).
/// </summary>
private static string AttributeKey(AttributeValueChanged a) =>
internal static string AttributeKey(AttributeValueChanged a) =>
string.Concat(
a.InstanceUniqueName ?? string.Empty, KeyDelimiter,
a.AttributePath ?? string.Empty, KeyDelimiter,
@@ -589,7 +620,7 @@ public class DebugStreamBridgeActor : ReceiveActor, IWithTimers
/// reference) are not conflated; empty for computed alarms. Each nullable component is
/// guarded with <c>?? string.Empty</c> to prevent silent key collisions.
/// </summary>
private static string AlarmKey(AlarmStateChanged al) =>
internal static string AlarmKey(AlarmStateChanged al) =>
string.Concat(
al.InstanceUniqueName ?? string.Empty, KeyDelimiter,
al.AlarmName ?? string.Empty, KeyDelimiter,
@@ -862,6 +893,15 @@ internal record ConsumerLivenessTick;
/// </summary>
internal record DebugSnapshotDeadline;
/// <summary>
/// Delivered through the bridge's <c>onEvent</c> callback when the snapshot request failed
/// fast at the command transport (COMM-7). <see cref="DebugStreamService"/> intercepts it and
/// fails the pending <c>StartStreamAsync</c> with <see cref="Cause"/>; it never reaches a
/// consumer.
/// </summary>
/// <param name="Cause">The transport failure.</param>
internal sealed record DebugSnapshotRequestFailed(Exception Cause);
/// <summary>
/// Internal message indicating a gRPC stream error occurred, stamped with the stream
/// generation it came from so a late error out of a cancelled stream can be ignored.
@@ -4,6 +4,7 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.DebugView;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming;
using ZB.MOM.WW.ScadaBridge.Communication.Actors;
using ZB.MOM.WW.ScadaBridge.Communication.Grpc;
@@ -138,16 +139,39 @@ public class DebugStreamService : IDisposable
// Capture the initial snapshot via a TaskCompletionSource
var snapshotTcs = new TaskCompletionSource<DebugViewSnapshot>(TaskCreationOptions.RunContinuationsAsynchronously);
// COMM-3: events that follow the snapshot (the bridge flushes its gap-window buffer
// synchronously, right after the snapshot) are HELD here until this method hands the
// snapshot back, then folded into it. Passing them straight to onEvent delivered them
// before the caller had applied the snapshot, so a consumer that replaces its state
// from the snapshot regressed to the older value (the SignalR hub sent
// OnAttributeChanged before OnSnapshot). All three fields are guarded by `gate`.
var gate = new object();
var handedOver = false;
var held = new List<object>();
Action<object> onEventWrapper = evt =>
{
if (evt is DebugViewSnapshot snapshot && !snapshotTcs.Task.IsCompleted)
if (evt is DebugSnapshotRequestFailed failed)
{
snapshotTcs.TrySetResult(snapshot);
// COMM-7: the snapshot request failed fast at the transport — fail the
// pending start with the real cause (onTerminatedWrapper follows).
snapshotTcs.TrySetException(failed.Cause);
return;
}
else
lock (gate)
{
onEvent(evt);
if (!handedOver)
{
if (evt is DebugViewSnapshot snapshot && !snapshotTcs.Task.IsCompleted)
snapshotTcs.TrySetResult(snapshot);
else
held.Add(evt);
return;
}
}
onEvent(evt);
};
Action onTerminatedWrapper = () =>
@@ -185,6 +209,17 @@ public class DebugStreamService : IDisposable
try
{
snapshot = await snapshotTcs.Task.WaitAsync(timeoutCts.Token);
// Hand over (COMM-3): fold every event held since the snapshot into it, then switch
// the wrapper to pass-through. Under the gate, so an event racing this either lands
// in `held` (and is folded) or is delivered after the switch — never both, never
// ahead of the snapshot it postdates.
lock (gate)
{
snapshot = FoldIntoSnapshot(snapshot, held);
held.Clear();
handedOver = true;
}
}
catch (Exception ex)
{
@@ -203,7 +238,7 @@ public class DebugStreamService : IDisposable
$"Timed out waiting for debug snapshot from {instanceUniqueName} on site {siteIdentifier}.");
throw new InvalidOperationException(
$"Debug stream for {instanceUniqueName} on site {siteIdentifier} terminated before a snapshot was received.",
$"Debug stream for {instanceUniqueName} on site {siteIdentifier} terminated before a snapshot was received: {ex.Message}",
ex);
}
@@ -226,6 +261,67 @@ public class DebugStreamService : IDisposable
return new DebugStreamSession(sessionId, snapshot);
}
/// <summary>
/// Folds live events that arrived after <paramref name="snapshot"/> into it (COMM-3): each
/// <see cref="AttributeValueChanged"/>/<see cref="AlarmStateChanged"/> replaces the snapshot
/// row for the same entity (same identity key the bridge's dedup uses) when it is at least as
/// new, or is appended when the snapshot has no row for it. Events are applied in arrival
/// order, so the result is the state as of the last held event.
/// </summary>
/// <param name="snapshot">The snapshot the site returned.</param>
/// <param name="events">Events received after the snapshot, in arrival order.</param>
/// <returns>The snapshot with the events applied (the same instance when there are none).</returns>
internal static DebugViewSnapshot FoldIntoSnapshot(DebugViewSnapshot snapshot, IReadOnlyList<object> events)
{
if (events.Count == 0 || snapshot.InstanceNotFound) return snapshot;
var attributes = snapshot.AttributeValues.ToList();
var alarms = snapshot.AlarmStates.ToList();
var attrIndex = new Dictionary<string, int>();
for (var i = 0; i < attributes.Count; i++)
attrIndex[DebugStreamBridgeActor.AttributeKey(attributes[i])] = i;
var alarmIndex = new Dictionary<string, int>();
for (var i = 0; i < alarms.Count; i++)
alarmIndex[DebugStreamBridgeActor.AlarmKey(alarms[i])] = i;
foreach (var evt in events)
{
switch (evt)
{
case AttributeValueChanged a:
{
var key = DebugStreamBridgeActor.AttributeKey(a);
if (attrIndex.TryGetValue(key, out var i))
{
if (a.Timestamp >= attributes[i].Timestamp) attributes[i] = a;
}
else
{
attrIndex[key] = attributes.Count;
attributes.Add(a);
}
break;
}
case AlarmStateChanged al:
{
var key = DebugStreamBridgeActor.AlarmKey(al);
if (alarmIndex.TryGetValue(key, out var i))
{
if (al.Timestamp >= alarms[i].Timestamp) alarms[i] = al;
}
else
{
alarmIndex[key] = alarms.Count;
alarms.Add(al);
}
break;
}
}
}
return snapshot with { AttributeValues = attributes, AlarmStates = alarms };
}
/// <summary>
/// Re-reads a site's current streaming endpoints for a running session's reconnect.
/// </summary>
@@ -224,6 +224,140 @@ public class DebugStreamServiceTests : TestKit
ExpectTerminated(bridgeActor, TimeSpan.FromSeconds(3));
}
// --- COMM-3 / COMM-7 ---
private (DebugStreamService Service, Akka.TestKit.TestProbe CommProbe, ServiceProvider Provider, IDisposable Factory) NewMockedService()
{
var instance = new Instance("Site1.Pump01") { Id = 7, SiteId = 3 };
var site = new Site("Site One", "site-1")
{
Id = 3,
GrpcNodeAAddress = "http://localhost:5100",
GrpcNodeBAddress = "http://localhost:5200"
};
var instanceRepo = Substitute.For<ITemplateEngineRepository>();
instanceRepo.GetInstanceByIdAsync(7, Arg.Any<CancellationToken>()).Returns(instance);
var siteRepo = Substitute.For<ISiteRepository>();
siteRepo.GetSiteByIdAsync(3, Arg.Any<CancellationToken>()).Returns(site);
var services = new ServiceCollection();
services.AddScoped(_ => instanceRepo);
services.AddScoped(_ => siteRepo);
var provider = services.BuildServiceProvider();
var commProbe = CreateTestProbe();
var commService = new CommunicationService(
Options.Create(new CommunicationOptions()),
NullLogger<CommunicationService>.Instance);
commService.SetCommunicationActor(commProbe.Ref);
var grpcFactory = new Grpc.MockSiteStreamGrpcClientFactory(new Grpc.MockSiteStreamGrpcClient());
var service = new DebugStreamService(
commService, provider, grpcFactory, NullLogger<DebugStreamService>.Instance);
service.SetActorSystem(Sys);
return (service, commProbe, provider, grpcFactory);
}
private static ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming.AttributeValueChanged Attr(
string name, object? value, DateTimeOffset ts) =>
new("Site1.Pump01", "", name, value, "Good", ts);
/// <summary>
/// COMM-3 regression: a gap-window event (captured while the snapshot was being built, newer
/// than the snapshot row) must not reach the consumer ahead of the snapshot. It is folded into
/// the snapshot StartStreamAsync returns, and only later events are delivered to onEvent.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Comm3_GapWindowEvent_IsFoldedIntoTheSnapshot_NotDeliveredAheadOfIt()
{
var (service, commProbe, provider, factory) = NewMockedService();
using var _p = provider;
using var _f = factory;
using var _s = service;
var delivered = new System.Collections.Concurrent.ConcurrentQueue<object>();
var t0 = DateTimeOffset.UtcNow;
var startTask = service.StartStreamAsync(7, onEvent: e => delivered.Enqueue(e), onTerminated: () => { });
commProbe.ExpectMsg<SiteEnvelope>(TimeSpan.FromSeconds(5));
var bridge = commProbe.LastSender;
// Arrives on the stream BEFORE the snapshot (stream-first), but is newer than the row.
bridge.Tell(Attr("Speed", 42.0, t0.AddSeconds(2)));
bridge.Tell(new ZB.MOM.WW.ScadaBridge.Commons.Messages.DebugView.DebugViewSnapshot(
"Site1.Pump01",
new List<ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming.AttributeValueChanged> { Attr("Speed", 10.0, t0.AddSeconds(1)) },
new List<ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming.AlarmStateChanged>(),
t0.AddSeconds(1)));
var session = await startTask;
var speed = Assert.Single(session.InitialSnapshot.AttributeValues);
Assert.Equal(42.0, speed.Value);
Assert.Empty(delivered);
// After the hand-over, events pass straight through.
bridge.Tell(Attr("Speed", 43.0, t0.AddSeconds(3)));
AwaitCondition(() => !delivered.IsEmpty, TimeSpan.FromSeconds(3));
var live = Assert.IsType<ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming.AttributeValueChanged>(Assert.Single(delivered));
Assert.Equal(43.0, live.Value);
service.StopStream(session.SessionId);
}
/// <summary>COMM-3: the fold keeps a newer snapshot row over an older event and appends unseen entities.</summary>
[Fact]
public void Comm3_FoldIntoSnapshot_RespectsTimestamps_AndAppendsNewEntities()
{
var t0 = DateTimeOffset.UtcNow;
var snapshot = new ZB.MOM.WW.ScadaBridge.Commons.Messages.DebugView.DebugViewSnapshot(
"Site1.Pump01",
new List<ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming.AttributeValueChanged> { Attr("A", 1, t0.AddSeconds(5)) },
new List<ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming.AlarmStateChanged>(),
t0);
var folded = DebugStreamService.FoldIntoSnapshot(snapshot, new object[]
{
Attr("A", 0, t0.AddSeconds(1)), // older than the row: ignored
Attr("B", 2, t0.AddSeconds(2)), // not in the snapshot: appended
new ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming.AlarmStateChanged(
"Site1.Pump01", "Hi", ZB.MOM.WW.ScadaBridge.Commons.Types.Enums.AlarmState.Active, 500, t0.AddSeconds(3)),
});
Assert.Equal(1, folded.AttributeValues.Single(a => a.AttributeName == "A").Value);
Assert.Equal(2, folded.AttributeValues.Single(a => a.AttributeName == "B").Value);
Assert.Single(folded.AlarmStates);
}
/// <summary>
/// COMM-7 regression: the command transport's fail-fast <c>Status.Failure</c> reply to the
/// snapshot request ends the start immediately with the real cause, instead of the 30 s
/// timeout, and tears the bridge actor down.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Comm7_SnapshotRequestFailure_FailsStartFastWithTheCause()
{
var (service, commProbe, provider, factory) = NewMockedService();
using var _p = provider;
using var _f = factory;
using var _s = service;
var terminated = false;
var startTask = service.StartStreamAsync(7, onEvent: _ => { }, onTerminated: () => terminated = true);
commProbe.ExpectMsg<SiteEnvelope>(TimeSpan.FromSeconds(5));
var bridge = commProbe.LastSender;
Watch(bridge);
bridge.Tell(new Status.Failure(new InvalidOperationException("no gRPC channel for site site-1")));
var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => startTask.WaitAsync(TimeSpan.FromSeconds(5)));
Assert.Contains("no gRPC channel for site site-1", ex.Message);
Assert.True(terminated);
ExpectTerminated(bridge, TimeSpan.FromSeconds(3));
Assert.Equal(0, service.SessionCount);
}
// --- single-endpoint sites ---
/// <summary>Verifies that a single-endpoint site uses its sole address for both node slots.</summary>