Skip to content

ImpressBasePipeline

impress.pipelines.impress_pipeline.ImpressBasePipeline

Bases: ABC

Abstract base class for all IMPRESS pipelines.

Subclasses implement register_pipeline_tasks() to bind task methods (via auto_register_task()) and run() to define the pipeline's control flow, and may optionally override finalize() for cleanup. The base class provides the adaptive execution protocol (run_adaptive_step()) and the child-pipeline request mechanism (submit_child_pipeline_request() / get_child_pipeline_request()) used by ImpressManager to support dynamic, self-spawning pipeline trees.

Attributes:

Name Type Description
name

Pipeline instance name.

flow

The radical.asyncflow WorkflowEngine used to submit executable tasks.

state

Free-form dict for passing data between pipeline stages.

config

Extra keyword arguments captured at construction time.

kill_parent

When set to True, the manager cancels this pipeline's task on its next poll.

invoke_adaptive_step

When True, the manager runs this pipeline's adaptive function on its next poll.

incoming_child_pipeline_request

Pending child-pipeline submission request, populated by submit_child_pipeline_request().

Source code in src/impress/pipelines/impress_pipeline.py
class ImpressBasePipeline(ABC):
    """
    Abstract base class for all IMPRESS pipelines.

    Subclasses implement `register_pipeline_tasks()` to bind task methods
    (via `auto_register_task()`) and `run()` to define the pipeline's
    control flow, and may optionally override `finalize()` for cleanup. The
    base class provides the adaptive
    execution protocol (`run_adaptive_step()`) and the child-pipeline
    request mechanism (`submit_child_pipeline_request()` /
    `get_child_pipeline_request()`) used by `ImpressManager` to support
    dynamic, self-spawning pipeline trees.

    Attributes:
        name: Pipeline instance name.
        flow: The `radical.asyncflow` `WorkflowEngine` used to submit
            executable tasks.
        state: Free-form dict for passing data between pipeline stages.
        config: Extra keyword arguments captured at construction time.
        kill_parent: When set to True, the manager cancels this pipeline's
            task on its next poll.
        invoke_adaptive_step: When True, the manager runs this pipeline's
            adaptive function on its next poll.
        incoming_child_pipeline_request: Pending child-pipeline submission
            request, populated by `submit_child_pipeline_request()`.
    """

    def __init__(self, name: str, flow=None, **config):
        """
        Initialize the pipeline and register its tasks.

        Args:
            name: Pipeline instance name.
            flow: The `radical.asyncflow` `WorkflowEngine` used to submit
                executable tasks.
            **config: Additional configuration stored in `self.config` and
                available to subclasses.
        """
        self.name = name
        self.flow = flow
        self.state = {}
        self.config = config
        self.kill_parent = False
        self.invoke_adaptive_step = False
        self.incoming_child_pipeline_request = {}
        self._adaptive_barrier = asyncio.Event()
        # Set by ImpressManager once telemetry has started; see `telemetry`.
        self._telemetry = None

        # Call the registration method - subclasses must implement this
        self.register_pipeline_tasks()

        self.logger = ImpressLogger(self.name)

    def submit_child_pipeline_request(self, pipeline_config):
        """
        Submit a request to spawn a child pipeline.

        Args:
            pipeline_config (dict): Configuration for the new pipeline including
                                  'name', 'type', 'config', and 'adaptive_fn'
        """
        self.incoming_child_pipeline_request = pipeline_config

    def get_child_pipeline_request(self):
        """
        Get and clear any pending spawn request for child pipelines.

        Returns:
            dict or None: The spawn request configuration if one exists, None otherwise.
                         After calling this method, the spawn request is cleared.
        """
        if self.incoming_child_pipeline_request:
            request = self.incoming_child_pipeline_request

            # reset the value to avoid submission request duplication
            self.incoming_child_pipeline_request = None
            return request

        return None

    @property
    def telemetry(self):
        """The running telemetry manager, or None when telemetry is off.

        `ImpressManager` sets it before `run()`. A pipeline driven without the
        manager has none unless the caller sets `_telemetry` itself.
        """
        return self._telemetry

    def auto_register_task(self, local_task=False, capture_stdio=True, **task_kwargs):
        """
        Decorator factory that binds a task function as a callable pipeline method.

        Used inside `register_pipeline_tasks()` to register the coroutines
        that make up a pipeline's stages.

        Args:
            local_task: If False (default), wraps the function via
                `self.flow.executable_task(**task_kwargs)`, turning it into
                an HPC-executable task submitted through the workflow
                engine. If True, the function runs as a plain local
                coroutine (e.g. for CPU-only analysis steps); each call is
                timed and emitted as an `impress.LocalStage` telemetry event.
            capture_stdio: For executable tasks, write the task's stdout and
                stderr to files in the backend's work dir (default True).
                The task's future then resolves to the stdout file path,
                not the stdout text. Pass False to get the text back.
            **task_kwargs: Forwarded to `self.flow.executable_task()` when
                `local_task` is False.

        Executable tasks get two more behaviours:

        - Each call is labelled `{pipeline}:{stage}` in telemetry unless the
          caller passes its own `workflow_id=`. Without a label, asyncflow
          names a task after its executable, which is usually `bash`.
        - When a task fails, the last lines of its captured stderr are
          logged, and attached to the exception as a note (Python 3.11+).

        Returns:
            A decorator that binds the wrapped function to `self` under its
            own name (so it becomes callable as `await self.<func_name>()`).
        """

        def decorator(func):
            if local_task:
                task = wrap_local_task(self, func)
            else:
                flow_task = self.flow.executable_task(
                    capture_stdio=capture_stdio, **task_kwargs
                )(func)
                task = self._wrap_executable_task(func, flow_task)
            setattr(self, func.__name__, task)
            return task

        return decorator

    def _wrap_executable_task(self, func, flow_task):
        """Label each call and report a failed task's stderr.

        Returns the engine's own future unchanged, so a stage future can
        still be passed to another task as a dependency.
        """
        stage = func.__name__

        @functools.wraps(flow_task)
        def call(*args, **kwargs):
            kwargs.setdefault("workflow_id", f"{self.name}:{stage}")
            fut = flow_task(*args, **kwargs)
            fut.add_done_callback(functools.partial(self._report_task_failure, stage))
            return fut

        return call

    def _report_task_failure(self, stage, fut):
        if fut.cancelled():
            return
        exc = fut.exception()
        if exc is None:
            return
        tail = stderr_tail(self.flow, fut, exc)
        message = f"{stage} failed: {exc!r}"
        if tail:
            message = f"{message}\n{tail}"
            if hasattr(exc, "add_note"):
                exc.add_note(tail)
        self.logger.pipeline_log(message, level=LogLevel.ERROR)

    def logged_command(self, log_file, cmd):
        """Wrap `cmd` so its combined output lands in `log_file`.

        For a per-task log next to the task's outputs. On failure the log's
        last lines also go to stderr, and so into the task's error.
        """
        return logged_command(log_file, cmd)

    async def run_adaptive_step(self, wait: bool = True):
        """Trigger adaptive step and optionally wait for completion.

        Args:
            wait: If True, waits for adaptive step completion.
                If False, triggers and returns immediately.
        """
        self._set_adaptive_flag(True)
        if wait:
            await self._await_adaptive_unlock()

    def _set_adaptive_flag(self, value: bool = True):
        """Set the adaptive flag and manage the barrier state"""
        self.invoke_adaptive_step = value
        if value:
            self._adaptive_barrier.clear()

    async def _await_adaptive_unlock(self) -> Any:
        """Pause until manager completes adaptive step and returns result."""
        await self._adaptive_barrier.wait()

    @abstractmethod
    async def run(self):
        """
        Main execution method; must be implemented by subclasses.

        Drives the pipeline's control flow: calling task methods registered
        in `register_pipeline_tasks()`, and calling
        `await self.run_adaptive_step(...)` at decision points where the
        pipeline should evaluate intermediate results and optionally spawn
        child pipelines.
        """
        pass

    @abstractmethod
    def register_pipeline_tasks(self):
        """
        Register pipeline tasks; must be implemented by subclasses.

        Called once, synchronously, from `__init__` before anything else
        runs. Implementations use `@self.auto_register_task()` to bind task
        coroutines as callable methods on `self` for use in `run()`.
        """
        pass

    # Optional methods that subclasses can override
    async def get_scores_map(self):
        """
        Return a mapping of scores for this pipeline.

        Optional extension point; subclasses may override this to expose
        fitness/quality scores to external callers. Returns an empty dict
        by default.

        Returns:
            dict: Mapping of score name to value.
        """
        return {}

    async def finalize(self):  # noqa: B027
        """
        Cleanup or finalization logic.

        Optional extension point; the default implementation is a no-op.
        Typically called by subclass-specific adaptive logic (for example,
        after spawning a child pipeline) to update or clear tracking state
        on the parent pipeline.
        """
        pass

    def get_current_config_for_next_pipeline(self):
        """
        Build a default configuration dict for a follow-on pipeline.

        Optional extension point; subclasses can override this to build the
        config dict passed to `submit_child_pipeline_request()`. Returns a
        generic default pointing at the same pipeline class.

        Returns:
            dict: Configuration with at least `name` and `type` keys.
        """
        return {"name": "default_pipeline", "type": self.__class__}

telemetry property

The running telemetry manager, or None when telemetry is off.

ImpressManager sets it before run(). A pipeline driven without the manager has none unless the caller sets _telemetry itself.

__init__(name, flow=None, **config)

Initialize the pipeline and register its tasks.

Parameters:

Name Type Description Default
name str

Pipeline instance name.

required
flow

The radical.asyncflow WorkflowEngine used to submit executable tasks.

None
**config

Additional configuration stored in self.config and available to subclasses.

{}
Source code in src/impress/pipelines/impress_pipeline.py
def __init__(self, name: str, flow=None, **config):
    """
    Initialize the pipeline and register its tasks.

    Args:
        name: Pipeline instance name.
        flow: The `radical.asyncflow` `WorkflowEngine` used to submit
            executable tasks.
        **config: Additional configuration stored in `self.config` and
            available to subclasses.
    """
    self.name = name
    self.flow = flow
    self.state = {}
    self.config = config
    self.kill_parent = False
    self.invoke_adaptive_step = False
    self.incoming_child_pipeline_request = {}
    self._adaptive_barrier = asyncio.Event()
    # Set by ImpressManager once telemetry has started; see `telemetry`.
    self._telemetry = None

    # Call the registration method - subclasses must implement this
    self.register_pipeline_tasks()

    self.logger = ImpressLogger(self.name)

auto_register_task(local_task=False, capture_stdio=True, **task_kwargs)

Decorator factory that binds a task function as a callable pipeline method.

Used inside register_pipeline_tasks() to register the coroutines that make up a pipeline's stages.

Parameters:

Name Type Description Default
local_task

If False (default), wraps the function via self.flow.executable_task(**task_kwargs), turning it into an HPC-executable task submitted through the workflow engine. If True, the function runs as a plain local coroutine (e.g. for CPU-only analysis steps); each call is timed and emitted as an impress.LocalStage telemetry event.

False
capture_stdio

For executable tasks, write the task's stdout and stderr to files in the backend's work dir (default True). The task's future then resolves to the stdout file path, not the stdout text. Pass False to get the text back.

True
**task_kwargs

Forwarded to self.flow.executable_task() when local_task is False.

{}

Executable tasks get two more behaviours:

  • Each call is labelled {pipeline}:{stage} in telemetry unless the caller passes its own workflow_id=. Without a label, asyncflow names a task after its executable, which is usually bash.
  • When a task fails, the last lines of its captured stderr are logged, and attached to the exception as a note (Python 3.11+).

Returns:

Type Description

A decorator that binds the wrapped function to self under its

own name (so it becomes callable as await self.<func_name>()).

Source code in src/impress/pipelines/impress_pipeline.py
def auto_register_task(self, local_task=False, capture_stdio=True, **task_kwargs):
    """
    Decorator factory that binds a task function as a callable pipeline method.

    Used inside `register_pipeline_tasks()` to register the coroutines
    that make up a pipeline's stages.

    Args:
        local_task: If False (default), wraps the function via
            `self.flow.executable_task(**task_kwargs)`, turning it into
            an HPC-executable task submitted through the workflow
            engine. If True, the function runs as a plain local
            coroutine (e.g. for CPU-only analysis steps); each call is
            timed and emitted as an `impress.LocalStage` telemetry event.
        capture_stdio: For executable tasks, write the task's stdout and
            stderr to files in the backend's work dir (default True).
            The task's future then resolves to the stdout file path,
            not the stdout text. Pass False to get the text back.
        **task_kwargs: Forwarded to `self.flow.executable_task()` when
            `local_task` is False.

    Executable tasks get two more behaviours:

    - Each call is labelled `{pipeline}:{stage}` in telemetry unless the
      caller passes its own `workflow_id=`. Without a label, asyncflow
      names a task after its executable, which is usually `bash`.
    - When a task fails, the last lines of its captured stderr are
      logged, and attached to the exception as a note (Python 3.11+).

    Returns:
        A decorator that binds the wrapped function to `self` under its
        own name (so it becomes callable as `await self.<func_name>()`).
    """

    def decorator(func):
        if local_task:
            task = wrap_local_task(self, func)
        else:
            flow_task = self.flow.executable_task(
                capture_stdio=capture_stdio, **task_kwargs
            )(func)
            task = self._wrap_executable_task(func, flow_task)
        setattr(self, func.__name__, task)
        return task

    return decorator

finalize() async

Cleanup or finalization logic.

Optional extension point; the default implementation is a no-op. Typically called by subclass-specific adaptive logic (for example, after spawning a child pipeline) to update or clear tracking state on the parent pipeline.

Source code in src/impress/pipelines/impress_pipeline.py
async def finalize(self):  # noqa: B027
    """
    Cleanup or finalization logic.

    Optional extension point; the default implementation is a no-op.
    Typically called by subclass-specific adaptive logic (for example,
    after spawning a child pipeline) to update or clear tracking state
    on the parent pipeline.
    """
    pass

get_child_pipeline_request()

Get and clear any pending spawn request for child pipelines.

Returns:

Type Description

dict or None: The spawn request configuration if one exists, None otherwise. After calling this method, the spawn request is cleared.

Source code in src/impress/pipelines/impress_pipeline.py
def get_child_pipeline_request(self):
    """
    Get and clear any pending spawn request for child pipelines.

    Returns:
        dict or None: The spawn request configuration if one exists, None otherwise.
                     After calling this method, the spawn request is cleared.
    """
    if self.incoming_child_pipeline_request:
        request = self.incoming_child_pipeline_request

        # reset the value to avoid submission request duplication
        self.incoming_child_pipeline_request = None
        return request

    return None

get_current_config_for_next_pipeline()

Build a default configuration dict for a follow-on pipeline.

Optional extension point; subclasses can override this to build the config dict passed to submit_child_pipeline_request(). Returns a generic default pointing at the same pipeline class.

Returns:

Name Type Description
dict

Configuration with at least name and type keys.

Source code in src/impress/pipelines/impress_pipeline.py
def get_current_config_for_next_pipeline(self):
    """
    Build a default configuration dict for a follow-on pipeline.

    Optional extension point; subclasses can override this to build the
    config dict passed to `submit_child_pipeline_request()`. Returns a
    generic default pointing at the same pipeline class.

    Returns:
        dict: Configuration with at least `name` and `type` keys.
    """
    return {"name": "default_pipeline", "type": self.__class__}

get_scores_map() async

Return a mapping of scores for this pipeline.

Optional extension point; subclasses may override this to expose fitness/quality scores to external callers. Returns an empty dict by default.

Returns:

Name Type Description
dict

Mapping of score name to value.

Source code in src/impress/pipelines/impress_pipeline.py
async def get_scores_map(self):
    """
    Return a mapping of scores for this pipeline.

    Optional extension point; subclasses may override this to expose
    fitness/quality scores to external callers. Returns an empty dict
    by default.

    Returns:
        dict: Mapping of score name to value.
    """
    return {}

logged_command(log_file, cmd)

Wrap cmd so its combined output lands in log_file.

For a per-task log next to the task's outputs. On failure the log's last lines also go to stderr, and so into the task's error.

Source code in src/impress/pipelines/impress_pipeline.py
def logged_command(self, log_file, cmd):
    """Wrap `cmd` so its combined output lands in `log_file`.

    For a per-task log next to the task's outputs. On failure the log's
    last lines also go to stderr, and so into the task's error.
    """
    return logged_command(log_file, cmd)

register_pipeline_tasks() abstractmethod

Register pipeline tasks; must be implemented by subclasses.

Called once, synchronously, from __init__ before anything else runs. Implementations use @self.auto_register_task() to bind task coroutines as callable methods on self for use in run().

Source code in src/impress/pipelines/impress_pipeline.py
@abstractmethod
def register_pipeline_tasks(self):
    """
    Register pipeline tasks; must be implemented by subclasses.

    Called once, synchronously, from `__init__` before anything else
    runs. Implementations use `@self.auto_register_task()` to bind task
    coroutines as callable methods on `self` for use in `run()`.
    """
    pass

run() abstractmethod async

Main execution method; must be implemented by subclasses.

Drives the pipeline's control flow: calling task methods registered in register_pipeline_tasks(), and calling await self.run_adaptive_step(...) at decision points where the pipeline should evaluate intermediate results and optionally spawn child pipelines.

Source code in src/impress/pipelines/impress_pipeline.py
@abstractmethod
async def run(self):
    """
    Main execution method; must be implemented by subclasses.

    Drives the pipeline's control flow: calling task methods registered
    in `register_pipeline_tasks()`, and calling
    `await self.run_adaptive_step(...)` at decision points where the
    pipeline should evaluate intermediate results and optionally spawn
    child pipelines.
    """
    pass

run_adaptive_step(wait=True) async

Trigger adaptive step and optionally wait for completion.

Parameters:

Name Type Description Default
wait bool

If True, waits for adaptive step completion. If False, triggers and returns immediately.

True
Source code in src/impress/pipelines/impress_pipeline.py
async def run_adaptive_step(self, wait: bool = True):
    """Trigger adaptive step and optionally wait for completion.

    Args:
        wait: If True, waits for adaptive step completion.
            If False, triggers and returns immediately.
    """
    self._set_adaptive_flag(True)
    if wait:
        await self._await_adaptive_unlock()

submit_child_pipeline_request(pipeline_config)

Submit a request to spawn a child pipeline.

Parameters:

Name Type Description Default
pipeline_config dict

Configuration for the new pipeline including 'name', 'type', 'config', and 'adaptive_fn'

required
Source code in src/impress/pipelines/impress_pipeline.py
def submit_child_pipeline_request(self, pipeline_config):
    """
    Submit a request to spawn a child pipeline.

    Args:
        pipeline_config (dict): Configuration for the new pipeline including
                              'name', 'type', 'config', and 'adaptive_fn'
    """
    self.incoming_child_pipeline_request = pipeline_config