At the November 2026 BFPG Hack Day my friend Raphael implemented a workflow system in Lean, inspired by his experience with DBOS. I promised that I’d make my own toy implementation and this blog post 🙂

The code is at carlohamalainen/lean-workflow-demo.

What is a workflow system? Link to heading

Consider a typical data workflow: we read the data, perhaps apply a cleaning step, run a computation, and save the data:

data = load_data()

if some_condition(data):
    data = clean_data(data)

output = step_two(data)

output.save()

For small runs this is fine, but as the workflow scales up things get out of hand and our attention turns to other aspects of this problem:

  • If the computer/network goes down half way through a run, can we safely restart?
  • If a piece of work crashes, can it be safely restarted? Can we inspect its input and output?
  • Can I guarantee that a piece of work is scheduled precisely once?
  • Can I schedule work to run on a regular schedule (cron, timers)?
  • When a workflow is running, how can I inspect which nodes have executed, which ones are blocked, etc?

Observability is particularly difficult because we can’t easily look at the Python runtime to see which function is currently executing, or what happened to an earlier function (imagine looking at the stack while clean_data is running).

DBOS takes the approach of using the underlying Postgres database for durability. Databases give you good properties backed by decades of development and countless hours of user testing in production.

To define a DBOS workflow, we just annotate the steps and the top level workflow function:

@DBOS.step()
def load_data(): ...

@DBOS.step()
def clean_data(data): ...

@DBOS.step()
def step_two(data): ...

@DBOS.workflow()
def workflow():
    data = load_data()

    if some_condition(data):
        data = clean_data(data)

    return step_two(data)

The check some_condition should be deterministic so that a restart won’t run a different body of work.

There’s no separate orchestration server to run - DBOS runs inside your application:

import os
from dbos import DBOS, DBOSConfig

config: DBOSConfig = {
    "name": "my-app",
    "application_version": "0.1.0",
    "system_database_url": os.environ.get("DBOS_SYSTEM_DATABASE_URL"),
}
DBOS(config=config)
DBOS.launch()

There are many different ways to approach this problem, and DBOS has an extensive comparison with other orchestration systems.

I’ve previously used Nipype to good effect for a modern port of volgenmodel. It took a bit of work to implement wrappers for the MINC command line tools but once they were in place, creating the workflow felt very productive.

While I was at Standard Chartered I used their Shepherd workflow system to orchestrate jobs in Mu:

(Screenshot is from Damian’s talk)

Mu’s superpower is the ability to serialise almost anything, including closures. You can seamlessly launch a closure from your Windows desktop on a remote Linux server! Or email a closure to a friend with a subject line “lol please run this”.

Obligatory link to the Bank Python blog post, a great example of convergent evolution.

Constructing the workflow graph Link to heading

At its core, a workflow system constructs a graph: nodes are units of work, and edges represent dependencies, namely the output of one node is used as the input for another. The question is whether the graph is completely defined before the workflow launches, or if it can be changed while it is executing.

In the DBOS workflow from before, the test some_condition is a Python function. We have no way of knowing, without running it, whether it will be true or false.

def workflow():
    data = load_data()

    if some_condition(data): # must be deterministic
        data = clean_data(data)

    return step_two(data)

So there is no way of knowing if the workflow graph will contain a clean_data node. In other words, the graph can only be seen after a run, as its checkpoint history.

Conversely, we could decide that the graph must be fully defined before it is run.

A free applicative workflow in Lean Link to heading

Let’s wrap IO actions in a Job structure:

structure Job (α β : Type) where
  name : String
  run  : α → IO β

Here’s a job to load data, reading a file into a ByteArray.

def jobLoadData : Job String ByteArray :=
    { name := "job-load-data", run := fun path => IO.FS.readBinFile path }

Next, we need a type for building the graph. A step is a node (an IO action) and pure and ap connect values to the nodes that use them.

inductive Work : Type → Type 1 where
  | pure : α → Work α
  | ap   : Work (α → β) → Work α → Work β
  | step : (label : String) → Job α β → Work α → Work β

How to read this:

  • pure lets us promote a value into a Work, e.g. a constant, or a function.
  • ap applies a function in a Work to a value in a Work.
  • step applies a job to a Work value.

Let’s define the input file:

def wrkInput : Work String := .pure "/data/bigfile.txt"

And make a step, connecting wrkInput to jobLoadData:

def stepLoadData : Work ByteArray := .step "load-data:big" jobLoadData wrkInput

The Work type is naturally an applicative with this definition:

instance : Applicative Work where
  pure := .pure
  seq f x := .ap f (x ())

For the Haskell readers: Lean is strict so the <*> operator seq is defined

seq : {α β : Type u} → f (α → β) → (Unit → f α) → f β

where the second argument is taken “lazily”, using a Unit → f α function.

As an aside, you can do this in any language with closures, like Go:

x := func() int { return expensive() } // nothing runs yet
v := x()                               // runs now

My hot take: laziness is a mistake. Mu and Lean get this right with selective laziness.

Why not a Monad? Link to heading

We could add bind : Work α → (α → Work β) → Work β, but the second argument is a function. To find out which steps come after bind, you have to call it on a real α, which means running the first half. You can’t draw the graph without running it, and the scheduler can’t see two independent steps ahead of time and start them together.

ap doesn’t have this problem. Both arguments are Work values whose structure can be examined before anything runs. This is the trade-off between applicative and monadic workflows, and it is also where DBOS goes the other way. It gives you full monadic freedom (any Python control flow), and in return the “graph” only exists as a log of what happened.

Executing a workflow Link to heading

A Work value is only a description, so we need something to run it. eval is an interpreter with one case per constructor:

def Work.eval : Work α → IO α
  | .pure a => return a
  | .ap f x => do
    let g ← f.eval      -- a function
    let a ← x.eval      -- its argument
    return g a
  | .step _ j input => do
    let a ← input.eval  -- whatever shape the input has
    j.run a

pure hands back its value, ap evaluates both sides and applies one to the other, and step evaluates its input and then runs the job. The step case doesn’t care what its input looks like: pure 42, another step, or a big ap tree that pairs two steps together. Each one comes back as a plain value of the right type.

This version has one problem: if the same step is used twice, it runs twice. The eval in the repo keeps a memo table keyed by the step’s label, so each label runs at most once. It also returns a Task per step instead of a value, so in parallel mode a step starts as soon as its input is ready. Swapping j.run a for “send the job’s name and input to a worker process” gives remote execution, and the workflow doesn’t change at all. These are all interpreters for the same value. The full version is in Work/Exec.lean.

A workflow Link to heading

Here’s an example workflow. Fetch three documents, split each into words, count each one’s words, compare two of them, and write a summary:

fetch:intro.md ── words:intro.md ──┬── stats:intro.md ──┐
                                   └──┐                 │
fetch:guide.md ── words:guide.md ─────┴─ overlap:… ─────┼── summary
                                   └──── stats:guide.md ┤
fetch:faq.md ──── words:faq.md ──────── stats:faq.md ───┘

The jobs are ordinary functions, and each one sleeps to stand in for slow IO:

-- helper to construct a Job
def job (name : String) (run : α → IO β) : Job α β := { name, run }

def tokenize : Job Doc Words := job "tokenize" fun d => do
  IO.sleep 700
  return { name := d.name, words := tokenizeText d.text }

def overlap : Job (Words × Words) Overlap := job "overlap" fun (a, b) => do
  IO.sleep 1200
  ...   -- how many distinct words the two documents share

fetchDoc looks a document up in a built-in list (in real life it would read a file or call an API), wordStats counts words and finds the top three, and summarize turns everything into one line of text. The workflow wires them together:

-- helper to construct a .step
def Work.call (label : String) (j : Job α β) (input : Work α) : Work β := .step label j input

def fetch (name : String) (delayMs : Nat) : Work Doc :=
  Work.call s!"fetch:{name}" fetchDoc (pure { name, delayMs })

def wordsOf (name : String) (delayMs : Nat) : Work Words :=
  Work.call s!"words:{name}" tokenize (fetch name delayMs)

def workflow : Work String :=
  let intro := wordsOf "intro.md" 1500
  let guide := wordsOf "guide.md" 2500
  let faq   := wordsOf "faq.md"   1000

  let stats name w := Work.call s!"stats:{name}" wordStats w

  let both := Work.call
                "overlap:intro.md~guide.md"
                overlap
                (Prod.mk <$> intro <*> guide)

  let summary := (fun i g f o => Summary.mk #[i, g, f] o)
    <$> stats "intro.md" intro <*> stats "guide.md" guide <*> stats "faq.md" faq <*> both

  Work.call "summary" summarize summary

Running it gives:

intro.md: 14 words, top graph, step, steps; guide.md: 19 words, top step, steps, build;
faq.md: 12 words, top name, already, code. intro.md and guide.md share 4 words (17%).

intro is used twice, once by stats:intro.md and once by the overlap step. As far as our code can tell, Work is a tree, so words:intro.md shows up in two places. (In memory it’s actually one shared object, as the next section shows, but ordinary code can’t observe that.) Both places have the same label, though, and each executor treats a label as a single node. That gives us a DAG with shared nodes instead of a tree that repeats work.

This is the main simplification in the design. The alternatives are a builder monad that hands out fresh node IDs, or hash-consing. Explicit labels are what Airflow task_ids and DBOS step names do anyway, and they are easy to understand.

Interlude: what is actually in memory? Link to heading

The Work structure might feel a little abstract, so let’s poke around in memory and look at concrete values. It’s a few records on the heap, with pointers. We can print them.

To keep the output short, here is a three-step workflow that uses one input twice:

def tiny : Work Overlap :=
  let intro := wordsOf "intro.md" 1500
  Work.call "overlap:intro.md~intro.md" overlap (Prod.mk <$> intro <*> intro)

toywork dump tiny walks the value and prints every object it reaches, with its memory address:

@2c653821540 Work.step "overlap:intro.md~intro.md"
├─ label: @675352a92de8 "overlap:intro.md~intro.md"
├─ job:   @2c653841110 Job "overlap"  (fields: name, plus pointers to compiled functions)
└─ input: @2c653770318 Work.ap
   ├─ fn:  @2c653770300 Work.ap
   │  ├─ fn:  @2c653782330 Work.pure
   │  │  └─ value: @2c653760b70  (some value; its type isn't stored)
   │  └─ arg: @2c653821f00 Work.step "words:intro.md"
   │     ├─ label: @2c6537b03c0 "words:intro.md"
   │     ├─ job:   @2c653840230 Job "tokenize"  (fields: name, plus pointers to compiled functions)
   │     └─ input: @2c653821f20 Work.step "fetch:intro.md"
   │        ├─ label: @2c6537b0a00 "fetch:intro.md"
   │        ├─ job:   @2c653840ce8 Job "fetchDoc"  (fields: name, plus pointers to compiled functions)
   │        └─ input: @2c653782190 Work.pure
   │           └─ value: @2c653770180  (some value; its type isn't stored)
   └─ arg: @2c653821f00 Work.step "words:intro.md"  ↑ already shown: a second pointer to the same object

Here is the same thing as a picture, with one box per object and one arrow per pointer (toywork dump tiny --mermaid):

flowchart TD
  o2c653821540["step overlap:intro.md~intro.md<br/>@2c653821540"]
  o2c653821540 -- job --> j2c653841110
  o2c653821540 -- input --> o2c653770318
  j2c653841110[/"Job overlap<br/>@2c653841110"/]
  o2c653770318["ap<br/>@2c653770318"]
  o2c653770318 -- fn --> o2c653770300
  o2c653770318 -- arg --> o2c653821f00
  o2c653770300["ap<br/>@2c653770300"]
  o2c653770300 -- fn --> o2c653782330
  o2c653770300 -- arg --> o2c653821f00
  o2c653782330["pure<br/>@2c653782330"]
  o2c653782330 -- value --> v2c653760b70(["a value<br/>@2c653760b70"])
  o2c653821f00["step words:intro.md<br/>@2c653821f00"]
  o2c653821f00 -- job --> j2c653840230
  o2c653821f00 -- input --> o2c653821f20
  j2c653840230[/"Job tokenize<br/>@2c653840230"/]
  o2c653821f20["step fetch:intro.md<br/>@2c653821f20"]
  o2c653821f20 -- job --> j2c653840ce8
  o2c653821f20 -- input --> o2c653782190
  j2c653840ce8[/"Job fetchDoc<br/>@2c653840ce8"/]
  o2c653782190["pure<br/>@2c653782190"]
  o2c653782190 -- value --> v2c653770180(["a value<br/>@2c653770180"])

How to read it:

  • Each @… is one object, and the hex number is where it lives in memory. (These are like Python’s id().) Each object is a small record. A Work.step record has three fields: a pointer to the label string, a pointer to a Job record, and a pointer to another Work record for its input.
  • <$> and <*> leave nothing behind except ap and pure records. Prod.mk <$> intro <*> intro became ap (ap (pure Prod.mk) intro) intro, two aps nested to the left. The value inside that pure is the function Prod.mk itself. Functions are heap objects too, so it’s just another pointer.
  • Look at the last line. words:intro.md at @2c653821f00 appears twice: the inner ap’s arg and the outer ap’s arg point to the same object. let intro := … built one object, and two fields point to it. In memory, our “tree” is already a DAG. The full toywork dump shows the same thing for jobs: all three stats:* steps point to one Job "wordStats" record.
  • The types are missing. There is no α, no β, and nothing about Type 1. Types and universes exist for the type checker and are erased before the program runs. At run time an ap is a header plus two pointers. Roughly: an 8-byte header, then 8 bytes per field, which makes pure 16 bytes, ap 24, and step 32. The whole demo workflow is 22 of these records, under 600 bytes, plus the strings and job records they point to.

Prior art Link to heading

None of this is new (apart from the Lean implementation). The design brings together a few well-known ideas, mostly from the Haskell world.

Free applicative functors. Paolo Capriotti and Ambrus Kaposi, Free Applicative Functors (MSFP 2014). This is the construction behind Work. Their version puts the primitive inside the Ap constructor (Pure a | Ap (f a) (FreeAp f (a → b))), which gives one normal form per value. Ours keeps pure and ap as separate constructors and adds step as the primitive. That form isn’t normalised, but it reads more directly as “a tree of glue with nodes in it”.

Haxl. Simon Marlow, Louis Brandy, Jonathan Coens and Jon Purdy, There is no Fork: an Abstraction for Efficient, Concurrent, and Concise Data Access (ICFP 2014). Facebook’s data-access library - they liked applicatives enough to add ApplicativeDo to GHC.

Shake, and Build Systems à la Carte. Neil Mitchell, Shake Before Building (ICFP 2012). Andrey Mokhov, Neil Mitchell and Simon Peyton Jones, Build Systems à la Carte (ICFP 2018). Shake is deliberately monadic: a build rule can read a file and only then decide what else it depends on. Build Systems à la Carte names the trade-off in this post: with applicative dependencies (Make, Bazel) the graph is known before anything runs, and with monadic ones (Shake, Excel) you find it by running.

Selective applicative functors. Andrey Mokhov, Georgy Lukyanov, Simon Marlow and Jeremie Dimino, Selective Applicative Functors (ICFP 2019), with a Haskell library, selective. The middle ground between applicative and monad: static branches, so both sides of an if still appear in the graph.

Funflow and Porcupine. These are Tweag’s Haskell workflow libraries and the closest published relatives of this toy. Funflow has named steps, a content-addressed store of step outputs, and steps that run externally (for example in Docker). It is built on arrows rather than a plain applicative, which gives a similarly static graph plus some extra structure. Porcupine builds data pipelines on top of Funflow.

DBOS (dbos.dev), along with Temporal and Azure Durable Functions, takes the monadic route: durable execution by journaling the steps of an ordinary, deterministic function.

Loading comments…

Comment form pending Cloudflare verification...