Coverage for src/python/ensembl/vep/workflow/executor.py: 98%
136 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"""Payload execution: who runs the work, and how the work is grouped into payloads.
16Three things, one per step of a run's spine. ``ExecutionSpec`` is what the configuration asked
17for. ``PayloadIterator`` groups a source's records into the payloads one unit of work holds.
18``Executor`` runs them against a ``Worker``, serially or across processes, and yields the results
19in payload order whatever order they finish in.
20"""
22from __future__ import annotations
24import multiprocessing
25from collections.abc import Callable, Iterable, Iterator
26from concurrent.futures import Future, ProcessPoolExecutor
27from typing import Any, Generic, TypeVar, cast
29from attrs import define, field
31from ensembl.vep.common.enums import StartMethod
32from ensembl.vep.config.sections.common.execution import ExecutionConfig
33from ensembl.vep.workflow.worker.base import Worker
35__all__ = ["ExecutionSpec", "Executor", "PayloadIterator"]
37PayloadT = TypeVar("PayloadT")
38RecordT = TypeVar("RecordT")
39ResultT = TypeVar("ResultT")
42@define(frozen=True, kw_only=True, auto_attribs=True)
43class ExecutionSpec:
44 """Worker-local annotation execution settings.
46 The payload and result types are deliberately absent from this value object. They must be
47 serialisable transport values whenever ``processes`` exceeds one; live model objects remain
48 inside a worker.
50 Attributes:
51 processes (int): Number of independent worker processes.
52 start_method (StartMethod): Multiprocessing context, or ``auto`` for the platform default.
53 threads (int): Threads available to independent tracks in each worker.
54 buffer_size (int): Maximum records in one sequence-region input buffer.
55 annotation_window (int): Maximum variations retaining overlap graphs at one time.
56 max_in_flight (int | None): Explicit submitted-payload cap, or None to match workers.
57 """
59 processes: int = 1
60 start_method: StartMethod = StartMethod.AUTO
61 threads: int = 1
62 buffer_size: int = 5000
63 annotation_window: int = 1024
64 max_in_flight: int | None = None
66 def __attrs_post_init__(self) -> None:
67 """Reject values that could drop work or create an unusable executor."""
69 if self.processes < 1:
70 raise ValueError("processes must be at least one")
71 if self.threads < 1:
72 raise ValueError("threads must be at least one")
73 if self.buffer_size < 1:
74 raise ValueError("buffer_size must be at least one")
75 if self.annotation_window < 1:
76 raise ValueError("annotation_window must be at least one")
77 if self.max_in_flight is not None and self.max_in_flight < 1:
78 raise ValueError("max_in_flight must be at least one")
80 @classmethod
81 def from_config(cls, config: ExecutionConfig) -> ExecutionSpec:
82 """Build a specification from the declared execution options."""
83 return cls(
84 processes=config.processes,
85 start_method=config.start_method,
86 threads=config.threads,
87 buffer_size=config.buffer_size,
88 annotation_window=config.annotation_window,
89 max_in_flight=config.max_in_flight,
90 )
92 @property
93 def effective_max_in_flight(self) -> int:
94 """Return the explicit queue cap, defaulting to one payload per worker."""
95 if self.max_in_flight is not None:
96 return self.max_in_flight
97 return self.processes
99 def multiprocessing_context(self) -> multiprocessing.context.BaseContext | None:
100 """Return the multiprocessing context to run workers in.
102 ``auto`` means fork wherever a forked worker is safe, which is what keeps the parallel path
103 fast: a forked worker inherits the loaded package, its catalogue and its caches, while a
104 spawned one re-imports all of it. Measured on 10,000 ClinVar variants across four workers,
105 spawning cost about 30% of wall time. Threads are the exception -- forking a process that
106 already has them is unsafe -- so a threaded run takes the platform default instead.
107 """
108 if self.start_method is not StartMethod.AUTO:
109 return multiprocessing.get_context(self.start_method.value)
110 if self.processes == 1 or self.threads > 1:
111 return None
112 if StartMethod.FORK.value not in multiprocessing.get_all_start_methods(): 112 ↛ 113line 112 didn't jump to line 113 because the condition on line 112 was never true
113 return None
114 return multiprocessing.get_context(StartMethod.FORK.value)
117@define(kw_only=True, auto_attribs=True)
118class PayloadIterator(Generic[RecordT]):
119 """One source's records, grouped into the payloads an executor runs.
121 Here rather than in the source being read: a source says what a record is and which region it
122 sits on, and how many records make one unit of work is an execution setting (``buffer_size``).
124 Attributes:
125 records (Iterable[RecordT]): The records to group, in input order. Closed with this
126 iterator, since reading them is what holds the input open.
127 batch_size (int): The most records one payload may hold.
128 region_of (Callable[[RecordT], str] | None): Name the sequence region a record sits on.
129 A payload then never spans two regions, which is what a worker's annotation tracks
130 prime from -- one region's features, fetched once for the whole payload. None groups
131 by size alone, for records that name no region.
132 """
134 records: Iterable[RecordT]
135 batch_size: int
136 region_of: Callable[[RecordT], str] | None = field(default=None)
138 def __attrs_post_init__(self) -> None:
139 """Reject a size no payload could hold a record at.
141 Raises:
142 ValueError: If ``batch_size`` is below one.
143 """
145 if self.batch_size < 1:
146 raise ValueError("batch_size must be at least one")
148 def __iter__(self) -> Iterator[tuple[RecordT, ...]]:
149 """Return this iterator's payloads, so an executor can be given it as it is."""
151 return self.payloads()
153 def payloads(self) -> Iterator[tuple[RecordT, ...]]:
154 """Yield payloads of at most ``batch_size`` records, in input order.
156 Yields:
157 Iterator[tuple[RecordT, ...]]: Each payload, closed by its size or by a region change.
158 """
160 region: str | None = None
161 payload: list[RecordT] = []
162 try:
163 for record in self.records:
164 record_region = self.region_of(record) if self.region_of is not None else None
165 if payload and (record_region != region or len(payload) == self.batch_size):
166 yield tuple(payload)
167 payload = []
168 region = record_region
169 payload.append(record)
170 if payload:
171 yield tuple(payload)
172 finally:
173 _stop_payload_iterator(self.records)
176@define(kw_only=True, auto_attribs=True)
177class Executor(Generic[PayloadT, ResultT]):
178 """Ordered payload executor with one worker per process.
180 A worker is built after its process starts and then reused, so what the executor transports is
181 the factory rather than the worker: a worker holds open sources and warm caches that neither
182 cross a process boundary nor survive a rebuild. The serial path runs the same way, against a
183 worker of its own in the calling process, so there is one execution contract rather than two.
185 Attributes:
186 specification (ExecutionSpec): Process and queue configuration.
187 worker_factory (Callable[[], Worker[PayloadT, ResultT]]): Construct one worker. It is what
188 crosses to a worker process, so it has to pickle; the worker it builds does not.
189 payload_iterator (Iterable[PayloadT]): The payloads to run, in input order, each
190 serialisable whenever ``processes`` exceeds one. A run passes a ``PayloadIterator``.
191 """
193 specification: ExecutionSpec
194 worker_factory: Callable[[], Worker[PayloadT, ResultT]]
195 payload_iterator: Iterable[PayloadT]
197 def execute(self) -> Iterator[ResultT]:
198 """Yield every payload's result in payload order, while limiting queued work.
200 Yields:
201 Iterator[ResultT]: Results in the order ``payload_iterator`` produced the payloads.
202 """
203 payloads = iter(self.payload_iterator)
204 if self.specification.processes == 1:
205 yield from self._execute_serial(payloads)
206 else:
207 yield from self._execute_parallel(payloads)
209 def _execute_serial(self, payloads: Iterator[PayloadT]) -> Iterator[ResultT]:
210 """Yield every result from one worker in the calling process."""
211 _start_worker(self.worker_factory)
212 try:
213 for payload in payloads:
214 yield cast(ResultT, _submit_payload_to_worker(payload))
215 finally:
216 _stop_payload_iterator(payloads)
218 def _execute_parallel(self, payloads: Iterator[PayloadT]) -> Iterator[ResultT]:
219 """Yield results in payload order from a pool of worker processes."""
220 pool = ProcessPoolExecutor(
221 max_workers=self.specification.processes,
222 mp_context=self.specification.multiprocessing_context(),
223 initializer=_start_worker,
224 initargs=(self.worker_factory,),
225 )
226 pending: dict[int, Future[object]] = {}
227 next_submit = 0
228 next_yield = 0
229 completed = False
231 try:
232 exhausted = False
233 while not exhausted or pending:
234 while not exhausted and len(pending) < self.specification.effective_max_in_flight:
235 try:
236 payload = next(payloads)
237 except StopIteration:
238 exhausted = True
239 break
240 pending[next_submit] = pool.submit(_submit_payload_to_worker, payload)
241 next_submit += 1
243 if not pending:
244 break
245 future = pending.pop(next_yield)
246 yield cast(ResultT, future.result())
247 next_yield += 1
248 completed = True
249 finally:
250 try:
251 _stop_payload_iterator(payloads)
252 finally:
253 _shut_down(pool, pending, completed=completed)
256_WORKER: Worker[Any, Any] | None = None
257"""This process's worker, built once before it is given any payload.
259Per process rather than per executor, because that is what it is: a worker process is initialised
260once and then runs whatever arrives. The serial path builds it the same way, in the calling
261process, which is why one run at a time per process is the contract."""
264def _start_worker(worker_factory: Callable[[], Worker[Any, Any]]) -> None:
265 """Build this process's worker, replacing one an earlier run left behind."""
266 global _WORKER # pylint: disable=global-statement
267 _WORKER = worker_factory()
270def _submit_payload_to_worker(payload: object) -> object:
271 """Run one payload against this process's worker.
273 Raises:
274 RuntimeError: If the process was never given a worker to run against.
275 """
276 if _WORKER is None:
277 raise RuntimeError("worker process was not initialised")
278 return _WORKER.run(payload)
281def _shut_down(
282 pool: ProcessPoolExecutor,
283 pending: dict[int, Future[object]],
284 *,
285 completed: bool,
286) -> None:
287 """Wait for a finished pool, or drop the queued work of an abandoned one."""
288 if completed:
289 pool.shutdown(wait=True)
290 return
291 for future in pending.values():
292 future.cancel()
293 terminate_workers = getattr(pool, "terminate_workers", None)
294 if terminate_workers is not None: 294 ↛ 297line 294 didn't jump to line 297 because the condition on line 294 was always true
295 terminate_workers()
296 else:
297 pool.shutdown(wait=False, cancel_futures=True)
300def _stop_payload_iterator(iterator: Iterable[object]) -> None:
301 """Close a payload or record iterator that owns input resources."""
302 close = getattr(iterator, "close", None)
303 if close is not None:
304 close()