perf(s7): fail the rest of a pass fast once the handle is dead (R07:P1)

No read or write loop checked _plcDead between items: on a frozen-but-
established peer the first op blew its deadline and marked the handle dead,
and every remaining span / tag / write still went to the wire and could wait
its own deadline under _gate (a 20-span pass ~100 s), with Degraded and the
comms-loss watchdog's clock deferred until the pass ended.

- The span loop, the multi-var chunk loop, the per-tag loop and the write
  loop stamp BadCommunicationError without I/O once _plcDead is set.
- A multi-var chunk that dies on a transport loss (socket / IO / timeout /
  ConnectionError) marks the handle dead instead of falling back to one
  doomed per-tag read per member. The framing class is deliberately excluded
  there: snap7/S7.Net report a multi-var with one refused item as
  ReadData(WrongNumberReceivedBytes) over a healthy stream.
- Live gate via an in-test freezable TCP proxy (counts request frames, not
  seconds). Mutation shows S7.Net 0.20 already self-closes on a cancelled op,
  so the gate pins the end-to-end property; the driver guard itself is proven
  by the unit tests (an op that ignores its token keeps the socket open).

Refs #742
Claude-Session: https://claude.ai/code/session_01Ub9hGmYLQvn9XETzw7CMsT
This commit is contained in:
Joseph Doherty
2026-10-22 15:26:14 -04:00
parent a1f20e78f9
commit 1d83cde6bc
6 changed files with 422 additions and 1 deletions
@@ -0,0 +1,104 @@
using System.Net;
using System.Net.Sockets;
namespace ZB.MOM.WW.OtOpcUa.Driver.S7.IntegrationTests;
/// <summary>
/// An in-test TCP forwarder in front of the S7 fixture that can be FROZEN: while frozen it keeps
/// every socket open but forwards nothing in either direction — the frozen-but-established peer
/// (cable pull, firewall DROP) that only a wire-op deadline can detect, produced without touching
/// the shared fixture. It counts the ISO-on-TCP (TPKT) request frames the client sends while frozen,
/// so a test can assert how many wire operations went out without timing anything.
/// </summary>
internal sealed class FreezableTcpProxy : IAsyncDisposable
{
private readonly string _targetHost;
private readonly int _targetPort;
private readonly TcpListener _listener = new(IPAddress.Loopback, 0);
private readonly CancellationTokenSource _cts = new();
private readonly List<TcpClient> _sockets = [];
private volatile bool _frozen;
private int _framesWhileFrozen;
/// <summary>Starts a proxy forwarding to <paramref name="targetHost"/>:<paramref name="targetPort"/>.</summary>
/// <param name="targetHost">The fixture host.</param>
/// <param name="targetPort">The fixture port.</param>
public FreezableTcpProxy(string targetHost, int targetPort)
{
_targetHost = targetHost;
_targetPort = targetPort;
_listener.Start();
_ = AcceptLoopAsync();
}
/// <summary>The local port clients connect to.</summary>
public int Port => ((IPEndPoint)_listener.LocalEndpoint).Port;
/// <summary>TPKT request frames the client sent while the proxy was frozen.</summary>
public int FramesWhileFrozen => Volatile.Read(ref _framesWhileFrozen);
/// <summary>Stops forwarding (sockets stay open).</summary>
public void Freeze() => _frozen = true;
/// <summary>Resumes forwarding for connections made from now on.</summary>
public void Unfreeze() => _frozen = false;
private async Task AcceptLoopAsync()
{
try
{
while (!_cts.IsCancellationRequested)
{
var client = await _listener.AcceptTcpClientAsync(_cts.Token).ConfigureAwait(false);
var upstream = new TcpClient();
await upstream.ConnectAsync(_targetHost, _targetPort, _cts.Token).ConfigureAwait(false);
lock (_sockets) { _sockets.Add(client); _sockets.Add(upstream); }
// A connection accepted while frozen stays frozen for its whole life (its peer is "gone").
var frozenAtBirth = _frozen;
_ = PumpAsync(client.GetStream(), upstream.GetStream(), countFrames: true, frozenAtBirth);
_ = PumpAsync(upstream.GetStream(), client.GetStream(), countFrames: false, frozenAtBirth);
}
}
catch { /* disposed */ }
}
private async Task PumpAsync(NetworkStream from, NetworkStream to, bool countFrames, bool frozenAtBirth)
{
var buffer = new byte[8192];
var pending = new List<byte>();
try
{
while (!_cts.IsCancellationRequested)
{
var n = await from.ReadAsync(buffer, _cts.Token).ConfigureAwait(false);
if (n == 0) return;
var frozen = _frozen || frozenAtBirth;
if (countFrames && frozen)
{
// Count complete TPKT frames: 0x03 0x00 then a big-endian total length.
pending.AddRange(buffer.AsSpan(0, n).ToArray());
while (pending.Count >= 4)
{
var len = (pending[2] << 8) | pending[3];
if (len < 4 || pending.Count < len) break;
pending.RemoveRange(0, len);
Interlocked.Increment(ref _framesWhileFrozen);
}
}
if (frozen) continue; // swallow — the peer never answers
await to.WriteAsync(buffer.AsMemory(0, n), _cts.Token).ConfigureAwait(false);
}
}
catch { /* socket closed / disposed */ }
}
/// <inheritdoc />
public ValueTask DisposeAsync()
{
_cts.Cancel();
_listener.Stop();
lock (_sockets) foreach (var s in _sockets) s.Dispose();
_cts.Dispose();
return ValueTask.CompletedTask;
}
}
@@ -0,0 +1,71 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Driver.S7.IntegrationTests.S7_1500;
/// <summary>
/// Live gate for R07:P1 over real S7comm: a frozen-but-established peer (produced by an in-test
/// <see cref="FreezableTcpProxy"/>, so the shared fixture is never touched). The first wire op of
/// the pass blows its deadline and marks the connection dead; the rest of the pass must NOT go to
/// the wire. The assertion counts request frames, not seconds.
/// </summary>
/// <remarks>
/// <b>What this gate does and does not prove.</b> Verified by mutation (2026-10-22): on the real
/// stack this test also passes with the driver's dead-handle guard removed, because S7.Net 0.20
/// honours the deadline's cancellation token and closes its own socket, so the next op fails at once
/// with <c>ConnectionError</c> and sends nothing. The driver guard (proven by
/// <c>S7DeadHandleShortCircuitTests</c> against a fake that does not self-close) is what covers an
/// op that ignores its token — the <c>WaitAsync</c> leg of <c>S7OperationDeadline</c>, where the
/// abandoned socket stays open and every further op would pay the full deadline. This test pins the
/// end-to-end property (one request per frozen pass, then recovery) against S7.Net upgrades.
/// </remarks>
[Collection(Snap7ServerCollection.Name)]
[Trait("Category", "Integration")]
[Trait("Device", "S7_1500")]
public sealed class S7_1500FrozenPeerTests(Snap7ServerFixture sim)
{
/// <summary>A pass against a frozen peer issues ONE request, then fails the rest fast; it recovers after.</summary>
[Fact]
public async Task A_frozen_peer_costs_one_wire_op_per_pass_not_one_per_tag()
{
if (sim.SkipReason is not null) Assert.Skip(sim.SkipReason);
var ct = TestContext.Current.CancellationToken;
await using var proxy = new FreezableTcpProxy(sim.Host, sim.Port);
var baseOptions = S7_1500Profile.BuildOptions("127.0.0.1", proxy.Port);
var options = new S7DriverOptions
{
Host = baseOptions.Host, Port = baseOptions.Port, CpuType = baseOptions.CpuType,
Rack = baseOptions.Rack, Slot = baseOptions.Slot,
Timeout = TimeSpan.FromSeconds(1), // the per-op deadline that detects the frozen peer
Probe = baseOptions.Probe,
SpanReadMaxGapBytes = -1, // one wire request per tag, so "one per tag" is countable
RawTags = baseOptions.RawTags,
};
string[] refs =
[
S7_1500Profile.ProbeTag, S7_1500Profile.SmokeI16Tag, S7_1500Profile.SmokeI32Tag,
S7_1500Profile.SmokeF32Tag, S7_1500Profile.SmokeBoolTag, S7_1500Profile.WriteScratchTag,
];
await using var drv = new S7Driver(options, driverInstanceId: "s7-frozen-peer-live");
await drv.InitializeAsync("{}", ct);
// Positive control: through the proxy, every tag reads Good.
(await drv.ReadAsync(refs, ct)).ShouldAllBe(s => s.StatusCode == 0u);
proxy.Freeze();
var frozen = await drv.ReadAsync(refs, ct);
frozen.ShouldAllBe(s => s.StatusCode != 0u);
proxy.FramesWhileFrozen.ShouldBe(1, "only the request that discovered the dead connection may go out");
drv.GetHealth().State.ShouldBe(DriverState.Degraded);
// Recovery: the next pass reopens (a fresh proxy connection) and reads Good again.
proxy.Unfreeze();
var recovered = await drv.ReadAsync(refs, ct);
recovered.ShouldAllBe(s => s.StatusCode == 0u);
Convert.ToInt32(recovered[0].Value).ShouldBe(S7_1500Profile.ProbeSeedValue);
drv.GetHealth().State.ShouldBe(DriverState.Healthy);
}
}