Long-term telemetry: hourly rollups in JSONL, a range selector in the UI
- telemetry/record.py: a Recorder subscribed to Telemetry keeps min/avg/max per metric for the current hour and appends each finished hour as one JSON line to records-YYYY-MM.jsonl in the data dir (~400 days kept; whole months older than that are pruned on start). Best effort by design: a failing disk logs once and stops recording; nothing else notices. load() merges lines per hour (a restart re-writes the current hour; torn last lines are skipped). - app.py: the recorder runs unless --demo (simulated samples must not mix into real records) and flushes the open hour in close(), after the telemetry thread has stopped. records(days) validates 1..400. - Web: GET /api/records?days=N (bad values answer 400 with the reason). - UI: a range selector above the power/temperature charts switches them between the live 10 minutes and hourly averages for 24 h / 7 d / 30 d / 1 y; the chart window, tick labels (min/h/d), tooltips and table captions adapt to the span. Live samples keep accumulating behind a long-range view, so switching back is instant. - Tests: test_record.py (5) and a /api/records case in test_web.py; README updated (API table, System section, layout).
This commit is contained in:
1 parent
ba39016d52
commit
f717f7a82f
8 files changed
+371
-18
No files matched your search
@@ -0,0 +1,96 @@
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
|
||||
from kurgan.telemetry.readings import PowerReadings, Readings
|
||||
from kurgan.telemetry.record import Recorder, load
|
||||
from kurgan.telemetry.service import Sample
|
||||
|
||||
HOUR = 1764892800 # any hour boundary; 1764892800 % 3600 == 0
|
||||
|
||||
|
||||
def sample(t, cpu_temp=50.0, gpu_temp=None, vram=None, cpu_w=30.0, gpu_w=80.0, other_w=20.0):
|
||||
return Sample(1, t, Readings(temp=cpu_temp, power=cpu_w), Readings(temp=gpu_temp, power=gpu_w),
|
||||
PowerReadings(cpu=cpu_w, gpu=gpu_w, other=other_w), vram)
|
||||
|
||||
|
||||
def written(directory):
|
||||
rows = []
|
||||
for name in sorted(os.listdir(directory)):
|
||||
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
|
||||
|
||||
|
||||
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
|
||||
month = time.strftime("%Y-%m", time.gmtime(HOUR))
|
||||
self.assertEqual(os.listdir(d), [f"records-{month}.jsonl"])
|
||||
rows = written(d)
|
||||
self.assertEqual(len(rows), 2)
|
||||
first, second = rows
|
||||
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.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):
|
||||
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)
|
||||
self.assertEqual(len(logs.output), 1)
|
||||
|
||||
def test_pruning_removes_months_older_than_the_retention(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
old = os.path.join(d, "records-2020-01.jsonl")
|
||||
current = os.path.join(d, f"records-{time.strftime('%Y-%m', time.gmtime())}.jsonl")
|
||||
open(old, "w").close()
|
||||
open(current, "w").close()
|
||||
Recorder(d, retention_days=400)
|
||||
self.assertFalse(os.path.exists(old))
|
||||
self.assertTrue(os.path.exists(current))
|
||||
|
||||
|
||||
class LoadTest(unittest.TestCase):
|
||||
def test_load_merges_restarts_and_skips_junk(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": 100, "cpu_temp": [40.0, 50.0, 60.0], "total_w": None}) + "\n")
|
||||
f.write(json.dumps({"hour": h, "n": 300, "cpu_temp": [30.0, 40.0, 80.0]}) + "\n") # a restart re-wrote this hour
|
||||
f.write(json.dumps({"hour": h - 5 * 86400, "n": 3600, "cpu_temp": [10.0, 20.0, 30.0]}) + "\n") # outside the window
|
||||
f.write("{torn\n") # the last line of a crashed run
|
||||
data = load(d, days=1)
|
||||
self.assertEqual(data["days"], 1)
|
||||
self.assertEqual(data["metrics"][0], "cpu_temp")
|
||||
self.assertEqual(len(data["rows"]), 1)
|
||||
row = data["rows"][0]
|
||||
self.assertEqual((row["hour"], row["n"]), (h, 400))
|
||||
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_without_a_directory_is_empty(self):
|
||||
data = load(os.path.join(tempfile.gettempdir(), "kurgan-no-such-records-dir"), 7)
|
||||
self.assertEqual(data["rows"], [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -35,6 +35,12 @@ class FakeApp:
|
||||
def ai_model(self, action):
|
||||
self.calls.append(("model", action))
|
||||
|
||||
def records(self, days):
|
||||
self.calls.append(("records", days))
|
||||
if not 1 <= days <= 400:
|
||||
raise ValueError("days must be a whole number from 1 to 400")
|
||||
return {"metrics": [], "rows": [], "days": days}
|
||||
|
||||
|
||||
def free_port() -> int:
|
||||
with socket.socket() as s:
|
||||
@@ -127,6 +133,19 @@ class WebServerTest(unittest.TestCase):
|
||||
self.request("POST", "/api/ai/active", {"backend": "strata", "variant": "iq3"})
|
||||
self.assertEqual(self.app.calls, [("ai", None, None), ("ai", "strata", "iq3")])
|
||||
|
||||
def test_records_serves_the_long_term_rollups(self):
|
||||
status, _, body = self.request("GET", "/api/records") # no days: the default week
|
||||
self.assertEqual((status, json.loads(body)["days"]), (200, 7))
|
||||
status, _, body = self.request("GET", "/api/records?days=30")
|
||||
self.assertEqual((status, json.loads(body)["days"]), (200, 30))
|
||||
self.assertEqual(self.app.calls, [("records", 7), ("records", 30)])
|
||||
for path in ("/api/records?days=abc", "/api/records?days=0", "/api/records?days=-3",
|
||||
"/api/records?days=401", "/api/records?days=1.5"):
|
||||
with self.subTest(path=path):
|
||||
status, _, raw = self.request("GET", path)
|
||||
self.assertEqual(status, 400)
|
||||
self.assertIn("whole number", json.loads(raw)["error"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user