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
@@ -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);
}
}