Skip to content

How to run background processing

A component that computes something slow, such as the median of every frame of a scan, can hand the work to the session's threads. The window and the run's other callbacks keep going while the work runs, and the result comes back to the component when it is ready. You ask the session for an executor, submit a function to it, and take the result with then. How background computation works explains what the session does behind the executor.

Prerequisites

You need a session and a presenter that receives the documents of a run. The blocks below are parts of one script, and the whole script is at the end.

Write the function

Put the work in a function that takes everything it needs as arguments and returns its result:

def median_of(frames: list[NDArray[np.uint16]]) -> NDArray[np.float64]:
    return np.median(np.stack(frames), axis=0)

The function reads nothing from the component, so it can run on any thread while the component goes on receiving documents. A thread helps only when the function spends its time in code that lets other threads run meanwhile, as numpy does in np.median. Code written in plain Python takes turns with every other thread, the window's included, so it runs no faster on a thread and slows the window down while it runs.

Choose an executor

Ask for a ThreadExecutor when the work lets go of the GIL, as np.median does, and for a ProcessExecutor when it is Python code that holds it. A ProcessExecutor runs each call in one of the component's own worker processes, so plain Python there runs alongside the window instead of taking turns with it. The cost is a copy: the call's arguments and its result travel between the processes, which for a stack of camera frames can take longer than the computation. Send large arrays through a shared block shows how to avoid most of that copy.

A call sent to a worker process travels by name, so the function must be defined at the top level of a module the worker can import. submit refuses a lambda, a function defined inside another one and a bound method. It refuses a function defined in the script you run too, because the functions of a component's pool belong in a module next to the component. Keep such functions in a module that doesn't import qtpy, because every worker that imports the module loads Qt too. Both executors take the same calls, so the rest of this page applies to either, except for the counts Read what the pool did describes.

Ask for an executor

Annotate a constructor parameter with ThreadExecutor:

class MedianPresenter(DocumentRouter, Loggable):
    sig_median = Signal(object)

    def __init__(
        self, name: str, executor: ThreadExecutor, *, source: str = "camera"
    ) -> None:
        super().__init__()
        self.name = name
        self.source = source
        self._executor = executor
        self._frames: list[NDArray[np.uint16]] = []

The session gives the presenter an executor of its own, over the thread pool every component shares. The executor is named after the component, its owner, so every count and log line about its calls says who made them. When the session shuts the presenter down, it shuts the executor down too, so you write no cleanup for it.

A setup method can ask for a ThreadExecutor with the same annotation, and receives the object the constructor received. A component that asks for the pool itself, ThreadPool, is skipped with a message naming the executor to ask for instead.

Submit the work

Call submit with the function and its arguments, and pass then what to do with the result:

def start(self, doc: RunStart) -> RunStart:
    self._frames = []
    return doc

def event(self, doc: Event) -> Event:
    self._frames.append(np.asarray(doc["data"][self.source]))
    return doc

def stop(self, doc: RunStop) -> RunStop:
    if self._frames:
        future = self._executor.submit(median_of, self._frames)
        future.then(self.sig_median.emit, self._report)
    return doc

def _report(self, error: BaseException) -> None:
    self.logger.warning(f"No median for this run: {error}")

submit returns at once with a Future, so stop returns while the median is still running. When the call finishes, then hands its result to the first callback, here the signal's emit, or the exception it raised to the second. Without a second callback, a failure is logged with the name of the first one.

In a Qt session the callback runs on the main thread, so it may touch a widget. A callback marked with @slot(thread=...) runs on the thread the marker names instead, where "current" stands for the thread the session was built on. In a session whose frontend names no thread for results, such as one without a GUI, the callback runs on the thread that finished the call; Frontend.results_thread is where a frontend names it.

A result that arrives after the session has shut its component down is dropped and never reaches the callback.

A coroutine slot can await the result instead:

median = await self._executor.run(median_of, frames)

Some libraries start threads of their own, which the session cannot limit, and take the number to start as an argument, such as workers= in scipy.fft. Pass them self._executor.native_threads, the number the session chose for each call.

Show the result in a view

The presenter publishes the median on a signal, so a view shows it in a slot:

class MedianView(QWidget):
    placement: Placement = Dock("right")

    def __init__(self, name: str, parent: QWidget) -> None:
        super().__init__(parent)
        self.name = name
        self.label = QLabel("No median yet")
        QVBoxLayout(self).addWidget(self.label)

    @slot
    def show_median(self, median: NDArray[np.float64]) -> None:
        self.label.setText(f"Median ready, mean {median.mean():.1f}")

Link the two in the session:

class MyApp(QtSession):
    median: AsPresenter[MedianPresenter]
    median_view: AsView[MedianView]

    def wire(self) -> Iterator[Link]:
        yield self.median.sig_median, self.median_view.show_median


if __name__ == "__main__":
    MyApp().run()

Start the session under the main guard

A worker process starts by importing the script you ran, so everything at the top level of the script runs again in every worker. Only the code under if __name__ == "__main__": doesn't, so build and run the session there:

if __name__ == "__main__":
    MyApp().run()

A script without the guard starts no workers

Without the guard, each worker would build a second session while it starts. The session refuses that with RuntimeError: Session.build ran inside a worker process, the worker never starts, and the calls of the component fail. Put the session's start under if __name__ == "__main__":.

Send large arrays through a shared block

A ProcessExecutor copies a call's arguments into the worker, so a stack of frames sent at the end of a run makes stop wait for the copy. Write the frames into a block of shared memory as they arrive instead, and send the worker only the block's name. The function opens the block by name and reads the frames where they are:

def fit_stack(name: str, shape: tuple[int, ...], dtype: str) -> NDArray[np.float64]:
    block = shared_memory.SharedMemory(name=name)
    stack = np.ndarray(shape, dtype, block.buf)
    try:
        return np.asarray(stack.mean(axis=0), dtype=np.float64)
    finally:
        del stack
        block.close()

The presenter asks for a ProcessExecutor:

class StackPresenter(DocumentRouter, Loggable):
    sig_fit = Signal(object)

    def __init__(
        self,
        name: str,
        executor: ProcessExecutor,
        *,
        source: str = "camera",
        frames: int = 40,
    ) -> None:
        super().__init__()
        self.name = name
        self.source = source
        self._executor = executor
        self._count = frames
        self._next = 0
        self._block: shared_memory.SharedMemory | None = None
        self._stack: NDArray[np.generic] | None = None
        self._sent: set[shared_memory.SharedMemory] = set()

It makes the block when the run describes its data, with room for the number of frames it is given, and fills one frame per event. At stop only the name, the shape and the type cross to the worker:

def start(self, doc: RunStart) -> RunStart:
    self._next = 0
    return doc

def descriptor(self, doc: EventDescriptor) -> EventDescriptor:
    if self.source not in doc["data_keys"]:
        return doc
    if self._block is not None:
        self._stack = None
        self._release(self._block)
    key = doc["data_keys"][self.source]
    shape = (self._count, *(int(n or 0) for n in key["shape"]))
    dtype = np.dtype(key.get("dtype_numpy", "uint16"))
    size = max(1, int(np.prod(shape)) * dtype.itemsize)
    self._block = shared_memory.SharedMemory(create=True, size=size)
    self._stack = np.ndarray(shape, dtype, self._block.buf)
    return doc

def event(self, doc: Event) -> Event:
    if (
        self._stack is not None
        and self._next < self._count
        and self.source in doc["data"]
    ):
        self._stack[self._next] = doc["data"][self.source]
        self._next += 1
    return doc

def stop(self, doc: RunStop) -> RunStop:
    if self._block is None or self._stack is None:
        return doc
    block, self._block = self._block, None
    shape, dtype = self._stack.shape, self._stack.dtype.str
    self._stack = None
    self._sent.add(block)
    future = self._executor.submit(fit_stack, block.name, shape, dtype)
    future.then(partial(self._publish, block), partial(self._report, block))
    return doc

The block belongs to the presenter, so the presenter closes and unlinks it once the result or the error comes back, and before it makes the block of the next descriptor. A session shutting down drops the result of a call still running, so shutdown releases every block it has not released yet:

def _publish(
    self, block: shared_memory.SharedMemory, fit: NDArray[np.float64]
) -> None:
    self._release(block)
    self.sig_fit.emit(fit)

def _report(self, block: shared_memory.SharedMemory, error: BaseException) -> None:
    self._release(block)
    self.logger.warning(f"No fit for this run: {error}")

def _release(self, block: shared_memory.SharedMemory) -> None:
    self._sent.discard(block)
    block.close()
    with suppress(FileNotFoundError):
        block.unlink()

def shutdown(self) -> None:
    self._stack = None
    for block in [*self._sent, self._block]:
        if block is not None:
            self._release(block)
    self._block = None

Warm up from setup

The first call of a function is often slower than the next ones, because a library loads or prepares something on first use. Submit a small call from setup, so that cost is paid before the first run:

def setup(self) -> None:
    blank = np.zeros((8, 8), dtype=np.uint16)
    self._executor.submit(median_of, [blank, blank]).then(self._warmed_up)

def _warmed_up(self, median: NDArray[np.float64]) -> None:
    self.logger.info("Median ready")

The session starts its pools only after every component's setup has returned. So a call submitted from setup waits in the pool, and runs first when the pool starts.

setup cannot wait for its own calls

A call submitted from setup cannot finish before setup returns, so waiting for it there would wait forever. result() and exception() without a timeout refuse to wait and raise RuntimeError: the pool starts after every setup; use .then(...), and the build logs that the component could not be set up. concurrent.futures.wait and as_completed don't raise; they hang the build. Take the result with then instead.

Choose how the cores are split

The session decides how many threads the pool has and how many threads each call's native libraries may use. A word in the session file picks the split:

compute: latency

latency gives one call all the cores, throughput runs as many calls at once as there are cores, and balanced, the default, sits between the two. Compute lists every key of the section. The build's summary names what the session chose, and Session.pool_settings returns the same numbers:

Compute: 15 cores, preset balanced
ThreadPool: 3 threads, 5 native threads each

The preset sizes the thread pool only. Each component that asks for a ProcessExecutor gets a pool of worker processes of its own, so one component's crash or long queue never reaches another's calls. The session shares the compute cores between those pools, at least one worker each, and each worker runs its native libraries on one thread. processes gives every such component the same count instead, and a component's own workers key wins over both:

compute:
  processes: 2

presenters:
  stack:
    workers: 4

The summary then has one line per pool, such as ProcessPool of stack: 4 processes, priority normal. When the pools add up to more workers than the compute cores, the build logs a warning and keeps the counts you asked for.

Set the priority of the workers

Worker processes run at normal priority, the same as the rest of the session. Set priority to low when their work can wait, so services such as a camera's driver keep their share of the CPU during an acquisition, or to high when the workers must keep up:

compute:
  priority: low

The priority applies to the worker processes only, never to the threads of the thread pool, which run in the session's own process.

high needs privileges on Linux and macOS

Raising a process above normal priority needs root, or the CAP_SYS_NICE capability on Linux. Without it each worker logs a warning and runs at normal priority. Windows lets any user choose high.

Handle a crashed worker

A worker process can die in the middle of a call, from a crash in compiled code or an os._exit. Python then fails every call of that pool that hadn't finished, without saying which one killed the worker, so each of them fails with WorkerCrashed. The pool starts new workers, and the component's next submit runs on them. Nothing is sent again on its own, because running a call twice could repeat what it did before the crash, such as writing a file. Send it again from the error callback if that is safe:

from redsun.compute import WorkerCrashed

def _report(self, error: BaseException) -> None:
    if isinstance(error, WorkerCrashed):
        self._executor.submit(median_of, self._frames).then(self.sig_median.emit)

A pool whose workers die more than 3 times within 60 s stops starting new ones: its calls fail with BrokenPool from then on, and the log says why. The pools of the other components go on.

Read what the pool did

usage returns the counts of the component's own calls: waiting, running, completed and failed, and the longest any call waited for a free thread. The session also logs what each pool did when it shuts down, with each owner's calls in parentheses; here the only owner is the median presenter:

thread pool: 3 workers, 214 calls (median 214), 2 failed, longest idle 1.4 s

A ProcessExecutor counts a call as running once it hands the call to its worker processes, where the call may still wait in a queue for a free worker. Its waiting count and longest wait cover only the time before that hand-over, for instance while the pool has not started yet.

A call that waited more than a second for a free thread is logged as a warning naming its owner when it starts. The session also keeps a thread that wakes every 50 ms. If it wakes more than 0.2 s late, something held every other thread back, so the session logs the name of each function the pool was running at that moment, once per function.

Test the component

Load the redsun.testing fixtures as How to test a plugin shows, and pass the component the inline_threads fixture:

def test_the_median_follows_the_run(inline_threads: ThreadExecutor) -> None:
    """Publish the median of a run's frames when the run stops."""
    presenter = MedianPresenter("median", inline_threads, source="camera")
    published: list[NDArray[np.float64]] = []
    presenter.sig_median.connect(published.append)

    presenter("start", {"uid": "run", "time": 0.0})
    for value in (1, 2, 9):
        presenter("event", {"data": {"camera": np.full((4, 4), value)}})
    presenter("stop", {"run_start": "run", "time": 1.0})

    assert np.array_equal(published[-1], np.full((4, 4), 2))

inline_threads is a ThreadExecutor over a pool with no threads, already started. Each call runs in the test's own thread before submit returns, and then hands its result over at once, so the test can check it on the next line.

inline_processes does the same for a ProcessExecutor. Each call still runs in the test's thread, but its arguments and its result are pickled and read back first, so a value that couldn't reach a real worker fails the call:

def test_the_fit_reads_the_shared_block(inline_processes: ProcessExecutor) -> None:
    """Publish the fit of a run's frames, read from the shared block by name."""
    presenter = StackPresenter("fit", inline_processes, source="camera", frames=3)
    published: list[NDArray[np.float64]] = []
    presenter.sig_fit.connect(published.append)

    presenter("start", {"uid": "run", "time": 0.0})
    presenter(
        "descriptor",
        {
            "uid": "d",
            "run_start": "run",
            "time": 0.0,
            "data_keys": {
                "camera": {
                    "source": "sim",
                    "dtype": "array",
                    "dtype_numpy": "<u2",
                    "shape": [4, 4],
                }
            },
        },
    )
    for value in (1, 2, 9):
        presenter("event", {"data": {"camera": np.full((4, 4), value)}})
    presenter("stop", {"run_start": "run", "time": 1.0})

    assert np.array_equal(published[-1], np.full((4, 4), 4.0))

Leave the window's teardown alone

Work started while the window closes fails

By the time Qt tears the window down and calls closeEvent, the session has shut down its executors and pools and closed the values it hands to components. A submit there raises RuntimeError: cannot schedule new futures after shutdown. A call submitted from a component's own shutdown is cancelled right after it. Start the work while the session runs, from a document, a signal or a user's action.

The example in full

The whole script
"""The session of the guide "How to run background processing"."""

from __future__ import annotations

from typing import TYPE_CHECKING

import numpy as np
from event_model import DocumentRouter
from psygnal import Signal
from qtpy.QtWidgets import QLabel, QVBoxLayout, QWidget

from redsun import AsPresenter, AsView, Placement, slot
from redsun.compute import ThreadExecutor
from redsun.log import Loggable
from redsun.qt import Dock, QtSession

if TYPE_CHECKING:
    from collections.abc import Iterator

    from event_model import Event, RunStart, RunStop
    from numpy.typing import NDArray

    from redsun import Link


def median_of(frames: list[NDArray[np.uint16]]) -> NDArray[np.float64]:
    return np.median(np.stack(frames), axis=0)


class MedianPresenter(DocumentRouter, Loggable):
    sig_median = Signal(object)

    def __init__(
        self, name: str, executor: ThreadExecutor, *, source: str = "camera"
    ) -> None:
        super().__init__()
        self.name = name
        self.source = source
        self._executor = executor
        self._frames: list[NDArray[np.uint16]] = []

    def setup(self) -> None:
        blank = np.zeros((8, 8), dtype=np.uint16)
        self._executor.submit(median_of, [blank, blank]).then(self._warmed_up)

    def _warmed_up(self, median: NDArray[np.float64]) -> None:
        self.logger.info("Median ready")

    def start(self, doc: RunStart) -> RunStart:
        self._frames = []
        return doc

    def event(self, doc: Event) -> Event:
        self._frames.append(np.asarray(doc["data"][self.source]))
        return doc

    def stop(self, doc: RunStop) -> RunStop:
        if self._frames:
            future = self._executor.submit(median_of, self._frames)
            future.then(self.sig_median.emit, self._report)
        return doc

    def _report(self, error: BaseException) -> None:
        self.logger.warning(f"No median for this run: {error}")


class MedianView(QWidget):
    placement: Placement = Dock("right")

    def __init__(self, name: str, parent: QWidget) -> None:
        super().__init__(parent)
        self.name = name
        self.label = QLabel("No median yet")
        QVBoxLayout(self).addWidget(self.label)

    @slot
    def show_median(self, median: NDArray[np.float64]) -> None:
        self.label.setText(f"Median ready, mean {median.mean():.1f}")


class MyApp(QtSession):
    median: AsPresenter[MedianPresenter]
    median_view: AsView[MedianView]

    def wire(self) -> Iterator[Link]:
        yield self.median.sig_median, self.median_view.show_median


if __name__ == "__main__":
    MyApp().run()
The shared block
"""The shared block of the guide "How to run background processing"."""

from __future__ import annotations

from contextlib import suppress
from functools import partial
from multiprocessing import shared_memory
from typing import TYPE_CHECKING

import numpy as np
from event_model import DocumentRouter
from psygnal import Signal

from redsun.compute import ProcessExecutor
from redsun.log import Loggable

if TYPE_CHECKING:
    from event_model import Event, EventDescriptor, RunStart, RunStop
    from numpy.typing import NDArray


def fit_stack(name: str, shape: tuple[int, ...], dtype: str) -> NDArray[np.float64]:
    block = shared_memory.SharedMemory(name=name)
    stack = np.ndarray(shape, dtype, block.buf)
    try:
        return np.asarray(stack.mean(axis=0), dtype=np.float64)
    finally:
        del stack
        block.close()


class StackPresenter(DocumentRouter, Loggable):
    sig_fit = Signal(object)

    def __init__(
        self,
        name: str,
        executor: ProcessExecutor,
        *,
        source: str = "camera",
        frames: int = 40,
    ) -> None:
        super().__init__()
        self.name = name
        self.source = source
        self._executor = executor
        self._count = frames
        self._next = 0
        self._block: shared_memory.SharedMemory | None = None
        self._stack: NDArray[np.generic] | None = None
        self._sent: set[shared_memory.SharedMemory] = set()

    def start(self, doc: RunStart) -> RunStart:
        self._next = 0
        return doc

    def descriptor(self, doc: EventDescriptor) -> EventDescriptor:
        if self.source not in doc["data_keys"]:
            return doc
        if self._block is not None:
            self._stack = None
            self._release(self._block)
        key = doc["data_keys"][self.source]
        shape = (self._count, *(int(n or 0) for n in key["shape"]))
        dtype = np.dtype(key.get("dtype_numpy", "uint16"))
        size = max(1, int(np.prod(shape)) * dtype.itemsize)
        self._block = shared_memory.SharedMemory(create=True, size=size)
        self._stack = np.ndarray(shape, dtype, self._block.buf)
        return doc

    def event(self, doc: Event) -> Event:
        if (
            self._stack is not None
            and self._next < self._count
            and self.source in doc["data"]
        ):
            self._stack[self._next] = doc["data"][self.source]
            self._next += 1
        return doc

    def stop(self, doc: RunStop) -> RunStop:
        if self._block is None or self._stack is None:
            return doc
        block, self._block = self._block, None
        shape, dtype = self._stack.shape, self._stack.dtype.str
        self._stack = None
        self._sent.add(block)
        future = self._executor.submit(fit_stack, block.name, shape, dtype)
        future.then(partial(self._publish, block), partial(self._report, block))
        return doc

    def _publish(
        self, block: shared_memory.SharedMemory, fit: NDArray[np.float64]
    ) -> None:
        self._release(block)
        self.sig_fit.emit(fit)

    def _report(self, block: shared_memory.SharedMemory, error: BaseException) -> None:
        self._release(block)
        self.logger.warning(f"No fit for this run: {error}")

    def _release(self, block: shared_memory.SharedMemory) -> None:
        self._sent.discard(block)
        block.close()
        with suppress(FileNotFoundError):
            block.unlink()

    def shutdown(self) -> None:
        self._stack = None
        for block in [*self._sent, self._block]:
            if block is not None:
                self._release(block)
        self._block = None