Files
the_kurgan/tests/test_fan_control.py
paulandClaude Opus 5.5 b983528183 Review fixes: demo fans, record averages and restarts, combined alerts, quiet sensors
- demo.py: FakeBoard grows rpms(). The top fans' stall check (b2da221) called
  it, so under --demo every poll raised AttributeError and the case fans sat
  in CONTROL ERROR at 100%.
- control.py: TopFanCurve.update hands the headers back to the BIOS on any
  failure, a bug included, instead of letting it escape into the case fans'
  loop (unexpected errors are logged with a traceback once). The worker's
  catch-all now fails the top fans safe as well as the case fans, as the
  device-error path already did. The snapshot gives None for a channel whose
  tach has never turned, and the UI says "no tach reading" (and "Channel",
  not "Port") rather than showing SYS_FAN1's unwired tach as a dead fan.
- record.py: an hour's average is over the samples that carried the metric,
  not all of them: a GPU that dropped out for half an hour no longer halves
  its recorded power. Lines carry the count as a fourth number; the reader
  weights by it, and treats three-number lines as before.
- record.py: the hour in progress is checkpointed to records-current.json
  every minute and on close and resumed at start, so a hard stop (schtasks
  /End, the documented restart) loses at most a minute instead of the hour;
  a checkpoint from an earlier hour is written out at start. A failing write
  no longer stops recording for the run: it is logged at most once an hour
  and finished hours wait in memory (up to 48) until the disk works.
- app.py: alerts that start together share one balloon (Windows shows one at
  a time, so each notify() replaced the last), shortened to fit 255
  characters; a problem that clears and comes back balloons again only after
  10 minutes.
- telemetry/service.py: health also counts a source that returns no
  temperature three reads running. GpuSensors and CpuSensors don't raise
  when their device is lost, so a lost GPU driver used to show as healthy.
- hid.py: buffers of IRPs the driver never finished cancelling are kept for
  the life of the process; freeing them with their channel could still let a
  late completion write into reused memory.
- Tests: 13 new (160 pass). README updated to match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 18:31:11 +13:00

424 lines
19 KiB
Python

import argparse
import contextlib
import threading
import unittest
from unittest.mock import Mock, call, mock_open, patch
from kurgan.cooling.board_fans import Nct6687
from kurgan.cooling.control import CaseFanControl, CpuTemperature, TopFanCurve, cpu_duty, gpu_duty, parse_ports
from kurgan.telemetry.sensors import CommanderPro, corsair_software_running
class FanCurveTest(unittest.TestCase):
def test_cpu_curve_and_failsafe(self):
for temp, expected in ((30, 40), (50, 40), (60, 50), (70, 65), (75, 83), (80, 100),
(88, 100), (100, 100), (None, 100), (float("nan"), 100)):
with self.subTest(temp=temp):
self.assertEqual(cpu_duty(temp), expected)
def test_temperature_curve_and_failsafe(self):
for temp, expected in ((20, 40), (40, 40), (50, 50), (55, 58), (60, 65),
(68, 93), (70, 100), (75, 100), (95, 100),
(None, 100), (float("nan"), 100),
(float("inf"), 100), (-1, 100), (111, 100)):
with self.subTest(temp=temp):
self.assertEqual(gpu_duty(temp), expected)
def test_only_three_distinct_physical_ports_are_accepted(self):
self.assertEqual(parse_ports(" 4, 6, 5 "), (4, 6, 5))
for text in ("", "1,2", "1,2,3,4", "1,1,2", "0,1,2", "4,5,7", "a,2,3"):
with self.subTest(text=text):
with self.assertRaises(argparse.ArgumentTypeError):
parse_ports(text)
class TopFanCurveTest(unittest.TestCase):
def setUp(self):
self.board = Mock(spec=Nct6687)
self.mask = 0
self.duties = []
self.board.manual_mask.side_effect = lambda: self.mask
self.board.rpms.return_value = [0] * 16 # nothing has been seen turning yet
def manual(ch, duty):
self.mask |= 0x24
self.duties.append(duty)
self.board.set_manual.side_effect = manual
self.board.set_auto.side_effect = lambda ch: setattr(self, "mask", self.mask & ~0x24)
self.top = TopFanCurve((2, 5), board_factory=lambda: self.board)
def test_stopped_while_cool_kicks_on_start_and_follows_curve(self):
self.top.update(40, 44, 0)
self.assertEqual((self.top.duty, self.mask), (0, 0x24))
self.top.update(40, 49, 1)
self.assertEqual(self.top.duty, 0) # below the start point
self.top.update(40, 50, 2)
self.assertEqual(self.top.duty, 40) # spin-up kick
self.top.update(40, 55, 5)
self.assertEqual(self.top.duty, 45)
for now, temp, duty in ((6, 60, 60), (7, 65, 80), (8, 70, 100), (9, 90, 100)):
self.top.update(40, temp, now)
self.assertEqual(self.top.duty, duty)
def test_stop_has_hysteresis_and_hold_time(self):
self.top.update(40, 52, 0)
for now in range(3, 40):
self.top.update(40, 46, now) # between stop and start: keeps running at minimum
self.assertEqual(self.top.duty, 30)
self.top.update(40, 44, 40)
self.top.update(40, 44, 69)
self.assertEqual(self.top.duty, 30)
self.top.update(40, 44, 70)
self.assertEqual(self.top.duty, 0)
def test_falls_slowly_and_case_fan_boost_forces_full_speed(self):
self.top.update(40, 70, 0)
self.top.update(40, 60, 5)
self.assertEqual(self.top.duty, 100) # holds after a rise
self.top.update(40, 60, 11)
self.assertEqual(self.top.duty, 96) # 2% per second
self.top.update(85, 40, 12)
self.assertEqual((self.top.duty, self.top.boosted), (100, True))
self.top.update(66, 40, 13)
self.assertTrue(self.top.boosted)
self.top.update(65, 40, 14)
self.assertFalse(self.top.boosted)
def test_invalid_temperature_is_failsafe_full_speed(self):
with self.assertLogs("kurgan.cooling.control", level="WARNING"):
self.top.update(40, None, 0)
self.assertEqual(self.top.duty, 100)
self.assertIn("FAILSAFE", self.top.status)
def test_firmware_reset_is_corrected(self):
self.top.update(40, 40, 0)
self.top.update(40, 40, 1)
self.assertEqual(self.board.set_manual.call_count, 1) # unchanged duty is not rewritten
self.mask = 0x04 # one channel reverted to the BIOS after sleep
self.top.update(40, 40, 2)
self.assertEqual(self.board.set_manual.call_count, 2)
def test_unavailable_board_reports_and_retries_later(self):
factory = Mock(side_effect=OSError("run as administrator"))
top = TopFanCurve((2, 5), board_factory=factory)
with self.assertLogs("kurgan.cooling.control", level="WARNING"):
top.update(100, 60, 0)
self.assertIn("UNAVAILABLE", top.status)
top.update(100, 60, 10)
self.assertEqual(factory.call_count, 1)
factory.side_effect = None
factory.return_value = self.board
top.update(100, 60, 31)
self.board.set_manual.assert_called_once_with((2, 5), 100)
def test_a_failed_write_hands_the_fans_back_to_the_bios_curve(self):
self.top.update(40, 70, 0) # manual 100% written on channels 2,5
self.mask = 0 # the EC forgot (sleep, crash): a rewrite is due ...
self.board.set_manual.side_effect = OSError("bus busy") # ... and fails
with self.assertLogs("kurgan.cooling.control", level="WARNING"):
self.top.update(40, 70, 1)
self.board.set_auto.assert_called_with((2, 5))
self.assertIn("BIOS curve keeps control", self.top.status)
def test_a_failed_hand_back_says_what_the_fans_are_left_at(self):
self.top.update(40, 70, 0)
self.mask = 0
self.board.set_manual.side_effect = OSError("bus busy")
self.board.set_auto.side_effect = OSError("still busy") # even the hand-back fails
with self.assertLogs("kurgan.cooling.control", level="WARNING"):
self.top.update(40, 70, 1)
self.assertIn("held at the last written duty (100%)", self.top.status)
def test_a_top_fan_that_stops_turning_is_detected(self):
tachs = [0] * 16
self.board.rpms.return_value = tachs
for now in range(10): # spinning, but no tach has been seen turning: no evidence yet
self.top.update(40, 55, now)
self.assertNotIn("FAILSAFE", self.top.status)
tachs[2], tachs[5] = 1500, 1400
self.top.update(40, 55, 10)
self.top.update(40, 55, 11)
self.assertNotIn("FAILSAFE", self.top.status) # learned: both tachs turn
tachs[5] = 0
self.top.update(40, 55, 12)
self.top.update(40, 55, 13)
self.assertNotIn("FAILSAFE", self.top.status) # one glitchy reading is not a stall
with self.assertLogs("kurgan.cooling.control", level="WARNING"):
self.top.update(40, 55, 14)
self.assertIn("FAILSAFE", self.top.status)
self.assertIn("[5]", self.top.status)
self.assertEqual(self.top.duty, 100)
self.board.set_manual.assert_called_with((2, 5), 100)
tachs[5] = 1300 # the fan turns again: the failsafe lifts on the next poll
self.top.update(40, 55, 15)
self.assertNotIn("FAILSAFE", self.top.status)
self.assertEqual(self.top.snapshot()["rpms"], {"2": 1500, "5": 1300})
def test_a_tach_never_seen_turning_shows_no_reading(self):
tachs = [0] * 16
self.board.rpms.return_value = tachs
tachs[5] = 1040 # channel 2's tach isn't wired: it always reads 0
for now in range(5):
self.top.update(40, 55, now)
self.assertEqual(self.top.snapshot()["rpms"], {"2": None, "5": 1040})
def test_an_unexpected_board_error_hands_back_to_the_bios_instead_of_escaping(self):
self.top.update(40, 70, 0)
self.board.rpms.side_effect = AttributeError("no rpms") # a bug, not a device error
with self.assertLogs("kurgan.cooling.control", level="ERROR"):
self.top.update(40, 70, 1) # must not raise into the case fans' loop
self.board.set_auto.assert_called_with((2, 5))
self.assertIn("UNAVAILABLE", self.top.status)
def test_the_demo_board_supports_stall_detection(self):
from kurgan.demo import FakeBoard
top = TopFanCurve((2, 5), board_factory=FakeBoard)
for now in range(8):
top.update(40, 60, now)
self.assertNotIn("UNAVAILABLE", top.status)
self.assertNotIn("FAILSAFE", top.status)
self.assertEqual(top.snapshot()["rpms"], {"2": 14 * top.duty, "5": 14 * top.duty})
def test_gpu_worker_drives_top_fans_and_releases_them_on_exit(self):
commander = Mock(spec=CommanderPro)
commander.set_duty.return_value = {p: 900 for p in range(1, 7)}
control = CaseFanControl(commander, (4, 5, 6), None, self.top)
control.update(40, 0) # startup runs the case fans at 100%
self.assertTrue(self.top.boosted)
stop = threading.Event()
stop.set()
with patch("kurgan.cooling.control.GpuSensors"):
control.run(stop)
self.assertEqual(self.mask, 0)
self.board.close.assert_called()
def test_top_fans_follow_the_hotter_side(self):
commander = Mock(spec=CommanderPro)
commander.set_duty.return_value = {p: 900 for p in range(1, 7)}
control = CaseFanControl(commander, (4, 5, 6), (1, 2, 3), self.top)
for now in range(70): # startup boost ends, then the top fans stop after the hold time
control.update(40, now, 44)
self.assertEqual((control.gpu.duty, control.cpu.duty, self.top.boosted), (40, 40, False))
self.assertEqual(self.top.duty, 0)
control.update(40, 70, 60) # CPU hotter than GPU
self.assertEqual(self.top.duty, 60)
control.update(40, 71, None)
self.assertEqual(self.top.duty, 100)
def test_cpu_side_follows_cpu_temperature_and_can_boost_alone(self):
commander = Mock(spec=CommanderPro)
commander.set_duty.return_value = {p: 900 for p in range(1, 7)}
control = CaseFanControl(commander, (4, 5, 6), (1, 2, 3), self.top)
for now in range(40):
control.update(40, now, 50)
self.assertEqual((control.gpu.duty, control.cpu.duty), (40, 40))
self.assertFalse(self.top.boosted)
commander.set_duty.assert_any_call((1, 2, 3), 40)
control.update(40, 40, 78) # CPU hot, GPU cool
commander.set_duty.assert_any_call((1, 2, 3), 93)
self.assertEqual(control.gpu.duty, 40)
self.assertTrue(self.top.boosted)
control.update(40, 41, None)
self.assertIn("FAILSAFE", control.cpu.status)
self.assertNotIn("FAILSAFE", control.gpu.status)
with self.assertRaises(ValueError):
CaseFanControl(commander, (4, 5, 6), (1, 2, 4))
def test_cpu_temperature_is_averaged_and_gaps_are_not(self):
pkg = Mock()
pkg.temperature.side_effect = [50, 90, None, 60]
cpu = CpuTemperature(factory=lambda: pkg)
self.assertEqual(cpu.read(0), 50)
self.assertEqual(cpu.read(1), 70)
self.assertIsNone(cpu.read(2))
self.assertEqual(cpu.read(3), 60)
class Nct6687ControlTest(unittest.TestCase):
def test_override_uses_config_handshake_and_keeps_other_channels(self):
nct = Nct6687.__new__(Nct6687)
nct._bus = contextlib.nullcontext
nct.read = Mock(return_value=0x01)
nct.write = Mock()
with patch("kurgan.cooling.board_fans.time.sleep"):
nct.set_manual((2, 5), 100)
self.assertEqual(nct.write.call_args_list, [
call(0xA01, 0x80), call(0xA00, 0x25), call(0xA2A, 255), call(0xA2D, 255), call(0xA01, 0x40)])
nct.write.reset_mock()
nct.read.return_value = 0x25
nct.set_auto((2, 5))
self.assertEqual(nct.write.call_args_list, [call(0xA01, 0x80), call(0xA00, 0x01), call(0xA01, 0x40)])
with self.assertRaises(ValueError):
nct.set_manual((8,), 100)
class FanWorkerTest(unittest.TestCase):
def setUp(self):
self.commander = Mock(spec=CommanderPro)
self.commander.set_duty.return_value = {p: 900 for p in range(1, 7)}
self.control = CaseFanControl(self.commander, (4, 5, 6))
def settle(self, temp=50):
for now in range(36):
self.control.update(temp, now)
def test_rises_immediately_and_falls_slowly_after_hold(self):
self.control.update(40, 0)
self.commander.set_duty.assert_called_with((4, 5, 6), 100)
self.control.update(40, 9)
self.commander.set_duty.assert_called_with((4, 5, 6), 100)
for now in range(10, 45):
self.control.update(50, now)
self.commander.set_duty.assert_called_with((4, 5, 6), 50)
self.control.update(68, 45)
self.commander.set_duty.assert_called_with((4, 5, 6), 93)
for now in range(46, 55):
self.control.update(40, now)
self.commander.set_duty.assert_called_with((4, 5, 6), 93)
self.control.update(40, 55)
self.commander.set_duty.assert_called_with((4, 5, 6), 91)
def test_missing_sensor_and_delayed_worker_use_full_speed(self):
self.settle()
self.control.update(None, 36)
self.commander.set_duty.assert_called_with((4, 5, 6), 100)
self.assertIn("FAILSAFE", self.control.status)
for now in range(37, 73):
self.control.update(50, now)
self.commander.set_duty.assert_called_with((4, 5, 6), 50)
self.control.update(40, 85)
self.commander.set_duty.assert_called_with((4, 5, 6), 100)
def test_stalled_selected_fan_forces_full_speed_but_other_side_does_not(self):
self.commander.set_duty.return_value = {1: 0, 4: 900, 5: 900, 6: 900}
self.settle()
self.assertNotIn("FAILSAFE", self.control.status)
# One glitchy reading is not a stall; STALL_READINGS in a row are.
self.commander.set_duty.return_value = {4: 900, 5: 0, 6: 900}
self.control.update(50, 36)
self.control.update(50, 37)
self.assertNotIn("FAILSAFE", self.control.status)
self.commander.set_duty.reset_mock()
self.control.update(50, 38)
self.commander.set_duty.assert_called_with((4, 5, 6), 100)
self.assertIn("FAILSAFE", self.control.status)
self.assertIn("[5]", self.control.status)
def test_exit_leaves_selected_ports_at_full_speed_even_without_lcd(self):
stop = threading.Event()
stop.set()
with patch("kurgan.cooling.control.GpuSensors"):
self.control.run(stop)
self.commander.set_duty.assert_called_once_with((4, 5, 6), 100)
self.commander.close.assert_called_once()
def test_worker_survives_unexpected_errors_and_keeps_failing_safe(self):
stop = threading.Event()
gpu = Mock()
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_with((4, 5, 6), 100)
def test_unexpected_errors_fail_the_top_fans_safe_too(self):
top = Mock(spec=TopFanCurve)
self.control.top = top
stop = threading.Event()
gpu = Mock()
def read():
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(top.update.call_args.args[:2], (100, None))
top.release.assert_called_once()
class CommanderControlTest(unittest.TestCase):
def setUp(self):
self.commander = CommanderPro()
self.commander.ports = list(range(6))
self.commander.ch = Mock()
self.commander._corsair_software_running = Mock(return_value=False)
self.commander._open = Mock()
def reply(self, op, *args):
if op == 0x20:
return bytes((0, 0, 2, 2, 2, 2, 2, 2))
if op == 0x21:
return bytes((0, 0, 3, 132)) # 900 RPM
return bytes(4)
def test_only_confirmed_side_receives_duty_commands(self):
self.commander._cmd = Mock(side_effect=self.reply)
rpms = self.commander.set_duty((4, 5, 6), 81)
writes = [c.args for c in self.commander._cmd.call_args_list if c.args[0] == 0x23]
self.assertEqual(writes, [(0x23, 3, 81), (0x23, 4, 81), (0x23, 5, 81)])
self.assertEqual(rpms, {p: 900 for p in range(1, 7)})
self.commander.controlled = True
self.commander._cmd.reset_mock()
self.assertEqual(self.commander.read(), [900] * 6)
self.commander._cmd.assert_not_called()
def test_disconnected_or_dc_port_rejected_before_any_write(self):
for modes in (bytes((0, 0, 2, 2, 0, 2, 2, 2)),
bytes((0, 0, 2, 2, 1, 2, 2, 2)), bytes(4)):
self.commander._cmd = Mock(return_value=modes)
with self.assertRaises(OSError):
self.commander.set_duty((1, 2, 3), 80)
self.commander._cmd.assert_called_once_with(0x20)
def test_competing_software_prevents_all_usb_writes(self):
self.commander._corsair_software_running.return_value = True
self.commander._cmd = Mock()
with self.assertRaisesRegex(OSError, "busy"):
self.commander.set_duty((1, 2, 3), 100)
self.commander._cmd.assert_not_called()
self.assertIsNone(self.commander.ch)
def test_openrgb_counts_as_released_only_when_detector_disabled_everywhere(self):
commander = CommanderPro()
disabled = '{"Detectors":{"detectors":{"Corsair Commander Pro":false}}}'
configs = {"user": disabled, "service": disabled}
def fake_open(path, *args, **kwargs):
return mock_open(read_data=configs["service" if "service_config" in path else "user"])()
with patch("kurgan.telemetry.sensors._process_names", return_value=["openrgb.exe"]), \
patch("kurgan.telemetry.sensors.os.path.exists", return_value=True), \
patch("builtins.open", side_effect=fake_open):
self.assertFalse(commander._corsair_software_running())
configs["service"] = disabled.replace("false", "true")
with self.assertLogs("kurgan.telemetry.sensors", level="WARNING"):
self.assertTrue(commander._corsair_software_running())
with patch("kurgan.telemetry.sensors._process_names", return_value=["openrgb.exe"]), \
patch("kurgan.telemetry.sensors.os.path.exists", return_value=True), \
patch("builtins.open", side_effect=OSError("missing config")):
with self.assertLogs("kurgan.telemetry.sensors", level="WARNING"):
self.assertTrue(commander._corsair_software_running())
with patch("kurgan.telemetry.sensors._process_names", return_value=["fancontrol.exe"]):
self.assertTrue(commander._corsair_software_running())
self.assertFalse(corsair_software_running("Corsair Lighting Node Core", fan_tools=False))
if __name__ == "__main__":
unittest.main()