From 2d28f5ea8a74107ccfd4b2a704bb48b088e7fa3c Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 11:55:28 -0500 Subject: [PATCH] =?UTF-8?q?fix(heidenhain):=20#990=20review=20=E2=80=94=20?= =?UTF-8?q?host-facing=20state=20keyed=20by=20host:port=20survives=20re-in?= =?UTF-8?q?it;=20dispose=20cancels=20before=20closing=20the=20session?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - _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. --- docs/drivers/Heidenhain.md | 8 ++- .../HeidenhainDeviceRuntime.cs | 12 +++- .../HeidenhainDriver.cs | 25 ++++++- .../HeidenhainReviewFixTests.cs | 68 +++++++++++++++++++ 4 files changed, 105 insertions(+), 8 deletions(-) diff --git a/docs/drivers/Heidenhain.md b/docs/drivers/Heidenhain.md index 1e2c92419..70577d205 100644 --- a/docs/drivers/Heidenhain.md +++ b/docs/drivers/Heidenhain.md @@ -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 diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDeviceRuntime.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDeviceRuntime.cs index 68a373ec0..ab41681de 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDeviceRuntime.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDeviceRuntime.cs @@ -442,7 +442,10 @@ internal sealed class HeidenhainDeviceRuntime : IAsyncDisposable catch (Exception ex) { _logger.LogDebug(ex, "Heidenhain state-change handler threw"); } } - /// Stops the loop: closes the session first (unblocks a read), cancels, joins ≤ 5 s, invalidates. + /// Test seam: awaited by right after it closes the session. + internal Func? AfterSessionCloseForTests { get; set; } + + /// Stops the loop: cancels, then closes the session (unblocks a read), joins ≤ 5 s, invalidates. 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); } diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDriver.cs index 0323cba50..a048269a6 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDriver.cs @@ -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(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 _facing = new(); + /// + /// Host-facing state last announced, per host:port (#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 (being + /// stopped by a re-init/shutdown) announce nothing; entries for hosts no longer configured are pruned at init. + /// + private readonly Dictionary _facing = new(StringComparer.Ordinal); + + /// Test seam: entries in the host-facing state map. + 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; diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests/HeidenhainReviewFixTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests/HeidenhainReviewFixTests.cs index 550ea8649..4d90249a4 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests/HeidenhainReviewFixTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests/HeidenhainReviewFixTests.cs @@ -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. ---- + + /// + /// 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. + /// + [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(); + 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. ---- + + /// + /// 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. + /// + [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(); + 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); + } }