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

+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]: