Sign in

Runner

Pipeline runner (directed acyclic graph executor)

A small pipeline executor that runs named steps in dependency order, with parallel steps, retries, skipping of blocked steps and resume.

Overview

An ML workflow is a set of steps where some need the results of others: you cannot train before you load, or report before you evaluate. Drawn as boxes and arrows this is a graph with no loops, called a directed acyclic graph or DAG. A runner reads that graph and works out a valid order by itself. It can run steps that do not depend on each other at the same time, and when one step fails it knows exactly which later steps can no longer run and which are unaffected.

A short history

Running steps in dependency order is an old idea in computing. Arthur Kahn published the topological sorting algorithm used here in 1962. Stuart Feldman's Make, written at Bell Labs in 1976, applied dependency graphs to building software. Data teams later built workflow tools on the same model: Luigi was open sourced by Spotify in 2012 and Airflow was started at Airbnb in 2014. A directed acyclic graph, or DAG, is a set of steps and dependencies with no loops.

How it works

  1. Register each step with add_step(name, function, depends_on=[...]). A step receives the return values of its dependencies as keyword arguments.
  2. order() sorts the steps so that every step comes after everything it depends on (Kahn's algorithm). It reports a cycle or an unknown dependency before anything runs.
  3. run() starts a step as soon as all its dependencies have succeeded, with at most max_workers steps running at once on threads.
  4. A step that raises is tried again up to max_retries more times, with retry_delay_s between tries, and is then marked failed.
  5. Every step downstream of a failed step is marked skipped. Independent branches keep running unless fail_fast is set.
  6. The RunResult holds the status, output, error, attempts and duration of each step. run(previous=result) reruns only what did not succeed.

Watch out for

  • A dependency you forget to declare can still work by luck in a sequential run and then fail when steps run in parallel, because the order is no longer what the script happened to give.
  • Steps that change shared state (a file, a global variable) can interfere with each other when run at the same time. Pass data through return values.
  • Retries repeat the whole step, so a step that is not safe to run twice (it appends rows, or sends a message) causes duplicates.
  • Adding workers cannot make the run shorter than its longest chain of dependent steps.
  • This template runs in one process and keeps results in memory. It has no scheduler daemon, no persistence and no workers on other machines, which full orchestrators provide.

Use cases

When to use it

To join the stages of an ML workflow (ingest, validate, featurise, train, evaluate, report) into one call with explicit dependencies, instead of a script that must be read from top to bottom.

In industry

Machine learning teams
A training pipeline of ingest, validate, featurise, train, evaluate and report is declared as steps with dependencies, so independent steps run in parallel.
Analytics and data warehousing
Nightly table builds depend on each other. When one fails, the runner skips everything downstream and reports exactly which steps were blocked.
Scientific computing
A long analysis is rerun after a crash and resumes from the last finished step, without repeating hours of earlier work.

Choosing it: what must hold

  • Work that divides into named steps with clear inputs and outputs.
  • Dependencies that form no cycle.
  • Steps that are safe to run again, since retries and resume repeat them.
  • A workload that fits in one process on one machine.

When to choose something else

IfUse instead
Steps must run on several machines or survive a restart of the hostA workflow system such as Apache Airflow, Prefect or Dagster
The pipeline must start at set times or on eventsThe job scheduling lesson, with this runner as the job
There are only two or three steps in a fixed orderA plain script that calls them in turn

Math foundations

  1. A valid order

    pos⁡(u)<pos⁡(v)for every dependency u→v\operatorname{pos}(u) < \operatorname{pos}(v) \quad \text{for every dependency } u \to v

    A topological order places each step after all the steps it needs. One exists exactly when the graph has no cycle, which is why a cycle is reported as an error.

  2. Sequential time and the critical path

    T1=∑idi,T∞=max⁡paths P∑i∈PdiT_1 = \sum_{i} d_i, \qquad T_{\infty} = \max_{\text{paths } P} \sum_{i \in P} d_i

    T1T_1 is the time with one worker: every duration added up. T∞T_{\infty} is the longest chain of dependent steps, the time needed even with unlimited workers. It is called the critical path.

  3. What W workers can achieve

    TW  ≥  max⁡ ⁣(T1W,  T∞)T_W \;\ge\; \max\!\left(\frac{T_1}{W},\; T_{\infty}\right)

    With WW workers the run can be at most WW times faster than sequential, and never faster than the critical path. Whichever limit is larger decides.

  4. Calls of one step

    1  ≤  attempts  ≤  1+r1 \;\le\; \text{attempts} \;\le\; 1 + r

    A step is called once, plus at most rr retries if it keeps raising. The actual number is recorded in RunResult.attempts.

Symbols

u→vu \to v
step v depends on step u
pos⁡(u)\operatorname{pos}(u)
position of step u in the execution order
did_i
duration of step i
T1T_1
total time with one worker
T∞T_{\infty}
length of the critical path
TWT_W
total time with W workers
WW
max_workers
rr
max_retries

Worked by hand

Four steps: load (2 s), then mean (1 s) and spread (3 s) which both need load, then report (1 s) which needs both. Compare one worker with two.

T1=2+1+3+1=7 sT_1 = 2 + 1 + 3 + 1 = 7\ \text{s}
T∞=max⁡(2+1+1,  2+3+1)=6 sT_{\infty} = \max(2 + 1 + 1,\; 2 + 3 + 1) = 6\ \text{s}
T2≥max⁡ ⁣(72,  6)=6 sT_2 \ge \max\!\left(\frac{7}{2},\; 6\right) = 6\ \text{s}

Two workers finish in 6 seconds, because mean and spread run side by side. A third worker would not help: the chain load, spread, report already takes 6 seconds.

Visual example

Loading the example.

Try this

  • Press Step and watch mean and spread start together once load has succeeded.
  • Set max_workers to 1 and compare the total time with the two worker run.
  • Make spread fail with max_retries at 0: report is skipped while mean still finishes. Then give it one retry.

Code sample

from impl import Pipeline
from config import RunnerConfig

pipeline = Pipeline(RunnerConfig(max_workers=2))
pipeline.add_step("load", lambda: [3.0, 1.0, 2.0])
pipeline.add_step("mean", lambda load: sum(load) / len(load), depends_on=["load"])
pipeline.add_step("spread", lambda load: max(load) - min(load), depends_on=["load"])
pipeline.add_step("report", lambda mean, spread: f"mean {mean}, spread {spread}", depends_on=["mean", "spread"])

print(pipeline.order())              # ['load', 'mean', 'spread', 'report']
result = pipeline.run()
print(result.ok, result.outputs["report"])   # True mean 2.0, spread 2.0
Read the implementation (158 lines)
"""Pipeline runner: execute named steps in dependency order (a directed acyclic graph).

Standard library only (NumPy is not needed here). A step is a function plus the names of the steps it
depends on; it receives their return values as keyword arguments. The runner orders the steps with a
topological sort, runs independent steps on a thread pool, retries failures, skips everything downstream
of a failed step and can resume a previous run without redoing the steps that succeeded.
"""
from __future__ import annotations

import time
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from dataclasses import dataclass, field
from typing import Callable

try:
    from .config import RunnerConfig
except ImportError:  # run from the template's own folder
    from config import RunnerConfig

SUCCESS, FAILED, SKIPPED = "success", "failed", "skipped"


class CycleError(ValueError):
    """The steps depend on each other in a circle, so no valid order exists."""


@dataclass
class RunResult:
    """Outcome of one run.

    status:    {step: "success" | "failed" | "skipped"}.
    outputs:   {step: return value} for the successful steps.
    errors:    {step: exception} for the failed steps.
    attempts:  {step: number of times the step function was called in this run}.
    durations: {step: seconds spent in the last attempt}.
    finished:  step names in the order they finished (successes and failures).
    """

    status: dict = field(default_factory=dict)
    outputs: dict = field(default_factory=dict)
    errors: dict = field(default_factory=dict)
    attempts: dict = field(default_factory=dict)
    durations: dict = field(default_factory=dict)
    finished: list = field(default_factory=list)

    @property
    def ok(self) -> bool:
        """True when every step succeeded."""
        return all(state == SUCCESS for state in self.status.values())


class Pipeline:
    """A set of steps and the dependencies between them."""

    def __init__(self, config: RunnerConfig | None = None) -> None:
        self.config = config or RunnerConfig()
        self._functions: dict[str, Callable] = {}
        self._depends: dict[str, tuple[str, ...]] = {}

    # ---------------------------------------------------------------------------------------- building
    def add_step(self, name: str, function: Callable, depends_on=()) -> None:
        """Register a step.

        function:   called as function(dep_a=<output of dep_a>, dep_b=...) with one keyword argument per
                    dependency. A step without dependencies is called with no arguments.
        depends_on: names of the steps that must succeed first. They may be added later.
        """
        if name in self._functions:
            raise ValueError(f"step {name!r} is already defined")
        self._functions[name] = function
        self._depends[name] = tuple(depends_on)

    def step(self, name: str, depends_on=()) -> Callable:
        """Decorator form of `add_step`."""
        def register(function: Callable) -> Callable:
            self.add_step(name, function, depends_on)
            return function
        return register

    def order(self) -> list[str]:
        """A valid execution order (Kahn's topological sort; ties keep the order the steps were added in)."""
        for name, deps in self._depends.items():
            for dep in deps:
                if dep not in self._functions:
                    raise ValueError(f"step {name!r} depends on unknown step {dep!r}")
        waiting = {name: len(set(deps)) for name, deps in self._depends.items()}
        ordered: list[str] = []
        while len(ordered) < len(waiting):
            ready = [name for name in waiting if waiting[name] == 0 and name not in ordered]
            if not ready:
                stuck = sorted(name for name in waiting if name not in ordered)
                raise CycleError(f"dependency cycle among steps {stuck}")
            for name in ready:
                ordered.append(name)
                for other, deps in self._depends.items():
                    if name in deps:
                        waiting[other] -= 1
        return ordered

    # ----------------------------------------------------------------------------------------- running
    def _attempt(self, name: str, kwargs: dict) -> tuple:
        """Call one step with retries. Returns (output, error, attempts, seconds of the last attempt)."""
        cfg = self.config
        attempts = 0
        while True:
            attempts += 1
            started = time.perf_counter()
            try:
                return self._functions[name](**kwargs), None, attempts, time.perf_counter() - started
            except Exception as error:
                if attempts > cfg.max_retries:
                    return None, error, attempts, time.perf_counter() - started
                time.sleep(cfg.retry_delay_s)

    def run(self, previous: RunResult | None = None) -> RunResult:
        """Execute the pipeline and return a RunResult. A failing step does not raise; look at `.status`.

        previous: the result of an earlier run of this pipeline. Steps that succeeded there are not run
                  again; their outputs are reused. This is how a run is resumed after a fix.
        """
        order = self.order()
        result = RunResult()
        if previous is not None:
            for name in order:
                if previous.status.get(name) == SUCCESS:
                    result.status[name] = SUCCESS
                    result.outputs[name] = previous.outputs[name]
                    result.attempts[name] = 0
        pending = [name for name in order if name not in result.status]
        running: dict = {}  # future -> step name
        stop_starting = False

        with ThreadPoolExecutor(max_workers=self.config.max_workers) as pool:
            while pending or running:
                for name in list(pending):
                    states = [result.status.get(dep) for dep in self._depends[name]]
                    if stop_starting or any(state in (FAILED, SKIPPED) for state in states):
                        result.status[name] = SKIPPED       # something it needs did not succeed
                        pending.remove(name)
                    elif all(state == SUCCESS for state in states) and len(running) < self.config.max_workers:
                        kwargs = {dep: result.outputs[dep] for dep in self._depends[name]}
                        running[pool.submit(self._attempt, name, kwargs)] = name
                        pending.remove(name)
                if not running:
                    continue  # only skips happened; look at the remaining steps again
                done, _ = wait(running, return_when=FIRST_COMPLETED)
                for future in done:
                    name = running.pop(future)
                    output, error, attempts, seconds = future.result()
                    result.attempts[name], result.durations[name] = attempts, seconds
                    result.finished.append(name)
                    if error is None:
                        result.status[name], result.outputs[name] = SUCCESS, output
                    else:
                        result.status[name], result.errors[name] = FAILED, error
                        stop_starting = stop_starting or self.config.fail_fast
        result.status = {name: result.status[name] for name in order}  # report in execution order
        return result
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Build the four-step pipeline from the worked example with time.sleep in each step. Time pipeline.run() with RunnerConfig(max_workers=1) and with 2. Then make spread raise an error, run again, and read result.status. Fix the step and call run(previous=result) to see which steps are executed.

Check on learning

  1. The step mean fails. Which of the other steps should still run, which should be skipped, and why is that better than stopping everything?
    A way to think about it

    Follow the arrows out of the failed step. Anything reachable from it lacks an input, and anything not reachable is unaffected.

  2. Your pipeline takes 60 minutes with one worker and 45 with four. Adding more workers changes nothing. What does that tell you about the graph?
    A way to think about it

    Compare the two limits, T1/WT_1 / W and T∞T_{\infty}. Work out which one you have hit and what its length must be.

  3. Why does the runner check for cycles before running anything, instead of finding out during the run?
    A way to think about it

    Imagine a cycle between the last two steps of a three-hour pipeline. Ask when you would rather learn about it.

  4. A step downloads a file and appends it to a table. It fails halfway and is retried. What can go wrong, and how would you write the step so a retry is safe?
    A way to think about it

    A step is safe to repeat if running it twice leaves the same result as running it once. Think of writing to a temporary place and replacing the target at the end.

  5. After a failure you fix the code and call run(previous=result). The step you fixed reruns, but so do steps that had been skipped. Why is that correct?
    A way to think about it

    A skipped step never ran, so it has no output to reuse. Only steps marked as succeeded carry their results over.