fix(heidenhain): #990 review — host-facing state keyed by host:port survives re-init; dispose cancels before closing the session
- _facing was keyed by runtime instance: it grew one entry per re-init (watchdog every ~90 s while a control is down) and each new runtime restarted at Unknown, so a down control's status flapped Stopped -> Unknown -> Stopped across every re-init. Now keyed by host:port, pruned to the configured hosts at init and cleared at shutdown; a runtime no longer in _devices (being stopped by re-init/shutdown) announces nothing. - DeviceRuntime.DisposeAsync cancels the loop BEFORE closing the session: closing first woke an in-flight read while the token was live, and the loop's normal tail set Backoff (host Stopped) for a plain stop. Seam AfterSessionCloseForTests makes the race deterministic.
This commit is contained in:
@@ -440,10 +440,12 @@ overrides, axes, tool, the whole alarm walk) and aliased custom addresses are re
|
||||
then drops is backed off, not re-dialled every `InitialDelayMs`. Unlike the Java base, an initial connect
|
||||
failure also retries (no manual restart). The loop survives any unexpected fault (logged, retired, backed off);
|
||||
JSON-`null` config sections are normalised to defaults by the parser.
|
||||
(#990) A deliberate stop (deploy / Force Reconnect) is never an outage: the runtime's generation is bumped before
|
||||
the session closes, and its values are invalidated. The backoff count is carried across a watchdog re-init, so a
|
||||
(#990) A deliberate stop (deploy / Force Reconnect) is never an outage: the runtime's generation is bumped and its
|
||||
loop CANCELLED before the session closes (closing first let a woken loop report `Backoff` — host `Stopped` — for a
|
||||
plain stop), and its values are invalidated. The backoff count is carried across a watchdog re-init, so a
|
||||
`MaxDelayMs` above ~90 s is reachable. While a control is down its host status stays `Stopped` (no
|
||||
`Stopped`/`Unknown` flap, "since" time stable). A refused optional DNC/DATA login is retried per session on a
|
||||
`Stopped`/`Unknown` flap, "since" time stable) — across a re-init too: the announced host state is kept per
|
||||
`host:port` (not per runtime instance), and a runtime being stopped by a re-init announces nothing. A refused optional DNC/DATA login is retried per session on a
|
||||
5 s to 5 min exponential schedule instead of on every poll batch.
|
||||
- Subscriptions: the initial push and later publications are ordered under one lock, so a subscriber never
|
||||
receives an older value after a newer one. A re-init disposes every control loop first; a late start of a
|
||||
|
||||
@@ -442,7 +442,10 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
|
||||
catch (Exception ex) { _logger.LogDebug(ex, "Heidenhain state-change handler threw"); }
|
||||
}
|
||||
|
||||
/// <summary>Stops the loop: closes the session first (unblocks a read), cancels, joins ≤ 5 s, invalidates.</summary>
|
||||
/// <summary>Test seam: awaited by <see cref="DisposeAsync"/> right after it closes the session.</summary>
|
||||
internal Func<Task>? AfterSessionCloseForTests { get; set; }
|
||||
|
||||
/// <summary>Stops the loop: cancels, then closes the session (unblocks a read), joins ≤ 5 s, invalidates.</summary>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
Task? loop;
|
||||
@@ -467,8 +470,13 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable
|
||||
session = _session;
|
||||
}
|
||||
|
||||
session?.Close();
|
||||
// #990 review: CANCEL before closing. Closing first unblocked an in-flight read while the loop's token was
|
||||
// still live, so a loop that woke before the cancel landed ran its "session gone" tail — a Backoff state,
|
||||
// i.e. host Stopped — and a deliberate stop showed as an outage. Cancelled first, whatever the closed read
|
||||
// does next, the loop sees its token cancelled and exits.
|
||||
if (cts is not null) await cts.CancelAsync().ConfigureAwait(false);
|
||||
session?.Close();
|
||||
if (AfterSessionCloseForTests is { } hook) await hook().ConfigureAwait(false);
|
||||
if (loop is not null)
|
||||
{
|
||||
try { await loop.WaitAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false); }
|
||||
|
||||
@@ -240,6 +240,11 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi
|
||||
|
||||
_devices = runtimes;
|
||||
_byRawPath = byPath;
|
||||
lock (_facing)
|
||||
{
|
||||
var live = runtimes.Select(r => r.HostName).ToHashSet(StringComparer.Ordinal);
|
||||
foreach (var stale in _facing.Keys.Where(k => !live.Contains(k)).ToList()) _facing.Remove(stale);
|
||||
}
|
||||
_alarms.Tags = alarmTags;
|
||||
}
|
||||
|
||||
@@ -267,6 +272,7 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi
|
||||
_initialized = false;
|
||||
await StopDevicesAsync().ConfigureAwait(false);
|
||||
_carriedFailures = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
lock (_facing) _facing.Clear();
|
||||
_subscriptions.Clear();
|
||||
lock (_lifecycleLock) _state = DriverState.Unknown;
|
||||
}
|
||||
@@ -400,7 +406,17 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi
|
||||
return a.Equals(b);
|
||||
}
|
||||
|
||||
private readonly Dictionary<HeidenhainDeviceRuntime, HostState> _facing = new();
|
||||
/// <summary>
|
||||
/// Host-facing state last announced, per <c>host:port</c> (#990 review). Keyed by HOST, not by runtime instance:
|
||||
/// a re-init (the comms-loss watchdog's remedy for a down control, every ~90 s) replaces every runtime, and
|
||||
/// an instance key both grew forever and restarted each new runtime at Unknown — flapping a down control's
|
||||
/// status Stopped → Unknown → Stopped across every re-init. Runtimes no longer in <see cref="_devices"/> (being
|
||||
/// stopped by a re-init/shutdown) announce nothing; entries for hosts no longer configured are pruned at init.
|
||||
/// </summary>
|
||||
private readonly Dictionary<string, HostState> _facing = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Test seam: entries in the host-facing state map.</summary>
|
||||
internal int FacingEntryCountForTests { get { lock (_facing) return _facing.Count; } }
|
||||
|
||||
private void OnRuntimeState(HeidenhainDeviceRuntime runtime, HeidenhainConnectionState old, HeidenhainConnectionState next)
|
||||
{
|
||||
@@ -409,8 +425,11 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi
|
||||
HostState o;
|
||||
lock (_facing)
|
||||
{
|
||||
o = _facing.GetValueOrDefault(runtime, HostState.Unknown);
|
||||
_facing[runtime] = n;
|
||||
// A runtime being stopped by a re-init/shutdown is no longer the host's voice: its Stopped/Unknown tail
|
||||
// must not reach the operator (its successor carries the failure state on, #990 M-19).
|
||||
if (!_devices.Contains(runtime)) return;
|
||||
o = _facing.GetValueOrDefault(runtime.HostName, HostState.Unknown);
|
||||
_facing[runtime.HostName] = n;
|
||||
}
|
||||
|
||||
if (o == n) return;
|
||||
|
||||
@@ -346,4 +346,72 @@ public sealed class HeidenhainReviewFixTests
|
||||
(_, _) => ValueTask.FromResult(""), publish, (_, o, n) => onState?.Invoke(o, n),
|
||||
(h, p, t) => new Lsv2Client(h, p, t), TimeProvider.System, NullLogger.Instance);
|
||||
}
|
||||
|
||||
// ---- #990 review: a deliberate stop cancels BEFORE it closes the session. ----
|
||||
|
||||
/// <summary>
|
||||
/// Closing the session first unblocked the in-flight read while the loop's token was still live, so a loop that
|
||||
/// woke before the cancel landed ran its normal "session gone" tail — a Backoff transition, i.e. a stop shown as
|
||||
/// an outage (host Stopped). The seam holds the dispose right after the close to let the loop win that race.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Disposing_mid_read_cancels_first_so_the_woken_loop_never_reports_backoff()
|
||||
{
|
||||
var inRead = new ManualResetEventSlim();
|
||||
var release = new ManualResetEventSlim();
|
||||
var control = new SimulatedControl();
|
||||
control.Runtime[23] = () => { inRead.Set(); release.Wait(TimeSpan.FromSeconds(5)); return SimulatedControl.U16(4); };
|
||||
await using var sim = Lsv2Simulator.WithControl(control);
|
||||
var states = new ConcurrentQueue<HeidenhainConnectionState>();
|
||||
var runtime = NewRuntime(sim.Port, (_, _) => { }, onState: (_, n) => states.Enqueue(n));
|
||||
runtime.AfterSessionCloseForTests = async () =>
|
||||
{
|
||||
release.Set();
|
||||
await Task.Delay(500, Ct); // the closed read fails now; give the loop every chance to run its tail
|
||||
};
|
||||
runtime.Start();
|
||||
inRead.Wait(TimeSpan.FromSeconds(5), Ct).ShouldBeTrue();
|
||||
|
||||
await runtime.DisposeAsync();
|
||||
|
||||
states.ShouldNotContain(HeidenhainConnectionState.Backoff);
|
||||
runtime.State.ShouldBe(HeidenhainConnectionState.Stopped);
|
||||
}
|
||||
|
||||
// ---- #990 review: host-facing state is per HOST and survives a re-init. ----
|
||||
|
||||
/// <summary>
|
||||
/// The facing map was keyed by runtime INSTANCE: it grew by one entry per re-init (the comms-loss watchdog
|
||||
/// re-inits a down control every ~90 s), and each new runtime started from Unknown — so the old runtime's
|
||||
/// stop (→ Unknown) and the new one's first retry (→ Stopped) flapped the host status across every re-init,
|
||||
/// the M-17 flap the per-retry fix had removed within one runtime.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Reinitialize_of_a_down_control_keeps_its_host_status_and_does_not_grow_the_facing_map()
|
||||
{
|
||||
var options = new HeidenhainDriverOptions
|
||||
{
|
||||
TimeoutMs = 500,
|
||||
Devices = [new HeidenhainDeviceOptions { Host = "127.0.0.1", Port = 1, DeviceName = "dev1" }],
|
||||
RawTags = [TestTags.Raw("Status/ExecutionState")],
|
||||
Reconnect = new HeidenhainReconnectOptions { InitialDelayMs = 100, MaxDelayMs = 200 },
|
||||
};
|
||||
await using var d = new HeidenhainDriver(options, "hh", null, new HeidenhainCredentials(null), null, null);
|
||||
var events = new ConcurrentQueue<HostStatusChangedEventArgs>();
|
||||
d.OnHostStatusChanged += (_, e) => events.Enqueue(e);
|
||||
await d.InitializeAsync("{}", Ct);
|
||||
await d.SubscribeAsync([options.RawTags[0].RawPath], TimeSpan.FromSeconds(1), Ct);
|
||||
await WaitFor(() => d.GetHostStatuses().Single().State == HostState.Stopped);
|
||||
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
await d.ReinitializeAsync("{}", Ct);
|
||||
await d.SubscribeAsync([options.RawTags[0].RawPath], TimeSpan.FromSeconds(1), Ct);
|
||||
await Task.Delay(400, Ct); // several retries of the new runtime
|
||||
}
|
||||
|
||||
events.ShouldNotContain(e => e.OldState == HostState.Stopped, "a down control never leaves Stopped across a re-init");
|
||||
events.Count(e => e.NewState == HostState.Stopped).ShouldBe(1);
|
||||
d.FacingEntryCountForTests.ShouldBe(1);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user