Multi Stage Pipeline With Fail Fast Ordering

A staged data pipeline that runs named stages in order, stops at the first failure, and reports which stage and record index broke.

PythonData Integrity

Code

from typing import Any, Callable, List, Optional, Sequence, Tuple


class StageError(RuntimeError):
    """Raised when a pipeline stage fails or breaks the record invariant."""

    def __init__(self, stage: str, index: Optional[int], message: str) -> None:
        self.stage = stage
        self.index = index
        location = stage if index is None else "%s[%d]" % (stage, index)
        super().__init__("%s: %s" % (location, message))


def run_pipeline(
    records: Sequence[Any],
    stages: Sequence[Tuple[str, Callable[[Any], Any]]],
) -> List[Any]:
    """Run named stages in order; fail fast with stage and index context."""
    if not records:
        raise StageError("pipeline", None, "no input records")

    current: List[Any] = list(records)
    for name, stage in stages:
        produced: List[Any] = []
        for index, record in enumerate(current):
            try:
                produced.append(stage(record))
            except Exception as exc:
                raise StageError(name, index, str(exc)) from exc
        if len(produced) != len(current):
            raise StageError(
                name,
                None,
                "record count changed from %d to %d" % (len(current), len(produced)),
            )
        current = produced
    return current

An ad hoc chain of list comprehensions hides where data was lost, so a silent empty output is discovered far downstream.

Use case: engineers composing validation, enrichment and output steps over records

Inputs / outputs

  • Input: a list of named stage callables and a list of records
  • Output: processed records, or a StageError naming the stage and record index

Error conditions

  • a stage raises
  • a stage changes the record count
  • records input is empty

Approach

apply stages sequentially; wrap each stage call to attach stage name and index on failure; verify the record count is preserved after each stage.

Implementation

from typing import Any, Callable, List, Optional, Sequence, Tuple


class StageError(RuntimeError):
    """Raised when a pipeline stage fails or breaks the record invariant."""

    def __init__(self, stage: str, index: Optional[int], message: str) -> None:
        self.stage = stage
        self.index = index
        location = stage if index is None else "%s[%d]" % (stage, index)
        super().__init__("%s: %s" % (location, message))


def run_pipeline(
    records: Sequence[Any],
    stages: Sequence[Tuple[str, Callable[[Any], Any]]],
) -> List[Any]:
    """Run named stages in order; fail fast with stage and index context."""
    if not records:
        raise StageError("pipeline", None, "no input records")

    current: List[Any] = list(records)
    for name, stage in stages:
        produced: List[Any] = []
        for index, record in enumerate(current):
            try:
                produced.append(stage(record))
            except Exception as exc:
                raise StageError(name, index, str(exc)) from exc
        if len(produced) != len(current):
            raise StageError(
                name,
                None,
                "record count changed from %d to %d" % (len(current), len(produced)),
            )
        current = produced
    return current

Verification tests

import unittest

from example import StageError, run_pipeline


class PipelineTests(unittest.TestCase):
    def test_runs_stages_in_order(self):
        stages = [
            ("normalise", lambda r: {**r, "name": r["name"].strip()}),
            ("upper", lambda r: {**r, "name": r["name"].upper()}),
        ]
        out = run_pipeline([{"name": "  ada  "}], stages)
        self.assertEqual(out, [{"name": "ADA"}])

    def test_names_the_failing_stage_and_index(self):
        def boom(record):
            raise ValueError("bad value")

        with self.assertRaises(StageError) as ctx:
            run_pipeline([{"a": 1}, {"a": 2}], [("check", boom)])
        self.assertEqual(ctx.exception.stage, "check")
        self.assertEqual(ctx.exception.index, 0)
        self.assertIn("bad value", str(ctx.exception))

    def test_record_count_invariant_holds_for_none_results(self):
        def maybe_none(record):
            return record if record["keep"] else None

        out = run_pipeline([{"keep": True}, {"keep": False}], [("filter", maybe_none)])
        self.assertEqual(len(out), 2)
        self.assertIsNone(out[1])

    def test_rejects_empty_input(self):
        with self.assertRaises(StageError):
            run_pipeline([], [("noop", lambda r: r)])


if __name__ == "__main__":
    unittest.main()

Dependencies and running

No external dependencies (standard library only).

Runtime: python >= 3.9 Entry point: python example.py

Limitations and error handling

in-memory batches only; no streaming and no parallelism between stages.

Verification boundary

execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox

Interactive Tools for This Topic