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:
1 parent
8cc1e9223f
commit
b983528183
12 files changed
+390
-69
No files matched your search
@@ -54,10 +54,12 @@ Open it from the tray icon (left-click, or **Open The Kurgan** in its menu) or b
|
||||
<http://127.0.0.1:8080/>. It only listens on 127.0.0.1. The page refreshes once a second while it
|
||||
is visible. Every chart has a **Table** button that shows the same numbers as a table. The tray
|
||||
icon also pops a balloon tip when something starts to go wrong — a fan group entering failsafe,
|
||||
an AI server reporting an error, or a sensor source starting to fail. What is already wrong when
|
||||
The Kurgan starts is not ballooned; it sits in the tray menu and the UI.
|
||||
an AI server reporting an error, or a sensor source starting to fail. Problems that start together
|
||||
share one balloon (Windows shows one at a time), and a problem that clears and comes back
|
||||
balloons again only after 10 minutes. What is already wrong when The Kurgan starts is not
|
||||
ballooned; it sits in the tray menu and the UI.
|
||||
|
||||
- **System**: CPU and GPU temperature, load, clock and power; GPU memory; the LCD's state. Charts show whole-PC power (stacked: other, CPU, GPU) and temperatures over the last 10 minutes. A range selector above the charts switches them to hourly averages for 24 hours, 7 days, 30 days or a year. Those long-term rollups live in `%LOCALAPPDATA%\Kurgan\records-YYYY-MM.jsonl` — one JSON line per hour, about 400 days kept, written best effort (a failing disk stops recording and nothing else notices; `--demo` never records). When a sensor source's last read failed — a disconnected Commander PRO, a busy NVML — a pill in the header names it and hover shows the error.
|
||||
- **System**: CPU and GPU temperature, load, clock and power; GPU memory; the LCD's state. Charts show whole-PC power (stacked: other, CPU, GPU) and temperatures over the last 10 minutes. A range selector above the charts switches them to hourly averages for 24 hours, 7 days, 30 days or a year. Those long-term rollups live in `%LOCALAPPDATA%\Kurgan\records-YYYY-MM.jsonl` — one JSON line per hour with min, average and max per metric (the average only over the samples that had the metric), about 400 days kept. The hour in progress is checkpointed to `records-current.json` every minute and on exit and resumed at the next start, so a restart — even `schtasks /End` — loses at most a minute. Writing is best effort: a failing disk is logged at most once an hour, and finished hours wait in memory (up to two days) until it works again. `--demo` never records. When a sensor source is failing — its read raised, or it has returned no temperature three times in a row (a lost GPU driver, an unavailable MSR reader) — a pill in the header names it and hover shows the error.
|
||||
- **Cooling**: the fan profile selector; each fan group's duty, temperature and RPMs; fan speeds over time; and the selected profile's curves, with a dot for each group's current operating point. Hover over a profile to preview its curves.
|
||||
- **Lighting**: a mode selector per zone (case fans, RAM, GPU), the zone's status, and the shared chase speed.
|
||||
- **AI**: pick Strata (and its model), llama.cpp or None; requests to either address also pick it. Then see the server's process, model, context size, live request progress and token speeds, and when it will stop if unused; load or unload the model; GPU memory over time; and recent requests.
|
||||
@@ -69,7 +71,7 @@ next start.
|
||||
|
||||
| Request | Body / result |
|
||||
| --- | --- |
|
||||
| `GET /api/state` | Everything live (what the UI polls), including `telemetry.health`: the sensor sources whose latest read failed, each with its error and age |
|
||||
| `GET /api/state` | Everything live (what the UI polls), including `telemetry.health`: the sensor sources that are failing (latest read raised, or no temperature three reads running), each with its error and age |
|
||||
| `GET /api/history` | The last 10 minutes of telemetry and fan duty |
|
||||
| `GET /api/records?days=N` | Hourly min/avg/max rollups for the last N days (1-400), oldest first |
|
||||
| `GET /api/config` | Fan profiles and LCD theme thresholds |
|
||||
@@ -263,7 +265,9 @@ last duty. If a top-fan write fails, The Kurgan hands those headers back to the
|
||||
once; if even that fails, the UI says what duty they are left at. Verify temperatures and fan
|
||||
rotation under your real workloads. Only SYS_FAN4's tach is wired to the EC, so top-fan stall
|
||||
detection covers that fan only: a channel whose tach has never been seen turning is left alone
|
||||
rather than crying wolf.
|
||||
rather than crying wolf, and the UI shows "no tach reading" for it instead of 0 rpm. If the
|
||||
top-fan code fails in any unexpected way, those headers go back to the BIOS curve and the case
|
||||
fans carry on; if the case fans' control loop itself hits an unexpected error, all fans go to 100%.
|
||||
|
||||
## Lighting
|
||||
|
||||
|
||||
+36
-2
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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:
|
||||
|
||||
+114
-31
@@ -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))
|
||||
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)
|
||||
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}
|
||||
@@ -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]:
|
||||
|
||||
@@ -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) {
|
||||
|
||||
+34
-1
@@ -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)
|
||||
|
||||
@@ -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
@@ -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"], [])
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user