fix(galaxy): #991 G-2/G-3 limit-bit qualities map without a per-event warning; a cleanly completed deploy-watch stream is re-subscribed with backoff

This commit is contained in:
Joseph Doherty
2026-12-03 10:15:00 -05:00
parent be5641fc06
commit 660a2ce9c0
4 changed files with 265 additions and 32 deletions
@@ -27,17 +27,26 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Browse;
/// so a reconnect doesn't fan out a redundant rediscover for state we already
/// knew about.
/// </para>
/// <para>
/// A stream the gateway COMPLETES without an error is paced exactly like a fault (#991 G-3): it used to
/// loop straight back into a new RPC, and since every event — the bootstrap each stream delivers
/// included — reset the backoff, a gateway that ends its streams after the bootstrap (a drain, an
/// idle-stream limit) was re-subscribed as fast as the RPC round-trips. The backoff now resets only when
/// a stream stayed open for <c>stableStreamDuration</c>.
/// </para>
/// </remarks>
public sealed class DeployWatcher : IDisposable
{
private static readonly TimeSpan DefaultInitialBackoff = TimeSpan.FromSeconds(1);
private static readonly TimeSpan DefaultMaxBackoff = TimeSpan.FromSeconds(30);
private static readonly TimeSpan DefaultStableStreamDuration = TimeSpan.FromSeconds(60);
private readonly IGalaxyDeployWatchSource _source;
private readonly ILogger _logger;
private readonly TimeSpan _initialBackoff;
private readonly TimeSpan _maxBackoff;
private readonly Func<int, TimeSpan>? _jitter;
private readonly TimeSpan _stableStreamDuration;
private CancellationTokenSource? _cts;
private Task? _loopTask;
@@ -63,13 +72,19 @@ public sealed class DeployWatcher : IDisposable
/// <param name="initialBackoff">Initial backoff duration for retry.</param>
/// <param name="maxBackoff">Maximum backoff duration for retry.</param>
/// <param name="jitter">Optional function to apply jitter to backoff intervals.</param>
/// <param name="stableStreamDuration">
/// How long a stream must stay open before its end resets the backoff (default 60 s). A shorter-lived
/// stream — clean completion or fault — keeps growing the backoff.
/// </param>
internal DeployWatcher(
IGalaxyDeployWatchSource source,
ILogger? logger,
TimeSpan initialBackoff,
TimeSpan maxBackoff,
Func<int, TimeSpan>? jitter)
Func<int, TimeSpan>? jitter,
TimeSpan? stableStreamDuration = null)
{
_stableStreamDuration = stableStreamDuration ?? DefaultStableStreamDuration;
_source = source ?? throw new ArgumentNullException(nameof(source));
_logger = logger ?? NullLogger.Instance;
_initialBackoff = initialBackoff;
@@ -140,6 +155,8 @@ public sealed class DeployWatcher : IDisposable
while (!cancellationToken.IsCancellationRequested)
{
var streamOpened = System.Diagnostics.Stopwatch.StartNew();
Exception? fault = null;
try
{
await foreach (DeployEvent ev in _source
@@ -147,10 +164,6 @@ public sealed class DeployWatcher : IDisposable
.WithCancellation(cancellationToken)
.ConfigureAwait(false))
{
// Successful read — reset retry state.
backoff = _initialBackoff;
attempt = 0;
DateTimeOffset? observedTime = ev.TimeOfLastDeployPresent && ev.TimeOfLastDeploy is not null
? ev.TimeOfLastDeploy.ToDateTimeOffset()
: null;
@@ -200,10 +213,9 @@ public sealed class DeployWatcher : IDisposable
}
}
// Stream completed normally — gateway closed the subscription. Re-open
// immediately if we weren't asked to stop.
_logger.LogDebug("DeployWatcher stream completed; re-subscribing.");
continue;
// Stream completed normally — the gateway (or a proxy) closed the subscription. Paced below like
// a fault (#991 G-3): an immediate re-open hammered a gateway that ends every stream after the
// bootstrap event.
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
@@ -211,26 +223,47 @@ public sealed class DeployWatcher : IDisposable
}
catch (Exception ex)
{
attempt++;
TimeSpan jitterAmount = _jitter?.Invoke(attempt) ?? RandomJitter(backoff);
TimeSpan delay = backoff + jitterAmount;
_logger.LogWarning(ex,
fault = ex;
}
if (cancellationToken.IsCancellationRequested) break;
// Reset only after a stream that stayed up — an event alone (every stream's bootstrap) proves nothing
// about the gateway keeping it open.
if (streamOpened.Elapsed >= _stableStreamDuration)
{
backoff = _initialBackoff;
attempt = 0;
}
attempt++;
TimeSpan jitterAmount = _jitter?.Invoke(attempt) ?? RandomJitter(backoff);
TimeSpan delay = backoff + jitterAmount;
if (fault is not null)
{
_logger.LogWarning(fault,
"DeployWatcher source threw; retrying in {Delay} (attempt {Attempt}, last-seen time {LastSeen}).",
delay, attempt, lastSeenDeployTime);
try
{
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
// Exponential backoff capped at _maxBackoff.
var doubled = TimeSpan.FromTicks(Math.Min(_maxBackoff.Ticks, backoff.Ticks * 2));
backoff = doubled < _initialBackoff ? _initialBackoff : doubled;
}
else
{
_logger.LogDebug(
"DeployWatcher stream completed by the gateway after {Open}; re-subscribing in {Delay} (attempt {Attempt}).",
streamOpened.Elapsed, delay, attempt);
}
try
{
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
// Exponential backoff capped at _maxBackoff.
var doubled = TimeSpan.FromTicks(Math.Min(_maxBackoff.Ticks, backoff.Ticks * 2));
backoff = doubled < _initialBackoff ? _initialBackoff : doubled;
}
}
@@ -79,7 +79,13 @@ internal static class StatusCodeMap
/// <param name="q">The OPC DA quality byte to convert.</param>
/// <param name="logger">Optional logger for diagnostics on unknown quality bytes.</param>
/// <returns>The OPC UA status code.</returns>
public static uint FromQualityByte(byte q, ILogger? logger = null) => q switch
/// <remarks>
/// #991 G-2: the two OPC DA LIMIT bits (<c>LL</c> in <c>QQSSSSLL</c> — low-limited, high-limited, constant) are
/// masked off before the lookup. They never change the quality category or substatus and every table entry has
/// them clear, so <c>Good | LowLimited</c> (0xC1) used to miss the table and log a Warning on EVERY event — on
/// the pump's single dispatch thread. A byte still unlisted after the mask warns once per distinct value.
/// </remarks>
public static uint FromQualityByte(byte q, ILogger? logger = null) => (byte)(q & QualityLimitMask) switch
{
// Good family — top two bits 11b (192-255).
192 => Good,
@@ -256,13 +262,21 @@ internal static class StatusCodeMap
return Bad;
}
/// <summary>Clears the OPC DA limit bits (the low two bits of the quality byte).</summary>
private const byte QualityLimitMask = 0xFC;
/// <summary>One flag per quality byte, set once that byte has been warned about (#991 G-2). Process-wide.</summary>
private static readonly int[] UnrecognisedQualityWarned = new int[256];
private static void Log(ILogger? logger, byte q, string bucket)
{
// Best-effort diagnostic so field captures can extend the table — once per bucket
// per session is plenty (the LogWarning level is rate-limited by Serilog filters
// in production).
logger?.LogWarning(
// Best-effort diagnostic so field captures can extend the table — once per distinct byte per process
// (#991 G-2). This runs on the event pump's dispatch thread for every event carrying the byte, and a
// per-event Warning slowed dispatch until the bounded channel started dropping events.
if (logger is null || Interlocked.Exchange(ref UnrecognisedQualityWarned[q], 1) != 0) return;
logger.LogWarning(
"Unrecognised MXAccess quality byte 0x{Q:X2} — falling back to {Bucket} category. " +
"Field capture welcome — extend StatusCodeMap.FromQualityByte.", q, bucket);
"Field capture welcome — extend StatusCodeMap.FromQualityByte. Further occurrences of this byte are not logged.",
q, bucket);
}
}
@@ -0,0 +1,90 @@
using System.Runtime.CompilerServices;
using Google.Protobuf.WellKnownTypes;
using Shouldly;
using Xunit;
using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Browse;
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Browse;
/// <summary>
/// #991 G-3 — a <c>WatchDeployEvents</c> stream the gateway (or a proxy in front of it) COMPLETES without an error
/// used to loop straight back into a new RPC: backoff lived only in the fault arm, and every received event reset
/// it. A gateway that delivers the bootstrap event and then ends the stream (a drain, an idle-stream limit) was
/// re-subscribed as fast as the RPC round-trips, indefinitely, with health unaffected.
/// </summary>
public sealed class DeployWatcherCleanCompletionTests
{
/// <summary>Each <c>WatchAsync</c> yields the bootstrap event and then completes cleanly.</summary>
private sealed class BootstrapThenCompleteSource : IGalaxyDeployWatchSource
{
private int _calls;
/// <summary>Gets the number of <c>WatchAsync</c> calls so far.</summary>
public int Calls => Volatile.Read(ref _calls);
/// <inheritdoc />
public async IAsyncEnumerable<DeployEvent> WatchAsync(
DateTimeOffset? lastSeenDeployTime, [EnumeratorCancellation] CancellationToken cancellationToken)
{
Interlocked.Increment(ref _calls);
await Task.Yield();
yield return new DeployEvent
{
Sequence = 0,
TimeOfLastDeployPresent = true,
TimeOfLastDeploy = Timestamp.FromDateTimeOffset(DateTimeOffset.Parse("2026-04-01T00:00:00Z")),
};
}
}
/// <summary>
/// A stream that completes after one event is paced by the backoff (50 ms doubling to 200 ms here): within
/// ~700 ms that is at most a handful of subscribes, not thousands — and it does keep re-subscribing (positive
/// control: the watcher is not simply dead).
/// </summary>
[Fact]
public async Task A_cleanly_completing_stream_is_resubscribed_with_backoff_not_in_a_tight_loop()
{
var source = new BootstrapThenCompleteSource();
using var watcher = new DeployWatcher(
source, logger: null,
initialBackoff: TimeSpan.FromMilliseconds(50),
maxBackoff: TimeSpan.FromMilliseconds(200),
jitter: _ => TimeSpan.Zero);
await watcher.StartAsync(CancellationToken.None);
await TestWait.UntilAsync(() => source.Calls >= 3, "the watcher must keep re-subscribing after a clean completion");
await Task.Delay(700, TestContext.Current.CancellationToken);
await watcher.StopAsync();
// 50 + 100 + 200 + 200 + ... ms: ~5 subscribes in ~0.75 s. Generous ceiling for a loaded runner; the
// unpaced loop managed thousands.
source.Calls.ShouldBeLessThanOrEqualTo(15, "a clean completion must be paced like a fault");
}
/// <summary>
/// The backoff resets only after a stream stayed open for the stable-stream window — an event alone (the
/// bootstrap every stream delivers) must not reset it, or a bootstrap-then-complete gateway is re-subscribed
/// at the initial backoff forever. With a 100 ms initial backoff growing to 400 ms, the subscribe count in
/// ~1.2 s stays well below the 12 a per-event reset would allow.
/// </summary>
[Fact]
public async Task An_event_alone_does_not_reset_the_backoff()
{
var source = new BootstrapThenCompleteSource();
using var watcher = new DeployWatcher(
source, logger: null,
initialBackoff: TimeSpan.FromMilliseconds(100),
maxBackoff: TimeSpan.FromMilliseconds(400),
jitter: _ => TimeSpan.Zero,
stableStreamDuration: TimeSpan.FromMinutes(1));
await watcher.StartAsync(CancellationToken.None);
await Task.Delay(1_200, TestContext.Current.CancellationToken);
await watcher.StopAsync();
// 0 + 100 + 200 + 400 + 400 = 1.1 s → ~5 subscribes; a per-event reset would give ~12 (every 100 ms).
source.Calls.ShouldBeInRange(2, 8);
}
}
@@ -0,0 +1,96 @@
using System.Runtime.CompilerServices;
using System.Threading.Channels;
using Microsoft.Extensions.Logging;
using Shouldly;
using Xunit;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime;
/// <summary>
/// #991 G-2 — <see cref="StatusCodeMap.FromQualityByte"/> used to log a Warning for EVERY event carrying a quality
/// byte outside its 15-entry table, on the pump's single dispatch thread. The commonest such bytes are the listed
/// qualities with the OPC DA limit bits set (<c>Good | LowLimited</c> = 0xC1): a few hundred limited attributes at
/// 1 s cadence meant hundreds of Warning lines per second, slowing dispatch until the bounded channel dropped events.
/// Now the two limit bits are masked before the lookup (they never change the category or substatus), and a byte
/// that is still unlisted warns once per distinct value.
/// </summary>
public sealed class QualityByteLimitBitsTests
{
/// <summary>The limit bits (LL in QQSSSSLL) do not change the mapped status, and are not "unrecognised".</summary>
/// <param name="input">A listed quality with limit bits set.</param>
/// <param name="expected">The status the same quality maps to without them.</param>
[Theory]
[InlineData((byte)0xC1, StatusCodeMap.Good)] // Good | LowLimited
[InlineData((byte)0xC2, StatusCodeMap.Good)] // Good | HighLimited
[InlineData((byte)0xC3, StatusCodeMap.Good)] // Good | Constant
[InlineData((byte)0xDA, StatusCodeMap.GoodLocalOverride)] // LocalOverride | HighLimited
[InlineData((byte)0x45, StatusCodeMap.UncertainLastUsableValue)] // LastUsable | LowLimited
[InlineData((byte)0x13, StatusCodeMap.BadSensorFailure)] // SensorFailure | Constant
public void Limit_bits_map_like_the_unlimited_quality_without_a_warning(byte input, uint expected)
{
var logger = new CapturingLogger();
StatusCodeMap.FromQualityByte(input, logger).ShouldBe(expected);
logger.Entries.ShouldBeEmpty($"0x{input:X2} is a listed quality with limit bits — nothing is unrecognised");
}
/// <summary>
/// 1,000 events carrying a genuinely unlisted byte through the pump: every one is published at its category,
/// and the log gets ONE line, not one per event. 0xE0 is used by no other test (the guard is process-wide).
/// </summary>
[Fact]
public async Task An_unlisted_quality_byte_warns_once_however_many_events_carry_it()
{
const int events = 1_000;
var subscriber = new ChannelSubscriber();
var registry = new SubscriptionRegistry();
registry.Register(1, [new TagBinding("Tank01.Level", 7)]);
var logger = new CapturingLogger();
var statuses = new List<uint>();
var allDelivered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var pump = new EventPump(subscriber, registry, logger, channelCapacity: events + 8, clientName: "G2");
pump.OnDataChange += (_, e) =>
{
statuses.Add(e.Snapshot.StatusCode);
if (statuses.Count == events) allDelivered.TrySetResult();
};
pump.Start();
for (var i = 0; i < events; i++) await subscriber.EmitAsync(7, quality: 0xE0);
await TestWait.ForAsync(allDelivered.Task, "every event must be dispatched");
statuses.ShouldAllBe(s => s == StatusCodeMap.Good, "0xE0 is in the Good category");
logger.Entries.Count(e => e.Level == LogLevel.Warning && e.Text.Contains("0xE0"))
.ShouldBe(1, "an unlisted byte is worth one diagnostic line, not one per event");
}
private sealed class ChannelSubscriber : IGalaxySubscriber
{
private readonly Channel<MxEvent> _events = Channel.CreateUnbounded<MxEvent>();
public Task<IReadOnlyList<SubscribeResult>> SubscribeBulkAsync(
IReadOnlyList<string> fullReferences, int bufferedUpdateIntervalMs, CancellationToken cancellationToken)
=> Task.FromResult<IReadOnlyList<SubscribeResult>>([]);
public Task UnsubscribeBulkAsync(IReadOnlyList<int> itemHandles, CancellationToken cancellationToken) => Task.CompletedTask;
public async IAsyncEnumerable<MxEvent> StreamEventsAsync([EnumeratorCancellation] CancellationToken cancellationToken)
{
await foreach (var ev in _events.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
yield return ev;
}
public ValueTask EmitAsync(int handle, int quality) => _events.Writer.WriteAsync(new MxEvent
{
Family = MxEventFamily.OnDataChange,
ItemHandle = handle,
Value = new MxValue { DoubleValue = 1 },
Quality = quality,
});
}
}