datalad-core/docs/patterns/results.rst

41 lines
4.9 KiB
ReStructuredText

Functions with (multiple, concurrently) computed outcomes
---------------------------------------------------------
Design goals:
- support parallel execution of internal tasks (e.g., download multiple files)
- provide individual results as quickly as possible, and before completion of all tasks
- uniform reporting of *success* and *failure* (to be expected errors vs unexpected exceptions) to enable *external* flow control and error compensation (e.g., raise an exception early vs. eventually, and continue vs cancel concurrently running tasks)
Design concept:
A :class:`TaskSuite` is an abstraction for functions that launch multiple internal tasks in parallel and may produce multiple user-facing outcomes over time.
A function returns a :class:`TaskSuite` "immediately", while tasks keep running in the background.
Internal code can submit *callable* tasks to the suite, each tracked by a :class:`concurrent.futures.Future`.
Tasks can also push user-facing outcomes into the suite one by one via :meth:`TaskSuite.add_result`, where each outcome is wrapped in a :class:`Result` object representing success or failure uniformly.
The suite is iterable, so consumers can process outcomes as they arrive, and it also supports cancelling remaining tasks if an external error condition occurs.
The execution model is abstracted through an :class:`concurrent.futures.Executor`, so the same pattern can work with serial or parallel execution.
Implementation details:
- return type of any such function is :class:`TaskSuite`
- :class:`TaskSuite` instance is created by the respective function, one function call, one suite
- :class:`TaskSuite` instance is parameterized with a :class:`concurrent.futures.Executor` that determines *how* tasks are executed (e.g., serial or multi-threaded). The possibilities partially depend on the nature of the tasks. In some cases, it will be possible to have ``executor`` be a parameter of the function that uses a :class:`TaskSuite`, in others a function would fix this internally.
- a :class:`TaskSuite` provides an optional :class:`ProgressHandler` that internal implementations can use. It should be practical to create a :class:`TaskSuite` instance early during a function call and pass it around internally.
- a :class:`TaskSuite` task is a *callable* with an arbitrary return value. This callable is given to :meth:`TaskSuite.submit`, and its execution is tracked with a :class:`concurrent.futures.Future`. The return value can be used for internal decision making and flow control. It is not generally user-facing, or representing a function *result*.
- a :class:`TaskSuite` task can deposit user-facing outcomes (results) of any type, one-by-one using :meth:`TaskSuite.add_result`. This wraps the given value into a monad-like :class:`Result`. This is inspired by `Railway Oriented Programming <https://fsharpforfunandprofit.com/rop>`_ as an approach to represent *success* or *failure* outcomes in a uniform way that allows for simple iteration over outcome without breaking the flow (in case of exceptions), and to allow for arbitrary error-mitigation approached (e.g. retry) *outside* the original function.
- task return value and user-facing outcome are distinguished, because a single task may be long-running and produce many user-facing outcomes that should be relayed to a user faster than at task-exit.
- :class:`TaskSuite` managed deposited results using a :class:`collections.deque` as a thread-safe facility
- :class:`TaskSuite` implements ``__next__()``, and ``__iter__()`` to be able to act as an *iterator* over outcomes. This makes it possible to directly consumer a function's outcomes, e.g., in a for-loop. However, it also does not require wrapping a function call in a consumer (compared to a generator-based approach). This leaves the choice of a synchronization approach to a user (e.g., consume outcomes as soon as they arrive individually, or simply block on the completion of all tasks).
- :class:`TaskSuite` uses `:class:`threading.Event` to signal the arrival of new results or the completion of all tasks to support a blocking iterator behavior without a busy-loop.
- outcomes do not arrive in a predictable order. The implementation of a particular task needs to include enough information in a result report to enable sensible, outside ordering (e.g., associate a respective input argument).
- :meth:`TaskSuite.cancel_tasks` can be used to stop ongoing (parallel) execution of tasks, in case a relevant error condition has been detected (externally).
Open questions:
- concrete approach to cancellation of running tasks
- it is easily possible to produce dead-locks by submitting tasks that have to wait for running tasks, when maximum concurrency is already reached.
- it is questionable whether this pattern could work with parallelism without a shared-memory context (multi-threading vs multi-processing)
- capacity control is not easily possible (no generic means to "pause" tasks when too many results are produced too fast), would need to be done from outside.