datalad-core/datalad_core/services/task_suite.py

496 lines
16 KiB
Python

import enum
import threading
from collections.abc import (
Callable,
Hashable,
Iterator,
)
from concurrent.futures import (
ALL_COMPLETED,
FIRST_COMPLETED,
FIRST_EXCEPTION,
Executor,
Future,
as_completed,
)
from concurrent.futures import (
wait as wait_futures,
)
from queue import (
Empty as QueueEmpty,
)
from queue import (
Queue,
)
from textwrap import indent
from typing import (
Generic,
Literal,
Self,
TypeVar,
)
from datasalad.progress import ProgressHandler
TaskResultType = TypeVar('TaskResultType')
MappedTaskResultType = TypeVar('MappedTaskResultType')
class FutureWaitModes(enum.StrEnum):
"""All wait modes for :func:`concurrent.futures.wait`"""
FIRST_COMPLETED = FIRST_COMPLETED
FIRST_EXCEPTION = FIRST_EXCEPTION
ALL_COMPLETED = ALL_COMPLETED
class TaskSuiteError(RuntimeError):
def __init__(
self,
*,
message: str = '',
errors: list[BaseException] | None = None,
) -> None:
"""Report errors that occurred in multiple tasks of a suite
A list of individual task-exceptions can be given. The
:meth:`TaskSuite.finalize` method can be used to produce
such a list.
"""
super().__init__(self, message)
self.errors = errors if errors else []
def __str__(self) -> str:
explain = '\n'.join(indent(str(e), ' ') for e in self.errors)
return f'{len(self.errors)} task(s) errored\n{explain}'
class TaskResult(Generic[TaskResultType]):
"""MIKE"""
def __init__(self, value: TaskResultType | Exception):
self.value = value
def map(
self,
f: Callable[[TaskResultType], MappedTaskResultType],
) -> 'TaskResult[MappedTaskResultType] | TaskResult[TaskResultType] | TaskResult[Exception]':
if isinstance(self.value, Exception):
return self
try:
return TaskResult(f(self.value))
except Exception as e: # noqa: BLE001
return TaskResult(e)
class TaskSuiteResults:
"""Read-only wrapper around a task suite (result queue)"""
def __init__(self, ts: 'TaskSuite') -> None:
self._ts = ts
def __iter__(self) -> Self:
return self
def __next__(self) -> TaskResult:
with self._ts._results_available_lock: # noqa: SLF001
tasks_running = len(self._ts._tasks_pending) > 0 # noqa: SLF001
try:
return self._ts._results.get(block=False) # noqa: SLF001
except QueueEmpty:
self._ts._results_available_or_tasks_done.clear() # noqa: SLF001
# no items in the queue
if not tasks_running:
# no tasks were running, no chance that there could be
# more results
self._ts.close()
raise StopIteration
self._ts._results_available_or_tasks_done.wait() # noqa: SLF001
return self.__next__()
class TaskSuite:
"""Convenience utility for working with :mod:`concurrent.futures`
An instance of this class wraps a :class:`concurrent.futures.Executor`
instance, and supports the submission of callables (here called "tasks")
for execution. The resulting :class:`concurrent.futures.Future` instances
are tracked internally (available via :meth:`TaskSuite.tasks`). This
grouping of tasks in a "suite" helps organizing the execution of unrelated
tasks via a single, common executor (which may be used to control a global
level of parallelization).
Usage patterns
--------------
Context manager
~~~~~~~~~~~~~~~
When used as a context manager, a :class:`TaskSuite` can wrap any number of
tasks, and wait for them to be completed. Depending on the choice of
``executor`` the task can run serially or in parallel. A
``progress_handler`` (see :class:`datasalad.progress.ProgressHandler`) can
be used to report on the task suite and its completion.
>>> from concurrent.futures import ThreadPoolExecutor
>>> import sys
>>> from time import sleep
>>> from datasalad.progress import FileIOProgressHandler
>>>
>>> def worker():
... sleep(0.1)
... return
>>>
>>> with TaskSuite(
... ThreadPoolExecutor(),
... progress_handler=FileIOProgressHandler(sys.stdout),
... description="Work package 1",
... exit_message="Done!",
... ) as suite:
... task = suite.submit(worker)
Work package 1: <working>
Done!
>>> print(f"DONE? {task.done()}!")
DONE? True!
Task suite composer
~~~~~~~~~~~~~~~~~~~
For more complex use cases, involving many, possibly interdependent task,
it may be useful to wrap the task suite creation into a dedicated
"composer".
>>> def task2():
... return 2
>>> def task1(ts):
... sleep(0.1)
... ts.submit(task2)
... return 1
>>> def mysuite():
... ts = TaskSuite(ThreadPoolExecutor())
... ts.submit(task1, ts)
... return ts
>>> with mysuite() as suite:
... assert any(t.running() for t in suite.tasks())
>>> assert {t.result() for t in suite.tasks()} == {1, 2}
Non context manager usage
~~~~~~~~~~~~~~~~~~~~~~~~~
The class provides the functionality of :func:`concurrent.futures.wait`.
The suite in the example above can also be executed in a blocking fashion
without a context manager:
>>> suite = mysuite()
>>> done, notdone = suite.wait()
>>> assert {t.result() for t in suite.tasks()} == {1, 2}
:meth:`TaskSuite.wait` provides a ``timeout`` parameter that can be used
for sorting all tasks into "done", and "not-yet-done".
Immediate processing of incoming task return values
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The class provides the functionality of
:func:`concurrent.futures.as_completed` to iterate over task return values
as the become available.
>>> suite = TaskSuite(ThreadPoolExecutor())
>>> _ = suite.submit(lambda: 1)
>>> _ = suite.submit(lambda: 2)
>>> for task in suite.as_completed():
... print(task.result())
1
2
Processing of (intermediate) task results prior task completion
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Via :meth:`TaskSuite.add_result` running tasks can submit (intermediate)
outcomes in a thread-safe manner. :meth:`TaskSuite.results` provides an
iterator over results across all tasks that enables further processing of
such results even before any task has been completed.
>>> from time import sleep
>>> suite = TaskSuite(ThreadPoolExecutor())
>>> def task1(ts):
... ts.add_result(1)
... sleep(0.1)
... ts.add_result(2)
...
>>> _ = suite.submit(task1, suite)
>>> for r in suite.results():
... print(f"{r.value} <- {any(t.done() for t in suite.tasks())}")
1 <- False
2 <- True
In order to streamline processing of results across different tasks in a
single loop, any value deposited via :meth:`TaskSuite.add_result` is
wrapped in an instance of :class:`TaskResult`.
Flow control and exception handling
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Exceptions raised in concurrently executed tasks are registered in the
respective :class:`~concurrent.futures.Future` instance. Unless retrieved
via :meth:`concurrent.futures.Future.result` or
:meth:`concurrent.futures.Future.exception` task-exceptions are silently
ignored.
Via :meth:`concurrent.futures.Future.add_done_callback` callbacks can be
registered for individual tasks. Likewise, a global callback can be
registered via the :class:`TaskSuite` parameter ``all_done_callback``. As
stated in the Python documentation ("if the callable raises an
``Exception`` [...], it will be logged and ignored"), it is not possible to
use such a callback to raise an exception.
However, an exception can be registered at :attr:`TaskSuite.exception` by
any callback. Such a registered exception will be raised (in the main
thread) on context manager exit, and by explicitly calling
:meth:`TaskSuite.as_completed`, or :meth:`TaskSuite.wait`. For other usage
patterns, :meth:`TaskSuite.close` takes care of reporting on the completion
of a task suite and raising any pending exception. :meth:`TaskSuite.wait`
can be parameterized with ``immediate_raise`` to raise any such exception
before all tasks have completed.
>>> def task():
... sleep(0.1)
... raise RuntimeError("this is bad")
>>> def finalizer(ts):
... errors = [t.exception() for t in ts.tasks() if t.exception()]
... if errors:
... ts.exception = TaskSuiteError(errors=errors)
>>> suite = TaskSuite(
... executor=ThreadPoolExecutor(),
... all_done_callback=finalizer,
... )
>>> _ = suite.submit(task)
>>> suite.wait(immediate_raise=False)
Traceback (most recent call last):
...
datalad_core.services.task_suite.TaskSuiteError: 1 task(s) errored
this is bad
>>> with TaskSuite(
... executor=ThreadPoolExecutor(),
... all_done_callback=finalizer,
... ) as suite:
... _ = suite.submit(task)
Traceback (most recent call last):
...
datalad_core.services.task_suite.TaskSuiteError: 1 task(s) errored
this is bad
Solely for reporting on the global success/failure state
:attr:`TaskSuite.failed` can be set, and determines the messaging via
any registered progress handler.
>>> def errortask():
... raise RuntimeError("this is bad")
>>> def finalizer(ts):
... if any(t.exception() for t in ts.tasks()):
... ts.failed = True
>>> with TaskSuite(
... executor=ThreadPoolExecutor(),
... all_done_callback=finalizer,
... progress_handler=FileIOProgressHandler(sys.stdout),
... description="Work package 2",
... exit_message="Done!",
... errorexit_message="Sad!",
... ) as suite:
... _ = suite.submit(errortask)
Work package 2: <working>
Sad!
"""
def __init__(
self,
executor: Executor,
*,
progress_handler: ProgressHandler | None = None,
description: str | None = None,
start_message: str | None = None,
exit_message: str | None = None,
errorexit_message: str | None = None,
all_done_callback: Callable[['TaskSuite'], None] | None = None,
# TODO: if multiprocessing would be supported, we would need
# a manager to build the proxy objects
# manager=None,
) -> None:
# TODO: make private?
self.executor = executor
self.progress_handler = progress_handler
self._messages: dict[str, str | None] = {
'start': start_message,
'exit': exit_message,
'errorexit': errorexit_message,
'description': description,
}
self._all_done_callback = all_done_callback
self._tasks_pending: set[Future] = set()
self._tasks_done: set[Future] = set()
self._umbrella_task_id: Hashable | None = None
# if manager:
# self._results: multiprocessing.Queue[TaskResult] = manager.Queue()
# self._results_available_lock = manager.Lock()
# self._results_available_or_tasks_done = manager.Event()
# else:
self._results: Queue[TaskResult] = Queue()
self._results_available_lock = threading.Lock()
self._results_available_or_tasks_done = threading.Event()
self._failed = False
self._exception: Exception | None = None
def submit(self, fn: Callable, /, *args, **kwargs) -> Future:
"""Submits a task to the executor.
All parameters are passed as-is to the executor's ``submit()``
method. The resulting :class:`~concurrent.futures.Future`
is tracked internally.
"""
# safe to call, even if it was done already
self._report_umbrella_task_start()
_f = self.executor.submit(fn, *args, **kwargs)
# first append to pending task list, tasks might exit immediately,
# and the callback wants to remove them from "pending"
self._tasks_pending.add(_f)
_f.add_done_callback(self._mark_future_as_done)
return _f
def as_completed(
self,
timeout: float | None = None,
) -> Iterator[Future]:
"""Frontend for :func:`concurrent.futures.as_completed`
All parameters are passed as-is, plus the list of tracked
futures in the suite.
"""
yield from as_completed(
self.tasks(),
timeout=timeout,
)
self.close()
def wait(
self,
*,
timeout: float | None = None,
return_when: FutureWaitModes = FutureWaitModes.ALL_COMPLETED,
immediate_raise: bool = True,
) -> tuple[set[Future], set[Future]]:
"""Frontend for :func:`concurrent.futures.wait`
All parameters are passed as-is, plus the list of tracked
futures in the suite.
"""
state = wait_futures(
self.tasks(),
timeout=timeout,
return_when=return_when,
)
if immediate_raise and self.exception:
# raises
self.close()
if not state[1]:
# no running task anymore
self.close()
return state
def close(self) -> None:
""" """
self._report_umbrella_task_end()
if self.exception:
# there could be some form of mitigation and continued
# use of the task suite. reset the exception in the suite
# before raising it
exc = self.exception
self.exception = None
raise exc
def add_result(self, res: TaskResultType) -> None:
"""Deposit (intermediate) task outcome"""
_res = TaskResult(res)
with self._results_available_lock:
self._results.put(_res)
self._results_available_or_tasks_done.set()
def __enter__(self) -> Self:
self._report_umbrella_task_start()
return self
def __exit__(self, exc_type, exc_value, traceback) -> Literal[False]:
self.wait()
# we do not want to suppress any outside exception handling
return False
@property
def failed(self) -> bool:
"""
For progress reporting only.
"""
return self._failed
@failed.setter
def failed(self, value: bool):
self._failed = value
@property
def exception(self) -> Exception | None:
"""
Setting an exception whenever an exception is already set silently
replace the previous exception.
"""
return self._exception
@exception.setter
def exception(self, value: Exception | None):
self._exception = value
def results(self) -> TaskSuiteResults:
"""Iterator"""
return TaskSuiteResults(self)
def tasks(self) -> set[Future]:
return self._tasks_pending.union(self._tasks_done)
def _mark_future_as_done(self, future):
# we add first and remove afterwards to avoid blindspots
# when composing the full task list via .tasks (with uses union())
with self._results_available_lock:
self._tasks_done.add(future)
self._tasks_pending.remove(future)
if self._tasks_pending:
return
self._results_available_or_tasks_done.set()
if self._all_done_callback:
self._all_done_callback(self)
def _report_umbrella_task_start(self) -> None:
if self._umbrella_task_id is not None:
# function was already called
return
if self.progress_handler:
ph = self.progress_handler
self._umbrella_task_id = ph.register_task(
description=self._messages['description'] or '',
message=self._messages['start'],
)
# send activity ping
ph.update_task(self._umbrella_task_id)
def _report_umbrella_task_end(self) -> None:
if self._umbrella_task_id is not None and self.progress_handler:
if self.failed:
self.progress_handler.remove_incomplete_task(
self._umbrella_task_id,
self._messages['errorexit'],
)
else:
self.progress_handler.remove_completed_task(
self._umbrella_task_id,
self._messages['exit'],
)
self._umbrella_task_id = None