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:
Joseph Doherty
2026-12-03 11:55:28 -05:00
parent 7a6e623485
commit 2d28f5ea8a
4 changed files with 105 additions and 8 deletions
@@ -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;