feat(mtconnect): refused Agent connections mark values BadNoCommunication after a short confirmation; clamp the raised sample count to the Agent's bufferSize (#846)
- A /sample or re-baseline failure whose chain holds SocketError.ConnectionRefused, unbroken for CommsLossConfirmMs (new, default 2000; 0 = first refusal; negative = off), publishes every subscribed value BadNoCommunication once per outage; the first delivery afterwards republishes all of them from the index (unchanged values included). Timeouts/resets/DNS/pause keep the #527 watchdog contract. - SampleCountCeiling clamps the adaptive raise to the /probe bufferSize (never below SampleCount). - Docs: MTConnect.md comms-loss section + config key; drivers.md rule. Refs #846
This commit is contained in:
@@ -308,9 +308,15 @@ host logger factory (wired in `DriverFactoryBootstrap`; the FOCAS and TwinCAT fa
|
||||
`InvalidDataException` — before #804 the 400 was a transport fault and the `OUT_OF_RANGE` re-baseline never ran
|
||||
live. The restart (`instanceId`) test also runs on every re-baseline snapshot (on 2.x that is where a restart is
|
||||
first seen). 3 re-baselines with no `/sample` chunk ⇒ Degraded with `LastSuccessfulRead` still advancing (no
|
||||
watchdog reconnect loop over a `SampleCount` > `bufferSize` — live: `count == bufferSize` is accepted; Test Connect + init warn, #825). Every parse prohibits DTDs; the streams walk is
|
||||
watchdog reconnect loop over a `SampleCount` > `bufferSize` — live: `count == bufferSize` is accepted; Test Connect + init warn, #825;
|
||||
the adaptive raised count is clamped to the known `bufferSize`, #846). Every parse prohibits DTDs; the streams walk is
|
||||
depth-bounded (64 — an unbounded recursion is a process-killing `StackOverflowException`). Non-finite floats are
|
||||
never Good; integer-valued decimals serve integral tags losslessly. Matrix: `docs/drivers/MTConnect.md`.
|
||||
- **MTConnect refused-connection fast path (#846):** a `/sample`/re-baseline failure whose chain holds
|
||||
`SocketError.ConnectionRefused`, unbroken for `CommsLossConfirmMs` (default 2000; 0 = first; negative = off), publishes
|
||||
every subscribed value `BadNoCommunication` once per outage; the first delivery afterwards republishes all of them from
|
||||
the index. Health/`LastSuccessfulRead` are untouched by it (the stream failure already degraded), so the #527 watchdog
|
||||
still re-inits at 90 s. Timeouts/resets/DNS/pause stay watchdog-only — never widen the definite set to them.
|
||||
- **MTConnect CONDITION alarms (#626):** a CONDITION raw tag is a native Part 9 condition only when its `TagConfig`
|
||||
carries the standard `alarm` object (opt-in — alarm tags leave the value subscription, so auto-promotion would break
|
||||
existing String tags). Normal→inactive, Warning→500, Fault→800; one condition per DataItem showing the most severe
|
||||
|
||||
@@ -157,6 +157,7 @@ clears, and the Agent's text is logged once per distinct refusal. An answer that
|
||||
"SampleIntervalMs": 1000,
|
||||
"SampleCount": 1000,
|
||||
"HeartbeatMs": 10000,
|
||||
"CommsLossConfirmMs": 2000,
|
||||
"Probe": { "Enabled": true, "IntervalMs": 5000, "TimeoutMs": 2000 },
|
||||
"Reconnect": { "MinBackoffMs": 0, "MaxBackoffMs": 30000, "BackoffMultiplier": 2.0 },
|
||||
"Write": { "Enabled": false },
|
||||
@@ -183,6 +184,7 @@ Read off `MTConnectDriverOptions` / `MTConnectDriverConfigDto`
|
||||
| `SampleIntervalMs` | `1000` | The Agent's `/sample?interval=` query param |
|
||||
| `SampleCount` | `1000` | The Agent's `/sample?count=` query param. **Caps subscription throughput** at `SampleCount / SampleIntervalMs` — see [Subscribe](#subscribe--the-sample-pump) for the adaptive raise |
|
||||
| `HeartbeatMs` | `10000` | The Agent's `/sample?heartbeat=` query param — also the watchdog's liveness window |
|
||||
| `CommsLossConfirmMs` | `2000` | #846: how long the Agent must keep **refusing** connections before every subscribed value goes `BadNoCommunication` (see [Comms loss](#comms-loss-refused-vs-ambiguous-846)). `0` = on the first refusal; negative = fast path off (watchdog only). JSON-only — the AdminUI form preserves it but has no field |
|
||||
| `Probe.Enabled` / `Probe.IntervalMs` / `Probe.TimeoutMs` | `true` / `5000` / `2000` | Background connectivity-probe knobs (mirrors `ModbusProbeOptions`) |
|
||||
| `Reconnect.MinBackoffMs` / `MaxBackoffMs` / `BackoffMultiplier` | `0` / `30000` / `2.0` | Geometric backoff after a failed request or a dropped `/sample` stream |
|
||||
| `Write.Enabled` | `false` | The driver-side half of the write-back opt-in. An absent block means disabled — see [Write-back](#write-back--observation-injection-off-by-default) |
|
||||
@@ -397,7 +399,10 @@ observations per chunk, one chunk per `SampleIntervalMs`; a machine producing mo
|
||||
buffer forever, re-baselining every buffer-length (dropping intermediate transitions) with nothing surfacing it.
|
||||
Each chunk is now measured: `lag = lastSequence + 1 − nextSequence` (unknown when the Agent omits `lastSequence`)
|
||||
and whether it was **saturated** (carried the full `count`). Three consecutive saturated chunks with a positive (or
|
||||
unknown) lag reopen the stream at the cursor reached with `count` doubled, up to 16× `SampleCount` (max 65 536). A
|
||||
unknown) lag reopen the stream at the cursor reached with `count` doubled, up to 16× `SampleCount` (max 65 536) —
|
||||
**and never above the Agent's `/probe` `bufferSize`** (#846; a count above it is refused `OUT_OF_RANGE`, so a raise past
|
||||
it only bought a refused stream and a step-back; a configured `SampleCount` already above the buffer is not raised and
|
||||
is the #825 warning's business). A
|
||||
raised stream that delivers nothing (an Agent refusing the larger count) steps back to the last count that delivered
|
||||
and stops raising; at the ceiling a still-behind stream logs one Warning per pump. Every new pump starts from the
|
||||
configured `SampleCount`. An Agent that refuses the raised count with an `MTConnectError` under HTTP 200 goes through
|
||||
@@ -724,6 +729,32 @@ deliberately different, kept.
|
||||
Agent's `bufferSize`, not a genuinely lapped ring buffer; no real machine tool or non-cppagent Agent was exercised.
|
||||
**Closed by the #823 gate below**, except the real-machine / non-cppagent caveat.
|
||||
|
||||
### Comms loss: refused vs ambiguous (#846)
|
||||
|
||||
The runtime's comms-loss watchdog (Degraded + `LastSuccessfulRead` frozen 90 s ⇒ re-initialize, host fans
|
||||
`BadNoCommunication`) is the contract for every **ambiguous** failure, and the #823 gate below measured what it costs:
|
||||
values Good-but-stale for ~94–118 s. A **refused** connection is not ambiguous — nothing is listening at `AgentUri` — so
|
||||
the `/sample` pump now handles it itself:
|
||||
|
||||
- **Definite = `SocketError.ConnectionRefused`** anywhere in the failure's exception chain (what `HttpClient` throws for
|
||||
a port nobody listens on), on a `/sample` open or a re-baseline `/current`. A request or stream-idle timeout, a reset or
|
||||
closed stream, DNS failure, a paused Agent, an `MTConnectError` refusal — all stay with the watchdog, unchanged.
|
||||
- **Confirmed:** the refusals must continue, unbroken, for `CommsLossConfirmMs` (default 2 s); any answer from the Agent or
|
||||
any ambiguous failure ends the run. While confirming, the reconnect delay is capped at the time remaining.
|
||||
- **Then every subscribed value is published `BadNoCommunication`** (value null) **once per outage**, with one Warning.
|
||||
Health was already Degraded with `LastSuccessfulRead` frozen by the stream failure, so the watchdog still re-initializes
|
||||
at 90 s exactly as before — this only stops stale values reading Good in between. Reads already fall back to `/current`
|
||||
on a degraded stream and fail on their own. Native CONDITIONS are untouched (the host annotates them on the
|
||||
connectivity edge, as before).
|
||||
- **Recovery republishes everything:** the first delivered chunk (a heartbeat counts) or re-baseline after a marked outage
|
||||
republishes every subscribed value from the index — a resumed `/sample` carries only what changed, so an unchanged item
|
||||
would otherwise stay Bad (the (value, status) recovery rule).
|
||||
- Consequence for an Agent **restart** that refuses for longer than the window (the #823 restart refused for ~1 s, inside
|
||||
it): values go Bad for the restart and come back on its first chunk / re-baseline. That is the honest answer — the
|
||||
Agent was down.
|
||||
|
||||
Tests: `MTConnectCommsLossTests` (incl. an ambiguous-failure falsification control and the confirmation window).
|
||||
|
||||
### End-to-end gate through a deployed server (#823, 2026-11-11, docker-dev)
|
||||
|
||||
An MTConnect driver (`SampleCount` 1000, `HeartbeatMs` 10000, `RequestTimeoutMs` 5000) against the shared fixture,
|
||||
@@ -735,7 +766,7 @@ NodeIds moved together in every leg. Fixture containers were restored healthy af
|
||||
|---|---|
|
||||
| Adapter stop | Both NodeIds `BadNoCommunication` within 1 s of the adapter dying (Agent marks items UNAVAILABLE); driver stayed Healthy. Adapter start ⇒ Good 1–2 s later. |
|
||||
| Agent restart (`docker restart`, ~12 s) | Stream lost and reconnected ~1 s; the stale cursor was refused `OUT_OF_RANGE`, the re-baseline saw the new `instanceId`, **rediscovery raised** — `/hosts` shows the **RE-BROWSE** chip. Values stayed Good (outage shorter than the comms-loss window). |
|
||||
| Agent stopped ~2 min | Values held Good-but-stale; **Bad at 118 s** (comms-loss watchdog, connection refused). Agent start ⇒ re-init on the 10 s retry, Good ~8 s after the Agent was back. |
|
||||
| Agent stopped ~2 min | Values held Good-but-stale; **Bad at 118 s** (comms-loss watchdog, connection refused). Agent start ⇒ re-init on the 10 s retry, Good ~8 s after the Agent was back. **Since #846** a refused connection marks the values `BadNoCommunication` after `CommsLossConfirmMs` (2 s) instead — unit-tested, not yet re-gated live. |
|
||||
| Agent paused (`docker pause`) | Stream idle watchdog at 24 s (2 × 10000 + 5000); **Bad at 94 s** (watchdog); unpause ⇒ Good within ~3 s. |
|
||||
| Genuine buffer overrun | A stalling TCP proxy froze the driver's transport while 32 000 observations were injected (`AllowPut`) — the Agent's `firstSequence` passed the driver's cursor (75 856 → 77 083). On release the resume was refused `OUT_OF_RANGE`, the driver re-baselined from `/current` within 1 s and resumed; values Good, no restart misdiagnosed. A raised-count stream (count 16, interval 5 s) was **not** lapped by a 266 obs/s burst: chunks are sent back-to-back while data is pending, so `interval` does not cap throughput. |
|
||||
| `SampleCount` vs `bufferSize` (#825) | Test Connect rendered the amber "OK with warning" chip and a deploy logged the Warning (`/hosts` shows `agentBufferSize`). The same gate measured the Agent's real edge — `count = 16384` streams, `16385` is `OUT_OF_RANGE` — so the first build's "at or above" threshold was corrected to "above" (pinned live by `Test_Connect_warns_when_SampleCount_exceeds_the_live_agents_buffer_size`). |
|
||||
|
||||
@@ -63,6 +63,15 @@ public sealed class MTConnectDriverOptions
|
||||
/// </summary>
|
||||
public int HeartbeatMs { get; init; } = 10000;
|
||||
|
||||
/// <summary>
|
||||
/// Gets how long, in milliseconds, the Agent must keep REFUSING connections (a definite loss — nothing is
|
||||
/// listening at <see cref="AgentUri"/>) before every subscribed value is marked <c>BadNoCommunication</c>
|
||||
/// (lmxopcua#846). Default <c>2000</c>; <c>0</c> marks on the first refusal; a negative value disables the fast
|
||||
/// path, leaving the comms-loss watchdog (~90 s) as the only signal. Ambiguous failures (timeouts, a stalled or
|
||||
/// reset stream, DNS) never use it — they keep the watchdog contract.
|
||||
/// </summary>
|
||||
public int CommsLossConfirmMs { get; init; } = 2000;
|
||||
|
||||
/// <summary>
|
||||
/// The authored tags this driver instance serves — one <see cref="MTConnectTagDefinition"/>
|
||||
/// per tag, keyed by the DataItem <c>id</c> it binds
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
using System.Net.Sockets;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.MTConnect;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#846 — the fast comms-loss path for a DEFINITE Agent loss. Before it, an Agent outage left every value
|
||||
/// Good-but-stale for ~94–118 s, until the runtime's comms-loss watchdog (Degraded + a frozen
|
||||
/// <c>LastSuccessfulRead</c> for 90 s) re-initialized the driver and the host fanned <c>BadNoCommunication</c>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>Only a refusal is definite.</b> A connection REFUSED (<see cref="SocketError.ConnectionRefused"/> anywhere
|
||||
/// in the exception chain — what an <c>HttpClient</c> connect to a port nobody listens on produces) proves
|
||||
/// nothing is serving the Agent URI. Everything else — a request or stream-idle timeout, a reset or half-closed
|
||||
/// stream, a DNS failure, a paused Agent — is ambiguous and keeps the watchdog contract
|
||||
/// (<c>docs/DriverLifecycle.md</c>, <c>.claude/rules/drivers.md</c> #527/#676): those must never mark early.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Confirmed, not instant.</b> Refusals must continue, unbroken, for
|
||||
/// <see cref="MTConnectDriverOptions.CommsLossConfirmMs"/> (default 2 s; 0 = first refusal; negative = off)
|
||||
/// before the values are marked, so a single refused connect during an Agent restart does not flap every value.
|
||||
/// While confirmation is pending the reconnect delay is capped at the time remaining, so the confirming
|
||||
/// attempt is not pushed out by the backoff ladder. Anything that reaches the Agent ends the run.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>What marking does — the driver half of the quality contract.</b> Every subscribed value is published
|
||||
/// <c>BadNoCommunication</c> (value null) ONCE per outage; the observation index keeps the last values. Health
|
||||
/// is already Degraded with <c>LastSuccessfulRead</c> frozen (the stream failure degraded it), so the watchdog
|
||||
/// still re-initializes at 90 s exactly as before — this path only stops serving stale values as Good in the
|
||||
/// meantime. Reads already fall back to <c>/current</c> on a degraded stream and fail Bad on their own.
|
||||
/// Native CONDITIONS are not touched: the host annotates them on the connectivity edge, as before.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Recovery republishes everything.</b> The first delivered chunk or re-baseline after a marked outage
|
||||
/// republishes every subscribed value from the index — a resumed <c>/sample</c> only carries what CHANGED, so
|
||||
/// an unchanged data item would otherwise stay Bad until it next moved (the (value, status) recovery rule).
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed partial class MTConnectDriver
|
||||
{
|
||||
/// <summary>Canonical <c>Opc.Ua.StatusCodes.BadNoCommunication</c>.</summary>
|
||||
private const uint BadNoCommunicationStatus = 0x80310000u;
|
||||
|
||||
/// <summary>1 while a confirmed refused-connection outage has marked the subscribed values Bad.</summary>
|
||||
private int _commsLostMarked;
|
||||
|
||||
/// <summary>Whether a refused-connection outage currently has the values marked Bad (test seam / diagnostics).</summary>
|
||||
internal bool CommsLossMarked => Volatile.Read(ref _commsLostMarked) == 1;
|
||||
|
||||
/// <summary>One pump's run of consecutive refused connections. Only that pump's task touches it.</summary>
|
||||
private sealed class RefusalState
|
||||
{
|
||||
/// <summary>When the current unbroken run of refusals started, or null when there is none.</summary>
|
||||
public DateTime? Since { get; set; }
|
||||
|
||||
/// <summary>Ends the run (anything reached the Agent, or an ambiguous failure broke it).</summary>
|
||||
public void Reset() => Since = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="error"/> proves nothing is listening at the Agent URI — a connection refused anywhere
|
||||
/// in its chain. Every other failure is ambiguous (see the class remarks).
|
||||
/// </summary>
|
||||
/// <param name="error">The stream / re-baseline failure.</param>
|
||||
/// <returns>True for a definite loss.</returns>
|
||||
internal static bool IsDefiniteConnectionLoss(Exception? error)
|
||||
{
|
||||
for (var e = error; e is not null; e = e.InnerException)
|
||||
{
|
||||
if (e is SocketException { SocketErrorCode: SocketError.ConnectionRefused })
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (e is AggregateException agg && agg.InnerExceptions.Any(IsDefiniteConnectionLoss))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records one transient stream failure and, once refusals have persisted for the confirmation window, marks
|
||||
/// every subscribed value <c>BadNoCommunication</c> (once per outage).
|
||||
/// </summary>
|
||||
/// <returns><see langword="false"/> when the pump's session has been replaced (nothing marked).</returns>
|
||||
private bool NoteStreamFailure(RefusalState refusals, StreamOutcome outcome, MTConnectDriverOptions options, long generation)
|
||||
{
|
||||
if (options.CommsLossConfirmMs < 0 || !IsDefiniteConnectionLoss(outcome.Error))
|
||||
{
|
||||
// An ambiguous failure breaks the run: only an UNBROKEN series of refusals is a confirmed loss.
|
||||
refusals.Reset();
|
||||
return true;
|
||||
}
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
refusals.Since ??= now;
|
||||
if (now - refusals.Since.Value < TimeSpan.FromMilliseconds(options.CommsLossConfirmMs))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return TryMarkCommsLost(generation, options, now - refusals.Since.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// While a refusal run is waiting for confirmation, the next attempt is made no later than the moment the window
|
||||
/// closes — so the confirming refusal is not deferred by a long backoff step.
|
||||
/// </summary>
|
||||
private static TimeSpan CapForCommsLossConfirmation(TimeSpan delay, RefusalState refusals, MTConnectDriverOptions options)
|
||||
{
|
||||
if (refusals.Since is not { } since || options.CommsLossConfirmMs < 0)
|
||||
{
|
||||
return delay;
|
||||
}
|
||||
|
||||
var remaining = since.AddMilliseconds(options.CommsLossConfirmMs) - DateTime.UtcNow;
|
||||
if (remaining <= TimeSpan.Zero)
|
||||
{
|
||||
return delay; // already confirmed (or about to be): the ordinary ladder paces the outage
|
||||
}
|
||||
|
||||
return remaining < delay ? remaining : delay;
|
||||
}
|
||||
|
||||
private bool TryMarkCommsLost(long generation, MTConnectDriverOptions options, TimeSpan refusedFor)
|
||||
{
|
||||
lock (_subscriptionLock)
|
||||
{
|
||||
if (_sessionGeneration != generation)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (Interlocked.Exchange(ref _commsLostMarked, 1) == 1)
|
||||
{
|
||||
return true; // already marked for this outage
|
||||
}
|
||||
|
||||
var references = SubscribedReferences();
|
||||
_logger.LogWarning(
|
||||
"MTConnect driver {DriverInstanceId}: {AgentUri} has refused every connection for {RefusedMs} ms (definite loss); marking {Count} subscribed value(s) BadNoCommunication until it answers again.",
|
||||
_driverInstanceId, AgentDisplay(options), (long)refusedFor.TotalMilliseconds, references.Count);
|
||||
FanOutStatus(references, BadNoCommunicationStatus);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Agent answered again after a marked outage: republish every subscribed value from the index (once).
|
||||
/// Generation-checked so a superseded pump cannot republish into the session that replaced it.
|
||||
/// </summary>
|
||||
private void RepublishAfterCommsLoss(long generation)
|
||||
{
|
||||
if (Volatile.Read(ref _commsLostMarked) == 0 || !IsCurrentSessionGeneration(generation))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (Interlocked.Exchange(ref _commsLostMarked, 0) == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogInformation(
|
||||
"MTConnect driver {DriverInstanceId}: the Agent answered again; republishing every subscribed value.",
|
||||
_driverInstanceId);
|
||||
FanOut(SubscribedReferences(), ObservationIndex);
|
||||
}
|
||||
|
||||
/// <summary>Publishes a value-less <paramref name="status"/> to every handle subscribing each reference.</summary>
|
||||
private void FanOutStatus(IReadOnlyList<string> references, uint status)
|
||||
{
|
||||
if (references.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
SubscriptionState[] states;
|
||||
lock (_subscriptionLock)
|
||||
{
|
||||
states = [.. _subscriptions.Values];
|
||||
}
|
||||
|
||||
var snapshot = new DataValueSnapshot(null, status, null, DateTime.UtcNow);
|
||||
foreach (var reference in references)
|
||||
{
|
||||
foreach (var state in states)
|
||||
{
|
||||
if (state.References.Contains(reference))
|
||||
{
|
||||
RaiseDataChange(state.Handle, reference, snapshot);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -79,9 +79,23 @@ public sealed partial class MTConnectDriver : IDriverDiagnostics
|
||||
|
||||
/// <summary>The ceiling a pump started with <paramref name="configured"/> may raise its count to.</summary>
|
||||
/// <param name="configured">The configured <see cref="MTConnectDriverOptions.SampleCount"/>.</param>
|
||||
/// <returns>The ceiling — never below <paramref name="configured"/>.</returns>
|
||||
internal static int SampleCountCeiling(int configured) =>
|
||||
Math.Max(configured, (int)Math.Min((long)configured * SampleCountMaxGrowth, SampleCountAbsoluteCeiling));
|
||||
/// <param name="agentBufferSize">
|
||||
/// The Agent's <c>/probe</c> <c>bufferSize</c>, or <c>0</c> when unknown. lmxopcua#846: an Agent refuses a
|
||||
/// <c>count</c> above it (<c>OUT_OF_RANGE</c>; live, <c>count == bufferSize</c> is accepted), so a known buffer
|
||||
/// caps the raised count — a raise past it would only buy a refused stream and a step-back.
|
||||
/// </param>
|
||||
/// <returns>The ceiling — never below <paramref name="configured"/> (a configured count above the buffer is the
|
||||
/// #825 configuration warning's business, not something to raise further).</returns>
|
||||
internal static int SampleCountCeiling(int configured, long agentBufferSize = 0)
|
||||
{
|
||||
long ceiling = Math.Min((long)configured * SampleCountMaxGrowth, SampleCountAbsoluteCeiling);
|
||||
if (agentBufferSize > 0)
|
||||
{
|
||||
ceiling = Math.Min(ceiling, agentBufferSize);
|
||||
}
|
||||
|
||||
return (int)Math.Max(configured, ceiling);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyDictionary<string, string> GetDiagnostics()
|
||||
@@ -132,7 +146,7 @@ public sealed partial class MTConnectDriver : IDriverDiagnostics
|
||||
}
|
||||
|
||||
/// <summary>One pump's adaptive-count state. Only that pump's task touches it.</summary>
|
||||
private sealed class SampleCountState(int configured)
|
||||
private sealed class SampleCountState(int configured, long agentBufferSize)
|
||||
{
|
||||
/// <summary>The count the next stream opens with.</summary>
|
||||
public int Count { get; set; } = configured;
|
||||
@@ -141,7 +155,7 @@ public sealed partial class MTConnectDriver : IDriverDiagnostics
|
||||
public int LastDelivered { get; set; } = configured;
|
||||
|
||||
/// <summary>The most <see cref="Count"/> may be raised to; lowered to the last good count on a refusal.</summary>
|
||||
public int Ceiling { get; set; } = SampleCountCeiling(configured);
|
||||
public int Ceiling { get; set; } = SampleCountCeiling(configured, agentBufferSize);
|
||||
|
||||
/// <summary>Whether the at-the-ceiling Warning has been logged for this pump.</summary>
|
||||
public bool CeilingWarned { get; set; }
|
||||
|
||||
@@ -2229,8 +2229,9 @@ public sealed partial class MTConnectDriver
|
||||
var cursor = from;
|
||||
var attempt = 0;
|
||||
_reconnectAttempts = 0;
|
||||
var counts = new SampleCountState(options.SampleCount);
|
||||
var counts = new SampleCountState(options.SampleCount, Interlocked.Read(ref _agentBufferSize));
|
||||
Volatile.Write(ref _effectiveSampleCount, counts.Count);
|
||||
var refusals = new RefusalState();
|
||||
|
||||
// #804 (Java-driver parity) — consecutive re-baselines with no /sample chunk delivered in between.
|
||||
var rebaselinesWithoutProgress = 0;
|
||||
@@ -2250,7 +2251,7 @@ public sealed partial class MTConnectDriver
|
||||
{
|
||||
if (attempt > 0)
|
||||
{
|
||||
var delay = BackoffFor(attempt, options.Reconnect);
|
||||
var delay = CapForCommsLossConfirmation(BackoffFor(attempt, options.Reconnect), refusals, options);
|
||||
if (delay > TimeSpan.Zero)
|
||||
{
|
||||
try
|
||||
@@ -2273,6 +2274,12 @@ public sealed partial class MTConnectDriver
|
||||
{
|
||||
rebaselinesWithoutProgress = 0;
|
||||
}
|
||||
|
||||
// #846 — only an unbroken run of refusals confirms a loss: anything that reached the Agent ends it.
|
||||
if (outcome.DeliveredAny || outcome.Verdict is not StreamVerdict.Transient)
|
||||
{
|
||||
refusals.Reset();
|
||||
}
|
||||
cursor = outcome.Cursor;
|
||||
instanceId = outcome.InstanceId;
|
||||
|
||||
@@ -2375,6 +2382,13 @@ public sealed partial class MTConnectDriver
|
||||
return;
|
||||
}
|
||||
|
||||
// #846 — a REFUSED connection is a definite loss; after CommsLossConfirmMs of nothing but
|
||||
// refusals the values go BadNoCommunication now instead of at the ~90 s watchdog.
|
||||
if (!NoteStreamFailure(refusals, outcome, options, generation))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// A stream that DELIVERED before it dropped proves the endpoint works, so
|
||||
// its failure starts a fresh backoff ladder. Without this the counter is
|
||||
// monotonic for the life of the process: a healthy agent that drops a
|
||||
@@ -2519,6 +2533,8 @@ public sealed partial class MTConnectDriver
|
||||
return new StreamOutcome(StreamVerdict.Cancelled, expected, instanceId, delivered, null);
|
||||
}
|
||||
|
||||
RepublishAfterCommsLoss(generation);
|
||||
|
||||
// R06:T-5 — a stream persistently behind the Agent reopens at the cursor it reached with a larger
|
||||
// count, rather than falling out of the ring buffer and re-baselining every buffer-length.
|
||||
if (!MeasureSampleLag(chunk, counts.Count))
|
||||
@@ -2643,6 +2659,9 @@ public sealed partial class MTConnectDriver
|
||||
StreamVerdict.Cancelled, fallbackCursor, fallbackInstanceId, deliveredAny, null);
|
||||
}
|
||||
|
||||
// #846 — the Agent answered: if a refused-connection outage marked the values Bad, put them all back.
|
||||
RepublishAfterCommsLoss(generation);
|
||||
|
||||
_logger.LogInformation(
|
||||
"MTConnect driver {DriverInstanceId} re-baselined from {AgentUri}'s /current ({ObservationCount} observation(s), agent instanceId {InstanceId}) and resumes /sample from sequence {NextSequence}.",
|
||||
_driverInstanceId,
|
||||
@@ -3247,6 +3266,7 @@ public sealed partial class MTConnectDriver
|
||||
SampleIntervalMs = dto.SampleIntervalMs ?? 1_000,
|
||||
SampleCount = dto.SampleCount ?? 1_000,
|
||||
HeartbeatMs = dto.HeartbeatMs ?? 10_000,
|
||||
CommsLossConfirmMs = dto.CommsLossConfirmMs ?? 2_000,
|
||||
Tags = dto.Tags is { Count: > 0 }
|
||||
? [.. dto.Tags.Select(t => BuildTag(t, driverInstanceId))]
|
||||
: [],
|
||||
@@ -4447,6 +4467,8 @@ public sealed partial class MTConnectDriver
|
||||
public int? SampleCount { get; init; }
|
||||
/// <summary>The /sample heartbeat in milliseconds.</summary>
|
||||
public int? HeartbeatMs { get; init; }
|
||||
/// <summary>How long refused connections must persist before values go BadNoCommunication (#846).</summary>
|
||||
public int? CommsLossConfirmMs { get; init; }
|
||||
/// <summary>The authored tags.</summary>
|
||||
public List<MTConnectTagDto>? Tags { get; init; }
|
||||
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net.Http;
|
||||
using System.Net.Sockets;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.MTConnect.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#846 — a REFUSED Agent connection is a definite loss: after <c>CommsLossConfirmMs</c> of nothing but
|
||||
/// refusals every subscribed value goes <c>BadNoCommunication</c> (instead of Good-but-stale until the ~90 s
|
||||
/// watchdog), and the first delivery afterwards republishes every value Good — including unchanged ones. Ambiguous
|
||||
/// failures (timeouts, a closed stream) keep the watchdog contract. Plus the raised-count ceiling is clamped to the
|
||||
/// Agent's <c>bufferSize</c>.
|
||||
/// </summary>
|
||||
public sealed class MTConnectCommsLossTests
|
||||
{
|
||||
private const long Instance = 1655000000L;
|
||||
private const long Primed = 108L;
|
||||
private const uint BadNoCommunication = 0x80310000u;
|
||||
private static readonly TimeSpan Watchdog = TimeSpan.FromSeconds(30);
|
||||
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
private static MTConnectStreamsResult Chunk(long first, int observations, long? last = null)
|
||||
{
|
||||
var obs = Enumerable.Range(0, observations)
|
||||
.Select(i => new MTConnectObservation(
|
||||
"dev1_pos", (first + i).ToString(System.Globalization.CultureInfo.InvariantCulture),
|
||||
new DateTime(2026, 11, 11, 12, 0, 0, DateTimeKind.Utc).AddSeconds(first + i)))
|
||||
.ToList();
|
||||
return new MTConnectStreamsResult(Instance, first + observations, first, obs, last);
|
||||
}
|
||||
|
||||
private static Exception Refused() =>
|
||||
new HttpRequestException("Connection refused (fixture-agent:5000)", new SocketException((int)SocketError.ConnectionRefused));
|
||||
|
||||
private static async Task<(MTConnectDriver Driver, CannedAgentClient Client, ConcurrentQueue<DataChangeEventArgs> Seen)>
|
||||
SubscribedAsync(int commsLossConfirmMs, int sampleCount = 1000, long? bufferSize = null)
|
||||
{
|
||||
var client = CannedAgentClient.FromFixtures();
|
||||
if (bufferSize is { } size) client.Probe = client.Probe with { BufferSize = size };
|
||||
var driver = new MTConnectDriver(
|
||||
new MTConnectDriverOptions
|
||||
{
|
||||
AgentUri = "http://fixture-agent:5000",
|
||||
RequestTimeoutMs = 5000,
|
||||
SampleCount = sampleCount,
|
||||
CommsLossConfirmMs = commsLossConfirmMs,
|
||||
Reconnect = new MTConnectReconnectOptions { MinBackoffMs = 0, MaxBackoffMs = 200 },
|
||||
Tags = [new MTConnectTagDefinition("dev1_pos", DriverDataType.Float64)],
|
||||
},
|
||||
"mt-846",
|
||||
_ => client);
|
||||
var seen = new ConcurrentQueue<DataChangeEventArgs>();
|
||||
driver.OnDataChange += (_, e) => seen.Enqueue(e);
|
||||
await driver.InitializeAsync("{}", Ct);
|
||||
await driver.SubscribeAsync(["dev1_pos"], TimeSpan.FromMilliseconds(50), Ct);
|
||||
await client.WaitForSampleCallsAsync(1).WaitAsync(Watchdog, Ct);
|
||||
return (driver, client, seen);
|
||||
}
|
||||
|
||||
private static async Task WaitUntil(Func<bool> condition, int timeoutMs = 10_000)
|
||||
{
|
||||
var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs);
|
||||
while (!condition())
|
||||
{
|
||||
if (DateTime.UtcNow > deadline) throw new TimeoutException("condition not reached");
|
||||
await Task.Delay(20, Ct);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Only_a_refused_connection_is_a_definite_loss()
|
||||
{
|
||||
MTConnectDriver.IsDefiniteConnectionLoss(Refused()).ShouldBeTrue();
|
||||
MTConnectDriver.IsDefiniteConnectionLoss(new SocketException((int)SocketError.ConnectionRefused)).ShouldBeTrue();
|
||||
MTConnectDriver.IsDefiniteConnectionLoss(new AggregateException(Refused())).ShouldBeTrue();
|
||||
|
||||
MTConnectDriver.IsDefiniteConnectionLoss(null).ShouldBeFalse();
|
||||
MTConnectDriver.IsDefiniteConnectionLoss(new TimeoutException("no answer")).ShouldBeFalse();
|
||||
MTConnectDriver.IsDefiniteConnectionLoss(new HttpRequestException("reset", new SocketException((int)SocketError.ConnectionReset))).ShouldBeFalse();
|
||||
MTConnectDriver.IsDefiniteConnectionLoss(new HttpRequestException("dns", new SocketException((int)SocketError.HostNotFound))).ShouldBeFalse();
|
||||
MTConnectDriver.IsDefiniteConnectionLoss(new MTConnectStreamEndedException(MTConnectStreamEndReason.ConnectionClosed, "x", 3)).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_refused_agent_marks_values_bad_at_once_and_the_first_delivery_republishes_them_good()
|
||||
{
|
||||
var (driver, client, seen) = await SubscribedAsync(commsLossConfirmMs: 0);
|
||||
try
|
||||
{
|
||||
await client.PumpAsync(Chunk(Primed, 1)).WaitAsync(Watchdog, Ct);
|
||||
seen.Last().Snapshot.StatusCode.ShouldBe(0u);
|
||||
|
||||
client.SampleFailure = Refused();
|
||||
client.EndStream(); // the connection drops; every reconnect is refused
|
||||
await WaitUntil(() => seen.Last().Snapshot.StatusCode == BadNoCommunication);
|
||||
driver.CommsLossMarked.ShouldBeTrue();
|
||||
driver.GetHealth().State.ShouldBe(DriverState.Degraded);
|
||||
var badCount = seen.Count(e => e.Snapshot.StatusCode == BadNoCommunication);
|
||||
await Task.Delay(400, Ct); // more refused attempts: marked ONCE per outage
|
||||
seen.Count(e => e.Snapshot.StatusCode == BadNoCommunication).ShouldBe(badCount);
|
||||
|
||||
// The Agent is back. An observation-free heartbeat is enough: the UNCHANGED value comes back Good.
|
||||
client.SampleFailure = null;
|
||||
var calls = client.SampleCallCount;
|
||||
await client.WaitForSampleCallsAsync(calls + 1).WaitAsync(Watchdog, Ct);
|
||||
await client.PumpAsync(Chunk(Primed + 1, 0)).WaitAsync(Watchdog, Ct);
|
||||
await WaitUntil(() => seen.Last().Snapshot.StatusCode == 0u);
|
||||
var recovered = seen.Last().Snapshot;
|
||||
recovered.Value.ShouldBe(108.0);
|
||||
driver.CommsLossMarked.ShouldBeFalse();
|
||||
driver.GetHealth().State.ShouldBe(DriverState.Healthy);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await driver.ShutdownAsync(CancellationToken.None);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task An_ambiguous_failure_keeps_the_watchdog_contract()
|
||||
{
|
||||
var (driver, client, seen) = await SubscribedAsync(commsLossConfirmMs: 0);
|
||||
try
|
||||
{
|
||||
await client.PumpAsync(Chunk(Primed, 1)).WaitAsync(Watchdog, Ct);
|
||||
client.SampleFailure = new TimeoutException("the Agent did not answer /sample in time");
|
||||
var calls = client.SampleCallCount;
|
||||
client.EndStream();
|
||||
await client.WaitForSampleCallsAsync(calls + 3).WaitAsync(Watchdog, Ct);
|
||||
seen.ShouldNotContain(e => e.Snapshot.StatusCode == BadNoCommunication);
|
||||
driver.CommsLossMarked.ShouldBeFalse();
|
||||
driver.GetHealth().State.ShouldBe(DriverState.Degraded); // the watchdog still has its evidence
|
||||
}
|
||||
finally
|
||||
{
|
||||
await driver.ShutdownAsync(CancellationToken.None);
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(60_000)] // a confirmation window not yet elapsed
|
||||
[InlineData(-1)] // the fast path disabled
|
||||
public async Task Refusals_inside_the_confirmation_window_or_with_the_fast_path_off_mark_nothing(int confirmMs)
|
||||
{
|
||||
var (driver, client, seen) = await SubscribedAsync(commsLossConfirmMs: confirmMs);
|
||||
try
|
||||
{
|
||||
await client.PumpAsync(Chunk(Primed, 1)).WaitAsync(Watchdog, Ct);
|
||||
client.SampleFailure = Refused();
|
||||
var calls = client.SampleCallCount;
|
||||
client.EndStream();
|
||||
await client.WaitForSampleCallsAsync(calls + 3).WaitAsync(Watchdog, Ct);
|
||||
seen.ShouldNotContain(e => e.Snapshot.StatusCode == BadNoCommunication);
|
||||
driver.CommsLossMarked.ShouldBeFalse();
|
||||
}
|
||||
finally
|
||||
{
|
||||
await driver.ShutdownAsync(CancellationToken.None);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_short_confirmation_window_marks_once_the_refusals_have_lasted_it()
|
||||
{
|
||||
var (driver, client, seen) = await SubscribedAsync(commsLossConfirmMs: 300);
|
||||
try
|
||||
{
|
||||
await client.PumpAsync(Chunk(Primed, 1)).WaitAsync(Watchdog, Ct);
|
||||
client.SampleFailure = Refused();
|
||||
var started = DateTime.UtcNow;
|
||||
client.EndStream();
|
||||
await WaitUntil(() => driver.CommsLossMarked, timeoutMs: 5000);
|
||||
(DateTime.UtcNow - started).ShouldBeGreaterThanOrEqualTo(TimeSpan.FromMilliseconds(280));
|
||||
seen.Last().Snapshot.StatusCode.ShouldBe(BadNoCommunication);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await driver.ShutdownAsync(CancellationToken.None);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the raised-count ceiling vs the Agent's bufferSize ----
|
||||
|
||||
[Theory]
|
||||
[InlineData(1000, 0, 16_000)] // unknown buffer: the 16× rule
|
||||
[InlineData(1000, 4096, 4096)] // a known buffer caps it
|
||||
[InlineData(1000, 131_072, 16_000)] // a big buffer changes nothing
|
||||
[InlineData(1000, 500, 1000)] // never below the configured count (#825 warns about that config)
|
||||
[InlineData(10_000, 16_384, 16_384)]
|
||||
public void The_count_ceiling_never_exceeds_the_agents_buffer(int configured, long bufferSize, int expected) =>
|
||||
MTConnectDriver.SampleCountCeiling(configured, bufferSize).ShouldBe(expected);
|
||||
|
||||
[Fact]
|
||||
public async Task A_behind_stream_stops_raising_at_the_agents_buffer_size()
|
||||
{
|
||||
var (driver, client, _) = await SubscribedAsync(commsLossConfirmMs: 0, sampleCount: 2, bufferSize: 5);
|
||||
try
|
||||
{
|
||||
var next = Primed;
|
||||
async Task Behind(int count)
|
||||
{
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
await client.PumpAsync(Chunk(next, count, last: 900)).WaitAsync(Watchdog, Ct);
|
||||
next += count;
|
||||
}
|
||||
}
|
||||
|
||||
await Behind(2);
|
||||
await client.WaitForSampleCallsAsync(2).WaitAsync(Watchdog, Ct);
|
||||
await Behind(4);
|
||||
await client.WaitForSampleCallsAsync(3).WaitAsync(Watchdog, Ct);
|
||||
client.SampleCounts.ToArray().ShouldBe(new[] { 2, 4, 5 }, "the raise is clamped to bufferSize 5, never 8");
|
||||
|
||||
await Behind(5); // at the ceiling: still behind, but not reopened
|
||||
await Task.Delay(200, Ct);
|
||||
client.SampleCallCount.ShouldBe(3);
|
||||
driver.GetDiagnostics()["sampleCount"].ShouldBe("5");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await driver.ShutdownAsync(CancellationToken.None);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user