fix(modbus): #1029 RTU reply must answer its request (FC + write-echo address); e2e rebuild-with-kept-driver; #1055 AutoReconnect=false redials once after a caller-cancel discard

#1029: ModbusRtuFraming.ReadResponsePduAsync takes the request PDU and refuses a CRC-valid, right-unit reply whose
function code (exception frames included) or write-echo start address differs (new DesyncReason.ResponseMismatch).
Runtime.Tests e2e: a full rebuild with a kept real ModbusDriver (deadbanded tag, same device value) leaves no node at
BadWaitingForInitialData; falsified by removing the S-2 baseline clear. V3ArtifactSeeder gained driverConfigByDriver.

#1055 (Modbus half): the RTU transport's caller-cancel teardown now grants ONE redial even with AutoReconnect=false, so
an unsubscribe/probe cancel no longer leaves the transport dead until the 90 s watchdog re-init; a link fault still stays down.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-12-03 15:04:36 -05:00
parent cc7155e5e9
commit 0245641720
9 changed files with 343 additions and 10 deletions
@@ -93,6 +93,14 @@ public static class ModbusRtuFraming
/// it after the CRC passes; a mismatch is a unit-mismatch desync.
/// </param>
/// <param name="ct">A token to cancel the read.</param>
/// <param name="requestPdu">
/// The request PDU this response answers (#1029). When supplied, the reply's function code (an exception
/// frame's masked code too) must equal the request's, and a write echo (FC 05/06/0F/10) must echo the
/// request's start address — RTU has no transaction id, so a CRC-valid reply from the right unit that
/// answers a DIFFERENT request is otherwise indistinguishable. A mismatch is a
/// <see cref="ModbusTransportDesyncException.DesyncReason.ResponseMismatch"/> desync. <see langword="null"/>
/// keeps the unit-only validation (framing tests that have no request).
/// </param>
/// <returns>The bare response PDU (function code followed by its data).</returns>
/// <exception cref="ModbusTransportDesyncException">
/// The frame was truncated (stream closed mid-frame), its trailing CRC did not validate, or its
@@ -102,7 +110,7 @@ public static class ModbusRtuFraming
/// The frame was a CRC-valid Modbus exception PDU (high bit set on the function code).
/// </exception>
public static async Task<byte[]> ReadResponsePduAsync(
Stream stream, byte expectedUnit, CancellationToken ct)
Stream stream, byte expectedUnit, CancellationToken ct, byte[]? requestPdu = null)
{
// R07:L5: the whole frame is read into ONE pooled buffer and validated in place; only the returned PDU is
// allocated (it used to be five arrays: header, byteCount, rest, the reassembled frame and the PDU).
@@ -137,7 +145,7 @@ public static class ModbusRtuFraming
}
await ReadExactlyAsync(stream, frame.AsMemory(already, length - already), ct).ConfigureAwait(false);
return ValidateAndStrip(expectedUnit, frame.AsSpan(0, length));
return ValidateAndStrip(expectedUnit, frame.AsSpan(0, length), requestPdu);
}
finally
{
@@ -150,7 +158,7 @@ public static class ModbusRtuFraming
/// against <paramref name="expectedUnit"/> and strips <c>addr</c> + <c>CRC</c> to return the bare PDU.
/// A CRC-valid exception PDU throws <see cref="ModbusException"/>.
/// </summary>
private static byte[] ValidateAndStrip(byte expectedUnit, ReadOnlySpan<byte> frame)
private static byte[] ValidateAndStrip(byte expectedUnit, ReadOnlySpan<byte> frame, byte[]? requestPdu)
{
// CRC covers everything except the trailing 2 CRC bytes.
var body = frame[..^2];
@@ -173,6 +181,8 @@ public static class ModbusRtuFraming
// Bare PDU = frame minus leading addr and trailing CRC.
var pdu = body[1..].ToArray();
if (requestPdu is { Length: > 0 }) CorrelateWithRequest(requestPdu, pdu);
// Exception PDU: high bit set on the function code. The CRC already validated, so this is a
// coherent protocol-level error — surface the ORIGINAL function code (fc & 0x7F).
if ((pdu[0] & 0x80) != 0)
@@ -185,6 +195,30 @@ public static class ModbusRtuFraming
return pdu;
}
/// <summary>
/// #1029: checks a CRC-valid, correctly-addressed reply against the request it must answer. Runs BEFORE the
/// exception-PDU throw, so a stale exception reply for another function is a desync, not a
/// <see cref="ModbusException"/> attributed to this request.
/// </summary>
private static void CorrelateWithRequest(byte[] request, byte[] response)
{
var requestFc = request[0];
var responseFc = (byte)(response[0] & 0x7F);
if (responseFc != requestFc)
throw new ModbusTransportDesyncException(
ModbusTransportDesyncException.DesyncReason.ResponseMismatch,
$"Modbus RTU response function code 0x{response[0]:X2} does not answer the request (fc 0x{requestFc:X2})");
// A write reply echoes the start address (bytes 1-2 of the PDU). The exception frame has no address.
if ((response[0] & 0x80) == 0
&& requestFc is 0x05 or 0x06 or 0x0F or 0x10
&& request.Length >= 3 && response.Length >= 3
&& (request[1] != response[1] || request[2] != response[2]))
throw new ModbusTransportDesyncException(
ModbusTransportDesyncException.DesyncReason.ResponseMismatch,
$"Modbus RTU write echo address {(response[1] << 8) | response[2]} does not match the request's {(request[1] << 8) | request[2]}");
}
/// <summary>
/// Fills <paramref name="buf"/> completely from <paramref name="stream"/>, throwing a
/// truncation desync if the stream ends first. Mirrors
@@ -178,7 +178,7 @@ public sealed class ModbusRtuOverTcpTransport : IModbusWriteOnceTransport
// Framing owns the length-less RTU deframe + CRC + unit-address validation. A CRC-valid
// exception PDU throws ModbusException (socket still coherent — propagates, no teardown);
// truncation / CRC / unit-mismatch throw ModbusTransportDesyncException.
return await ModbusRtuFraming.ReadResponsePduAsync(stream, unitId, cts.Token).ConfigureAwait(false);
return await ModbusRtuFraming.ReadResponsePduAsync(stream, unitId, cts.Token, pdu).ConfigureAwait(false);
}
catch (ModbusTransportDesyncException)
{
@@ -204,7 +204,12 @@ public sealed class ModbusRtuOverTcpTransport : IModbusWriteOnceTransport
// request on this socket would read that stale reply as its own answer (valid CRC, same unit) and
// publish it Good. Discard the socket; the next call re-dials. A ModbusException is a CRC-valid
// exception PDU: the frame was fully consumed, the socket is coherent, so it is excluded.
if (_life is not null) await _life.TearDownAsync().ConfigureAwait(false);
// A caller cancel is OUR abandonment, not a link fault: with auto-reconnect off it still owes one redial (#1055).
if (_life is not null)
{
if (ex is OperationCanceledException) await _life.DiscardAsync().ConfigureAwait(false);
else await _life.TearDownAsync().ConfigureAwait(false);
}
throw;
}
finally
@@ -146,9 +146,21 @@ public sealed class ModbusSocketLifecycle : IAsyncDisposable
public async Task EnsureConnectedAsync(CancellationToken ct)
{
if (_stream is not null) return;
var redialAfterDiscard = _redialAfterDiscard;
_redialAfterDiscard = false;
if (!_autoReconnect)
throw new ModbusTransportUnavailableException(
$"Modbus transport to {_host}:{_port} is not connected and auto-reconnect is disabled");
{
if (!redialAfterDiscard)
throw new ModbusTransportUnavailableException(
$"Modbus transport to {_host}:{_port} is not connected and auto-reconnect is disabled");
// #1055: the socket was discarded by US (a caller-cancelled RTU transaction), not lost to a fault —
// one fresh dial is owed even with auto-reconnect off, otherwise a single unsubscribe/probe cancel
// would leave the transport dead until the 90 s comms-loss watchdog re-initialised the driver. A
// failed dial just throws; the allowance is spent, so a dead device stays "not connected".
await ConnectAsync(ct).ConfigureAwait(false);
return;
}
var now = NowMs();
if (now < _connectNotBeforeMs)
@@ -198,6 +210,21 @@ public sealed class ModbusSocketLifecycle : IAsyncDisposable
/// <summary>Records that a transaction just succeeded, resetting the idle-disconnect clock.</summary>
public void MarkSuccess() => _lastSuccessUtc = DateTime.UtcNow;
// Guarded by the composing transport's single-flight gate, like the throttle state above.
private bool _redialAfterDiscard;
/// <summary>
/// Discards the current socket because THIS side abandoned a transaction (a caller cancel with a reply possibly in
/// flight) — not because the link failed. Unlike <see cref="TearDownAsync"/> it grants the next
/// <see cref="EnsureConnectedAsync"/> exactly one dial even when auto-reconnect is disabled (#1055).
/// </summary>
/// <returns>A task representing the asynchronous teardown operation.</returns>
public async Task DiscardAsync()
{
await TearDownAsync().ConfigureAwait(false);
_redialAfterDiscard = true;
}
/// <summary>Tears down the current socket + stream, leaving the lifecycle ready to reconnect.</summary>
/// <returns>A task representing the asynchronous teardown operation.</returns>
public async Task TearDownAsync()
@@ -42,6 +42,12 @@ public sealed class ModbusTransportDesyncException : IOException
/// RS-485 multi-drop bus, a reply from the wrong slave.
/// </summary>
UnitMismatch,
/// <summary>
/// A CRC-valid reply from the addressed unit answered a different request than the one in flight — its
/// function code (or, for a write echo, its start address) differs from the request's (#1029).
/// </summary>
ResponseMismatch,
}
/// <summary>Gets the reason the socket was classified desynchronized.</summary>