Coverage for src/python/ensembl/vep/bench/endtoend.py: 99%
110 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
1# See the NOTICE file distributed with this work for additional information
2# regarding copyright ownership.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""Timing whole runs of the command line, one configuration at a time.
16``bench matrix`` times an annotator over overlaps that are already built. This times what a user
17runs: reading the VCF, loading transcripts from the indexed GFF3, fetching sequence, annotating,
18and writing the output. The difference between the two is the point -- a strategy that wins several
19times over in isolation moves the end-to-end number by whatever share of the run annotation is.
21Each run is a fresh process, so no configuration is timed against another's warmed module state,
22and the process cost a real run pays is counted rather than amortised away. The child is given this
23tree on ``PYTHONPATH``, so the benchmark measures the working copy it was started from and never an
24``ensembl-vep`` installed elsewhere.
25"""
27from __future__ import annotations
29import logging
30import os
31import statistics
32import subprocess
33import sys
34import time
35from pathlib import Path
37from attrs import field, frozen
39import ensembl.vep
40from ensembl.vep.bench.suites import Configuration
41from ensembl.vep.bench.workspace import Workspace
43__all__ = [
44 "MISMATCH_LIMIT",
45 "EndToEndRow",
46 "RunOutcome",
47 "consequence_sets",
48 "output_mismatches",
49 "repository_path",
50 "run_command",
51 "run_once",
52 "time_runs",
53]
55logger = logging.getLogger(__name__)
57MISMATCH_LIMIT = 20
58"""Output mismatches collected before the gate stops, so one broken configuration cannot flood it."""
60_CSQ_PREFIX = "CSQ="
61"""The INFO key the consequence terms are written under."""
63_RSS_UNIT_BYTES = 1 if sys.platform == "darwin" else 1024
64"""``ru_maxrss`` is bytes on macOS and kibibytes on Linux."""
67@frozen(kw_only=True, auto_attribs=True)
68class RunOutcome:
69 """What one run of the command line cost.
71 Attributes:
72 seconds (float): Wall clock of the whole process.
73 peak_rss_bytes (int): The high-water mark of the largest process in the tree -- not the sum
74 across workers, which is what a sampling profiler would report instead.
75 """
77 seconds: float
78 peak_rss_bytes: int
81@frozen(kw_only=True, auto_attribs=True)
82class EndToEndRow:
83 """One configuration's measurements over one corpus.
85 Attributes:
86 corpus (str): The corpus kind annotated.
87 configuration (str): The configuration's label, as ``bench matrix`` spells it.
88 processes (int): Worker processes the run was given.
89 variants (int): Variants in the input.
90 seconds (float): Median wall clock over the timed repeats.
91 ms_per_1k (float): Median wall clock per thousand variants.
92 variants_per_second (float): Throughput at the median.
93 peak_rss_bytes (int): Largest peak seen over the timed repeats.
94 """
96 corpus: str
97 configuration: str
98 processes: int
99 variants: int
100 seconds: float
101 ms_per_1k: float
102 variants_per_second: float
103 peak_rss_bytes: int = field(default=0)
105 def to_json(self) -> dict[str, object]:
106 """Return the row as plain JSON values."""
107 return {
108 "corpus": self.corpus,
109 "configuration": self.configuration,
110 "processes": self.processes,
111 "variants": self.variants,
112 "seconds": self.seconds,
113 "ms_per_1k": self.ms_per_1k,
114 "variants_per_second": self.variants_per_second,
115 "peak_rss_bytes": self.peak_rss_bytes,
116 }
119def repository_path() -> Path:
120 """Return the directory holding the ``ensembl`` package this process imported.
122 What makes the benchmark measure the working copy it runs from: the child gets this on
123 ``PYTHONPATH``, which takes precedence over anything installed into the interpreter.
124 """
125 return Path(ensembl.vep.__file__).resolve().parents[2]
128def child_environment() -> dict[str, str]:
129 """Return the environment for a run, with this tree ahead of any installed copy."""
130 environment = dict(os.environ)
131 existing = environment.get("PYTHONPATH")
132 tree = str(repository_path())
133 environment["PYTHONPATH"] = f"{tree}{os.pathsep}{existing}" if existing else tree
134 return environment
137def run_command(
138 configuration: Configuration, *, processes: int, workspace: Workspace, output: Path
139) -> list[str]:
140 """Return the command line for one run of one configuration.
142 Args:
143 configuration (Configuration): The strategy and caches to run with.
144 processes (int): Worker processes for the run.
145 workspace (Workspace): The corpus the run annotates.
146 output (Path): Where the run writes its annotated VCF.
148 Returns:
149 list[str]: The argv, invoking this tree's CLI module rather than an installed entry point.
150 """
151 caches = configuration.caches
152 return [
153 sys.executable, "-m", "ensembl.vep.cli", "run", "default",
154 "--input_file", str(workspace.vcf_path),
155 "--gff", str(workspace.indexed_gff3_path),
156 "--fasta", str(workspace.fasta_path),
157 "--output_file", str(output),
158 "--force_overwrite",
159 "--no_stats",
160 "--no_progress",
161 "--annotator", configuration.strategy,
162 "--batch_size", str(configuration.batch_size),
163 "--processes", str(processes),
164 "--zone_map" if "zonemap" in caches else "--no-zone_map",
165 "--codon_cache" if "codon" in caches else "--no-codon_cache",
166 "--mapper_cache" if "mapper" in caches else "--no-mapper_cache",
167 ] # fmt: skip
170def run_once(command: list[str], *, log_path: Path) -> RunOutcome:
171 """Run one command to completion, timing it and reading its resource usage.
173 Stderr goes to a file rather than a pipe: the run is waited for with ``os.wait4``, which cannot
174 drain a pipe, and a chatty run would otherwise fill it and deadlock.
176 Args:
177 command (list[str]): The argv to run.
178 log_path (Path): Where the run's stderr is written.
180 Returns:
181 RunOutcome: The wall clock and peak resident size.
183 Raises:
184 subprocess.CalledProcessError: If the run fails, carrying its log as output.
185 """
186 started = time.perf_counter()
187 with log_path.open("wb") as log:
188 process = subprocess.Popen( # pylint: disable=consider-using-with
189 command, env=child_environment(), stdout=subprocess.DEVNULL, stderr=log
190 )
191 _pid, status, usage = os.wait4(process.pid, 0)
192 elapsed = time.perf_counter() - started
194 # The child is already reaped, so tell Popen rather than letting it wait for a process that
195 # no longer exists.
196 process.returncode = os.waitstatus_to_exitcode(status)
197 if process.returncode != 0:
198 raise subprocess.CalledProcessError(
199 process.returncode, command, stderr=log_path.read_text(encoding="utf-8", errors="replace")
200 )
201 return RunOutcome(seconds=elapsed, peak_rss_bytes=usage.ru_maxrss * _RSS_UNIT_BYTES)
204def time_runs(command: list[str], *, log_path: Path, repeats: int, warmup: int) -> list[RunOutcome]:
205 """Run a command untimed ``warmup`` times, then return the outcome of ``repeats`` timed runs.
207 Raises:
208 subprocess.CalledProcessError: If any run fails.
209 """
210 for _ in range(warmup):
211 run_once(command, log_path=log_path)
212 return [run_once(command, log_path=log_path) for _ in range(repeats)]
215def summarise(
216 outcomes: list[RunOutcome], *, corpus: str, configuration: str, processes: int, variants: int
217) -> EndToEndRow:
218 """Return the row a configuration's timed runs add up to.
220 Args:
221 outcomes (list[RunOutcome]): The timed runs, at least one.
222 corpus (str): The corpus kind annotated.
223 configuration (str): The configuration's label.
224 processes (int): Worker processes the runs were given.
225 variants (int): Variants in the input.
227 Returns:
228 EndToEndRow: The median wall clock, what it works out to per variant, and the largest peak.
229 """
230 seconds = statistics.median(outcome.seconds for outcome in outcomes)
231 return EndToEndRow(
232 corpus=corpus,
233 configuration=configuration,
234 processes=processes,
235 variants=variants,
236 seconds=seconds,
237 ms_per_1k=(seconds * 1000.0 * 1000.0 / variants) if variants else 0.0,
238 variants_per_second=(variants / seconds) if seconds else 0.0,
239 peak_rss_bytes=max(outcome.peak_rss_bytes for outcome in outcomes),
240 )
243def consequence_sets(output: Path) -> dict[tuple[str, str, str, str], frozenset[str]]:
244 """Return each variant's consequence terms, keyed by the variant it was called on.
246 Terms are compared as a set per variant rather than as file bytes: entry order can legitimately
247 follow the worker count and the buffering, and neither of those is a wrong answer.
249 Args:
250 output (Path): An annotated VCF.
252 Returns:
253 dict[tuple[str, str, str, str], frozenset[str]]: Terms by
254 ``(region, position, reference, alternates)``.
255 """
256 terms_by_variant: dict[tuple[str, str, str, str], frozenset[str]] = {}
257 with output.open(encoding="utf-8") as handle:
258 for line in handle:
259 if line.startswith("#"):
260 continue
261 columns = line.rstrip("\n").split("\t")
262 if len(columns) < 8:
263 continue
264 key = (columns[0], columns[1], columns[3], columns[4])
265 terms: set[str] = set()
266 for entry in _csq_entries(columns[7]):
267 terms.update(term for term in entry.split("&") if term)
268 terms_by_variant[key] = frozenset(terms)
269 return terms_by_variant
272def _csq_entries(info: str) -> list[str]:
273 """Return the consequence field of every CSQ entry in one INFO column."""
274 entries: list[str] = []
275 for field_text in info.split(";"):
276 if not field_text.startswith(_CSQ_PREFIX):
277 continue
278 for entry in field_text[len(_CSQ_PREFIX) :].split(","):
279 parts = entry.split("|")
280 if len(parts) > 1: 280 ↛ 278line 280 didn't jump to line 278 because the condition on line 280 was always true
281 entries.append(parts[1])
282 return entries
285def output_mismatches(reference: Path, candidate: Path) -> list[str]:
286 """Return how a candidate's output differs from the reference's, up to ``MISMATCH_LIMIT``.
288 Args:
289 reference (Path): The reference configuration's annotated VCF.
290 candidate (Path): The configuration being checked.
292 Returns:
293 list[str]: One description per differing variant; empty when the two agree.
294 """
295 expected = consequence_sets(reference)
296 actual = consequence_sets(candidate)
297 mismatches: list[str] = []
299 for key, terms in expected.items():
300 if len(mismatches) >= MISMATCH_LIMIT:
301 break
302 found = actual.get(key)
303 if found is None:
304 mismatches.append(f"{_variant(key)}: missing from the output")
305 elif found != terms:
306 mismatches.append(f"{_variant(key)}: expected {sorted(terms)}, got {sorted(found)}")
308 for key in actual:
309 if len(mismatches) >= MISMATCH_LIMIT:
310 break
311 if key not in expected:
312 mismatches.append(f"{_variant(key)}: not in the reference output")
313 return mismatches
316def _variant(key: tuple[str, str, str, str]) -> str:
317 """Return a variant key as ``region:position ref/alt``."""
318 region, position, reference, alternates = key
319 return f"{region}:{position} {reference}/{alternates}"