Programming Search⌘K

Conceptresearch

Build system models

Also called build systems a la carte, build systems à la carte, scheduler and rebuilder, verifying traces, constructive traces, early cutoff, minimal build system, dynamic dependencies.

A model of build systems by Mokhov, Mitchell and Peyton Jones splits each build system into a scheduler, which orders the tasks, and a rebuilder, which decides if a task must run again.

Applies to
core-languages

Idea

Build tools differ in many ways. Make compares the times of files, Excel recalculates the cells of a sheet, Shake finds dependencies while its rules run, and Bazel shares results between users through a cache. The paper Build Systems à la Carte, by Andrey Mokhov, Neil Mitchell and Simon Peyton Jones, describes all of them with one small model.1

In the model, a build system brings a store up to date. The store maps keys to values. In a software build the store is the file system, the keys are file names and the values are the contents of the files. In Excel the keys are cell names such as A1.1 Some keys are inputs, which the user sets. A task description says how to compute the value of each other key from the values of the keys that it needs. The store also holds the persistent build information: what the build system keeps from one run to the next, such as file times or hashes.1

The main result of the paper is that two choices are usually built deep into each build system, and that the two are independent:1

  • The scheduler decides the order in which the tasks run.
  • The rebuilder decides if a task must run, or if the value that the store holds is still up to date.

A build system is then one scheduler with one rebuilder. The paper places real build systems in a table of these pairs, and finds pairs that no tool used.1

How it works

Correctness and minimality. The model gives exact meanings to two words that build tools use loosely. A build result is correct when the inputs are unchanged, and when each non-input key that the target needs holds the value that its task computes from the final store.1 A build system is minimal when it runs each task at most once per build, and only when the task transitively depends on an input that changed since the last build.1

Tasks and their dependencies. Each task gets a callback, fetch, that returns the value of another key. When a task is an applicative computation, the keys that it fetches are fixed, and a build system can list them without running the task. When a task is a monadic computation, it can choose the next key from the value of a key that it already fetched, so its dependencies are dynamic.1 An Excel formula with INDIRECT reads a cell whose name it computes. A Shake rule can read a list of files from a file that the build made, and then depend on each file in the list.1

**Three schedulers.**1

  • A topological scheduler computes one linear order of the tasks before it runs them. It must know all the dependencies first, so it cannot handle dynamic dependencies. Make uses it.
  • A restarting scheduler runs the tasks in some order and finds the dependencies as it goes. When a task fetches a key that is out of date, the scheduler stops the task, builds the key, and runs the task again later. Excel keeps the order that it found, the calc chain, for the next build, so that it seldom has to stop a task. The build engine of Bazel also restarts tasks.
  • A suspending scheduler builds a dependency at the moment that a task asks for it, and the task waits. With a record of the keys that it already built, this gives a minimal build system with dynamic dependencies. Shake uses it.

**Four rebuilders.**1

  • A dirty bit is one bit per key. After a build all bits are clean, and a change marks a key dirty. Excel has a dirty bit for each cell. Make uses file times as a dirty bit: a file is dirty when it is older than one of its dependencies.
  • A verifying trace records, for each key, the hashes of the dependencies that the task read in the last run, and the hash of its result. The key is up to date when each recorded dependency still has the same hash. Shake and Ninja work this way.
  • A constructive trace also stores the result value. A build system can keep many traces for each key and share them between users. When a trace matches, the build system copies its value into the store and does not run the task. This is a cloud build.
  • A deep constructive trace records only the hashes of the terminal inputs, not of the keys between them. The check is faster, but the tasks must be deterministic.

The paper puts the pairs in a table. Eight of the twelve cells hold a real build system:1

Rebuilder Topological Restarting Suspending
Dirty bit Make Excel none
Verifying traces Ninja none Shake
Constructive traces CloudBuild Bazel none
Deep constructive traces Buck none Nix

The authors say that each empty cell gives a build system that works. They call the suspending scheduler with constructive traces Cloud Shake, because it would join the dynamic dependencies of Shake with the shared cache of Bazel.1

Early cutoff. When a task runs again and gives the same value as before, the tasks that depend on it do not need to run. Shake and Bazel stop the build there, and Make and Excel do not.1 With file times, Make cannot mark a file clean without marking the files that depend on it dirty.1 Ninja gives a form of early cutoff with the restat rule variable: after the command runs, "Each output whose modification time the command did not change will be treated as though it had never needed to be built."2

In languages

LanguageVerdictNote
PythonIdiom
C++IdiomA std::map of std::function tasks, and a recursive std::function or a member function for the suspending fetch. Alternative: The C# example.
JavaIdiom
CIdiomKeys as array indices, tasks as function pointers that take a fetch callback and a context pointer, and arrays for the traces. Alternative: The Go example.
C#Idiom
JavaScriptIdiomA Map from each key to a function that takes fetch, a closure for the suspending fetch, and arrays for the traces. Alternative: The Python example.
TypeScriptIdiomAs in JavaScript, with a function type for a task that takes the fetch callback and returns a value. Alternative: The C# example.
GoIdiom
RustIdiomA HashMap of boxed closures for the tasks. A suspending fetch that calls itself needs a function with the state passed in, or RefCell for the store. Alternative: The Go example.
KotlinIdiomA map of lambdas that take fetch, and data classes for the traces, as in the Java example. Alternative: The Java example.
SQLIdiomTables of keys, values and traces can store the persistent build information. The tasks themselves need a host language. Alternative: The Python example.
BashIdiomMake, ninja and other build tools are the usual way to run a build from the shell. A model of the scheduler and the rebuilder needs a general language. Alternative: The Python example.
PowerShellIdiomHashtables of script blocks for the tasks, and a recursive function for the suspending fetch. Alternative: The C# example.
HTMLDoes not applyMarkup has no tasks or stored build information.
CSSDoes not applyStyle rules have no tasks or stored build information.
Regular expressionsDoes not applyA pattern has no tasks or stored build information.

The examples model a small sheet. The inputs are A1 = 10, A2 = 20 and C1 = 1. The tasks are B1 = A1 + A2, B2 = B1 * 2, and B3 = B2 when C1 is 1 and B3 = A2 when it is not. So B3 has a dynamic dependency. Each example builds the targets B2 and B3 with two build systems that share the same tasks:

  • Make-like: a topological scheduler with a dirty bit. It needs a static list of dependencies, so the list for B3 holds C1, B2 and A2. Writing an input sets its dirty bit, as writing a file sets its time.
  • Shake-like: a suspending scheduler with verifying traces. A task calls fetch, and the build system brings that key up to date before it returns. The hash in a trace is the value as text.

Then the examples change the inputs and print the tasks that each build system runs:

  • A2 = 20 again writes the same value. The Make-like system runs all three tasks. The Shake-like system compares the hashes and runs nothing.
  • A1 = 11, A2 = 19 keeps B1 at 30. The Shake-like system runs B1, sees the same result, and stops there: this is early cutoff.
  • C1 = 2 makes B3 read A2 in place of B2. Both systems run only B3.
  • A1 = 12 changes B1 and B2. The Make-like system also runs B3, because its static list holds B2. The trace of the Shake-like system shows that B3 read only C1 and A2 in its last run.

At the end, both systems hold the same values. Both are correct, and only the Shake-like one is minimal.

PythonGitHub
# Two build systems from the same parts: a scheduler and a rebuilder.
# The tasks are a small spreadsheet. B3 has a dynamic dependency.

TASKS = {
    "B1": lambda fetch: fetch("A1") + fetch("A2"),
    "B2": lambda fetch: fetch("B1") * 2,
    "B3": lambda fetch: fetch("B2") if fetch("C1") == 1 else fetch("A2"),
}
# A topological scheduler must know the dependencies before the build.
# For B3 it must list both branches.
STATIC_DEPS = {"B1": ["A1", "A2"], "B2": ["B1"], "B3": ["C1", "B2", "A2"]}
TARGETS = ["B2", "B3"]


class MakeLike:
    """Topological scheduler with a dirty bit."""

    def __init__(self, inputs):
        self.store = dict(inputs)
        self.dirty = set(inputs)

    def set_input(self, key, value):
        self.store[key] = value
        self.dirty.add(key)  # writing a file sets its time, even with the same content

    def build(self):
        order, seen = [], set()

        def visit(k):
            if k in seen or k not in TASKS:
                return
            seen.add(k)
            for d in STATIC_DEPS[k]:
                visit(d)
            order.append(k)

        for t in TARGETS:
            visit(t)
        ran = []
        for k in order:
            if k not in self.store or any(d in self.dirty for d in STATIC_DEPS[k]):
                self.store[k] = TASKS[k](lambda d: self.store[d])
                self.dirty.add(k)
                ran.append(k)
        self.dirty.clear()
        return ran


class ShakeLike:
    """Suspending scheduler with verifying traces."""

    def __init__(self, inputs):
        self.store = dict(inputs)
        self.traces = {}  # key -> (list of (dependency, hash), hash of the result)

    def set_input(self, key, value):
        self.store[key] = value

    def build(self):
        done, ran = set(), []

        def fetch(k):
            if k not in TASKS or k in done:
                return self.store[k]
            trace = self.traces.get(k)
            if trace is not None and str(self.store[k]) == trace[1]:
                if all(str(fetch(d)) == h for d, h in trace[0]):
                    done.add(k)
                    return self.store[k]
            deps = []

            def tracked(d):
                # The task stops here until d is up to date: this is the suspending scheduler.
                v = fetch(d)
                deps.append((d, str(v)))
                return v

            v = TASKS[k](tracked)
            self.store[k] = v
            self.traces[k] = (deps, str(v))
            done.add(k)
            ran.append(k)
            return v

        for t in TARGETS:
            fetch(t)
        return ran


inputs = {"A1": 10, "A2": 20, "C1": 1}
make, shake = MakeLike(inputs), ShakeLike(inputs)
steps = [
    ("clean build", {}),
    ("A2 = 20 again", {"A2": 20}),
    ("A1 = 11, A2 = 19", {"A1": 11, "A2": 19}),
    ("C1 = 2", {"C1": 2}),
    ("A1 = 12", {"A1": 12}),
]
print(f"{'step':<18}{'make-like':<14}shake-like")
for name, changes in steps:
    for k, v in changes.items():
        make.set_input(k, v)
        shake.set_input(k, v)
    m = " ".join(make.build()) or "-"
    s = " ".join(shake.build()) or "-"
    print(f"{name:<18}{m:<14}{s}")
print("same values:", all(make.store[k] == shake.store[k] for k in TASKS))
print("B1, B2, B3 =", shake.store["B1"], shake.store["B2"], shake.store["B3"])
Output
step              make-like     shake-like
clean build       B1 B2 B3      B1 B2 B3
A2 = 20 again     B1 B2 B3      -
A1 = 11, A2 = 19  B1 B2 B3      B1
C1 = 2            B3            B3
A1 = 12           B1 B2 B3      B1 B2
same values: True
B1, B2, B3 = 31 62 19
  • Verdict: idiom. A dict maps each key to a task, and a task is a lambda that takes fetch. The dict of static dependencies is used only by the Make-like system.
  • ShakeLike.build defines fetch inside the build, so the set done belongs to one run. tracked wraps fetch and records each key that the task reads, in order, with its hash.
  • all stops at the first dependency whose hash changed. So when C1 changes, the old trace of B3 does not make the build fetch B2.
JavaGitHub
// Two build systems from the same parts: a scheduler and a rebuilder.
// The tasks are a small spreadsheet. B3 has a dynamic dependency.
import java.util.*;
import java.util.function.Function;

public class Main {
    interface Task {
        int run(Function<String, Integer> fetch);
    }

    static final Map<String, Task> TASKS = Map.of(
        "B1", f -> f.apply("A1") + f.apply("A2"),
        "B2", f -> f.apply("B1") * 2,
        "B3", f -> f.apply("C1") == 1 ? f.apply("B2") : f.apply("A2"));
    // A topological scheduler must know the dependencies before the build.
    // For B3 it must list both branches.
    static final Map<String, List<String>> STATIC_DEPS = Map.of(
        "B1", List.of("A1", "A2"), "B2", List.of("B1"), "B3", List.of("C1", "B2", "A2"));
    static final List<String> TARGETS = List.of("B2", "B3");

    interface BuildSystem {
        void setInput(String key, int value);
        List<String> build();
        Map<String, Integer> store();
    }

    /** Topological scheduler with a dirty bit. */
    static class MakeLike implements BuildSystem {
        final Map<String, Integer> store = new HashMap<>();
        final Set<String> dirty = new HashSet<>();

        public void setInput(String key, int value) {
            store.put(key, value);
            dirty.add(key); // writing a file sets its time, even with the same content
        }

        void visit(String k, Set<String> seen, List<String> order) {
            if (!TASKS.containsKey(k) || !seen.add(k)) return;
            for (String d : STATIC_DEPS.get(k)) visit(d, seen, order);
            order.add(k);
        }

        public List<String> build() {
            List<String> order = new ArrayList<>();
            Set<String> seen = new HashSet<>();
            for (String t : TARGETS) visit(t, seen, order);
            List<String> ran = new ArrayList<>();
            for (String k : order) {
                boolean changed = STATIC_DEPS.get(k).stream().anyMatch(dirty::contains);
                if (!store.containsKey(k) || changed) {
                    store.put(k, TASKS.get(k).run(store::get));
                    dirty.add(k);
                    ran.add(k);
                }
            }
            dirty.clear();
            return ran;
        }

        public Map<String, Integer> store() { return store; }
    }

    record Dep(String key, String hash) {}
    record Trace(List<Dep> deps, String result) {}

    /** Suspending scheduler with verifying traces. */
    static class ShakeLike implements BuildSystem {
        final Map<String, Integer> store = new HashMap<>();
        final Map<String, Trace> traces = new HashMap<>();
        Set<String> done;
        List<String> ran;

        public void setInput(String key, int value) { store.put(key, value); }

        int fetch(String k) {
            if (!TASKS.containsKey(k) || done.contains(k)) return store.get(k);
            Trace t = traces.get(k);
            if (t != null && String.valueOf(store.get(k)).equals(t.result())) {
                boolean upToDate = true;
                for (Dep d : t.deps()) {
                    if (!String.valueOf(fetch(d.key())).equals(d.hash())) { upToDate = false; break; }
                }
                if (upToDate) { done.add(k); return store.get(k); }
            }
            List<Dep> deps = new ArrayList<>();
            int v = TASKS.get(k).run(d -> {
                // The task waits here until d is up to date: this is the suspending scheduler.
                int dv = fetch(d);
                deps.add(new Dep(d, String.valueOf(dv)));
                return dv;
            });
            store.put(k, v);
            traces.put(k, new Trace(deps, String.valueOf(v)));
            done.add(k);
            ran.add(k);
            return v;
        }

        public List<String> build() {
            done = new HashSet<>();
            ran = new ArrayList<>();
            for (String t : TARGETS) fetch(t);
            return ran;
        }

        public Map<String, Integer> store() { return store; }
    }

    static String show(List<String> ran) {
        return ran.isEmpty() ? "-" : String.join(" ", ran);
    }

    public static void main(String[] args) {
        BuildSystem make = new MakeLike(), shake = new ShakeLike();
        for (BuildSystem b : List.of(make, shake)) {
            b.setInput("A1", 10); b.setInput("A2", 20); b.setInput("C1", 1);
        }
        Object[][] steps = {
            {"clean build", Map.of()},
            {"A2 = 20 again", Map.of("A2", 20)},
            {"A1 = 11, A2 = 19", Map.of("A1", 11, "A2", 19)},
            {"C1 = 2", Map.of("C1", 2)},
            {"A1 = 12", Map.of("A1", 12)},
        };
        System.out.printf("%-18s%-14s%s%n", "step", "make-like", "shake-like");
        for (Object[] step : steps) {
            @SuppressWarnings("unchecked")
            Map<String, Integer> changes = (Map<String, Integer>) step[1];
            for (BuildSystem b : List.of(make, shake)) changes.forEach(b::setInput);
            System.out.printf("%-18s%-14s%s%n", step[0], show(make.build()), show(shake.build()));
        }
        boolean same = TASKS.keySet().stream().allMatch(k -> make.store().get(k).equals(shake.store().get(k)));
        System.out.println("same values: " + same);
        Map<String, Integer> s = shake.store();
        System.out.println("B1, B2, B3 = " + s.get("B1") + " " + s.get("B2") + " " + s.get("B3"));
    }
}
Output
step              make-like     shake-like
clean build       B1 B2 B3      B1 B2 B3
A2 = 20 again     B1 B2 B3      -
A1 = 11, A2 = 19  B1 B2 B3      B1
C1 = 2            B3            B3
A1 = 12           B1 B2 B3      B1 B2
same values: true
B1, B2, B3 = 31 62 19
  • Verdict: idiom. A task is a functional interface that takes a Function<String, Integer> as its fetch callback, and the tasks are lambdas in a Map.of.
  • The Make-like system passes store::get as fetch, so a task reads the store directly. The Shake-like system passes a lambda that first brings the key up to date with fetch, then records it.
  • record Dep and record Trace hold the verifying trace: the dependencies with their hashes, and the hash of the result.
// Two build systems from the same parts: a scheduler and a rebuilder.
// The tasks are a small spreadsheet. B3 has a dynamic dependency.
using System;
using System.Collections.Generic;
using System.Linq;

static class Model
{
    public static readonly Dictionary<string, Func<Func<string, int>, int>> Tasks = new()
    {
        ["B1"] = f => f("A1") + f("A2"),
        ["B2"] = f => f("B1") * 2,
        ["B3"] = f => f("C1") == 1 ? f("B2") : f("A2"),
    };
    // A topological scheduler must know the dependencies before the build.
    // For B3 it must list both branches.
    public static readonly Dictionary<string, string[]> StaticDeps = new()
    {
        ["B1"] = new[] { "A1", "A2" },
        ["B2"] = new[] { "B1" },
        ["B3"] = new[] { "C1", "B2", "A2" },
    };
    public static readonly string[] Targets = { "B2", "B3" };
}

interface IBuildSystem
{
    Dictionary<string, int> Store { get; }
    void SetInput(string key, int value);
    List<string> Build();
}

// Topological scheduler with a dirty bit.
class MakeLike : IBuildSystem
{
    public Dictionary<string, int> Store { get; } = new();
    readonly HashSet<string> dirty = new();

    public void SetInput(string key, int value)
    {
        Store[key] = value;
        dirty.Add(key); // writing a file sets its time, even with the same content
    }

    void Visit(string k, HashSet<string> seen, List<string> order)
    {
        if (!Model.Tasks.ContainsKey(k) || !seen.Add(k)) return;
        foreach (var d in Model.StaticDeps[k]) Visit(d, seen, order);
        order.Add(k);
    }

    public List<string> Build()
    {
        var order = new List<string>();
        var seen = new HashSet<string>();
        foreach (var t in Model.Targets) Visit(t, seen, order);
        var ran = new List<string>();
        foreach (var k in order)
        {
            if (!Store.ContainsKey(k) || Model.StaticDeps[k].Any(dirty.Contains))
            {
                Store[k] = Model.Tasks[k](d => Store[d]);
                dirty.Add(k);
                ran.Add(k);
            }
        }
        dirty.Clear();
        return ran;
    }
}

// Suspending scheduler with verifying traces.
class ShakeLike : IBuildSystem
{
    public Dictionary<string, int> Store { get; } = new();
    readonly Dictionary<string, (List<(string Key, string Hash)> Deps, string Result)> traces = new();
    HashSet<string> done = new();
    List<string> ran = new();

    public void SetInput(string key, int value) => Store[key] = value;

    int Fetch(string k)
    {
        if (!Model.Tasks.ContainsKey(k) || done.Contains(k)) return Store[k];
        if (traces.TryGetValue(k, out var t) && Store[k].ToString() == t.Result
            && t.Deps.All(d => Fetch(d.Key).ToString() == d.Hash))
        {
            done.Add(k);
            return Store[k];
        }
        var deps = new List<(string, string)>();
        int v = Model.Tasks[k](d =>
        {
            // The task waits here until d is up to date: this is the suspending scheduler.
            int dv = Fetch(d);
            deps.Add((d, dv.ToString()));
            return dv;
        });
        Store[k] = v;
        traces[k] = (deps, v.ToString());
        done.Add(k);
        ran.Add(k);
        return v;
    }

    public List<string> Build()
    {
        done = new();
        ran = new();
        foreach (var t in Model.Targets) Fetch(t);
        return ran;
    }
}

static class Program
{
    static string Show(List<string> ran) => ran.Count == 0 ? "-" : string.Join(" ", ran);

    static void Main()
    {
        IBuildSystem make = new MakeLike(), shake = new ShakeLike();
        foreach (var b in new[] { make, shake })
        {
            b.SetInput("A1", 10); b.SetInput("A2", 20); b.SetInput("C1", 1);
        }
        var steps = new (string Name, (string, int)[] Changes)[]
        {
            ("clean build", new (string, int)[0]),
            ("A2 = 20 again", new[] { ("A2", 20) }),
            ("A1 = 11, A2 = 19", new[] { ("A1", 11), ("A2", 19) }),
            ("C1 = 2", new[] { ("C1", 2) }),
            ("A1 = 12", new[] { ("A1", 12) }),
        };
        Console.WriteLine($"{"step",-18}{"make-like",-14}shake-like");
        foreach (var (name, changes) in steps)
        {
            foreach (var b in new[] { make, shake })
                foreach (var (k, v) in changes) b.SetInput(k, v);
            Console.WriteLine($"{name,-18}{Show(make.Build()),-14}{Show(shake.Build())}");
        }
        bool same = Model.Tasks.Keys.All(k => make.Store[k] == shake.Store[k]);
        Console.WriteLine($"same values: {same}");
        var s = shake.Store;
        Console.WriteLine($"B1, B2, B3 = {s["B1"]} {s["B2"]} {s["B3"]}");
    }
}
Output
step              make-like     shake-like
clean build       B1 B2 B3      B1 B2 B3
A2 = 20 again     B1 B2 B3      -
A1 = 11, A2 = 19  B1 B2 B3      B1
C1 = 2            B3            B3
A1 = 12           B1 B2 B3      B1 B2
same values: True
B1, B2, B3 = 31 62 19
  • Verdict: idiom. A Dictionary<string, Func<Func<string, int>, int>> holds the tasks: each task is a function from the fetch callback to a value.
  • A trace is a tuple of a list of (Key, Hash) tuples and the hash of the result. All stops at the first dependency whose hash changed.
  • Both build systems implement IBuildSystem, so Main changes the inputs of both in one loop and compares their stores at the end.
// Two build systems from the same parts: a scheduler and a rebuilder.
// The tasks are a small spreadsheet. B3 has a dynamic dependency.
package main

import (
	"fmt"
	"strconv"
	"strings"
)

type fetchFunc func(key string) int

var tasks = map[string]func(fetch fetchFunc) int{
	"B1": func(fetch fetchFunc) int { return fetch("A1") + fetch("A2") },
	"B2": func(fetch fetchFunc) int { return fetch("B1") * 2 },
	"B3": func(fetch fetchFunc) int {
		if fetch("C1") == 1 {
			return fetch("B2")
		}
		return fetch("A2")
	},
}

// A topological scheduler must know the dependencies before the build.
// For B3 it must list both branches.
var staticDeps = map[string][]string{"B1": {"A1", "A2"}, "B2": {"B1"}, "B3": {"C1", "B2", "A2"}}
var targets = []string{"B2", "B3"}

type dep struct {
	key, hash string
}

type trace struct {
	deps   []dep
	result string
}

// makeLike is a topological scheduler with a dirty bit.
type makeLike struct {
	store map[string]int
	dirty map[string]bool
}

func (m *makeLike) setInput(k string, v int) {
	m.store[k] = v
	// Writing a file sets its time, even with the same content.
	m.dirty[k] = true
}

func (m *makeLike) build() []string {
	var order []string
	seen := map[string]bool{}
	var visit func(k string)
	visit = func(k string) {
		if _, isTask := tasks[k]; seen[k] || !isTask {
			return
		}
		seen[k] = true
		for _, d := range staticDeps[k] {
			visit(d)
		}
		order = append(order, k)
	}
	for _, t := range targets {
		visit(t)
	}
	var ran []string
	read := func(d string) int { return m.store[d] }
	for _, k := range order {
		_, built := m.store[k]
		changed := false
		for _, d := range staticDeps[k] {
			changed = changed || m.dirty[d]
		}
		if !built || changed {
			m.store[k] = tasks[k](read)
			m.dirty[k] = true
			ran = append(ran, k)
		}
	}
	m.dirty = map[string]bool{}
	return ran
}

// shakeLike is a suspending scheduler with verifying traces.
type shakeLike struct {
	store  map[string]int
	traces map[string]trace
}

func (s *shakeLike) setInput(k string, v int) {
	s.store[k] = v
}

func (s *shakeLike) build() []string {
	done := map[string]bool{}
	var ran []string
	var fetch func(k string) int
	fetch = func(k string) int {
		task, isTask := tasks[k]
		if !isTask || done[k] {
			return s.store[k]
		}
		if t, ok := s.traces[k]; ok && strconv.Itoa(s.store[k]) == t.result {
			upToDate := true
			for _, d := range t.deps {
				if strconv.Itoa(fetch(d.key)) != d.hash {
					upToDate = false
					break
				}
			}
			if upToDate {
				done[k] = true
				return s.store[k]
			}
		}
		var deps []dep
		tracked := func(d string) int {
			// The task waits here until d is up to date: this is the suspending scheduler.
			v := fetch(d)
			deps = append(deps, dep{d, strconv.Itoa(v)})
			return v
		}
		v := task(tracked)
		s.store[k] = v
		s.traces[k] = trace{deps, strconv.Itoa(v)}
		done[k] = true
		ran = append(ran, k)
		return v
	}
	for _, t := range targets {
		fetch(t)
	}
	return ran
}

func show(ran []string) string {
	if len(ran) == 0 {
		return "-"
	}
	return strings.Join(ran, " ")
}

func main() {
	inputs := map[string]int{"A1": 10, "A2": 20, "C1": 1}
	m := &makeLike{store: map[string]int{}, dirty: map[string]bool{}}
	s := &shakeLike{store: map[string]int{}, traces: map[string]trace{}}
	for k, v := range inputs {
		m.setInput(k, v)
		s.setInput(k, v)
	}
	type change struct {
		key   string
		value int
	}
	steps := []struct {
		name    string
		changes []change
	}{
		{"clean build", nil},
		{"A2 = 20 again", []change{{"A2", 20}}},
		{"A1 = 11, A2 = 19", []change{{"A1", 11}, {"A2", 19}}},
		{"C1 = 2", []change{{"C1", 2}}},
		{"A1 = 12", []change{{"A1", 12}}},
	}
	fmt.Printf("%-18s%-14s%s\n", "step", "make-like", "shake-like")
	for _, st := range steps {
		for _, c := range st.changes {
			m.setInput(c.key, c.value)
			s.setInput(c.key, c.value)
		}
		fmt.Printf("%-18s%-14s%s\n", st.name, show(m.build()), show(s.build()))
	}
	same := true
	for k := range tasks {
		same = same && m.store[k] == s.store[k]
	}
	fmt.Println("same values:", same)
	fmt.Println("B1, B2, B3 =", s.store["B1"], s.store["B2"], s.store["B3"])
}
Output
step              make-like     shake-like
clean build       B1 B2 B3      B1 B2 B3
A2 = 20 again     B1 B2 B3      -
A1 = 11, A2 = 19  B1 B2 B3      B1
C1 = 2            B3            B3
A1 = 12           B1 B2 B3      B1 B2
same values: true
B1, B2, B3 = 31 62 19
  • Verdict: idiom. A map from each key to a func(fetch fetchFunc) int holds the tasks, and two structs hold the two build systems.
  • fetch is a closure that calls itself, so it is declared with var fetch func(k string) int first. The closure tracked appends each dependency and its hash to the slice deps.
  • The order of a Go map is not fixed, so the examples keep the targets and the steps in slices, and the topological order comes from a depth-first search over a slice of dependencies.
  • Parallel builds. The paper models one thread, and says that all the build systems that it covers can build independent keys in parallel. The extra complexity stays in the scheduler.1
  • Impure tasks. Real tasks are not always functions. A task can read a dependency that the build system does not track, such as the version of the compiler. It can be non-deterministic, as when a parallel compiler gives different but equal results. It can be volatile, as when it must run in every build. The paper models a volatile task as one that depends on a special key whose value changes in each build.1
  • Cloud builds. Constructive traces lead to more design questions: how much data to send, workers in the cloud that run the tasks, eviction of old values from the cache, and shallow builds that download only the final products.1 Bazel keeps an action cache, "a map of action hashes to action result metadata", and a content-addressable store of output files.3 See Remote caching and execution.
  • Self-tracking. Most build systems track changes to the inputs but not to the tasks. Excel and Ninja also notice a change to a task.1 Ninja keeps a log of the command that built each file, and builds the file again when the command line changed.2

Pitfalls

  • The model is not the tool. No implementation of Make comes with a formal specification, so the paper models an approximation of Make that is close to the usual tools.1 Check the documentation of the real tool before you depend on a property from the table.
  • File times are a weak dirty bit. A command such as touch changes the time of a file without a change to its content. So Make is minimal only when nobody does that. Make also needs file times that only go forward, and backup software can break this.1
  • Static lists of dependencies over-approximate. A topological scheduler must list every key that a task can read. A task with a choice then runs more often than it needs to, as B3 does in the examples. Excel makes the same over-approximation for INDIRECT and for both branches of IF.1
  • Restarting wastes work. A restarting scheduler can start a task, do useful work, and then stop it, so it is not minimal.1
  • Deep traces need deterministic tasks. When a deep constructive trace skips two or more levels of dependencies, a non-deterministic task can make the build incorrect.1

Cost

A dirty bit costs one bit for each key and no hashing, but it gives no early cutoff. A verifying trace stores only hashes, so it stays small, and it costs one hash of each file that a task reads. A system with verifying traces gains little from more than one trace for each key.1 A constructive trace stores whole values, so the cache grows until the system evicts old items.1 To verify a key, a constructive trace looks at the direct dependencies of the key, which must be up to date first, so the time grows with the number of transitive dependencies. A deep constructive trace looks only at the inputs, so it is faster to check, but it cannot stop early except at the levels that it records.1

A suspending scheduler needs tasks that can wait in the middle. Shake first used cheap green threads, and later continuation-passing style.1

History

Make was the main build tool for many years. The paper says that the challenges of scale then led large firms such as Microsoft, Facebook and Google to write their own build systems.1 Neil Mitchell presented Shake, a build system written in Haskell, at ICFP 2012.4 The paper says that Shake was made to handle dynamic dependencies without the loss of minimality.1 Mokhov, Mitchell and Peyton Jones presented Build Systems à la Carte at ICFP 2018. They wrote all the models in Haskell, so each model runs.1 The paper ends with a plan to build the monadic suspending cloud build system that the table suggests.1 An extended version, Build systems à la carte: Theory and practice, appeared in the Journal of Functional Programming in 2020.5

References

  1. Andrey Mokhov, Neil Mitchell and Simon Peyton Jones, Build Systems à la Carte, Proceedings of the ACM on Programming Languages 2 (ICFP), Article 79, 2018, 1 Introduction; 2 Background (Table 1); 3.1 Common Vocabulary; 3.4 and 3.5 (applicative and monadic tasks); 3.6 Correctness; 4.1 The Scheduler; 4.2 The Rebuilder; 4.4 (Table 2); 6.2 Parallelism; 6.3 Impure Computations; 6.4 Cloud Implementation; 8 Conclusions
  2. The Ninja build system manual, The Ninja log; Rule variables (restat)
  3. Bazel documentation, Remote Caching, the two types of data in the remote cache (the action cache and the CAS)
  4. Neil Mitchell, Shake before building, replacing make with Haskell, Proceedings of the 17th ACM SIGPLAN International Conference on Functional Programming (ICFP 2012), pages 55 to 66, the publication record
  5. Andrey Mokhov, Neil Mitchell and Simon Peyton Jones, Build systems à la carte, Theory and practice, Journal of Functional Programming 30, e11, 2020, the abstract and the publication record

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/FQQR5F/text.yaml