Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
7a4957a
Make qlever commands engine-agnostic and clean up style issues
tanmay-9 Aug 15, 2026
3f7a67d
Apply ruff 0.16 automatic fixes
tanmay-9 Aug 15, 2026
86e3555
Remove redundant pytest import and importorskip call from test_footer.py
tanmay-9 Aug 15, 2026
50f469a
Remove not-yet accurate comment
tanmay-9 Aug 15, 2026
c290769
Add ResourceMonitor for the new engines and improve usage_plot so tha…
tanmay-9 Aug 17, 2026
cbd94dc
Add <dataset>.<engine> prefix to resource-usage log and plot for non-…
tanmay-9 Aug 18, 2026
6955a1c
Merge remote-tracking branch 'origin/main' into share-resource-usage-…
tanmay-9 Aug 18, 2026
46b1648
Merge remote-tracking branch 'origin/main' into make-qlever-engine-ag…
tanmay-9 Aug 18, 2026
f0e6902
Fix failing test
tanmay-9 Aug 18, 2026
16753b5
Merge remote-tracking branch 'origin/make-qlever-engine-agnostic' int…
tanmay-9 Aug 18, 2026
1c9fbe9
Merge remote-tracking branch 'origin/main' into share-resource-usage-…
tanmay-9 Aug 18, 2026
723b992
Merge remote-tracking branch 'origin/main' into share-resource-usage-…
tanmay-9 Sep 8, 2026
1229933
Merge remote-tracking branch 'origin/main' into share-resource-usage-…
tanmay-9 Oct 10, 2026
6c06ed6
Merge remote-tracking branch 'origin/main' into share-resource-usage-…
tanmay-9 Oct 13, 2026
ea94b51
Remove the Virtuoso-specific parts from the shared resource-usage mon…
tanmay-9 Oct 13, 2026
2d73c0e
Remove semicolons, single-letter names and engine examples from `Reso…
tanmay-9 Oct 13, 2026
6073f61
Move `ResourceMonitor` and its helpers to `qeval` and share the test …
tanmay-9 Oct 13, 2026
9c9a723
Move the shared resource-usage plot code to `plot_util` so engines pa…
tanmay-9 Oct 13, 2026
d2baf1b
Move parse_git_hash from util to usage_plot.py
tanmay-9 Oct 13, 2026
004e086
Name the plot hook types, drop the unused `output_dir` pass-through a…
tanmay-9 Oct 13, 2026
a90b9f1
Drop the test-only `output_dir` parameter from `render_usage_plot`
tanmay-9 Oct 21, 2026
76cf9a3
Remove an always-true check from `ResourceMonitor.run_loop` and type …
tanmay-9 Oct 21, 2026
6c62f75
Merge remote-tracking branch 'origin/main' into share-resource-usage-…
tanmay-9 Oct 21, 2026
0b48f14
Merge remote-tracking branch 'origin/main' into share-resource-usage-…
tanmay-9 Nov 2, 2026
4b97520
Fix resource monitor wait interval timing
tanmay-9 Nov 2, 2026
462aa09
Merge remote-tracking branch 'origin/main' into share-resource-usage-…
tanmay-9 Nov 13, 2026
28cbcbf
Test `ResourceMonitor` against a real child process and log the peak RSS
tanmay-9 Nov 13, 2026
fb77f26
Skip the RSS 0 reading of an exiting process in `ResourceMonitor`
tanmay-9 Nov 13, 2026
0f28941
Skip the memory 0 reading of an exiting container in `ResourceMonitor`
hannahbast Nov 20, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
249 changes: 249 additions & 0 deletions src/qeval/resource_monitor.py
Original file line number Diff line number Diff line change
@@ -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
`<system> 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
67 changes: 4 additions & 63 deletions src/qlever/commands/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Loading
Loading