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>
This commit is contained in:
paulandClaude Opus 5.5 committed 2026-12-05 18:31:11 +13:00
1 parent 8cc1e9223f
commit b983528183
12 files changed
+394 -73

No files matched your search

+34 -1
View File
@@ -2,7 +2,7 @@ import unittest
from unittest.mock import Mock, patch
from kurgan import tray
from kurgan.app import alert_states, new_alerts
from kurgan.app import ALERT_REPEAT_SECONDS, alert_states, balloon, due_alerts, new_alerts
def fake_fans(gpu_status="GPU 50 C, 40% PWM", top_status="55 C, 45%"):
@@ -61,6 +61,39 @@ class NewAlertsTest(unittest.TestCase):
self.assertEqual(new_alerts({}, states), [("ai/strata", "exited"), ("fans/GPU", "still failing")])
class DueAlertsTest(unittest.TestCase):
def test_a_flapping_problem_balloons_once_per_cooldown(self):
alerted = {}
flap = [("telemetry/GPU sensors", "GPU sensors read failed")]
self.assertEqual(due_alerts(flap, alerted, 0), flap)
self.assertEqual(due_alerts(flap, alerted, 15), []) # cleared and came back: quiet
self.assertEqual(due_alerts(flap, alerted, ALERT_REPEAT_SECONDS - 1), [])
self.assertEqual(due_alerts(flap, alerted, ALERT_REPEAT_SECONDS), flap)
other = [("fans/GPU", "GPU case fans: FAILSAFE")]
self.assertEqual(due_alerts(other, alerted, 20), other) # each problem has its own cooldown
class BalloonTest(unittest.TestCase):
def test_one_alert_is_its_own_balloon(self):
self.assertEqual(balloon(["Top fans: FAILSAFE 100%"]), ("The Kurgan", "Top fans: FAILSAFE 100%"))
def test_alerts_at_the_same_moment_share_one_balloon(self):
title, text = balloon(["GPU case fans: CONTROL ERROR", "CPU case fans: CONTROL ERROR", "Top fans: FAILSAFE"])
self.assertEqual(title, "The Kurgan: 3 problems")
self.assertEqual(text, "GPU case fans: CONTROL ERROR\nCPU case fans: CONTROL ERROR\nTop fans: FAILSAFE")
def test_too_many_for_the_balloon_end_with_a_count(self):
messages = [f"problem {i}: " + "x" * 60 for i in range(6)]
title, text = balloon(messages)
self.assertLessEqual(len(text), 255)
lines = text.split("\n")
self.assertEqual(lines[:3], messages[:3])
self.assertEqual(lines[-1], f"...and {6 - (len(lines) - 1)} more")
_, text = balloon(["y" * 300, "short"]) # even the first alone doesn't fit
self.assertLessEqual(len(text), 255)
self.assertTrue(text.endswith("...\n...and 1 more"))
class TrayNotifyTest(unittest.TestCase):
def make_icon(self):
return tray.TrayIcon("The Kurgan", "unused.ico", on_exit=lambda: None)
+44
View File
@@ -154,6 +154,32 @@ class TopFanCurveTest(unittest.TestCase):
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)}
@@ -307,6 +333,24 @@ class FanWorkerTest(unittest.TestCase):
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):
+74 -13
View File
@@ -3,6 +3,7 @@ import os
import tempfile
import time
import unittest
from unittest.mock import patch
from kurgan.telemetry.readings import PowerReadings, Readings
from kurgan.telemetry.record import Recorder, load
@@ -19,43 +20,92 @@ def sample(t, cpu_temp=50.0, gpu_temp=None, vram=None, cpu_w=30.0, gpu_w=80.0, o
def written(directory):
rows = []
for name in sorted(os.listdir(directory)):
if not name.endswith(".jsonl"):
continue # records-current.json is the checkpoint of the hour in progress
with open(os.path.join(directory, name), encoding="utf-8") as f:
rows += [json.loads(line) for line in f if line.strip()]
return rows
def at(t):
"""Pretend the wall clock reads t (the recorder decides at startup whether its checkpoint is this hour)."""
return patch("kurgan.telemetry.record.time.time", return_value=t)
class RecorderTest(unittest.TestCase):
def test_an_hour_is_written_when_it_ends(self):
with tempfile.TemporaryDirectory() as d:
rec = Recorder(d)
rec.on_sample(sample(HOUR + 1))
rec.on_sample(sample(HOUR + 3599, cpu_temp=70.0))
rec.on_sample(sample(HOUR + 3600, cpu_temp=40.0)) # the new hour flushes the old one
rec.close() # ... and closing writes the hour still in progress
rec.on_sample(sample(HOUR + 3600, cpu_temp=40.0)) # the new hour writes the old one
rec.close() # ... and closing checkpoints the hour still in progress
month = time.strftime("%Y-%m", time.gmtime(HOUR))
self.assertEqual(os.listdir(d), [f"records-{month}.jsonl"])
self.assertEqual(sorted(os.listdir(d)), [f"records-{month}.jsonl", "records-current.json"])
rows = written(d)
self.assertEqual(len(rows), 2)
first, second = rows
self.assertEqual(len(rows), 1)
first = rows[0]
self.assertEqual((first["hour"], first["n"]), (HOUR, 2))
self.assertEqual(first["cpu_temp"], [50.0, 60.0, 70.0]) # min, avg, max
self.assertEqual(first["total_w"], [130.0, 130.0, 130.0]) # 30 + 80 + 20 W every sample
self.assertEqual(first["cpu_temp"], [50.0, 60.0, 70.0, 2]) # min, avg, max, samples
self.assertEqual(first["total_w"], [130.0, 130.0, 130.0, 2]) # 30 + 80 + 20 W every sample
self.assertIsNone(first["gpu_temp"]) # a metric no sample carried stays null ...
self.assertIsNone(first["vram_used"])
self.assertEqual((second["hour"], second["n"], second["cpu_temp"]), (HOUR + 3600, 1, [40.0, 40.0, 40.0]))
def test_a_failing_disk_stops_recording_quietly(self):
def test_an_average_counts_only_the_samples_that_had_the_metric(self):
with tempfile.TemporaryDirectory() as d:
rec = Recorder(d)
rec.on_sample(sample(HOUR + 1, gpu_w=80.0))
rec.on_sample(sample(HOUR + 2, gpu_w=None)) # the GPU's power reading dropped out
rec.on_sample(sample(HOUR + 3, gpu_w=100.0))
rec.on_sample(sample(HOUR + 3600))
row = written(d)[0]
self.assertEqual(row["n"], 3)
self.assertEqual(row["gpu_w"], [80.0, 90.0, 100.0, 2]) # not 60: the gap isn't a zero
def test_a_hard_stop_loses_at_most_a_minute(self):
with tempfile.TemporaryDirectory() as d:
with at(HOUR + 1):
first = Recorder(d)
first.on_sample(sample(HOUR + 1, cpu_temp=40.0))
first.on_sample(sample(HOUR + 61, cpu_temp=60.0)) # checkpointed; then killed, no close()
with at(HOUR + 300):
second = Recorder(d) # the same hour: carries on with it
second.on_sample(sample(HOUR + 301, cpu_temp=80.0))
second.on_sample(sample(HOUR + 3600))
rows = written(d)
self.assertEqual(len(rows), 1)
self.assertEqual((rows[0]["n"], rows[0]["cpu_temp"]), (3, [40.0, 60.0, 80.0, 3]))
def test_a_checkpoint_from_an_earlier_hour_is_written_at_start(self):
with tempfile.TemporaryDirectory() as d:
with at(HOUR + 1):
first = Recorder(d)
first.on_sample(sample(HOUR + 1))
first.close()
self.assertEqual(written(d), [])
with at(HOUR + 7200):
Recorder(d)
rows = written(d)
self.assertNotIn("records-current.json", os.listdir(d))
with at(HOUR + 7300):
Recorder(d) # nothing left to write a second time
self.assertEqual(written(d), rows)
self.assertEqual([(r["hour"], r["n"]) for r in rows], [(HOUR, 1)])
def test_a_failing_disk_is_logged_once_and_catches_up_when_it_recovers(self):
with tempfile.TemporaryDirectory() as d:
blocked = os.path.join(d, "blocked")
open(blocked, "w").close()
rec = Recorder(blocked) # the "directory" is a file: every write fails
with self.assertLogs("kurgan.telemetry.record", level="WARNING") as logs:
rec.on_sample(sample(HOUR))
rec.on_sample(sample(HOUR + 3600)) # the hour boundary is where the write fails
rec.on_sample(sample(HOUR + 7200)) # already stopped: nothing happens, nothing raised
rec.close()
self.assertTrue(rec._stopped)
rec.on_sample(sample(HOUR + 3600)) # the hour can't be written: it waits
rec.on_sample(sample(HOUR + 7200))
self.assertEqual(len(logs.output), 1)
os.remove(blocked)
os.makedirs(blocked) # the disk is back
rec.on_sample(sample(HOUR + 10800))
self.assertEqual([r["hour"] for r in written(blocked)], [HOUR, HOUR + 3600, HOUR + 7200])
def test_pruning_removes_months_older_than_the_retention(self):
with tempfile.TemporaryDirectory() as d:
@@ -87,6 +137,17 @@ class LoadTest(unittest.TestCase):
self.assertEqual(row["cpu_temp"], [30.0, 42.5, 80.0]) # min, sample-weighted avg, max
self.assertIsNone(row.get("total_w"))
def test_load_weights_averages_by_the_samples_that_had_the_metric(self):
h = int(time.time() // 3600) * 3600
with tempfile.TemporaryDirectory() as d:
path = os.path.join(d, f"records-{time.strftime('%Y-%m', time.gmtime(h))}.jsonl")
with open(path, "w", encoding="utf-8") as f:
f.write(json.dumps({"hour": h, "n": 3000, "gpu_w": [50.0, 100.0, 150.0, 3000]}) + "\n")
f.write(json.dumps({"hour": h, "n": 600, "gpu_w": [10.0, 40.0, 70.0, 100]}) + "\n") # the GPU dropped out
row = load(d, days=1)["rows"][0]
self.assertEqual(row["n"], 3600)
self.assertEqual([round(v, 2) for v in row["gpu_w"]], [10.0, 98.06, 150.0]) # (100*3000 + 40*100) / 3100
def test_load_without_a_directory_is_empty(self):
data = load(os.path.join(tempfile.gettempdir(), "kurgan-no-such-records-dir"), 7)
self.assertEqual(data["rows"], [])
+16
View File
@@ -66,6 +66,22 @@ class TelemetryHealthTest(unittest.TestCase):
self.telemetry.read()
self.assertEqual(self.telemetry.health(), {})
def test_a_source_that_goes_quiet_without_raising_is_reported(self):
# GpuSensors returns empty readings when the driver is lost (and while it backs off)
self.gpu.read = lambda *args: Readings()
self.telemetry.read()
self.telemetry.read()
self.assertEqual(self.telemetry.health(), {}) # a gap or two proves nothing
with self.assertLogs("kurgan.telemetry.service", level="WARNING"):
self.telemetry.read()
health = self.telemetry.health()
self.assertEqual(list(health), ["GPU sensors"])
self.assertIn("driver unavailable", health["GPU sensors"]["error"])
del self.gpu.read # the driver is back
with self.assertLogs("kurgan.telemetry.service", level="INFO"):
self.telemetry.read()
self.assertEqual(self.telemetry.health(), {})
def test_the_snapshot_carries_health(self):
self.system.fail = True
self.gpu.memory_fails = True