From 4f41d8fb7f1b538e7050b89459736d5edc166220 Mon Sep 17 00:00:00 2001 From: Matej Kocourek Date: Thu, 19 Nov 2026 20:57:44 +0100 Subject: [PATCH 1/3] Add Thermal: flag executions run on a hot or throttled CPU A hot or throttled CPU runs slower, so the numbers measured on it are suspect. Thermal is both a Hook and a Metric: around every execution it samples the CPU package temperature (Linux hwmon: coretemp, k10temp) and reads the kernel's thermal-throttle counters, then emits cpu_temp_max and cpu_throttle as process samples. Both carry extra={"suspect": True} when the CPU throttled or came within `margin` degrees of its crit temperature. Without the sensors it emits nothing. Co-Authored-By: Claude Opus 5.5 --- README.md | 5 +- src/bench/__init__.py | 2 + src/bench/core/metric/__init__.py | 2 + src/bench/core/metric/thermal.py | 148 ++++++++++++++++++++++++++++++ tests/test_thermal.py | 90 ++++++++++++++++++ 5 files changed, 246 insertions(+), 1 deletion(-) create mode 100644 src/bench/core/metric/thermal.py create mode 100644 tests/test_thermal.py diff --git a/README.md b/README.md index 4ed5130..4a8396e 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,10 @@ runs spaced with `.with_cooldown(s)`, and a suite's order randomized with sources, exiting non-zero on a high-severity one. On Linux as root, `bench denoise minimize|restore|status` quiets those knobs and reverts them. `bench run --check-environment` / `--denoise` do the same around a run; -scripts use `bench_app(probe=SystemProbe(), denoise=True)`. +scripts use `bench_app(probe=SystemProbe(), denoise=True)`. During a run, +`Thermal()` (added as both a hook and a metric) records each execution's hottest +CPU package temperature and thermal-throttle events on Linux, flagging the +samples `suspect` when the CPU throttled or ran near its limit. ## Development diff --git a/src/bench/__init__.py b/src/bench/__init__.py index 0bfc67c..3227941 100644 --- a/src/bench/__init__.py +++ b/src/bench/__init__.py @@ -72,6 +72,7 @@ RegexMetric, RUsage, SystemTime, + Thermal, Time, UserTime, as_metric_source, @@ -234,6 +235,7 @@ "SystemTime", "RUsage", "max_rss", + "Thermal", "RebenchMetric", "RegexMetric", "FloatPerLine", diff --git a/src/bench/core/metric/__init__.py b/src/bench/core/metric/__init__.py index 890d227..271a4f0 100644 --- a/src/bench/core/metric/__init__.py +++ b/src/bench/core/metric/__init__.py @@ -10,6 +10,7 @@ from bench.core.metric.rebench import RebenchMetric from bench.core.metric.regex import RegexMetric from bench.core.metric.rusage import RUsage, max_rss +from bench.core.metric.thermal import Thermal from bench.core.metric.time import SystemTime, Time, UserTime __all__ = [ @@ -18,6 +19,7 @@ "SystemTime", "RUsage", "max_rss", + "Thermal", "RebenchMetric", "RegexMetric", "FloatPerLine", diff --git a/src/bench/core/metric/thermal.py b/src/bench/core/metric/thermal.py new file mode 100644 index 0000000..1d68fe6 --- /dev/null +++ b/src/bench/core/metric/thermal.py @@ -0,0 +1,148 @@ +"""Thermal: was the CPU hot or throttled while a benchmark ran? + +A hot or throttled CPU runs slower, so its numbers are suspect. `Thermal` is +both a `Hook` and a `Metric`; add the same object as each: + + t = Thermal() + bench("x").with_hook(t).with_metric(t) + +Around every execution it samples the CPU package temperature (Linux hwmon: +`coretemp` on Intel, `k10temp` on AMD) and reads the kernel's thermal-throttle +counters, then emits two process samples: + +- `cpu_temp_max`: the hottest package temperature seen (C); +- `cpu_throttle`: how many throttle events the CPUs counted (summed over CPUs). + +Both carry `extra={"suspect": True}` when the CPU throttled or came within +`margin` degrees of the temperature where it starts throttling (hwmon's `crit`, +else `fallback_crit`). Where the sensors are missing, it emits nothing. +""" + +from __future__ import annotations + +import threading +from collections.abc import Iterable +from pathlib import Path +from typing import TYPE_CHECKING + +from bench.core.hook import Hook +from bench.core.metric.base import Metric +from bench.model.invocation import InvocationResult +from bench.model.results import Sample + +if TYPE_CHECKING: + from bench.model.benchmark import Benchmark + +_DRIVERS = {"coretemp": ("Package id",), "k10temp": ("Tctl", "Tdie")} + + +def _read(path: Path) -> int | None: + try: + return int(path.read_text()) + except (OSError, ValueError): + return None + + +def package_sensors(sysfs: Path = Path("/sys")) -> list[tuple[Path, int | None]]: + """(temp*_input, crit in m°C or None) of every CPU package sensor.""" + sensors: list[tuple[Path, int | None]] = [] + for hwmon in sorted((sysfs / "class/hwmon").glob("hwmon*")): + try: + labels = _DRIVERS.get((hwmon / "name").read_text().strip()) + except OSError: + continue + if labels is None: + continue + for label in sorted(hwmon.glob("temp*_label")): + if label.read_text().strip().startswith(labels): + base = label.name.removesuffix("_label") + sensors.append((hwmon / f"{base}_input", _read(hwmon / f"{base}_crit"))) + return sensors + + +def throttle_events(sysfs: Path = Path("/sys")) -> int | None: + """Thermal-throttle events counted so far, summed over all CPUs.""" + counts = [ + _read(f) + for f in (sysfs / "devices/system/cpu").glob( + "cpu[0-9]*/thermal_throttle/*_throttle_count" + ) + ] + counts = [c for c in counts if c is not None] + return sum(counts) if counts else None + + +class _Watch: + """Sample the hottest package temperature every `interval` s until stopped.""" + + def __init__( + self, sensors: list[tuple[Path, int | None]], sysfs: Path, interval: float + ) -> None: + self.sensors, self.sysfs = sensors, sysfs + self.hottest: int | None = None + self.throttles_before = throttle_events(sysfs) + self.throttles: int | None = None + self._stop = threading.Event() + self._sample() + self._thread = threading.Thread( + target=self._loop, args=(interval,), daemon=True + ) + self._thread.start() + + def _sample(self) -> None: + for path, _ in self.sensors: + t = _read(path) + if t is not None and (self.hottest is None or t > self.hottest): + self.hottest = t + + def _loop(self, interval: float) -> None: + while not self._stop.wait(interval): + self._sample() + + def stop(self) -> None: + self._stop.set() + self._thread.join() + self._sample() + after = throttle_events(self.sysfs) + if self.throttles_before is not None and after is not None: + self.throttles = after - self.throttles_before + + +class Thermal(Hook, Metric): + """CPU temperature and throttling during each execution (see module doc).""" + + def __init__( + self, + interval: float = 1.0, + margin: float = 10.0, + fallback_crit: float = 100.0, + sysfs: Path = Path("/sys"), + ) -> None: + Metric.__init__(self, "cpu_temp_max", "C") + self.interval, self.margin, self.fallback_crit = interval, margin, fallback_crit + self.sysfs = sysfs + self._sensors = package_sensors(sysfs) + # one watch per thread: executions may run in parallel + self._local = threading.local() + + def setup(self, benchmark: Benchmark) -> None: + self._local.watch = _Watch(self._sensors, self.sysfs, self.interval) + + def teardown(self, benchmark: Benchmark) -> None: + self._local.watch.stop() + + def process(self, data: InvocationResult) -> Iterable[Sample]: + watch: _Watch | None = getattr(self._local, "watch", None) + self._local.watch = None + if watch is None: + return + crits = [c / 1000 for _, c in self._sensors if c is not None] + limit = (min(crits) if crits else self.fallback_crit) - self.margin + hot = watch.hottest is not None and watch.hottest / 1000 >= limit + extra = {"suspect": True} if hot or (watch.throttles or 0) > 0 else {} + if watch.hottest is not None: + yield self.get_sample(watch.hottest / 1000, extra=extra) + if watch.throttles is not None: + yield self.get_sample( + float(watch.throttles), "cpu_throttle", "", extra=extra + ) diff --git a/tests/test_thermal.py b/tests/test_thermal.py new file mode 100644 index 0000000..d5126a1 --- /dev/null +++ b/tests/test_thermal.py @@ -0,0 +1,90 @@ +"""Thermal: CPU temperature and throttling around each execution, read from a +fake sysfs tree (Linux hwmon and thermal_throttle counters).""" + +from pathlib import Path + +from bench import Controller, FixedRuns, Reporter, Thermal, bench, suite +from bench.builder.suite import plan +from bench.model.invocation import InvocationResult +from bench.params import Params + + +def _sysfs( + root: Path, temp_mc: int = 50000, throttles: int = 0, crit_mc: int | None = 100000 +) -> Path: + hwmon = root / "class/hwmon/hwmon2" + hwmon.mkdir(parents=True, exist_ok=True) + (hwmon / "name").write_text("coretemp\n") + (hwmon / "temp1_label").write_text("Package id 0\n") + (hwmon / "temp1_input").write_text(f"{temp_mc}\n") + if crit_mc is not None: + (hwmon / "temp1_crit").write_text(f"{crit_mc}\n") + (hwmon / "temp2_label").write_text("Core 0\n") + (hwmon / "temp2_input").write_text("99000\n") # a core, not the package: ignored + tt = root / "devices/system/cpu/cpu0/thermal_throttle" + tt.mkdir(parents=True, exist_ok=True) + (tt / "core_throttle_count").write_text(f"{throttles}\n") + (tt / "package_throttle_count").write_text("0\n") + return root + + +def _measure(t: Thermal, during) -> dict[str, tuple[float, dict]]: + t.setup(None) # type: ignore[arg-type] + during() + t.teardown(None) # type: ignore[arg-type] + samples = t.process(InvocationResult.__new__(InvocationResult)) + return {s.metric: (s.value, dict(s.extra)) for s in samples} + + +def test_cool_and_unthrottled_is_not_suspect(tmp_path: Path): + t = Thermal(sysfs=_sysfs(tmp_path)) + assert _measure(t, lambda: None) == { + "cpu_temp_max": (50.0, {}), + "cpu_throttle": (0.0, {}), + } + + +def test_hottest_reading_is_kept_and_flagged_near_crit(tmp_path: Path): + root = _sysfs(tmp_path) + t = Thermal(sysfs=root) + + def heat_up(): + _sysfs(root, temp_mc=93000) + + got = _measure(t, heat_up) + assert got["cpu_temp_max"] == (93.0, {"suspect": True}) # within 10 C of crit 100 + + +def test_throttling_during_the_execution_is_flagged(tmp_path: Path): + root = _sysfs(tmp_path, throttles=4) + t = Thermal(sysfs=root) + got = _measure(t, lambda: _sysfs(root, throttles=6)) + assert got["cpu_throttle"] == (2.0, {"suspect": True}) + assert got["cpu_temp_max"] == (50.0, {"suspect": True}) + + +def test_without_crit_the_fallback_applies(tmp_path: Path): + root = _sysfs(tmp_path, temp_mc=85000, crit_mc=None) + assert _measure(Thermal(sysfs=root), lambda: None)["cpu_temp_max"] == (85.0, {}) + assert _measure(Thermal(sysfs=root, margin=20), lambda: None)["cpu_temp_max"] == ( + 85.0, + {"suspect": True}, + ) + + +def test_no_sensors_no_samples(tmp_path: Path): + assert _measure(Thermal(sysfs=tmp_path), lambda: None) == {} + + +def test_as_hook_and_metric_of_a_benchmark(tmp_path: Path): + t = Thermal(sysfs=_sysfs(tmp_path, temp_mc=61000)) + b = bench("b").with_command(["true"]).with_hook(t).with_metric(t) + s = suite("S").add(b).with_cwd(Path("/tmp")).with_runs(FixedRuns(2)) + + executions = Controller().run_benchmark(plan([s], Params())[0], Reporter(), False) + + for e in executions: + assert {x.metric: x.value for x in e.process_samples} == { + "cpu_temp_max": 61.0, + "cpu_throttle": 0.0, + } From c1f336eff5b0f02543c1dd1c328fcc91473ba264 Mon Sep 17 00:00:00 2001 From: Matej Kocourek Date: Thu, 19 Nov 2026 23:04:01 +0100 Subject: [PATCH 2/3] Thermal: read limits from the hardware, never fail a benchmark Read CPU thermal zones as well as hwmon, and take each sensor's limit from the hardware (hwmon crit, the zone's lowest passive/hot/critical trip point) instead of a fixed fallback: without a declared limit nothing is flagged as hot. Guard every read and the hook so that missing or broken sensors only mean no samples. Co-Authored-By: Claude Opus 5.5 --- src/bench/core/metric/thermal.py | 153 ++++++++++++++++--------------- tests/test_thermal.py | 126 ++++++++++++++++--------- 2 files changed, 162 insertions(+), 117 deletions(-) diff --git a/src/bench/core/metric/thermal.py b/src/bench/core/metric/thermal.py index 1d68fe6..04b5bd2 100644 --- a/src/bench/core/metric/thermal.py +++ b/src/bench/core/metric/thermal.py @@ -1,21 +1,17 @@ -"""Thermal: was the CPU hot or throttled while a benchmark ran? +"""CPU temperature and thermal throttling during each execution. -A hot or throttled CPU runs slower, so its numbers are suspect. `Thermal` is -both a `Hook` and a `Metric`; add the same object as each: +A hot or throttled CPU runs slower, so the measurements taken on it are +suspect. `Thermal` is both a `Hook` and a `Metric`; add the same object as +each:: t = Thermal() bench("x").with_hook(t).with_metric(t) -Around every execution it samples the CPU package temperature (Linux hwmon: -`coretemp` on Intel, `k10temp` on AMD) and reads the kernel's thermal-throttle -counters, then emits two process samples: - -- `cpu_temp_max`: the hottest package temperature seen (C); -- `cpu_throttle`: how many throttle events the CPUs counted (summed over CPUs). - -Both carry `extra={"suspect": True}` when the CPU throttled or came within -`margin` degrees of the temperature where it starts throttling (hwmon's `crit`, -else `fallback_crit`). Where the sensors are missing, it emits nothing. +It emits two process samples, `cpu_temp_max` (C) and `cpu_throttle` (throttle +events), marked `extra={"suspect": True}` when the CPU throttled or came within +`margin` degrees of a limit the hardware declares. On Linux it reads the CPU's +hwmon and thermal-zone sensors and the kernel's throttle counters; where they +are missing it emits nothing, and a sensor that fails never fails a benchmark. """ from __future__ import annotations @@ -33,113 +29,126 @@ if TYPE_CHECKING: from bench.model.benchmark import Benchmark -_DRIVERS = {"coretemp": ("Package id",), "k10temp": ("Tctl", "Tdie")} +# hwmon drivers of CPU packages, and the labels of their package sensors +_HWMON = {"coretemp": ("Package id",), "k10temp": ("Tctl", "Tdie")} +# thermal zones that measure the CPU, by their type +_ZONES = ("cpu", "pkg", "soc") +_TRIPS = ("passive", "hot", "critical") + +type Sensor = tuple[Path, int | None] # its reading, and its limit in m°C + + +def _text(path: Path) -> str: + try: + return path.read_text().strip() + except (OSError, UnicodeDecodeError): + return "" -def _read(path: Path) -> int | None: +def _int(path: Path) -> int | None: try: - return int(path.read_text()) - except (OSError, ValueError): + return int(_text(path)) + except ValueError: return None -def package_sensors(sysfs: Path = Path("/sys")) -> list[tuple[Path, int | None]]: - """(temp*_input, crit in m°C or None) of every CPU package sensor.""" - sensors: list[tuple[Path, int | None]] = [] - for hwmon in sorted((sysfs / "class/hwmon").glob("hwmon*")): - try: - labels = _DRIVERS.get((hwmon / "name").read_text().strip()) - except OSError: - continue - if labels is None: - continue - for label in sorted(hwmon.glob("temp*_label")): - if label.read_text().strip().startswith(labels): - base = label.name.removesuffix("_label") - sensors.append((hwmon / f"{base}_input", _read(hwmon / f"{base}_crit"))) +def cpu_sensors(sysfs: Path = Path("/sys")) -> list[Sensor]: + """The CPU temperature sensors, each with the limit it declares.""" + sensors: list[Sensor] = [] + for hwmon in sorted(sysfs.glob("class/hwmon/hwmon*")): + labels = _HWMON.get(_text(hwmon / "name")) + for label in sorted(hwmon.glob("temp*_label")) if labels else []: + if _text(label).startswith(labels or ()): + base = str(label).removesuffix("_label") + sensors.append((Path(f"{base}_input"), _int(Path(f"{base}_crit")))) + for zone in sorted(sysfs.glob("class/thermal/thermal_zone*")): + if any(z in _text(zone / "type").lower() for z in _ZONES): + trips = [ + _int(Path(str(t).replace("_type", "_temp"))) + for t in zone.glob("trip_point_*_type") + if _text(t) in _TRIPS + ] + limits = [t for t in trips if t is not None and t > 0] + sensors.append((zone / "temp", min(limits, default=None))) return sensors def throttle_events(sysfs: Path = Path("/sys")) -> int | None: """Thermal-throttle events counted so far, summed over all CPUs.""" - counts = [ - _read(f) - for f in (sysfs / "devices/system/cpu").glob( - "cpu[0-9]*/thermal_throttle/*_throttle_count" - ) - ] - counts = [c for c in counts if c is not None] + files = sysfs.glob("devices/system/cpu/cpu[0-9]*/thermal_throttle/*_throttle_count") + counts = [c for c in map(_int, files) if c is not None] return sum(counts) if counts else None class _Watch: - """Sample the hottest package temperature every `interval` s until stopped.""" + """Samples the sensors every `interval` seconds until stopped.""" - def __init__( - self, sensors: list[tuple[Path, int | None]], sysfs: Path, interval: float - ) -> None: - self.sensors, self.sysfs = sensors, sysfs + def __init__(self, thermal: Thermal) -> None: + self.thermal = thermal self.hottest: int | None = None - self.throttles_before = throttle_events(sysfs) + self.hot = False + self.throttles_before = throttle_events(thermal.sysfs) self.throttles: int | None = None self._stop = threading.Event() self._sample() - self._thread = threading.Thread( - target=self._loop, args=(interval,), daemon=True - ) + self._thread = threading.Thread(target=self._loop, daemon=True) self._thread.start() def _sample(self) -> None: - for path, _ in self.sensors: - t = _read(path) - if t is not None and (self.hottest is None or t > self.hottest): - self.hottest = t - - def _loop(self, interval: float) -> None: - while not self._stop.wait(interval): + for path, limit in self.thermal.sensors: + if (t := _int(path)) is None: + continue + self.hottest = t if self.hottest is None else max(self.hottest, t) + if limit is not None and t >= limit - self.thermal.margin * 1000: + self.hot = True + + def _loop(self) -> None: + while not self._stop.wait(self.thermal.interval): self._sample() def stop(self) -> None: self._stop.set() self._thread.join() self._sample() - after = throttle_events(self.sysfs) + after = throttle_events(self.thermal.sysfs) if self.throttles_before is not None and after is not None: self.throttles = after - self.throttles_before class Thermal(Hook, Metric): - """CPU temperature and throttling during each execution (see module doc).""" + """CPU temperature and thermal throttling around each execution.""" def __init__( - self, - interval: float = 1.0, - margin: float = 10.0, - fallback_crit: float = 100.0, - sysfs: Path = Path("/sys"), + self, interval: float = 1.0, margin: float = 10.0, sysfs: Path = Path("/sys") ) -> None: Metric.__init__(self, "cpu_temp_max", "C") - self.interval, self.margin, self.fallback_crit = interval, margin, fallback_crit - self.sysfs = sysfs - self._sensors = package_sensors(sysfs) - # one watch per thread: executions may run in parallel - self._local = threading.local() + self.interval, self.margin, self.sysfs = interval, margin, sysfs + try: + self.sensors = cpu_sensors(sysfs) + self.observable = bool(self.sensors) or throttle_events(sysfs) is not None + except Exception: + self.sensors, self.observable = [], False + self._local = threading.local() # executions may run in parallel threads def setup(self, benchmark: Benchmark) -> None: - self._local.watch = _Watch(self._sensors, self.sysfs, self.interval) + self._local.watch = None + if self.observable: + try: + self._local.watch = _Watch(self) + except Exception: + pass def teardown(self, benchmark: Benchmark) -> None: - self._local.watch.stop() + if (watch := getattr(self._local, "watch", None)) is not None: + watch.stop() def process(self, data: InvocationResult) -> Iterable[Sample]: watch: _Watch | None = getattr(self._local, "watch", None) self._local.watch = None if watch is None: return - crits = [c / 1000 for _, c in self._sensors if c is not None] - limit = (min(crits) if crits else self.fallback_crit) - self.margin - hot = watch.hottest is not None and watch.hottest / 1000 >= limit - extra = {"suspect": True} if hot or (watch.throttles or 0) > 0 else {} + suspect = watch.hot or (watch.throttles or 0) > 0 + extra = {"suspect": True} if suspect else {} if watch.hottest is not None: yield self.get_sample(watch.hottest / 1000, extra=extra) if watch.throttles is not None: diff --git a/tests/test_thermal.py b/tests/test_thermal.py index d5126a1..5962b29 100644 --- a/tests/test_thermal.py +++ b/tests/test_thermal.py @@ -1,7 +1,9 @@ """Thermal: CPU temperature and throttling around each execution, read from a -fake sysfs tree (Linux hwmon and thermal_throttle counters).""" +fake sysfs tree.""" +from collections.abc import Callable from pathlib import Path +from typing import Any from bench import Controller, FixedRuns, Reporter, Thermal, bench, suite from bench.builder.suite import plan @@ -9,26 +11,30 @@ from bench.params import Params -def _sysfs( - root: Path, temp_mc: int = 50000, throttles: int = 0, crit_mc: int | None = 100000 -) -> Path: - hwmon = root / "class/hwmon/hwmon2" - hwmon.mkdir(parents=True, exist_ok=True) - (hwmon / "name").write_text("coretemp\n") - (hwmon / "temp1_label").write_text("Package id 0\n") - (hwmon / "temp1_input").write_text(f"{temp_mc}\n") - if crit_mc is not None: - (hwmon / "temp1_crit").write_text(f"{crit_mc}\n") - (hwmon / "temp2_label").write_text("Core 0\n") - (hwmon / "temp2_input").write_text("99000\n") # a core, not the package: ignored - tt = root / "devices/system/cpu/cpu0/thermal_throttle" - tt.mkdir(parents=True, exist_ok=True) - (tt / "core_throttle_count").write_text(f"{throttles}\n") - (tt / "package_throttle_count").write_text("0\n") +def _write(root: Path, files: dict[str, str]) -> Path: + for name, content in files.items(): + (root / name).parent.mkdir(parents=True, exist_ok=True) + (root / name).write_text(content) return root -def _measure(t: Thermal, during) -> dict[str, tuple[float, dict]]: +def _coretemp(root: Path, temp: int = 50000, throttles: int = 0) -> Path: + return _write( + root, + { + "class/hwmon/hwmon2/name": "coretemp\n", + "class/hwmon/hwmon2/temp1_label": "Package id 0\n", + "class/hwmon/hwmon2/temp1_input": f"{temp}\n", + "class/hwmon/hwmon2/temp1_crit": "100000\n", + "class/hwmon/hwmon2/temp2_label": "Core 0\n", # not the package + "class/hwmon/hwmon2/temp2_input": "99000\n", + "devices/system/cpu/cpu0/thermal_throttle/core_throttle_count": f"{throttles}\n", + "devices/system/cpu/cpu0/thermal_throttle/package_throttle_count": "0\n", + }, + ) + + +def _measure(t: Thermal, during: Callable[[], Any] = lambda: None) -> dict[str, Any]: t.setup(None) # type: ignore[arg-type] during() t.teardown(None) # type: ignore[arg-type] @@ -36,48 +42,78 @@ def _measure(t: Thermal, during) -> dict[str, tuple[float, dict]]: return {s.metric: (s.value, dict(s.extra)) for s in samples} -def test_cool_and_unthrottled_is_not_suspect(tmp_path: Path): - t = Thermal(sysfs=_sysfs(tmp_path)) - assert _measure(t, lambda: None) == { - "cpu_temp_max": (50.0, {}), - "cpu_throttle": (0.0, {}), - } +def test_cool_and_unthrottled(tmp_path: Path): + t = Thermal(sysfs=_coretemp(tmp_path)) + assert _measure(t) == {"cpu_temp_max": (50.0, {}), "cpu_throttle": (0.0, {})} -def test_hottest_reading_is_kept_and_flagged_near_crit(tmp_path: Path): - root = _sysfs(tmp_path) - t = Thermal(sysfs=root) +def test_near_the_declared_limit_is_suspect(tmp_path: Path): + root = _coretemp(tmp_path) + got = _measure(Thermal(sysfs=root), lambda: _coretemp(root, temp=93000)) + assert got["cpu_temp_max"] == (93.0, {"suspect": True}) # within 10 C of crit - def heat_up(): - _sysfs(root, temp_mc=93000) - got = _measure(t, heat_up) - assert got["cpu_temp_max"] == (93.0, {"suspect": True}) # within 10 C of crit 100 +def test_throttling_is_suspect(tmp_path: Path): + root = _coretemp(tmp_path, throttles=4) + got = _measure(Thermal(sysfs=root), lambda: _coretemp(root, throttles=6)) + assert got["cpu_throttle"] == (2.0, {"suspect": True}) -def test_throttling_during_the_execution_is_flagged(tmp_path: Path): - root = _sysfs(tmp_path, throttles=4) - t = Thermal(sysfs=root) - got = _measure(t, lambda: _sysfs(root, throttles=6)) - assert got["cpu_throttle"] == (2.0, {"suspect": True}) - assert got["cpu_temp_max"] == (50.0, {"suspect": True}) +def test_thermal_zone_uses_its_lowest_trip_point(tmp_path: Path): + root = _write( + tmp_path, + { + "class/thermal/thermal_zone0/type": "cpu-thermal\n", + "class/thermal/thermal_zone0/temp": "77000\n", + "class/thermal/thermal_zone0/trip_point_0_type": "active\n", # a fan, not a limit + "class/thermal/thermal_zone0/trip_point_0_temp": "60000\n", + "class/thermal/thermal_zone0/trip_point_1_type": "passive\n", + "class/thermal/thermal_zone0/trip_point_1_temp": "85000\n", + "class/thermal/thermal_zone0/trip_point_2_type": "critical\n", + "class/thermal/thermal_zone0/trip_point_2_temp": "105000\n", + "class/thermal/thermal_zone1/type": "battery\n", # not the CPU + "class/thermal/thermal_zone1/temp": "99000\n", + }, + ) + assert _measure(Thermal(sysfs=root)) == {"cpu_temp_max": (77.0, {"suspect": True})} -def test_without_crit_the_fallback_applies(tmp_path: Path): - root = _sysfs(tmp_path, temp_mc=85000, crit_mc=None) - assert _measure(Thermal(sysfs=root), lambda: None)["cpu_temp_max"] == (85.0, {}) - assert _measure(Thermal(sysfs=root, margin=20), lambda: None)["cpu_temp_max"] == ( - 85.0, - {"suspect": True}, +def test_without_a_declared_limit_nothing_is_guessed(tmp_path: Path): + root = _write( + tmp_path, + { + "class/hwmon/hwmon0/name": "k10temp\n", + "class/hwmon/hwmon0/temp1_label": "Tctl\n", + "class/hwmon/hwmon0/temp1_input": "99000\n", + }, ) + assert _measure(Thermal(sysfs=root)) == {"cpu_temp_max": (99.0, {})} def test_no_sensors_no_samples(tmp_path: Path): - assert _measure(Thermal(sysfs=tmp_path), lambda: None) == {} + t = Thermal(sysfs=tmp_path) + assert not t.observable + assert _measure(t) == {} + + +def test_broken_sensors_never_raise(tmp_path: Path): + root = _write( + tmp_path, + { + "class/hwmon/hwmon0/name": "coretemp\n", + "class/hwmon/hwmon0/temp1_label": "Package id 0\n", + "class/hwmon/hwmon0/temp1_input": "garbage\n", + "class/hwmon/hwmon0/temp1_crit": "\xff\n", + "class/thermal/thermal_zone0/type": "x86_pkg_temp\n", + "devices/system/cpu/cpu0/thermal_throttle/core_throttle_count": "n/a\n", + }, + ) + (root / "class/thermal/thermal_zone0/temp").mkdir() # unreadable as a file + assert _measure(Thermal(sysfs=root)) == {} def test_as_hook_and_metric_of_a_benchmark(tmp_path: Path): - t = Thermal(sysfs=_sysfs(tmp_path, temp_mc=61000)) + t = Thermal(sysfs=_coretemp(tmp_path, temp=61000)) b = bench("b").with_command(["true"]).with_hook(t).with_metric(t) s = suite("S").add(b).with_cwd(Path("/tmp")).with_runs(FixedRuns(2)) From 139ab198a8b663aeef09531fa29f906053a86173 Mon Sep 17 00:00:00 2001 From: Matej Kocourek Date: Fri, 20 Nov 2026 00:02:51 +0100 Subject: [PATCH 3/3] Thermal: skip thermal zones where hwmon covers the CPU On x86 laptops firmware zones such as CPUV match the CPU zone names and declare policy trip points (a 60 C passive one), which flagged nearly every execution. Co-Authored-By: Claude Opus 5.5 --- src/bench/core/metric/thermal.py | 4 ++++ tests/test_thermal.py | 13 +++++++++++++ 2 files changed, 17 insertions(+) diff --git a/src/bench/core/metric/thermal.py b/src/bench/core/metric/thermal.py index 04b5bd2..6a4a915 100644 --- a/src/bench/core/metric/thermal.py +++ b/src/bench/core/metric/thermal.py @@ -61,6 +61,10 @@ def cpu_sensors(sysfs: Path = Path("/sys")) -> list[Sensor]: if _text(label).startswith(labels or ()): base = str(label).removesuffix("_label") sensors.append((Path(f"{base}_input"), _int(Path(f"{base}_crit")))) + if sensors: + # where a driver covers the package, thermal zones add only firmware + # policy zones, whose trip points are not CPU limits + return sensors for zone in sorted(sysfs.glob("class/thermal/thermal_zone*")): if any(z in _text(zone / "type").lower() for z in _ZONES): trips = [ diff --git a/tests/test_thermal.py b/tests/test_thermal.py index 5962b29..643969c 100644 --- a/tests/test_thermal.py +++ b/tests/test_thermal.py @@ -78,6 +78,19 @@ def test_thermal_zone_uses_its_lowest_trip_point(tmp_path: Path): assert _measure(Thermal(sysfs=root)) == {"cpu_temp_max": (77.0, {"suspect": True})} +def test_thermal_zones_are_ignored_where_hwmon_covers_the_cpu(tmp_path: Path): + root = _write( + _coretemp(tmp_path), + { + "class/thermal/thermal_zone0/type": "CPUV\n", # a firmware policy zone + "class/thermal/thermal_zone0/temp": "55000\n", + "class/thermal/thermal_zone0/trip_point_0_type": "passive\n", + "class/thermal/thermal_zone0/trip_point_0_temp": "60050\n", + }, + ) + assert _measure(Thermal(sysfs=root))["cpu_temp_max"] == (50.0, {}) + + def test_without_a_declared_limit_nothing_is_guessed(tmp_path: Path): root = _write( tmp_path,