fix(twincat): #1035 writes to a gone device fail fast per call; a read in flight on a retired client is re-read on a fresh one
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -337,6 +337,14 @@ client, and its 2 s used to silently override a raised driver `Timeout` for ever
|
||||
and the rest of that device's tags fail fast with no wire attempt, an answer and the failure was that one
|
||||
tag's. A device the probe already counts unreachable (3 failed ticks) fails fast outright. A native subscribe
|
||||
applies the same rule. Health is applied once per device per call (P-19), still Degraded on a comms failure.
|
||||
**Writes get the same per-call verdict (#1035):** the first comms-class write failure is state-checked once per
|
||||
device, and a gone (or never-connected / probe-unreachable) device's remaining writes answer `BadCommunicationError`
|
||||
with no wire attempt — a 10-write batch used to pay the timeout ten times. And a read already in flight when the
|
||||
client is retired (symbol-table invalidation / reconnect) is discarded and re-read once on a fresh client rather than
|
||||
published from the retired symbol cache (a sum-read chunk falls back to single reads). A retirement landing after
|
||||
the read returned is still the P-1 window; writes cannot be un-sent and are not re-run. Hardware gate: stop the PLC
|
||||
runtime/route mid-batch on a real device and confirm the batch returns in ~one timeout, and an online change during a
|
||||
slow read never publishes a pre-change value.
|
||||
- **The probe does not replay against an offline PLC (P-4).** The probe connects without replaying the stored
|
||||
registrations, probes, and re-registers them only after the device answered; a replay that hits a dead device
|
||||
stops dialling it. While the device is down the registrations publish `BadCommunicationError` once and one
|
||||
|
||||
@@ -617,6 +617,18 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery
|
||||
var (value, status) = await client.ReadValueAsync(
|
||||
e.Tag.SymbolName, def.DataType, e.Tag.BitIndex, def.ArrayLength, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (IsRetiredClient(device, client))
|
||||
{
|
||||
// #1035: the symbol table was invalidated (or the client replaced) WHILE this read was in flight, so the
|
||||
// value was addressed through an IndexGroup/IndexOffset resolved before the program change — it could be
|
||||
// other memory. Discard it and read once on a fresh client; if that one is retired too, answer Bad for
|
||||
// this poll (no health write: nothing about the device's comms was learned) rather than publish it.
|
||||
client = await EnsureConnectedAsync(device, cancellationToken).ConfigureAwait(false);
|
||||
(value, status) = await client.ReadValueAsync(
|
||||
e.Tag.SymbolName, def.DataType, e.Tag.BitIndex, def.ArrayLength, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (IsRetiredClient(device, client)) return CommsBad(now);
|
||||
}
|
||||
var snapshot = CompleteRead(e, value, status, now, batch);
|
||||
if (IsCommsStatus(status)) await VerifyDeviceAsync(device, client, batch, cancellationToken).ConfigureAwait(false);
|
||||
return snapshot;
|
||||
@@ -632,6 +644,13 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when <paramref name="client"/> is no longer the device's usable client: its symbol table was invalidated
|
||||
/// (<see cref="DeviceState.StaleClient"/>) or a reconnect replaced it while a call was in flight.
|
||||
/// </summary>
|
||||
private static bool IsRetiredClient(DeviceState device, ITwinCATClient client) =>
|
||||
ReferenceEquals(device.StaleClient, client) || !ReferenceEquals(device.Client, client);
|
||||
|
||||
/// <summary>
|
||||
/// After a comms-class failure, asks the device for its ADS state once per call: no answer ⇒ the device is
|
||||
/// gone and its remaining tags fail fast; an answer ⇒ the failure was that one tag's (a slow / oversized
|
||||
@@ -785,6 +804,18 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery
|
||||
"is not working on this target; this warning is logged once per device",
|
||||
_driverInstanceId, device.Options.HostAddress, client.LastSumFallbackCode);
|
||||
}
|
||||
if (IsRetiredClient(device, client))
|
||||
{
|
||||
// #1035: retired while the sum-read was in flight — its values are not trustworthy; re-read each tag
|
||||
// singly (ReadOneAsync repeats this check and reconnects).
|
||||
for (var k = 0; k < count; k++)
|
||||
{
|
||||
var e = bucket[start + k];
|
||||
results[e.Index] = await ReadOneAsync(e, device, now, batch, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
var anyComms = false;
|
||||
for (var k = 0; k < count; k++)
|
||||
{
|
||||
@@ -838,6 +869,13 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery
|
||||
ArgumentNullException.ThrowIfNull(writes);
|
||||
var results = new WriteResult[writes.Count];
|
||||
|
||||
// #1035: the per-call fail-fast verdict the read path has (P-3), for writes. A device that is gone costs ONE
|
||||
// timeout per call — its remaining writes answer BadCommunicationError at once, with no wire attempt. A device
|
||||
// the probe already counts as unreachable is never dialled; a comms failure is checked against the device's
|
||||
// ADS state once per call (an answer = that one write's fault, its siblings still go out).
|
||||
HashSet<DeviceState> unreachable = [];
|
||||
HashSet<DeviceState> verified = [];
|
||||
|
||||
for (var i = 0; i < writes.Count; i++)
|
||||
{
|
||||
var w = writes[i];
|
||||
@@ -870,6 +908,13 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery
|
||||
? TwinCATArrayCodec.ToWriteElements(def.DataType, w.Value, arrayLength)
|
||||
: null;
|
||||
|
||||
if (device.ConsecutiveProbeFailures >= ProbeFailuresBeforeDegraded) unreachable.Add(device);
|
||||
if (unreachable.Contains(device))
|
||||
{
|
||||
results[i] = new WriteResult(TwinCATStatusMapper.BadCommunicationError);
|
||||
continue;
|
||||
}
|
||||
|
||||
var client = await EnsureConnectedAsync(device, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// BOOL-within-word write — a read-modify-write of the parent word at the parent's OWN
|
||||
@@ -892,6 +937,8 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery
|
||||
gate.Release();
|
||||
}
|
||||
NoteWriteOutcome(device, results[i].StatusCode, w.FullReference);
|
||||
if (IsCommsStatus(results[i].StatusCode))
|
||||
await NoteWriteCommsFailureAsync(device, client, verified, unreachable, cancellationToken).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -903,6 +950,8 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery
|
||||
results[i] = new WriteResult(await client.WriteArrayAsync(
|
||||
symbolName, def.DataType, elements, cancellationToken).ConfigureAwait(false));
|
||||
NoteWriteOutcome(device, results[i].StatusCode, w.FullReference);
|
||||
if (IsCommsStatus(results[i].StatusCode))
|
||||
await NoteWriteCommsFailureAsync(device, client, verified, unreachable, cancellationToken).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -910,6 +959,8 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery
|
||||
symbolName, def.DataType, tag.BitIndex, w.Value, cancellationToken).ConfigureAwait(false);
|
||||
results[i] = new WriteResult(status);
|
||||
NoteWriteOutcome(device, status, w.FullReference);
|
||||
if (IsCommsStatus(status))
|
||||
await NoteWriteCommsFailureAsync(device, client, verified, unreachable, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch (NotSupportedException)
|
||||
@@ -930,12 +981,39 @@ public sealed class TwinCATDriver : IDriver, IReadable, IWritable, ITagDiscovery
|
||||
{
|
||||
results[i] = new WriteResult(TwinCATStatusMapper.BadCommunicationError);
|
||||
MarkCommsFault(ex.Message, device);
|
||||
// No live client = the connect itself failed or was throttled: the device is unreachable.
|
||||
await NoteWriteCommsFailureAsync(
|
||||
device, device.Client is { IsConnected: true } live ? live : null, verified, unreachable,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// After a comms-class write failure, asks the device for its ADS state once per call: no answer (or no client at
|
||||
/// all) ⇒ the device is gone and its remaining writes fail fast; an answer ⇒ the failure was that one write's.
|
||||
/// </summary>
|
||||
private async Task NoteWriteCommsFailureAsync(DeviceState device, ITwinCATClient? client,
|
||||
HashSet<DeviceState> verified, HashSet<DeviceState> unreachable, CancellationToken cancellationToken)
|
||||
{
|
||||
if (unreachable.Contains(device)) return;
|
||||
if (client is null)
|
||||
{
|
||||
unreachable.Add(device);
|
||||
return;
|
||||
}
|
||||
if (!verified.Add(device)) return;
|
||||
if (!await DeviceStillAnswersAsync(client, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
unreachable.Add(device);
|
||||
_logger.LogDebug(
|
||||
"TwinCAT driver '{DriverInstanceId}' device '{HostAddress}' did not answer its state after a failed write; " +
|
||||
"its remaining writes fail fast for this call", _driverInstanceId, device.Options.HostAddress);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- ITagDiscovery ----
|
||||
|
||||
/// <inheritdoc />
|
||||
|
||||
@@ -709,4 +709,160 @@ public sealed class TwinCATReview20261202Tests
|
||||
factory.Clients.ShouldContain(c => c.LastConnectTimeout == TimeSpan.FromSeconds(8));
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
// ======================= #1035 — write fail-fast + retired-client read =======================
|
||||
|
||||
/// <summary>A client for one silent AMS target that waits <see cref="Delay"/> per write, then answers BadTimeout.</summary>
|
||||
private sealed class SilentWriteFake(string silentNetId, TimeSpan delay, bool targetAnswersProbe) : FakeTwinCATClient
|
||||
{
|
||||
private int _silentWrites;
|
||||
public int SilentWrites => Volatile.Read(ref _silentWrites);
|
||||
private bool Silent => ConnectedAddress?.NetId == silentNetId;
|
||||
|
||||
public override async Task<uint> WriteValueAsync(
|
||||
string symbolPath, TwinCATDataType type, int? bitIndex, object? value, CancellationToken ct)
|
||||
{
|
||||
if (!Silent) return await base.WriteValueAsync(symbolPath, type, bitIndex, value, ct);
|
||||
Interlocked.Increment(ref _silentWrites);
|
||||
await Task.Delay(delay, ct);
|
||||
return TwinCATStatusMapper.BadTimeout;
|
||||
}
|
||||
|
||||
public override Task<bool> ProbeAsync(CancellationToken ct) =>
|
||||
Silent && !targetAnswersProbe ? Task.FromResult(false) : base.ProbeAsync(ct);
|
||||
}
|
||||
|
||||
private static (TwinCATDriver drv, List<SilentWriteFake> clients, TwinCATTagDefinition[] tags) SilentWriteDriver(
|
||||
TimeSpan delay, bool targetAnswersProbe)
|
||||
{
|
||||
var clients = new List<SilentWriteFake>();
|
||||
var factory = new FakeTwinCATClientFactory();
|
||||
factory.Customise = () =>
|
||||
{
|
||||
var c = new SilentWriteFake("5.23.91.23.1.1", delay, targetAnswersProbe);
|
||||
lock (clients) clients.Add(c);
|
||||
return c;
|
||||
};
|
||||
var tags = TagsOn(HostA, "A", 10)
|
||||
.Append(new TwinCATTagDefinition("B0", HostB, "MAIN.B0", TwinCATDataType.DInt)).ToArray();
|
||||
tags = [.. tags.Select(t => t with { Writable = true })];
|
||||
var drv = new TwinCATDriver(new TwinCATDriverOptions
|
||||
{
|
||||
Devices = [new TwinCATDeviceOptions(HostA), new TwinCATDeviceOptions(HostB)],
|
||||
RawTags = TwinCATRawTags.Entries(tags),
|
||||
Probe = NoProbe,
|
||||
Timeout = TimeSpan.FromSeconds(2),
|
||||
}, "drv-1035", factory);
|
||||
return (drv, clients, tags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #1035: a write batch to a device that stopped answering paid the timeout once PER WRITE (reads got the P-3 fail-fast,
|
||||
/// writes did not). Now the first comms failure is checked against the device's ADS state and the rest of that
|
||||
/// device's writes in the call answer BadCommunicationError with no wire attempt; another device's write is unaffected.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_silent_device_costs_one_write_timeout_per_call_not_one_per_write()
|
||||
{
|
||||
var delay = TimeSpan.FromMilliseconds(300);
|
||||
var (drv, clients, tags) = SilentWriteDriver(delay, targetAnswersProbe: false);
|
||||
await drv.InitializeAsync("{}", Ct);
|
||||
|
||||
var sw = Stopwatch.StartNew();
|
||||
var results = await drv.WriteAsync([.. tags.Select(t => new WriteRequest(t.Name, 5))], Ct);
|
||||
sw.Stop();
|
||||
|
||||
sw.Elapsed.ShouldBeLessThan(delay * 5, "A's writes must short-circuit after the first comms failure");
|
||||
clients.Sum(c => c.SilentWrites).ShouldBe(1, "one wire attempt on the silent device per call");
|
||||
results.Take(10).ShouldAllBe(r => IsComms(r.StatusCode));
|
||||
results[10].StatusCode.ShouldBe(TwinCATStatusMapper.Good, "the healthy device's write goes out");
|
||||
drv.GetHealth().State.ShouldBe(DriverState.Degraded);
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #1035 positive control: a write that times out on a device that STILL answers its state read is that one write's
|
||||
/// fault — its siblings are still attempted (the short-circuit is reserved for a device that is gone).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_write_timeout_on_a_device_that_still_answers_does_not_short_circuit_its_siblings()
|
||||
{
|
||||
var (drv, clients, tags) = SilentWriteDriver(TimeSpan.FromMilliseconds(20), targetAnswersProbe: true);
|
||||
await drv.InitializeAsync("{}", Ct);
|
||||
|
||||
var results = await drv.WriteAsync([.. tags.Take(10).Select(t => new WriteRequest(t.Name, 5))], Ct);
|
||||
|
||||
clients.Sum(c => c.SilentWrites).ShouldBe(10, "every sibling is still attempted on a live device");
|
||||
results.ShouldAllBe(r => r.StatusCode == TwinCATStatusMapper.BadTimeout);
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
/// <summary>A device whose connect fails: the first write pays it, the throttled rest do not even try.</summary>
|
||||
[Fact]
|
||||
public async Task A_device_that_cannot_connect_fails_the_rest_of_the_batch_without_further_attempts()
|
||||
{
|
||||
var factory = new FakeTwinCATClientFactory();
|
||||
factory.Customise = () => new FakeTwinCATClient { ThrowOnConnect = true };
|
||||
var tags = TagsOn(HostA, "A", 6).Select(t => t with { Writable = true }).ToArray();
|
||||
var drv = NewDriver(factory, NoProbe, native: false, null, [HostA], tags);
|
||||
await drv.InitializeAsync("{}", Ct);
|
||||
|
||||
var results = await drv.WriteAsync([.. tags.Select(t => new WriteRequest(t.Name, 1))], Ct);
|
||||
|
||||
results.ShouldAllBe(r => r.StatusCode == TwinCATStatusMapper.BadCommunicationError);
|
||||
factory.Clients.Count.ShouldBe(1, "one connect attempt; the rest of the batch failed fast");
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
private static bool IsComms(uint status) =>
|
||||
status is TwinCATStatusMapper.BadCommunicationError or TwinCATStatusMapper.BadTimeout;
|
||||
|
||||
/// <summary>
|
||||
/// #1035: a read already in flight when the symbol table is invalidated used to finish on the retired client and
|
||||
/// publish its stale-offset value at Good. It is now discarded and re-read on a fresh client.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_read_in_flight_when_the_client_is_retired_is_re_read_on_a_fresh_client()
|
||||
{
|
||||
var factory = GenerationalFactory();
|
||||
var drv = NewDriver(factory, NoProbe, native: false, null, [HostA],
|
||||
new TwinCATTagDefinition("X", HostA, "MAIN.X", TwinCATDataType.DInt));
|
||||
await drv.InitializeAsync("{}", Ct);
|
||||
(await drv.ReadAsync(["X"], Ct))[0].Value.ShouldBe(111);
|
||||
|
||||
var first = factory.Clients[0];
|
||||
first.BlockRead = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var inFlight = drv.ReadAsync(["X"], Ct);
|
||||
await Task.Delay(100, Ct);
|
||||
inFlight.IsCompleted.ShouldBeFalse("the read must be wedged in the wire call");
|
||||
|
||||
first.FireSymbolVersionChanged(); // a program change retires the client mid-read
|
||||
first.BlockRead!.SetResult();
|
||||
|
||||
var after = (await inFlight.WaitAsync(TimeSpan.FromSeconds(5), Ct))[0];
|
||||
after.StatusCode.ShouldBe(TwinCATStatusMapper.Good);
|
||||
after.Value.ShouldBe(211, "the retired client's 111 must be discarded, not published");
|
||||
factory.Clients.Count.ShouldBe(2);
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
|
||||
/// <summary>Positive control for the above: with no invalidation the in-flight read keeps its value and no reconnect happens.</summary>
|
||||
[Fact]
|
||||
public async Task A_read_in_flight_with_no_invalidation_keeps_its_client_and_value()
|
||||
{
|
||||
var factory = GenerationalFactory();
|
||||
var drv = NewDriver(factory, NoProbe, native: false, null, [HostA],
|
||||
new TwinCATTagDefinition("X", HostA, "MAIN.X", TwinCATDataType.DInt));
|
||||
await drv.InitializeAsync("{}", Ct);
|
||||
(await drv.ReadAsync(["X"], Ct))[0].Value.ShouldBe(111);
|
||||
|
||||
factory.Clients[0].BlockRead = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var inFlight = drv.ReadAsync(["X"], Ct);
|
||||
await Task.Delay(100, Ct);
|
||||
factory.Clients[0].BlockRead!.SetResult();
|
||||
|
||||
(await inFlight.WaitAsync(TimeSpan.FromSeconds(5), Ct))[0].Value.ShouldBe(111);
|
||||
factory.Clients.Count.ShouldBe(1);
|
||||
await drv.ShutdownAsync(Ct);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user