diff --git a/src/qeval/resource_monitor.py b/src/qeval/resource_monitor.py new file mode 100644 index 00000000..62310e3a --- /dev/null +++ b/src/qeval/resource_monitor.py @@ -0,0 +1,249 @@ +from __future__ import annotations + +import os +import threading +import time +from dataclasses import dataclass, fields +from pathlib import Path + +import psutil + +from qlever.containerize import Containerize +from qlever.log import log +from qlever.util import resource_usage_prefix, run_command + + +@dataclass +class Sample: + """ + One sample of elapsed time, memory (RSS) and CPU usage. A field that + is None is written as an empty TSV column. + """ + + elapsed_s: float | None = None + rss: int | None = None + cpu_percent: float | None = None + + +def sample_to_tsv_row(sample: Sample) -> str: + """Format a `Sample` as a TSV row.""" + values = [getattr(sample, field.name) for field in fields(sample)] + return ( + "\t".join("" if value is None else str(value) for value in values) + + "\n" + ) + + +def sample_process(proc: psutil.Process) -> Sample: + """ + One reading of the memory and CPU usage of `proc`. Empty if the + process is gone or cannot be read. + """ + try: + mem = proc.memory_info() + cpu_pct = proc.cpu_percent(interval=None) + except (psutil.NoSuchProcess, psutil.AccessDenied): + return Sample() + # A process that is exiting has already freed its memory. + if mem.rss == 0: + return Sample() + return Sample(rss=mem.rss, cpu_percent=cpu_pct) + + +def container_memory_to_bytes(memory_string: str) -> int: + """ + Parse a memory usage string from `docker stats` or `podman stats` + into bytes. Docker reports binary units (GiB, MiB) while Podman + reports decimal units (GB, MB). + """ + memory_string = memory_string.strip() + # Order matters: the first endswith match wins, and "B" is a suffix + # of every other unit, so it must stay last. + units = { + "TIB": 1024**4, + "TB": 1000**4, + "GIB": 1024**3, + "GB": 1000**3, + "MIB": 1024**2, + "MB": 1000**2, + "KIB": 1024, + "KB": 1000, + "B": 1, + } + for suffix, multiplier in units.items(): + if memory_string.upper().endswith(suffix): + number = float(memory_string[: len(memory_string) - len(suffix)]) + return int(number * multiplier) + return 0 + + +def sample_container(system: str, container: str) -> Sample: + """ + One reading of the memory and CPU usage of `container`, via + ` stats --no-stream`. Empty if it cannot be read. + """ + try: + output = run_command( + f"{system} stats --no-stream" + f" --format '{{{{.MemUsage}}}}\t{{{{.CPUPerc}}}}'" + f" {container}", + return_output=True, + ) + memory_field, cpu_field = output.strip().split("\t") + used_memory = memory_field.split("/")[0].strip() + cpu_percent = float(cpu_field.strip().rstrip("%")) + rss = container_memory_to_bytes(used_memory) + except Exception: + return Sample() + # A container that is exiting reports `0B / 0B` (like a process that + # is exiting, see `sample_process`). + if rss == 0: + return Sample() + return Sample(rss=rss, cpu_percent=cpu_percent) + + +def find_process_by_binary( + parent_pid: int, binary: str +) -> psutil.Process | None: + """Find a descendant of parent_pid whose argv[0] basename matches binary.""" + try: + root = psutil.Process(parent_pid) + candidates = [root] + root.children(recursive=True) + except (psutil.NoSuchProcess, psutil.AccessDenied): + return None + # Both sides use Path(...).name so any path form (relative, absolute, + # bare, symlink) matches as long as argv[0] preserves the binary's name. + target = Path(binary).name + for proc in candidates: + try: + cmdline = proc.cmdline() + except (psutil.NoSuchProcess, psutil.AccessDenied): + continue + if cmdline and Path(cmdline[0]).name == target: + return proc + return None + + +class ResourceMonitor: + """ + Monitor resource usage (memory, CPU) of an index-building + process. Works in both native mode (via psutil) and container mode + (via docker/podman stats). Use it as a context manager around the + index command. + """ + + def __init__( + self, + dataset: str, + engine: str, + binary: str, + container: str | None = None, + system: str | None = None, + interval: float = 1.0, + ): + """ + Args: + dataset: Name of the dataset being indexed. + engine: Engine key, which the log and plot names start with. + binary: Name of the index executable, matched against the + descendant processes (native mode only). + container: Container name to sample. When set with `system`, + sampling uses `docker/podman stats`, not psutil. + system: Container runtime ("docker" or "podman"). + interval: Seconds between samples. + """ + self.dataset = dataset + self.engine = engine + self.binary = binary + self.container = container + self.system = system + self.interval = interval + self.peak_rss = 0 + self.worker_proc = None + self.log_path = None + self.log_file = None + self.stop_event = threading.Event() + self.start_time = 0.0 + self.thread = None + + @classmethod + def from_args(cls, args) -> ResourceMonitor: + """Monitor the index build configured by `args`.""" + return cls( + dataset=args.name, + engine=args.engine_short_name, + binary=args.index_binary, + container=args.index_container, + system=args.system, + interval=args.resource_usage_interval, + ) + + def take_sample(self) -> Sample: + """ + Read one sample from the container or from the index process. + The process is only searched for again once it is gone. + """ + if self.system in Containerize.supported_systems(): + return sample_container(self.system, self.container) + if self.worker_proc is None or not self.worker_proc.is_running(): + self.worker_proc = find_process_by_binary(os.getpid(), self.binary) + if self.worker_proc is None: + return Sample() + # cpu_percent reports usage since the previous call, so this + # first call seeds the baseline and its 0.0 result is discarded. + try: + self.worker_proc.cpu_percent(interval=None) + except (psutil.NoSuchProcess, psutil.AccessDenied): + self.worker_proc = None + return Sample() + return sample_process(self.worker_proc) + + def run_loop(self): + """ + Polling loop on a background thread. Samples resource usage + and appends one TSV row per iteration until stop_event is set. + """ + while not self.stop_event.is_set(): + sample_start = time.monotonic() + sample = self.take_sample() + sample.elapsed_s = round(sample_start - self.start_time, 1) + if sample.rss is not None: + self.peak_rss = max(self.peak_rss, sample.rss) + self.log_file.write(sample_to_tsv_row(sample)) + self.log_file.flush() + # Subtract the sampling time so samples stay one interval apart. + sample_duration = time.monotonic() - sample_start + self.stop_event.wait(max(0.0, self.interval - sample_duration)) + + def __enter__(self): + """Open the TSV log, write its header, and start the sampling thread.""" + prefix = resource_usage_prefix(self.engine, self.dataset) + self.log_path = Path(f"{prefix}.index.resource-usage-log.tsv") + self.log_file = open(self.log_path, "w") + header = "\t".join(field.name for field in fields(Sample)) + "\n" + self.log_file.write(header) + self.log_file.flush() + self.start_time = time.monotonic() + self.thread = threading.Thread(target=self.run_loop, daemon=True) + self.thread.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + """ + Stop sampling and close the log, reporting where it was saved and + the peak RSS. + """ + self.stop_event.set() + self.thread.join() + self.log_file.close() + if self.peak_rss > 0: + log.info( + "Resource-usage log (RSS memory and CPU usage) saved to " + f"`{self.log_path.name}`, peak RSS " + f"{self.peak_rss / 1024**3:.1f} GB" + ) + else: + log.warning( + "Resource usage was not recorded (no samples collected)." + ) + return False diff --git a/src/qlever/commands/index.py b/src/qlever/commands/index.py index bc15de13..4f121c34 100644 --- a/src/qlever/commands/index.py +++ b/src/qlever/commands/index.py @@ -9,6 +9,7 @@ from qlever.command import QleverCommand from qlever.containerize import Containerize from qlever.log import log +from qlever.resource_usage.plot_util import render_usage_plot_if_installed from qlever.util import ( binary_exists, get_existing_index_files, @@ -18,45 +19,6 @@ ) -def render_usage_plot( - dataset: str, - stxxl_memory: str, - settings_json: str, - plot_max_points: int, - plot_only: bool, - main_command_name: str, - engine_display_name: str, -) -> Path | None: - """Render the resource-usage plot. - - When the plotting libraries are missing, this is an error if the - user asked for the plot directly via `plot_only`, otherwise it notes - how to get the plot at info level since the index build succeeded. - """ - try: - from qlever.resource_usage import usage_plot - except ImportError: - if plot_only: - log.error( - "Resource-usage plot needs matplotlib and numpy " - "(`pip install qlever[plot]`). Install them and rerun." - ) - else: - log.info( - "To plot the resource-usage log, install matplotlib and " - "numpy (`pip install qlever[plot]`), then run " - f"`{main_command_name} index --resource-usage-plot-only`." - ) - return None - return usage_plot.render_usage_plot( - dataset, - stxxl_memory=stxxl_memory, - settings_json=settings_json, - plot_max_points=plot_max_points, - engine_display_name=engine_display_name, - ) - - class IndexCommand(QleverCommand): """ Class for executing the `index` command. @@ -242,19 +204,8 @@ def execute(self, args) -> bool: # Render the resource-usage plot from the existing log without # rebuilding the index. if args.resource_usage_plot_only: - plot_path = render_usage_plot( - args.name, - stxxl_memory=args.stxxl_memory or "", - settings_json=args.settings_json, - plot_max_points=args.resource_usage_plot_max_points, - plot_only=True, - main_command_name=args.main_command_name, - engine_display_name=args.engine_display_name, - ) - if plot_path is None: - return False - log.info(f"Resource-usage plot saved to `{plot_path.name}`") - return True + plot_path = render_usage_plot_if_installed(args, plot_only=True) + return plot_path is not None # The mandatory part of the command line (specifying the input, the # basename of the index, and the settings file). There are two ways @@ -438,16 +389,6 @@ def execute(self, args) -> bool: Path(f"{args.name}.index.resource-usage-log.tsv").exists() or Path(f"{args.name}.resource-usage-log.tsv").exists() ): - plot_path = render_usage_plot( - args.name, - stxxl_memory=args.stxxl_memory or "", - settings_json=args.settings_json, - plot_max_points=args.resource_usage_plot_max_points, - plot_only=False, - main_command_name=args.main_command_name, - engine_display_name=args.engine_display_name, - ) - if plot_path is not None: - log.info(f"Resource-usage plot saved to `{plot_path.name}`") + render_usage_plot_if_installed(args, plot_only=False) return True diff --git a/src/qlever/resource_usage/plot_util.py b/src/qlever/resource_usage/plot_util.py new file mode 100644 index 00000000..a29da888 --- /dev/null +++ b/src/qlever/resource_usage/plot_util.py @@ -0,0 +1,78 @@ +""" +Resource-usage plot code shared by all engines. Kept apart from +`usage_plot`, so that it can be imported without the optional plotting +libraries. +""" + +from __future__ import annotations + +from collections.abc import Callable +from pathlib import Path +from typing import Any + +from qlever.log import log + +# One shaded region of the plot: name, start and end in seconds. +BandType = tuple[str, float, float] + +# The engine-specific parts of the plot, called with `args` and the path +# of the index log. +OverlayType = Callable[[Any, Path], list[BandType]] +SubtitleType = Callable[[Any, Path], str | None] + +# Separator between the fields of a subtitle. +SUBTITLE_SEPARATOR = " | " + + +def bands_from_durations( + durations: dict[str, float], +) -> list[BandType]: + """ + Turn phase durations in seconds into `(label, start_s, end_s)` bands, + laying the phases back to back from the build start in the given + order. The `TOTAL time` entry is skipped. + """ + bands = [] + start_s = 0.0 + for label, duration_s in durations.items(): + if label == "TOTAL time": + continue + bands.append((label, start_s, start_s + duration_s)) + start_s += duration_s + return bands + + +def render_usage_plot_if_installed( + args, + *, + plot_only: bool, + engine_overlay: OverlayType | None = None, + engine_subtitle: SubtitleType | None = None, +) -> Path | None: + """ + Render the resource-usage plot with `usage_plot.render_usage_plot`. + The plotting libraries are an optional dependency, so the import has + to happen here and not at module level. Missing them is an error when + the user asked for the plot directly via `plot_only`, and only a hint + otherwise, because then the index build itself succeeded. + """ + try: + from qlever.resource_usage import usage_plot + except ImportError: + if plot_only: + log.error( + "Resource-usage plot needs matplotlib and numpy " + "(`pip install qlever[plot]`). Install them and rerun." + ) + else: + log.info( + "To plot the resource-usage log, install matplotlib and " + "numpy (`pip install qlever[plot]`), then run " + f"`{args.main_command_name} index --resource-usage-plot-only`." + ) + return None + return usage_plot.render_usage_plot( + args, + engine_overlay=engine_overlay, + engine_subtitle=engine_subtitle, + ) diff --git a/src/qlever/resource_usage/usage_plot.py b/src/qlever/resource_usage/usage_plot.py index f798fd5c..ebcd0756 100644 --- a/src/qlever/resource_usage/usage_plot.py +++ b/src/qlever/resource_usage/usage_plot.py @@ -2,6 +2,7 @@ import csv import json +import re import warnings from datetime import datetime from pathlib import Path @@ -14,10 +15,16 @@ from matplotlib import pyplot as plt from qlever.log import log +from qlever.resource_usage.plot_util import ( + SUBTITLE_SEPARATOR, + BandType, + OverlayType, + SubtitleType, +) from qlever.util import ( iter_permutation_phases, - parse_git_hash, parse_phase_markers, + resource_usage_prefix, ) GB = 1024**3 @@ -159,6 +166,16 @@ def add(name: str, start: datetime | None, end: datetime | None) -> None: return phases +def parse_git_hash(log_path: Path) -> str | None: + """Return the git hash printed on the first line of a QLever index log.""" + try: + first_line = log_path.read_text().splitlines()[0] + except (OSError, IndexError): + return None + match = re.search(r"git hash ([0-9a-f]+)", first_line) + return match.group(1) if match else None + + def build_plot_subtitle( log_path: Path, stxxl_memory: str, settings_json: str ) -> str | None: @@ -183,24 +200,38 @@ def build_plot_subtitle( parts.append(f"git = {git_hash}") if stxxl_memory: parts.append(f"STXXL = {stxxl_memory}") - return " | ".join(parts) if parts else None + return SUBTITLE_SEPARATOR.join(parts) if parts else None + + +def overlay(args, log_path: Path) -> list[BandType]: + """Shade one band per phase of a QLever index build.""" + phases = compute_phase_boundaries(log_path) + return [ + (name, start_s, end_s) for name, (start_s, end_s) in phases.items() + ] + + +def subtitle(args, log_path: Path) -> str | None: + """Subtitle for a QLever index build.""" + return build_plot_subtitle( + log_path, args.stxxl_memory or "", args.settings_json + ) def write_usage_plot( tsv_path: Path, - log_path: Path, - stxxl_memory: str, - settings_json: str, out_path: Path, title: str, + bands: list[BandType], + subtitle_text: str | None, plot_max_points: int = 500, ) -> bool: """ - Read the usage TSV and index log, render a dual-axis plot of - memory and CPU over time with phase bands from the index log, - and save it to `out_path`. Returns True if a plot was saved, - False if the TSV has no usable samples. `plot_max_points` caps - the number of points drawn per series. + Read the usage TSV, render a dual-axis plot of memory and CPU over + time with the `bands` regions shaded, and save it to `out_path`. + Returns True if a plot was saved, False if the TSV has no usable + samples. `plot_max_points` caps the number of points drawn per + series. """ data = read_usage_tsv(tsv_path) if not data or len(data.get("elapsed_s", [])) == 0: @@ -214,8 +245,6 @@ def write_usage_plot( data = {name: values[valid[0] :] for name, values in data.items()} data["elapsed_s"] = data["elapsed_s"] - data["elapsed_s"][0] - phases = compute_phase_boundaries(log_path) - data = downsample_for_plot(data, plot_max_points) elapsed_s = data["elapsed_s"] @@ -232,10 +261,10 @@ def write_usage_plot( band_colors = plt.colormaps["Pastel1"].colors total_s = float(elapsed_s[-1]) if len(elapsed_s) else 0.0 - # skip drawing the phase name when the band is too narrow to fit it + # skip drawing the region name when the band is too narrow to fit it # legibly; arbitrary 2% of total duration. min_label_s = total_s * 0.02 - for band_idx, (name, (start_s, end_s)) in enumerate(phases.items()): + for band_idx, (name, start_s, end_s) in enumerate(bands): band_s = end_s - start_s if band_s <= 0: continue @@ -298,47 +327,49 @@ def write_usage_plot( bbox_to_anchor=(1.08, 0.5), ) - subtitle = build_plot_subtitle(log_path, stxxl_memory, settings_json) - ax_mem.set_title(f"{title}\n{subtitle}" if subtitle else title) + ax_mem.set_title(f"{title}\n{subtitle_text}" if subtitle_text else title) fig.savefig(out_path, dpi=120) plt.close(fig) return True def render_usage_plot( - dataset: str, - engine_display_name: str, - stxxl_memory: str = "", - settings_json: str = "{}", - output_dir: Path | None = None, - plot_max_points: int = 500, + args, + *, + engine_overlay: OverlayType | None = None, + engine_subtitle: SubtitleType | None = None, ) -> Path | None: """ - Render `.resource-usage-plot.png` from - `.index.resource-usage-log.tsv` in `output_dir`, falling - back to `.resource-usage-log.tsv` as written by older - qlever versions. Returns the plot path on success, None if the log - is missing or the plot could not be rendered. + Render `.resource-usage-plot.png` from + `.index.resource-usage-log.tsv` in the current directory, where + `prefix` comes from `resource_usage_prefix`, falling back to + `.resource-usage-log.tsv` as written by older qlever + versions. `engine_overlay` and `engine_subtitle` are called with + `(args, log_path)` and provide the engine-specific parts of the plot. + Without them, the plot describes a QLever index build. Returns the + plot path on success, None if the plot was not rendered. """ - output_dir = output_dir or Path.cwd() - tsv_path = output_dir / f"{dataset}.index.resource-usage-log.tsv" + engine_overlay = engine_overlay or overlay + engine_subtitle = engine_subtitle or subtitle + dataset = args.name + prefix = resource_usage_prefix(args.engine_short_name, dataset) + tsv_path = Path(f"{prefix}.index.resource-usage-log.tsv") # Backwards compatibility with older resource-usage log filename if not tsv_path.exists(): - tsv_path = output_dir / f"{dataset}.resource-usage-log.tsv" - log_path = output_dir / f"{dataset}.index-log.txt" - plot_path = output_dir / f"{dataset}.resource-usage-plot.png" + tsv_path = Path(f"{prefix}.resource-usage-log.tsv") + log_path = Path(f"{dataset}.index-log.txt") + plot_path = Path(f"{prefix}.resource-usage-plot.png") if not tsv_path.exists(): log.warning(f"Resource-usage log not found: `{tsv_path.name}`") return None try: rendered = write_usage_plot( tsv_path=tsv_path, - log_path=log_path, - stxxl_memory=stxxl_memory, - settings_json=settings_json, out_path=plot_path, - title=f"{engine_display_name} index build: {dataset}", - plot_max_points=plot_max_points, + title=f"{args.engine_display_name} index build: {dataset}", + bands=engine_overlay(args, log_path), + subtitle_text=engine_subtitle(args, log_path), + plot_max_points=args.resource_usage_plot_max_points, ) except Exception as error: log.warning(f"Could not render resource-usage plot: {error}") @@ -349,4 +380,5 @@ def render_usage_plot( f"resource-usage log `{tsv_path.name}`" ) return None + log.info(f"Resource-usage plot saved to `{plot_path.name}`") return plot_path diff --git a/src/qlever/util.py b/src/qlever/util.py index ceb16e43..d18af2a3 100644 --- a/src/qlever/util.py +++ b/src/qlever/util.py @@ -262,6 +262,17 @@ def get_existing_index_files( return [path.name for path in existing_index_files] +def resource_usage_prefix(engine: str, dataset: str) -> str: + """ + Name that the resource-usage log and plot start with, that is + `.`. The engine goes after the dataset, so that it + is clear which engine a log or plot belongs to. QLever's own binaries + write the log and do not know the engine name, so QLever gets plain + ``. + """ + return dataset if engine == "qlever" else f"{dataset}.{engine}" + + def show_process_info(psutil_process, cmdline_regex, show_heading=True): """ Helper function that shows information about a process if information @@ -299,28 +310,6 @@ def show_table_line(pid, user, start_time, rss, cmdline): return False -def find_process_by_binary( - parent_pid: int | None, binary: str -) -> psutil.Process | None: - """Find a descendant of parent_pid whose argv[0] basename matches binary.""" - try: - root = psutil.Process(parent_pid) - candidates = [root] + root.children(recursive=True) - except (psutil.NoSuchProcess, psutil.AccessDenied): - return None - # Both sides use Path(...).name so any path form (relative, absolute, - # bare, symlink) matches as long as argv[0] preserves the binary's name. - target = Path(binary).name - for proc in candidates: - try: - cmdline = proc.cmdline() - except (psutil.NoSuchProcess, psutil.AccessDenied): - continue - if cmdline and Path(cmdline[0]).name == target: - return proc - return None - - def get_random_string(length: int) -> str: """ Helper function that returns a randomly chosen string of the given @@ -878,33 +867,6 @@ def timeout_seconds(value: str) -> int: return int(number) * SECONDS_PER_TIME_UNIT[unit] -def container_memory_to_bytes(memory_string: str) -> int: - """ - Parse a memory usage string from `docker stats` or `podman stats` - into bytes. Docker reports binary units (GiB, MiB) while Podman - reports decimal units (GB, MB). - """ - memory_string = memory_string.strip() - # Order matters: the first endswith match wins, and "B" is a suffix - # of every other unit, so it must stay last. - units = { - "TIB": 1024**4, - "TB": 1000**4, - "GIB": 1024**3, - "GB": 1000**3, - "MIB": 1024**2, - "MB": 1000**2, - "KIB": 1024, - "KB": 1000, - "B": 1, - } - for suffix, multiplier in units.items(): - if memory_string.upper().endswith(suffix): - number = float(memory_string[: len(memory_string) - len(suffix)]) - return int(number * multiplier) - return 0 - - def positive_int(value: str) -> int: """ Parse a CLI value as an `int` and reject anything that is not a @@ -1009,16 +971,6 @@ def stop_tailing(tail_proc: subprocess.Popen) -> None: os.killpg(pid, signal.SIGTERM) -def parse_git_hash(log_path: Path) -> str | None: - """Return the git hash printed on the first line of a QLever index log.""" - try: - first_line = log_path.read_text().splitlines()[0] - except (OSError, IndexError): - return None - match = re.search(r"git hash ([0-9a-f]+)", first_line) - return match.group(1) if match else None - - class PhaseMarkers(NamedTuple): """ Timestamp markers delimiting each phase of an index build. Any diff --git a/test/conftest.py b/test/conftest.py new file mode 100644 index 00000000..e8919e1c --- /dev/null +++ b/test/conftest.py @@ -0,0 +1,40 @@ +import os +from unittest.mock import MagicMock + +import pytest + + +# A signal to a process id or group of 1 or less goes to the caller's own +# group (0), to every process of the user (-1, which is also what `killpg(1)` +# means), or to a group given as a negative number. No test may do that: on +# 2026-09-13, a `killpg` with the `pid` of a mocked `Popen` (a `MagicMock`, +# which evaluates to 1) killed every process of the user on two machines, +# including the production servers. Such a call now fails the test instead. +@pytest.fixture(autouse=True) +def no_broadcast_signals(monkeypatch): + def guarded(name, original): + def send(target, sig, *rest): + if not isinstance(target, int) or target <= 1: + raise AssertionError( + f"os.{name}({target!r}, {sig!r}) would signal processes " + "that are not children of the test, refused" + ) + return original(target, sig, *rest) + + return send + + monkeypatch.setattr(os, "kill", guarded("kill", os.kill)) + monkeypatch.setattr(os, "killpg", guarded("killpg", os.killpg)) + + +@pytest.fixture +def mock_command(monkeypatch): + def _mock(module_name: str, function_name: str, override=None): + if override: + monkeypatch.setattr(f"{module_name}.{function_name}", override) + return override + mock = MagicMock(name=f"{function_name}_mock") + monkeypatch.setattr(f"{module_name}.{function_name}", mock) + return mock + + return _mock diff --git a/test/qeval/test_resource_monitor.py b/test/qeval/test_resource_monitor.py new file mode 100644 index 00000000..12f8f8a5 --- /dev/null +++ b/test/qeval/test_resource_monitor.py @@ -0,0 +1,155 @@ +import logging +import os +import subprocess +import time +from unittest.mock import MagicMock + +import psutil +import pytest + +from qeval.resource_monitor import ( + ResourceMonitor, + Sample, + container_memory_to_bytes, + find_process_by_binary, + sample_container, + sample_process, + sample_to_tsv_row, +) + +MODULE = "qeval.resource_monitor" + + +@pytest.mark.parametrize( + "usage,expected", + [ + ("2TiB", 2 * 1024**4), + ("1.5GiB", int(1.5 * 1024**3)), + ("512MiB", 512 * 1024**2), + ("4KiB", 4 * 1024), + ("2TB", 2 * 1000**4), + ("1.5GB", int(1.5 * 1000**3)), + ("512MB", 512 * 1000**2), + ("4KB", 4 * 1000), + ("100B", 100), + ("0B", 0), + # Longest matching suffix wins; "GiB"/"GB" must not be read as + # bare bytes via the trailing "B". + ("2GiB", 2 * 1024**3), + ("2GB", 2 * 1000**3), + # Leading/trailing whitespace and case are tolerated. + (" 1.5gib ", int(1.5 * 1024**3)), + # A space between number and unit is accepted by float(). + ("1.5 GiB", int(1.5 * 1024**3)), + ("", 0), + ("garbage", 0), + ], +) +def test_container_memory_to_bytes(usage, expected): + assert container_memory_to_bytes(usage) == expected + + +@pytest.mark.parametrize( + "sample,expected", + [ + (Sample(elapsed_s=1.0, rss=100, cpu_percent=5.0), "1.0\t100\t5.0\n"), + (Sample(), "\t\t\n"), + (Sample(elapsed_s=2.0), "2.0\t\t\n"), + # Zero is a real reading, not a missing one: it renders as "0" + # / "0.0", never as an empty column. + (Sample(elapsed_s=0.0, rss=0, cpu_percent=0.0), "0.0\t0\t0.0\n"), + ], +) +def test_sample_to_tsv_row(sample, expected): + assert sample_to_tsv_row(sample) == expected + + +def test_sample_container_parses_stats_output(mock_command): + run_cmd_mock = mock_command(MODULE, "run_command") + run_cmd_mock.return_value = "1.5GiB / 7.6GiB\t12.5%" + sample = sample_container("docker", "qlever.index.test") + assert sample.rss == int(1.5 * 1024**3) + assert sample.cpu_percent == 12.5 + + +def test_sample_container_returns_empty_on_malformed_output(mock_command): + run_cmd_mock = mock_command(MODULE, "run_command") + run_cmd_mock.return_value = "garbage" + sample = sample_container("docker", "qlever.index.test") + assert sample == Sample() + + +def test_sample_container_returns_empty_for_exiting_container(mock_command): + run_cmd_mock = mock_command(MODULE, "run_command") + run_cmd_mock.return_value = "0B / 0B\t0.00%" + sample = sample_container("docker", "qlever.index.test") + assert sample == Sample() + + +def test_sample_process_reads_rss_and_cpu(): + proc = MagicMock() + proc.memory_info.return_value.rss = 2048 + proc.cpu_percent.return_value = 7.5 + sample = sample_process(proc) + assert sample.rss == 2048 + assert sample.cpu_percent == 7.5 + + +def test_sample_process_returns_empty_when_process_gone(): + proc = MagicMock() + proc.memory_info.side_effect = psutil.NoSuchProcess(pid=123) + sample = sample_process(proc) + assert sample == Sample() + + +def test_find_process_by_binary_finds_child(): + child = subprocess.Popen(["sleep", "5"]) + try: + proc = find_process_by_binary(os.getpid(), "sleep") + assert proc is not None + assert proc.pid == child.pid + finally: + child.kill() + child.wait() + + +def test_find_process_by_binary_returns_none_when_not_running(): + assert find_process_by_binary(os.getpid(), "no-such-binary") is None + + +def read_log_rows(path): + """Split the TSV log into a list of rows, each a list of columns.""" + return [line.split("\t") for line in path.read_text().splitlines()] + + +def test_resource_monitor_logs_samples_of_child(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + with ResourceMonitor( + dataset="data", engine="testengine", binary="sleep", interval=0.05 + ): + subprocess.run(["sleep", "0.5"]) + rows = read_log_rows( + tmp_path / "data.testengine.index.resource-usage-log.tsv" + ) + assert rows[0] == ["elapsed_s", "rss", "cpu_percent"] + samples = rows[1:] + assert len(samples) >= 3 + assert all(int(rss) > 0 for _, rss, _ in samples) + elapsed = [float(elapsed_s) for elapsed_s, _, _ in samples] + assert elapsed == sorted(elapsed) + assert elapsed[0] < elapsed[-1] + + +def test_resource_monitor_without_child_writes_header_only( + tmp_path, monkeypatch, caplog +): + monkeypatch.chdir(tmp_path) + with ResourceMonitor( + dataset="data", engine="testengine", binary="sleep", interval=0.05 + ): + time.sleep(0.2) + rows = read_log_rows( + tmp_path / "data.testengine.index.resource-usage-log.tsv" + ) + assert rows == [["elapsed_s", "rss", "cpu_percent"]] + assert caplog.records[-1].levelno == logging.WARNING diff --git a/test/qlever/conftest.py b/test/qlever/conftest.py index 71607ac7..a96e69d3 100644 --- a/test/qlever/conftest.py +++ b/test/qlever/conftest.py @@ -1,32 +1,6 @@ -import os -from unittest.mock import MagicMock - import pytest -# A signal to a process id or group of 1 or less goes to the caller's own -# group (0), to every process of the user (-1, which is also what `killpg(1)` -# means), or to a group given as a negative number. No test may do that: on -# 2026-09-13, a `killpg` with the `pid` of a mocked `Popen` (a `MagicMock`, -# which evaluates to 1) killed every process of the user on two machines, -# including the production servers. Such a call now fails the test instead. -@pytest.fixture(autouse=True) -def no_broadcast_signals(monkeypatch): - def guarded(name, original): - def send(target, sig, *rest): - if not isinstance(target, int) or target <= 1: - raise AssertionError( - f"os.{name}({target!r}, {sig!r}) would signal processes " - "that are not children of the test, refused" - ) - return original(target, sig, *rest) - - return send - - monkeypatch.setattr(os, "kill", guarded("kill", os.kill)) - monkeypatch.setattr(os, "killpg", guarded("killpg", os.killpg)) - - @pytest.fixture def write_log(tmp_path): """Write bytes to a fresh log file and return its Path.""" @@ -37,16 +11,3 @@ def make(data): return path return make - - -@pytest.fixture -def mock_command(monkeypatch): - def _mock(module_name: str, function_name: str, override=None): - if override: - monkeypatch.setattr(f"{module_name}.{function_name}", override) - return override - mock = MagicMock(name=f"{function_name}_mock") - monkeypatch.setattr(f"{module_name}.{function_name}", mock) - return mock - - return _mock diff --git a/test/qlever/resource_usage/test_plot_util.py b/test/qlever/resource_usage/test_plot_util.py new file mode 100644 index 00000000..c6d01513 --- /dev/null +++ b/test/qlever/resource_usage/test_plot_util.py @@ -0,0 +1,8 @@ +from qlever.resource_usage.plot_util import bands_from_durations + + +def test_bands_from_durations_lays_phases_back_to_back(): + bands = bands_from_durations( + {"Load": 10.0, "Optimize": 5.0, "TOTAL time": 15.0} + ) + assert bands == [("Load", 0.0, 10.0), ("Optimize", 10.0, 15.0)] diff --git a/test/qlever/resource_usage/test_usage_plot.py b/test/qlever/resource_usage/test_usage_plot.py index b581e897..9b31f161 100644 --- a/test/qlever/resource_usage/test_usage_plot.py +++ b/test/qlever/resource_usage/test_usage_plot.py @@ -1,3 +1,6 @@ +from pathlib import Path +from types import SimpleNamespace + import pytest # The plot extra (numpy, matplotlib) is optional, so skip this whole @@ -9,6 +12,7 @@ build_plot_subtitle, compute_phase_boundaries, downsample_for_plot, + parse_git_hash, pick_time_unit, read_usage_tsv, render_usage_plot, @@ -39,6 +43,30 @@ def test_pick_time_unit(seconds, expected): assert pick_time_unit(seconds) == expected +@pytest.mark.parametrize( + "first_line,expected", + [ + ("qlever-server, git hash 1a2b3c4, compiled", "1a2b3c4"), + ("no hash on this line", None), + ], +) +def test_parse_git_hash_reads_first_line_only(first_line, expected, tmp_path): + path = tmp_path / "index-log.txt" + # Second line also carries a hash; only the first line should count. + path.write_text(first_line + "\nsomething git hash deadbeef here\n") + assert parse_git_hash(path) == expected + + +def test_parse_git_hash_missing_file(tmp_path): + assert parse_git_hash(tmp_path / "nope.txt") is None + + +def test_parse_git_hash_empty_file(tmp_path): + path = tmp_path / "empty.txt" + path.write_text("") + assert parse_git_hash(path) is None + + @pytest.mark.parametrize( "triples,expected_fragment", [ @@ -209,25 +237,78 @@ def test_compute_phase_boundaries_skips_incomplete_phase(tmp_path): assert phases == {} -def test_render_usage_plot_missing_tsv(tmp_path): - assert render_usage_plot("missing", "QLever", output_dir=tmp_path) is None +def plot_args(name): + """The `args` attributes that `render_usage_plot` reads.""" + return SimpleNamespace( + name=name, + engine_short_name="qlever", + engine_display_name="QLever", + resource_usage_plot_max_points=500, + stxxl_memory="", + settings_json="{}", + ) + + +def test_render_usage_plot_missing_tsv(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + assert render_usage_plot(plot_args("missing")) is None -def test_render_usage_plot_header_only_tsv_renders_nothing(tmp_path): +def test_render_usage_plot_header_only_tsv_renders_nothing( + tmp_path, monkeypatch +): # A TSV with only the header (no samples) must not report success # or leave a PNG behind. + monkeypatch.chdir(tmp_path) tsv_path = tmp_path / "data.index.resource-usage-log.tsv" tsv_path.write_text("elapsed_s\trss\tcpu_percent\n") - assert render_usage_plot("data", "QLever", output_dir=tmp_path) is None + assert render_usage_plot(plot_args("data")) is None assert not (tmp_path / "data.resource-usage-plot.png").exists() -def test_render_usage_plot_falls_back_to_old_tsv_name(tmp_path): +def test_render_usage_plot_falls_back_to_old_tsv_name(tmp_path, monkeypatch): # Older qlever versions wrote the log without the `.index.` part. + monkeypatch.chdir(tmp_path) tsv_path = tmp_path / "data.resource-usage-log.tsv" tsv_path.write_text( "elapsed_s\trss\tcpu_percent\n1.0\t100\t5.0\n2.0\t200\t6.0\n" ) - plot_path = render_usage_plot("data", "QLever", output_dir=tmp_path) - assert plot_path == tmp_path / "data.resource-usage-plot.png" - assert plot_path.exists() + plot_path = render_usage_plot(plot_args("data")) + assert plot_path == Path("data.resource-usage-plot.png") + assert (tmp_path / plot_path).exists() + + +def test_render_usage_plot_passes_args_and_log_to_engine_hooks( + tmp_path, monkeypatch +): + # Another engine passes its own hooks and gets `.` + # file names. + monkeypatch.chdir(tmp_path) + tsv_path = tmp_path / "data.testengine.index.resource-usage-log.tsv" + tsv_path.write_text( + "elapsed_s\trss\tcpu_percent\n1.0\t100\t5.0\n2.0\t200\t6.0\n" + ) + received = {} + + def overlay(args, log_path): + received["overlay"] = (args, log_path) + return [("Load", 0.0, 1.0)] + + def subtitle(args, log_path): + received["subtitle"] = (args, log_path) + return "testengine v1" + + args = plot_args("data") + args.engine_short_name = "testengine" + plot_path = render_usage_plot( + args, + engine_overlay=overlay, + engine_subtitle=subtitle, + ) + log_path = Path("data.index-log.txt") + assert received == { + "overlay": (args, log_path), + "subtitle": (args, log_path), + } + assert plot_path == Path("data.testengine.resource-usage-plot.png") + assert (tmp_path / plot_path).exists() diff --git a/test/qlever/test_util.py b/test/qlever/test_util.py index 664ce741..3725f68e 100644 --- a/test/qlever/test_util.py +++ b/test/qlever/test_util.py @@ -3,10 +3,8 @@ import pytest from qlever.util import ( - container_memory_to_bytes, edit_option_line, get_random_string, - parse_git_hash, parse_timeout, positive_int, stop_systemd_unit, @@ -33,49 +31,6 @@ def test_get_random_string(): assert random_string_1 != random_string_2 -@pytest.mark.parametrize( - "usage,expected", - [ - ("2TiB", 2 * 1024**4), - ("1.5GiB", int(1.5 * 1024**3)), - ("512MiB", 512 * 1024**2), - ("4KiB", 4 * 1024), - ("2TB", 2 * 1000**4), - ("1.5GB", int(1.5 * 1000**3)), - ("512MB", 512 * 1000**2), - ("4KB", 4 * 1000), - ("100B", 100), - ("0B", 0), - # Longest matching suffix wins; "GiB"/"GB" must not be read as - # bare bytes via the trailing "B". - ("2GiB", 2 * 1024**3), - ("2GB", 2 * 1000**3), - # Leading/trailing whitespace and case are tolerated. - (" 1.5gib ", int(1.5 * 1024**3)), - # A space between number and unit is accepted by float(). - ("1.5 GiB", int(1.5 * 1024**3)), - ("", 0), - ("garbage", 0), - ], -) -def test_container_memory_to_bytes(usage, expected): - assert container_memory_to_bytes(usage) == expected - - -@pytest.mark.parametrize( - "first_line,expected", - [ - ("qlever-server, git hash 1a2b3c4, compiled", "1a2b3c4"), - ("no hash on this line", None), - ], -) -def test_parse_git_hash_reads_first_line_only(first_line, expected, tmp_path): - path = tmp_path / "index-log.txt" - # Second line also carries a hash; only the first line should count. - path.write_text(first_line + "\nsomething git hash deadbeef here\n") - assert parse_git_hash(path) == expected - - @pytest.mark.parametrize("value,expected", [("1", 1), ("500", 500)]) def test_positive_int_accepts(value, expected): assert positive_int(value) == expected @@ -94,16 +49,6 @@ def test_positive_int_rejects_non_integer(value): positive_int(value) -def test_parse_git_hash_missing_file(tmp_path): - assert parse_git_hash(tmp_path / "nope.txt") is None - - -def test_parse_git_hash_empty_file(tmp_path): - path = tmp_path / "empty.txt" - path.write_text("") - assert parse_git_hash(path) is None - - @pytest.mark.parametrize("value", ["30s", "5min", "2h"]) def test_parse_timeout_accepts_every_unit(value): assert parse_timeout(value) == value