3  Pipelines as Function Composition

3.1 Learning Outcomes

By the end of this chapter, you will:

  • Understand the fundamental problem of mutable state in scripts and computational notebooks.
  • Grasp the mathematical and practical definition of pure functions (determinism and zero side effects).
  • See why every T node is a pure function, and why a pipeline is function composition.
  • Write pure helper functions in R and Python that plug into pipeline nodes.
  • Understand how decoupling logic into external function files (functions = [...]) keeps domain logic orchestrator-agnostic.

3.2 Introduction: The Hidden Problem with State

In the previous chapter, we introduced T and saw how to declare polyglot pipelines with nodes and serialization contracts. Now we take a step back and ask: why is T designed this way? Why mandatory pipelines? Why must each node produce exactly one artifact? Why does the declaration order inside pipeline { } not matter?

The answer lies in a body of programming principles called functional programming (FP). You do not need to become a lambda calculus theorist to build reproducible pipelines. But understanding the core ideas—purity, composition, and immutability—will make you a vastly better data scientist, a better author of R and Python code, and a more effective collaborator with AI assistants.

Consider a typical data analysis script:

# Step 1
data <- read.csv("sales.csv")

# Step 2
data <- data[data$revenue > 0, ]

# Step 3
data$margin <- (data$revenue - data$cost) / data$revenue

# Step 4
model <- lm(margin ~ region, data = data)
# Python equivalent
import pandas as pd
data = pd.read_csv("sales.csv")
data = data[data["revenue"] > 0]
data["margin"] = (data["revenue"] - data["cost"]) / data["revenue"]

This code runs. But it possesses a hidden and dangerous property: state. Each step mutates the variable data in the global environment. The script can only be understood by reading it from top to bottom, in exact sequence.

If scripting with mutable state is a crack in the foundation of reproducibility, then computational notebooks (like Jupyter) are a gaping sinkhole. Notebooks introduce an even more insidious form of state: cell execution order. You can run cells out of order, re-run cell 3 after cell 7, or delete a cell whose variable persists in memory. What you see on screen no longer reflects the computational state of the kernel!

This is the root problem that functional programming solves.

3.3 Pure Functions: The Mathematical Ideal

In mathematics, a function has a beautiful property: for a given input, it always returns the exact same output. The function \(f(x) = x^2\) does not depend on what you computed earlier, nor does it mutate anything outside itself.

A pure function in programming satisfies two conditions:

  1. Deterministic: Given the same inputs, it always produces the same output. It depends only on its explicit parameters—never on global variables or hidden state.
  2. Zero Side Effects: It does not alter anything outside its scope. It does not modify global variables, rewrite files unexpectedly, or mutate input objects in place.

Compare these two functions:

# Impure: secretly depends on a global variable
threshold <- 0

filter_positive <- function(df) {
  df[df$value > threshold, ]  # What is threshold? Who defined it? When?
}

# Pure: all inputs are explicit
filter_above <- function(df, threshold) {
  df[df$value > threshold, ]  # Everything required is explicitly passed
}

The pure version is predictable. You can test it in isolation, run it in parallel, and reason about it without needing to know what happened elsewhere in the program.

3.4 T Nodes Are Pure Functions

This is not a metaphor. A T pipeline node is, by construction, a pure function:

  1. Explicit Inputs: Upstream data is passed into the node’s sandbox as named inputs. There is no global environment to accidentally read from.
  2. Explicit Single Output: A node returns exactly one thing: the artifact written to the Nix store by its serializer. A node cannot secretly alter another node’s output.
  3. Hermetic Execution: Because Nix runs the node inside a hermetic sandbox with no outside network or filesystem leakage, the execution is guaranteed to be pure.

Look at a concrete example:

p = pipeline {
  -- Node 1: Produce data. Pure: inputs = none, output = DataFrame (^ipc)
  data_node = rn(
    command = <{
      data.frame(
        x = c(1.0, 2.0, 3.0, 4.0, 5.0),
        y = c(0.0, 0.0, 1.0, 1.0, 1.0)
      )
    }>,
    serializer = ^ipc
  )

  -- Node 2: Fit model. Pure: inputs = data_node (^ipc), output = model (^pmml)
  model_node = rn(
    command = <{
      d <- transform(data_node, y = as.factor(y))
      glm(y ~ x, data = d, family = binomial(link = "logit"))
    }>,
    deserializer = ^ipc,
    serializer = ^pmml
  )
}

build_pipeline(p)

data_node takes no inputs and returns a DataFrame. model_node takes one DataFrame (data_node) and produces a model artifact. Neither can reach outside its sandbox.

Because nodes are pure functions, T can cache them safely: if data_node has not changed, T never re-evaluates it. Furthermore, the declaration order inside pipeline { } does not matter. T infers the execution graph solely from data dependencies.

3.5 A Pipeline Is Function Composition

When you write a pipeline in T, you are composing pure functions:

\[\text{Pipeline} = (f_n \circ \dots \circ f_2 \circ f_1)(\text{data})\]

This is identical to the pipe operator in R (|>) or method chaining in pandas:

# Function composition in R
mtcars |>
  filter(am == 1) |>
  select(mpg)

T elevates this concept to the architectural level. Each step is an explicit, named, cached pure function that can run in any language.

-- Pure R node
raw = rn(command = <{ read.csv("data.csv") }>, serializer = ^ipc)

-- Pure Python node composing on R output
transformed = pyn(
  command = <{
    transformed = raw.assign(log_val = numpy.log(raw["val"]))
  }>,
  deserializer = ^ipc,
  serializer = ^ipc
)

Because both nodes are pure, the serializer/deserializer contract (^ipc) functions as the type signature between them. The underlying runtime is an implementation detail!

3.6 Writing Clean, Pure Helper Functions

The pure function model applies not just to T nodes as a whole, but to the R and Python code you write inside those nodes.

To keep your code reproducible:

  • Never mutate inputs in place: Return a new object instead of modifying an existing one.
  • Never rely on global variables: Pass all configuration parameters explicitly.
  • Isolate file I/O: Separate functions that calculate values from functions that read/write disks.

3.6.1 Decoupling Logic: External Functions

You do not have to write all your computational code inline inside <{ ... }>. In fact, professional projects keep domain logic in plain .R or .py files loaded via the functions parameter, while command = <{ ... }> acts as a thin one-line call:

p = pipeline {
  raw = node(
    command = read_csv("data/sales.csv"),
    serializer = ^ipc
  )

  cleaned = rn(
    command = <{ clean_sales(raw) }>,
    functions = ["src/utils.R"],
    deserializer = ^ipc,
    serializer = ^ipc
  )

  model = pyn(
    command = <{ train_model(cleaned) }>,
    functions = ["src/train.py"],
    deserializer = ^ipc,
    serializer = ^pmml
  )
}

Notice the tremendous advantage of this approach: src/utils.R and src/train.py carry zero T-specific syntax. They are standard, idiomatic R and Python files containing pure functions. They can be:

  • Sourced or imported and debugged interactively in your IDE.
  • Tested using standard tools (pytest, testthat).
  • Reused by colleagues who do not use T.

T acts purely as the orchestration layer: handling scheduling, caching, sandboxing, and data exchange.

3.7 Hands-On Exercise: Decoupling a Pipeline with External Functions

In this exercise, you will put pure functional design into practice by building a pipeline that decouples its computational logic into standalone external .R and .py function files.

3.7.1 The Objective

Instead of writing multi-line logic inline inside <{ ... }>, you will:

  1. Scaffold a T project and declare the required R and Python dependencies in tproject.toml.
  2. Create a pure R helper function in src/helpers.R that filters sentinel values and computes derived columns without side effects.
  3. Write a pure R function in src/clean.R that composes src/helpers.R to process an input dataset.
  4. Write a pure Python function in src/summarize.py that takes the cleaned DataFrame and returns a summary dictionary.
  5. Orchestrate the workflow in src/pipeline.t using command = <{ ... }> and functions = [...].
  6. Verify caching and inspect the computed outputs.

3.7.2 Project Layout

By the end of this exercise, your project structure will look like this:

my_project/
├── data/
│   └── weather.csv
├── src/
│   ├── helpers.R        # Reusable pure helper functions
│   ├── clean.R          # Pure R cleaning function
│   ├── summarize.py     # Pure Python aggregation function
│   └── pipeline.t       # Declarative T orchestrator
├── tproject.toml
└── flake.nix

3.7.3 Step 1: Initialize the Project and Create a Toy Dataset

If you are starting fresh, initialize a new T project and enter its Nix shell:

nix shell --accept-flake-config github:b-rodrigues/tlang -c t init --project my_project
cd my_project
nix develop

Declare the R and Python packages needed for Arrow IPC (^ipc), JSON metadata (^json), and pandas in tproject.toml (if you skip this, t run will prompt you to add them automatically):

[r-dependencies]
packages = ["arrow", "jsonlite"]

[py-dependencies]
packages = ["pandas", "pyarrow"]

Next, create a small dataset data/weather.csv:

city,temperature,humidity,rainfall
Luxembourg,18.5,72,2.4
Esch,21.0,65,0.0
Differdange,-99.0,80,12.1
Dudelange,19.2,68,1.0
Wiltz,16.8,85,5.6

(Notice the faulty sensor reading -99.0 for Differdange!)


3.7.4 Step 2: Write Pure Helper Functions in src/helpers.R

Create src/helpers.R. This file will contain pure utility functions with explicit arguments and no global state:

  • Define clean_temperatures(df, min_valid = -40, max_valid = 55) that filters df to rows where temperature is between min_valid and max_valid (inclusive), adds a temp_fahrenheit column ((temperature * 9 / 5) + 32), and returns the resulting data frame.

Because clean_temperatures is a pure function, you can source it into an interactive R session or write a unit test with {testthat} without needing T or Nix running!


3.7.5 Step 3: Write the External Pure Functions

Now create the domain functions in standalone .R and .py files.

3.7.5.1 R Node Function: src/clean.R

Define a pure function clean_weather(df) that calls clean_temperatures(df) and returns the rows sorted by temperature descending.

3.7.5.2 Python Node Function: src/summarize.py

Define a pure function summarize_weather(df) (using pandas) that returns a dictionary with keys total_cities (int), avg_temp_c (float), avg_temp_f (float), and total_rainfall (float).

Notice that neither file contains any T-specific code or decorators, and neither depends on global pipeline variable names. They are 100% standard, portable R and Python functions!


3.7.6 Step 4: Orchestrate in src/pipeline.t

Now, link everything together declaratively in src/pipeline.t using command = <{ ... }> and functions = [...]:

  1. raw_weather: ingest data/weather.csv via node(command = read_csv("data/weather.csv"), serializer = ^ipc).
  2. cleaned_weather: an R node (rn()) calling clean_weather(raw_weather) inside command = <{ ... }>, sourcing ["src/helpers.R", "src/clean.R"] via functions, with deserializer = ^ipc and serializer = ^ipc.
  3. weather_summary: a Python node (pyn()) calling summarize_weather(cleaned_weather) inside command = <{ ... }>, loading ["src/summarize.py"] via functions, with deserializer = ^ipc and serializer = ^json.
  4. Execute build_pipeline(p) and print read_node(p.cleaned_weather) and read_node(p.weather_summary).
TipPrompting Your AI Assistant for Clean Architecture

When working with an AI coding assistant, enforce this architectural separation by prompting:

“Write a pure helper file src/helpers.R and a pure R function clean_weather(df) in src/clean.R. Ensure all functions only take explicit arguments with no global state. Then write a pure Python function summarize_weather(df) in src/summarize.py. Finally, connect them in src/pipeline.t using functions = [...] and one-line command = <{ ... }> calls. Keep all domain logic in the standalone R and Python files.”


3.7.7 Step 5: Run, Inspect, and Verify Caching

Run the pipeline:

t run src/pipeline.t
  1. Inspect Artifacts: The print(read_node(...)) calls at the bottom of src/pipeline.t display the 4-row cleaned DataFrame (excluding Differdange) and the summary dictionary (total_cities: 4, avg_temp_c: 18.875, avg_temp_f: 65.975, total_rainfall: 9.).
  2. Verify Caching: Re-run t run src/pipeline.t immediately without editing any files. T detects that no inputs or source files changed and prints: All nodes were already cached — nothing to build.
  3. Update External Logic: Add "max_temp_c": float(df["temperature"].max()) inside summarize_weather in src/summarize.py and re-run t run src/pipeline.t. T rebuilds with the updated file and prints the new max_temp_c: 21. field in weather_summary.

3.8 Summary

  • Mutable state in scripts and notebooks creates fragile, order-dependent code.
  • Pure functions are deterministic and side-effect free.
  • T nodes are pure functions running in isolated Nix sandboxes.
  • A pipeline is a Directed Acyclic Graph of function compositions.
  • Writing your analytical code in plain, pure R and Python files keeps your work testable and portable.