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

+36 -2
View File
@@ -88,11 +88,42 @@ def alert_states(fans, ai, telemetry) -> dict[str, str]:
return states
ALERT_REPEAT_SECONDS = 600.0 # a problem that clears and comes back balloons again only after this
def new_alerts(known: dict[str, str], states: dict[str, str]) -> list[tuple[str, str]]:
"""(key, message) for alerts that are new since the last look; recovered ones stay quiet."""
return [(key, states[key]) for key in sorted(states.keys() - known.keys())]
def due_alerts(new: list[tuple[str, str]], alerted: dict[str, float], now: float) -> list[tuple[str, str]]:
"""The new alerts not already ballooned in the last ALERT_REPEAT_SECONDS; records them in
`alerted` (key -> when). A flapping problem balloons once, not every time it comes back."""
due = [(key, message) for key, message in new if now - alerted.get(key, -1e18) >= ALERT_REPEAT_SECONDS]
alerted.update((key, now) for key, _ in due)
return due
def balloon(messages: list[str]) -> tuple[str, str]:
"""One balloon (title, text) for all of them: Windows shows one balloon at a time, so a
second notify() would only replace the first. The text holds up to 255 characters."""
if len(messages) == 1:
return APP_NAME, messages[0]
lines: list[str] = []
for i, message in enumerate(messages):
rest = len(messages) - i - 1
tail = f"\n...and {rest} more" if rest else ""
if len("\n".join(lines + [message])) + len(tail) > 255:
if not lines: # the first one alone is too long: shorten it
lines.append(message[:255 - len(tail) - 3] + "...")
lines.append(tail.lstrip("\n"))
else: # the previous round made sure this note fits
lines.append(f"...and {rest + 1} more")
break
lines.append(message)
return f"{APP_NAME}: {len(messages)} problems", "\n".join(filter(None, lines))
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
from kurgan.cooling.control import parse_ports
@@ -283,6 +314,7 @@ class Kurgan:
"""Balloon tips for things starting to go wrong. The first look is the baseline: what
is already wrong at startup sits in the tray menu and the UI, it doesn't need a balloon."""
known: dict[str, str] | None = None
alerted: dict[str, float] = {} # key -> when it last ballooned
while not stop.wait(ALERT_SECONDS):
if self.tray is None:
continue # no icon, no balloons -- and no baseline burnt before the icon exists
@@ -294,9 +326,11 @@ class Kurgan:
if known is None:
known = states
continue
for _, message in new_alerts(known, states):
due = due_alerts(new_alerts(known, states), alerted, time.monotonic())
for _, message in due:
log.warning("Alert: %s", message)
self.tray.notify(APP_NAME, message, warning=True)
if due:
self.tray.notify(*balloon([message for _, message in due]), warning=True)
known = states
def _start_tray(self) -> None:
+19 -4
View File
@@ -97,9 +97,15 @@ class TopFanCurve:
def snapshot(self) -> dict:
return {"channels": list(self.channels), "temp": self.temp, "duty": self.duty, "running": self.running,
"boosted": self.boosted, "status": self.status,
"rpms": {str(c): self.rpms.get(c) for c in self.channels},
"rpms": {str(c): self._shown_rpm(c) for c in self.channels},
"failsafe": self.status.startswith(("FAILSAFE", "UNAVAILABLE"))}
def _shown_rpm(self, channel: int) -> int | None:
"""The channel's RPM, or None while its tach has never been seen turning: on this board
SYS_FAN1's tach isn't wired, and a constant 0 would read as a dead fan."""
rpm = self.rpms.get(channel)
return rpm if rpm or channel in self._spun else None
def close(self) -> None:
if self.board is not None:
self.board.close()
@@ -179,9 +185,13 @@ class TopFanCurve:
if stalled:
text = f"FAILSAFE 100%: no RPM on channels {stalled}"
self._status(text.format(duty=self.duty), warning=text.startswith("FAILSAFE"))
except (OSError, ValueError) as e:
# Best effort: hand the channels back to the BIOS curve, so a manual duty left
# behind (0% included) doesn't persist until the next successful write or a reboot.
except Exception as e:
# Any failure, a bug included: the top fans must not take the case fans' control
# loop down with them. Best effort: hand the channels back to the BIOS curve, so a
# manual duty left behind (0% included) doesn't persist until the next successful
# write or a reboot.
if not isinstance(e, (OSError, ValueError)) and not self.status.startswith("UNAVAILABLE"):
log.error("Top fan control failed unexpectedly", exc_info=True)
held, handed_back = self._written, False
try:
if self.board is not None:
@@ -404,6 +414,11 @@ class CaseFanControl:
log.exception("Case fan control error; failing safe and retrying")
self._error(f"CONTROL ERROR: {e}")
self.failsafe()
if self.top is not None:
try: # as the device-error path does; update() never raises for the board
self.top.update(100, None, time.monotonic())
except Exception:
log.debug("Top fans: failsafe update failed", exc_info=True)
gpu = None
retry_in = self.ERROR_RETRY_SECONDS
stop.wait(retry_in)
+8
View File
@@ -73,14 +73,22 @@ class FakeSystem:
class FakeBoard:
BIOS_RPM = 700 # what a channel left to the BIOS curve turns at
def __init__(self):
self.mask = 0
self.duties: dict[int, int] = {}
def manual_mask(self) -> int:
return self.mask
def rpms(self) -> list[int]:
"""All 16 tachs, like Nct6687.rpms(): 14 RPM per % of duty, a fixed speed under the BIOS."""
return [14 * self.duties.get(c, 0) if self.mask >> c & 1 else self.BIOS_RPM for c in range(16)]
def set_manual(self, channels, duty: int) -> None:
self.mask |= sum(1 << c for c in channels)
self.duties.update((c, duty) for c in channels)
def set_auto(self, channels) -> None:
self.mask &= ~sum(1 << c for c in channels)
+6 -7
View File
@@ -35,6 +35,11 @@ _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
# OVERLAPPED structs and buffers of IRPs the driver never finished cancelling, kept for the life
# of the process. Nothing can tell us when the driver is done with them, so freeing them (even
# with their channel) could let a late completion write into reused memory. A few hundred
# bytes each, and only after a wedged device.
_ABANDONED: list = []
class _GUID(ctypes.Structure):
@@ -198,9 +203,6 @@ class HidChannel:
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
@@ -210,9 +212,6 @@ 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.
@@ -225,7 +224,7 @@ class HidChannel:
if _k32.WaitForSingleObject(event, _ABANDON_GRACE_MS) == _WAIT_OBJECT_0:
return
self._broken = True
self._abandoned.append((ov, buf))
_ABANDONED.append((ov, buf))
def send(self, payload: bytes, timeout_ms: int = 1000) -> None:
if self._broken:
+118 -35
View File
@@ -4,11 +4,18 @@ The live history in the service keeps ten minutes; this keeps about a year, so t
draw weeks and months. Files are append-only JSONL in the data dir, one per month
(records-YYYY-MM.jsonl); each line looks like:
{"hour":1764892800,"n":3600,"cpu_temp":[41.0,55.3,78.0],...}
{"hour":1764892800,"n":3600,"cpu_temp":[41.0,55.3,78.0,3600],...}
Recording is best effort: a failing disk logs once and stops the recorder; nothing else
notices. Restarting within an hour writes a second line for that hour; the reader merges
lines per hour, so that is harmless.
that is min, average and max, and how many samples carried the metric (a sensor can drop out
for part of an hour; its average is over the samples that had it). Lines written before the
count existed have three numbers and count as `n` samples.
The hour in progress is checkpointed to records-current.json every minute and on exit, and
resumed at the next start: a restart, even a hard stop such as `schtasks /End`, loses at most
a minute. Should two lines ever exist for one hour, the reader merges them.
Recording is best effort: a failing write is logged at most once an hour and retried; finished
hours wait in memory (up to two days of them) until the disk takes them again.
"""
from __future__ import annotations
@@ -23,7 +30,11 @@ log = logging.getLogger(__name__)
METRICS = ("cpu_temp", "gpu_temp", "cpu_load", "gpu_load", "cpu_w", "gpu_w", "other_w", "total_w", "vram_used")
RETENTION_DAYS = 400 # a little over a year of monthly files
CHECKPOINT_SECONDS = 60
MAX_PENDING = 48 # finished hours kept in memory while writes fail
REPORT_SECONDS = 3600 # a failing disk is logged at most this often
_FILE = "records-%s.jsonl"
_CURRENT = "records-current.json"
def _values(sample) -> dict[str, float | None]:
@@ -42,49 +53,113 @@ class Recorder:
self.retention_days = retention_days
self._hour = 0
self._n = 0
self._stats: dict[str, list[float]] = {} # metric -> [min, max, sum]
self._stopped = False
self._stats: dict[str, list[float]] = {} # metric -> [min, max, sum, count]
self._pending: list[dict] = [] # finished hours not written yet
self._checkpoint_at = 0.0
self._reported: float | None = None # when a failure was last logged
self._prune()
self._resume()
def on_sample(self, sample) -> None:
if self._stopped:
return
try:
hour = int(sample.t // 3600) * 3600
if hour != self._hour:
self._flush()
self._finish_hour()
self._hour, self._n, self._stats = hour, 0, {}
self._n += 1
for name, value in _values(sample).items():
if value is None:
continue
s = self._stats.setdefault(name, [value, value, 0.0])
s[0], s[1], s[2] = min(s[0], value), max(s[1], value), s[2] + value
s = self._stats.get(name)
if s is None:
self._stats[name] = [value, value, value, 1]
else:
s[0], s[1], s[2], s[3] = min(s[0], value), max(s[1], value), s[2] + value, s[3] + 1
if abs(sample.t - self._checkpoint_at) >= CHECKPOINT_SECONDS:
self._checkpoint_at = sample.t
self._save_checkpoint()
except Exception:
self._stopped = True
log.warning("Telemetry recording stopped for this run", exc_info=True)
self._report("Telemetry recording failed")
def close(self) -> None:
"""Write the hour still in progress; a short line is fine, the reader merges per hour."""
if self._stopped:
return
"""Checkpoint the hour in progress (the next start carries on with it) and write anything pending."""
try:
self._flush()
self._save_checkpoint()
self._write_pending()
except Exception:
self._stopped = True
log.warning("Telemetry recording stopped while closing", exc_info=True)
self._report("Telemetry recording failed while closing")
def _flush(self) -> None:
if not self._hour or not self._n:
return
# ------------------------------------------------------------------ the hour in progress
def _row(self) -> dict:
row = {"hour": self._hour, "n": self._n}
for name in METRICS:
s = self._stats.get(name)
row[name] = [round(s[0], 1), round(s[2] / self._n, 1), round(s[1], 1)] if s else None
month = time.strftime("%Y-%m", time.gmtime(self._hour))
os.makedirs(self.directory, exist_ok=True)
with open(os.path.join(self.directory, _FILE % month), "a", encoding="utf-8") as f:
f.write(json.dumps(row, separators=(",", ":")) + "\n")
row[name] = [round(s[0], 1), round(s[2] / s[3], 1), round(s[1], 1), s[3]] if s else None
return row
def _finish_hour(self) -> None:
if self._hour and self._n:
self._pending.append(self._row())
del self._pending[:-MAX_PENDING]
self._write_pending()
def _save_checkpoint(self) -> None:
if not self._hour or not self._n:
return
try:
os.makedirs(self.directory, exist_ok=True)
path = os.path.join(self.directory, _CURRENT)
with open(path + ".tmp", "w", encoding="utf-8") as f:
json.dump({"hour": self._hour, "n": self._n, "stats": self._stats}, f, separators=(",", ":"))
os.replace(path + ".tmp", path)
except OSError:
self._report("Couldn't checkpoint the hour's telemetry")
def _resume(self) -> None:
"""Carry on with the checkpointed hour if it is this hour; otherwise it is finished: write it."""
path = os.path.join(self.directory, _CURRENT)
try:
with open(path, encoding="utf-8") as f:
saved = json.load(f)
hour, n, stats = int(saved["hour"]), int(saved["n"]), saved["stats"]
if not all(isinstance(v, list) and len(v) == 4 for v in stats.values()):
raise ValueError("bad stats")
except (FileNotFoundError, NotADirectoryError):
return # nothing to resume (a broken data dir shows up at the first write)
except (OSError, ValueError, KeyError, TypeError, AttributeError):
log.warning("Ignoring an unreadable telemetry checkpoint", exc_info=True)
return
self._hour, self._n, self._stats = hour, n, {k: v for k, v in stats.items() if k in METRICS}
if hour != int(time.time() // 3600) * 3600:
self._finish_hour()
self._hour, self._n, self._stats = 0, 0, {}
if not self._pending: # written: the checkpoint must not be written again next start
try:
os.remove(path)
except OSError:
pass
# ------------------------------------------------------------------ the month files
def _write_pending(self) -> None:
while self._pending:
row = self._pending[0]
month = time.strftime("%Y-%m", time.gmtime(row["hour"]))
try:
os.makedirs(self.directory, exist_ok=True)
with open(os.path.join(self.directory, _FILE % month), "a", encoding="utf-8") as f:
f.write(json.dumps(row, separators=(",", ":")) + "\n")
except OSError:
self._report(f"Couldn't write telemetry records ({len(self._pending)} hours waiting)")
return
self._pending.pop(0)
def _report(self, what: str) -> None:
now = time.monotonic()
if self._reported is None or now - self._reported >= REPORT_SECONDS:
self._reported = now
log.warning("%s; will keep trying", what, exc_info=True)
def _prune(self) -> None:
"""Delete month files whose whole month is older than the retention window."""
@@ -106,7 +181,10 @@ class Recorder:
def load(directory: str, days: int) -> dict:
"""Hourly rollups for the last `days` days, oldest first: {"metrics", "rows", "days"}."""
"""Hourly rollups for the last `days` days, oldest first: {"metrics", "rows", "days"}.
Each metric of a row is [min, avg, max] (or null); lines for the same hour are merged,
their averages weighted by how many samples carried the metric."""
since = time.time() - days * 86400
rows: dict[int, dict] = {}
try:
@@ -135,18 +213,23 @@ def load(directory: str, days: int) -> dict:
continue
merged = rows.setdefault(int(hour), {"hour": int(hour), "n": 0})
n = row.get("n") if isinstance(row.get("n"), int) else 0
before = merged["n"]
merged["n"] = before + n
merged["n"] += n
for metric in METRICS:
stats = row.get(metric)
if not isinstance(stats, list) or len(stats) != 3:
if not isinstance(stats, list) or len(stats) not in (3, 4):
continue
count = stats[3] if len(stats) == 4 else n # older lines: every sample counted
cur = merged.get(metric)
if cur is None:
merged[metric] = list(stats)
merged[metric] = [stats[0], stats[1], stats[2], count]
else:
cur[0] = min(cur[0], stats[0])
cur[2] = max(cur[2], stats[2])
if before + n:
cur[1] = (cur[1] * before + stats[1] * n) / (before + n)
return {"metrics": list(METRICS), "rows": [rows[h] for h in sorted(rows)], "days": days}
if cur[3] + count:
cur[1] = (cur[1] * cur[3] + stats[1] * count) / (cur[3] + count)
cur[3] += count
for row in rows.values():
for metric in METRICS:
if row.get(metric) is not None:
row[metric] = row[metric][:3]
return {"metrics": list(METRICS), "rows": [rows[h] for h in sorted(rows)], "days": days}
+22 -4
View File
@@ -19,6 +19,7 @@ from kurgan.telemetry.readings import PowerReadings, Readings
log = logging.getLogger(__name__)
HISTORY_SECONDS = 600
EMPTY_READS = 3 # consecutive empty readings before a source counts as failing
SERIES = ("t", "cpu_temp", "gpu_temp", "cpu_load", "gpu_load", "cpu_w", "gpu_w", "other_w", "total_w", "vram_used")
@@ -51,20 +52,27 @@ class Telemetry:
self._listeners: list[Callable[[Sample], None]] = []
self._seq = 0
self._failures: dict[str, tuple[float, str]] = {} # source -> (monotonic, message) of its latest failed read
self._empty: dict[str, int] = {} # source -> consecutive empty readings
def subscribe(self, listener: Callable[[Sample], None]) -> None:
self._listeners.append(listener)
def read(self) -> Sample:
"""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())
# The sensor classes don't raise when their device is lost (they back off and return
# empty readings), so a reading without a temperature counts as failing too.
c = self._source("CPU sensors", self.cpu.read, Readings(),
missing=lambda r: None if r.temp is not None else "no CPU temperature (MSR reader unavailable)")
g = self._source("GPU sensors", self.gpu.read, Readings(),
missing=lambda r: None if r.temp is not None else "no GPU readings (driver unavailable)")
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, vram)
def _source(self, name: str, read: Callable, fallback, *args):
def _source(self, name: str, read: Callable, fallback, *args, missing: Callable | None = None):
"""read(*args), or fallback if it raises. Failures are kept for health(); so is a result
that missing(result) describes as empty (a message), once EMPTY_READS in a row were."""
try:
result = read(*args)
except Exception as e:
@@ -75,7 +83,17 @@ class Telemetry:
log.warning("%s read failed; continuing without it: %s", name, e, exc_info=True)
self._failures[name] = (now, f"{type(e).__name__}: {e}")
return fallback
self._failures.pop(name, None) # reading again: healthy
problem = missing(result) if missing is not None else None
if problem is None:
self._empty.pop(name, None)
if self._failures.pop(name, None) is not None: # reading again: healthy
log.info("%s reading again", name)
return result
self._empty[name] = self._empty.get(name, 0) + 1
if self._empty[name] >= EMPTY_READS: # one empty read at startup or a glitch proves nothing
if name not in self._failures:
log.warning("%s: %s", name, problem)
self._failures[name] = (time.monotonic(), problem)
return result
def health(self) -> dict[str, dict]:
+8 -2
View File
@@ -564,7 +564,8 @@ function fanCard(g, kind) {
el("div", { class: "fan-head", style: "margin-top:4px" }, el("span", { class: "fan-duty", "data-f": "duty" }),
el("span", { class: "muted", "data-f": "temp" })),
el("div", { class: `meter ${kind}`, role: "meter", "aria-label": "PWM duty", "data-f": "meter" }, el("span")),
el("div", { class: "fan-ports", "data-f": "ports" }, ports.map(([p]) => el("span", {}, `Port ${p} `, el("b", { "data-port": p }), " rpm"))),
el("div", { class: "fan-ports", "data-f": "ports" }, ports.map(([p]) => el("span", {},
`${kind === "top" ? "Channel" : "Port"} ${p} `, el("b", { "data-port": p }), el("span", { "data-unit": p }, " rpm")))),
el("div", { "data-f": "note" }));
}
@@ -577,7 +578,12 @@ function updateFanCard(card, g, kind) {
meter.firstChild.style.width = `${g.duty}%`;
meter.setAttribute("aria-valuenow", g.duty);
meter.className = `meter ${g.failsafe ? "critical" : kind}`;
for (const [p, rpm] of Object.entries(g.rpms ?? {})) setText(card.querySelector(`[data-port="${p}"]`), fmt.n0(rpm));
for (const [p, rpm] of Object.entries(g.rpms ?? {})) {
// null: a top-fan channel whose tach has never reported a speed (SYS_FAN1's isn't wired)
const noTach = kind === "top" && rpm == null;
setText(card.querySelector(`[data-port="${p}"]`), noTach ? "no tach reading" : fmt.n0(rpm));
card.querySelector(`[data-unit="${p}"]`).hidden = noTach;
}
const n = q("note");
const text = g.failsafe ? g.status : kind === "top" && g.boosted ? "Held at 100% while a case-fan group runs at 85% or more." : "";
if (n.dataset.text !== text) {