diff --git a/kurgan/cooling/control.py b/kurgan/cooling/control.py index edc6368..8652d27 100644 --- a/kurgan/cooling/control.py +++ b/kurgan/cooling/control.py @@ -222,7 +222,7 @@ class CaseFanGroup: self._last_update = None try: self.commander.set_duty(self.ports, 100) - except (OSError, HidError): + except Exception: # the worker's finally block depends on this never raising log.exception("Cannot set %s case fans to failsafe 100%%; controller unavailable", self.name) @@ -262,6 +262,10 @@ class CpuTemperature: class CaseFanControl: + # Pause after a control error before polling again, so a lost device is not re-opened + # (with a full traceback and process enumeration) every second. + ERROR_RETRY_SECONDS = 5.0 + def __init__(self, commander: CommanderPro, gpu_ports: tuple[int, ...], cpu_ports: tuple[int, ...] | None = None, top: TopFanCurve | None = None, profile: FanProfile = BALANCED, sensors=None): @@ -316,11 +320,15 @@ class CaseFanControl: def run(self, stop: threading.Event) -> None: gpu_factory, cpu_factory = self._sensors cpu_temp = cpu_factory() if self.cpu is not None else None + gpu = None + reported: float | None = None # when the last unexpected error was logged try: - gpu = gpu_factory() while not stop.is_set(): now = time.monotonic() + retry_in = 1.0 try: + if gpu is None: + gpu = gpu_factory() self.update(gpu.read().temp, now, cpu_temp.read(now) if cpu_temp else None) except (OSError, HidError) as e: self._error(f"CONTROL ERROR: {e}") @@ -328,10 +336,19 @@ class CaseFanControl: self.commander.close() if self.top is not None: self.top.update(100, None, time.monotonic()) - stop.wait(1) - except Exception: - log.exception("Case fan worker failed") - self._error("CONTROL ERROR: fan worker stopped; check dashboard.log") + retry_in = self.ERROR_RETRY_SECONDS + except Exception as e: + # A sensor or control bug must not end fan control for the life of the + # process: fail safe, log at most once a minute, and retry with a freshly + # built sensor object. + if reported is None or now - reported >= 60: + reported = now + log.exception("Case fan control error; failing safe and retrying") + self._error(f"CONTROL ERROR: {e}") + self.failsafe() + gpu = None + retry_in = self.ERROR_RETRY_SECONDS + stop.wait(retry_in) finally: self.failsafe() self.commander.close() diff --git a/kurgan/hardware/hid.py b/kurgan/hardware/hid.py index c7ec5b5..cdf8504 100644 --- a/kurgan/hardware/hid.py +++ b/kurgan/hardware/hid.py @@ -33,6 +33,8 @@ _ERROR_IO_PENDING = 997 _ERROR_NO_MORE_ITEMS = 259 _WAIT_OBJECT_0 = 0 _WAIT_TIMEOUT = 0x102 +# How long to wait for the driver to finish a cancelled IRP before giving up on the channel. +_ABANDON_GRACE_MS = 1000 class _GUID(ctypes.Structure): @@ -193,6 +195,12 @@ class HidChannel: ) self._wevent = _k32.CreateEventW(None, True, False, None) self._revent = _k32.CreateEventW(None, True, False, None) + if not self._wevent or not self._revent: + raise _winerr("CreateEventW") + self._broken = False + # OVERLAPPED structs and buffers of IRPs we gave up on, kept alive so a late + # completion by the driver can never write into memory that has been reused. + self._abandoned: list = [] except Exception: _k32.CloseHandle(self.handle) raise @@ -202,8 +210,26 @@ class HidChannel: if h: _k32.CloseHandle(h) self.handle = None + # _abandoned is deliberately not cleared: closing the handle cancels the pending IRPs, + # but the driver may still complete them asynchronously. The channel object is dropped + # by the caller (a broken channel is always reopened), which frees the buffers then. + + def _cancel(self, ov, buf, event, what: str) -> None: + """Cancel a timed-out IRP and give the driver a moment to finish it. + + If the device is wedged and the cancellation never completes, mark the channel broken: + further calls fail fast instead of queueing more IRPs behind a dead one, and the + caller's reconnect path closes the handle (which cancels the IRP for good). + """ + _k32.CancelIoEx(self.handle, ctypes.byref(ov)) + if _k32.WaitForSingleObject(event, _ABANDON_GRACE_MS) == _WAIT_OBJECT_0: + return + self._broken = True + self._abandoned.append((ov, buf)) def send(self, payload: bytes, timeout_ms: int = 1000) -> None: + if self._broken: + raise HidError(f"HID write on {self.path}: channel abandoned after a timeout; reconnect it") data = bytes(1) + payload if len(data) < self.output_len: data += bytes(self.output_len - len(data)) @@ -216,14 +242,15 @@ class HidChannel: if ctypes.get_last_error() != _ERROR_IO_PENDING: raise _winerr("WriteFile") if _k32.WaitForSingleObject(self._wevent, timeout_ms) != _WAIT_OBJECT_0: - _k32.CancelIoEx(self.handle, ctypes.byref(ov)) - _k32.GetOverlappedResult(self.handle, ctypes.byref(ov), ctypes.byref(written), True) + self._cancel(ov, buf, self._wevent, "write") raise HidError(f"HID write timed out on {self.path}") if not _k32.GetOverlappedResult(self.handle, ctypes.byref(ov), ctypes.byref(written), True): raise _winerr("WriteFile (completion)") def read(self, timeout_ms: int) -> bytes | None: """Read one input report, or None on timeout.""" + if self._broken: + raise HidError(f"HID read on {self.path}: channel abandoned after a timeout; reconnect it") buf = ctypes.create_string_buffer(self.input_len) ov = _OVERLAPPED() ov.hEvent = self._revent @@ -232,8 +259,10 @@ class HidChannel: if not _k32.ReadFile(self.handle, buf, self.input_len, None, ctypes.byref(ov)): if ctypes.get_last_error() != _ERROR_IO_PENDING: raise _winerr("ReadFile") - if _k32.WaitForSingleObject(self._revent, timeout_ms) == _WAIT_TIMEOUT: - _k32.CancelIoEx(self.handle, ctypes.byref(ov)) + if _k32.WaitForSingleObject(self._revent, timeout_ms) != _WAIT_OBJECT_0: + self._cancel(ov, buf, self._revent, "read") + if self._broken: + raise HidError(f"HID read timed out on {self.path} and the device ignored the cancel") ok = _k32.GetOverlappedResult(self.handle, ctypes.byref(ov), ctypes.byref(got), True) return buf.raw[: got.value] if ok and got.value else None if not _k32.GetOverlappedResult(self.handle, ctypes.byref(ov), ctypes.byref(got), True): diff --git a/kurgan/telemetry/sensors.py b/kurgan/telemetry/sensors.py index ade8e80..8c1556b 100644 --- a/kurgan/telemetry/sensors.py +++ b/kurgan/telemetry/sensors.py @@ -691,16 +691,22 @@ class CommanderPro: now = time.monotonic() if now >= self._next_check: self._next_check = now + self.RECHECK - if self._corsair_software_running(): - self.close() - self._say("iCUE is running, leaving the device to it") - elif self.ch is None: - try: - self._open() - self._say(f"reading {len(self.ports)} fans (ports {', '.join(str(p + 1) for p in self.ports)})") - except Exception as e: + try: + if self._corsair_software_running(): self.close() - self._say(f"unavailable ({e})") + self._say("iCUE is running, leaving the device to it") + elif self.ch is None: + try: + self._open() + self._say(f"reading {len(self.ports)} fans (ports {', '.join(str(p + 1) for p in self.ports)})") + except Exception as e: + self.close() + self._say(f"unavailable ({e})") + except Exception as e: + # Ownership cannot be established (e.g. process enumeration failed): give the + # device up rather than risk swapped replies, and retry on the next check. + self.close() + self._say(f"ownership check failed ({e}); device released, retrying in {self.RECHECK:.0f} s") if self.ch is not None: try: for p in self.ports: diff --git a/kurgan/telemetry/service.py b/kurgan/telemetry/service.py index bb5c291..38800eb 100644 --- a/kurgan/telemetry/service.py +++ b/kurgan/telemetry/service.py @@ -50,15 +50,29 @@ class Telemetry: self._history: collections.deque[tuple] = collections.deque(maxlen=int(HISTORY_SECONDS / interval)) self._listeners: list[Callable[[Sample], None]] = [] self._seq = 0 + self._last_failure: dict[str, float] = {} def subscribe(self, listener: Callable[[Sample], None]) -> None: self._listeners.append(listener) def read(self) -> Sample: - c, g = self.cpu.read(), self.gpu.read() - p = self.system.read(c, g) + """Read every source independently: one failing source costs only its own readings.""" + c = self._source("CPU sensors", self.cpu.read, Readings()) + g = self._source("GPU sensors", self.gpu.read, Readings()) + p = self._source("system power", self.system.read, PowerReadings(), c, g) + vram = self._source("GPU memory", self.gpu.memory, None) self._seq += 1 - return Sample(self._seq, time.time(), c, g, p, self.gpu.memory()) + return Sample(self._seq, time.time(), c, g, p, vram) + + def _source(self, name: str, read: Callable, fallback, *args): + try: + return read(*args) + except Exception as e: + # The loop retries every second, so log each failing source at most once a minute. + if time.monotonic() - self._last_failure.get(name, -1e9) >= 60: + self._last_failure[name] = time.monotonic() + log.warning("%s read failed; continuing without it: %s", name, e, exc_info=True) + return fallback def run(self, stop: threading.Event) -> None: while not stop.is_set(): diff --git a/tests/test_fan_control.py b/tests/test_fan_control.py index 5291eb1..089411d 100644 --- a/tests/test_fan_control.py +++ b/tests/test_fan_control.py @@ -238,15 +238,25 @@ class FanWorkerTest(unittest.TestCase): self.commander.set_duty.assert_called_once_with((4, 5, 6), 100) self.commander.close.assert_called_once() - def test_worker_error_is_visible_and_attempts_failsafe(self): + def test_worker_survives_unexpected_errors_and_keeps_failing_safe(self): stop = threading.Event() gpu = Mock() - gpu.read.side_effect = RuntimeError("sensor failure") - with patch("kurgan.cooling.control.GpuSensors", return_value=gpu): + reads = [] + + def read(): + reads.append(1) + if len(reads) >= 3: + stop.set() + raise RuntimeError("sensor failure") + + gpu.read.side_effect = read + with patch("kurgan.cooling.control.GpuSensors", return_value=gpu), \ + patch.object(CaseFanControl, "ERROR_RETRY_SECONDS", 0): with self.assertLogs("kurgan.cooling.control", level="ERROR"): self.control.run(stop) + self.assertEqual(len(reads), 3) # retried instead of dying on the first error self.assertIn("CONTROL ERROR", self.control.status) - self.commander.set_duty.assert_called_once_with((4, 5, 6), 100) + self.commander.set_duty.assert_called_with((4, 5, 6), 100) class CommanderControlTest(unittest.TestCase):