import json 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 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)): 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 writes the old one rec.close() # ... and closing checkpoints the hour still in progress month = time.strftime("%Y-%m", time.gmtime(HOUR)) self.assertEqual(sorted(os.listdir(d)), [f"records-{month}.jsonl", "records-current.json"]) rows = written(d) 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, 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"]) 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 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: 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_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"], []) if __name__ == "__main__": unittest.main()