Introduction
Most build tools trust their build files completely. A Makefile can run any program. A build
script in a general-purpose language can read your SSH keys, call out to the network, or delete
your home directory. Usually none of them do, but nothing stops them, and nothing tells you what a
build will touch before it runs.
buildl is a build system that starts from the other end. Its build files are written in Lua and
run inside airsl, an embedded Lua runtime that decides what a
script may reach. The rule buildl takes from airsl is short: nothing is ambient. A build
cannot run a program, read a file or see an environment variable unless that was declared, and the
workspace allowed it.
Three things follow from that rule, and they are what buildl is for:
- Build files are safe to read. You can clone a repository and let
buildlevaluate its build files before you trust it, because evaluating them grants them nothing. - Rebuilds you can explain. Whether a target is out of date is decided by hashing what it
declared it reads, so
buildl plancan always tell you what would rebuild, and why. - Authority you can see. The programs, paths and environment variables a build may touch are worked out from the build itself, and checked against a limit the workspace sets, before anything runs.
Declare, then execute
The most important idea in buildl is a split between two phases. Build files only declare:
they say which targets exist, what each one reads, and what command makes it. They never run a
compiler and never write an artifact. The buildl program, written in Rust, then executes: it
works out what is out of date, runs those commands in parallel, each in a sandbox, and caches what
they produce.
%% Two-phase architecture
graph TD
subgraph D["Declaration phase — Lua, sandboxed by airsl"]
BF["build.lua files<br/>targets and deps"] --> ENG["airsl engine<br/>confined policy"]
ENG --> MOD["buildl host module<br/>records the graph"]
end
MOD --> DAG["Target graph — DAG"]
DAG --> E1
subgraph X["Execution phase — Rust host, parallel"]
E1["Scheduler<br/>topological order"] --> E2["Dirty check<br/>hashes vs cache"]
E2 --> E3["Parallel workers<br/>run each action in a sandbox"]
end
The line between the two boxes is airsl's boundary. A build file that loops forever is stopped
there, by a limit on how many instructions it may run. Everything that can do harm, such as
running a program or writing a file, happens on the Rust side, where buildl controls it.
Why Lua, and why airsl
Build configuration sits somewhere between plain data and a full programming language. Data, such as YAML or TOML, cannot say "do this for every source file". A full language can say that, and also anything else, including things a build file should never do. Lua in a sandbox sits in the middle: you get real loops and functions, and the host decides what they can reach.
airsl gives buildl that sandbox. Lua is built into the buildl binary, so there is nothing else
to install. airsl's permission model is what buildl uses to decide what a build may do, and its
host-module seam is how the buildl functions your build files call are added to Lua. Starting a
fresh Lua engine is cheap enough that every build file gets its own.
Who this book is for
You are an engineer who has used a build tool before, such as make, cargo or go build. You do
not need to know Lua. Build files use very little of it, and this book explains what they use as
it goes.
How this book is organised
| Chapter | What you will do |
|---|---|
| 1. Getting Started | Install buildl and build a one-target workspace |
| 2. A First Project | Build and test a small Go program |
| 3. Build Files | Declare targets, inputs, dependencies and settings |
| 4. Asking Permission | Set the workspace's limits and choose who approves a build |
| 5. Caching | See how buildl decides what to rebuild, and tidy up after it |
| 6. The Sandbox | See where each command runs, and what it can see |
| 7. Discovery Targets | Let a build ask a tool what it needs |
| 8. Plugins | Load shared build logic, from the workspace or from git |
| 9. Remote Cache and Execution | Share results through a server, and run actions on it |
| 10. Watch Mode | Rebuild whenever a file changes |
| 11. Under the Hood | How buildl is built, and what it can and cannot promise |
Chapters 1 to 5 are enough to use buildl on your own projects. Chapters 6 to 10 cover the parts
you reach for as a project grows. Chapter 11 is optional reading, for the curious: how buildl is
put together, and why. The appendix collects the reference material: every
command and flag, every buildl.toml key, every build-file function and every exit code.
Getting Started
In this chapter you will install buildl, build a workspace with one target in it, and then ask
buildl what it did. There are four sections:
- Installation installs
buildland puts it on yourPATH. - Hello, buildl writes a
buildl.tomland abuild.luafrom nothing, and builds them. - What Did It Do? asks
buildlwhat would rebuild and why, what a target printed, and what the workspace allows. - With an AI Agent installs two skills that teach an AI coding agent
to write build files, run
buildland move an existing build over.
By the end of the chapter you will have seen the whole loop: declare a target, build it, change
one of its files, and watch buildl rebuild exactly that.
Installation
buildl ships as a single prebuilt binary for macOS and Linux. You do not need Rust, Lua or a C
compiler to run it.
macOS and Linux
$ curl -LsSf https://airsstack.github.io/buildl/install.sh | sh
The installer puts buildl in ~/.local/bin and adds that folder to your PATH. Open a new
terminal so the change takes effect, then check it worked:
$ buildl --version
buildl 0.3.1
buildl --help lists every command. If you would rather the installer left your PATH alone, set
BUILDL_CLI_NO_MODIFY_PATH=1 for the sh that runs it:
$ curl -LsSf https://airsstack.github.io/buildl/install.sh | BUILDL_CLI_NO_MODIFY_PATH=1 sh
That command always installs the newest release. To install a particular one instead, name it in
BUILDL_VERSION:
$ curl -LsSf https://airsstack.github.io/buildl/install.sh | BUILDL_VERSION=0.1.0 sh
From crates.io
If you already have a Rust toolchain, you can build buildl yourself:
$ cargo install --locked buildl-cli
buildl-cli is the package that holds the buildl binary. This takes several minutes and needs:
- Rust 1.94 or newer. That is the oldest compiler
buildlsupports, recorded asrust-versionin itsCargo.toml. - A C compiler, such as
cc,gccorclang.buildlbuilds Lua from its C source and links it into the binary. That is also why the prebuilt binary needs nothing else installed: Lua is already inside it.
--locked builds with the exact dependency versions the crate records in its Cargo.lock. When it
finishes, Cargo prints where it put the binary, usually ~/.cargo/bin, which rustup has already
added to your PATH.
From GitHub
To build the newest unreleased code, Cargo can install the binary straight from the repository:
$ cargo install --git https://github.com/airsstack/buildl buildl-cli --locked
This needs the same Rust and C compiler as above. Cargo prints where it put the binary:
Installed package `buildl-cli v0.3.0 (https://github.com/airsstack/buildl#d99e72c9)` (executable `buildl`)
The commit after the # is whichever one the repository's default branch is at when you install.
From a checkout
If you have cloned the repository, install from there with cargo-make:
$ cargo make install
That runs this, which you can also run yourself if you do not use cargo-make:
$ cargo install --path crates/buildl-cli --locked --force
--force replaces a buildl you installed before, so running it again after a git pull gives
you the new version.
A checkout also carries a rust-toolchain.toml that asks for the current stable release, so
inside a checkout rustup uses stable.
Other ways to install
Each release also carries a plain archive for
macOS and for Linux on both x86_64 and aarch64, named buildl-cli-<target>.tar.xz. On Linux there
are two builds of each, one for glibc and one for musl, which is fully static and runs on any
distribution, including Alpine. A .sha256 file sits next to every archive. The installer does not fetch it: it checks the
archive against a checksum built into the installer itself, which is the same value.
Every archive also carries a GitHub artifact attestation, a signed record that ties the file to this repository and the build that made it. That catches even an archive swapped together with its checksum file:
$ gh attestation verify buildl-cli-x86_64-unknown-linux-musl.tar.xz --repo airsstack/buildl
To have an AI agent write and migrate build files for you, see With an AI Agent.
Hello, buildl
A buildl workspace is a folder with two files at its top: buildl.toml, which says what builds
in this workspace may do, and build.lua, which declares what to build. Make a new folder and save
these three files in it.
The first is the input, a short list of names:
zoe
ada
mia
Save it as names.in. The target will sort it with sort, a program every Unix machine has.
Next, buildl.toml:
[workspace]
name = "hello"
[ceiling]
proc.run = ["sort"]
fs.read = ["."]
fs.write = ["out", ".buildl"]
The [ceiling] table is the most any build in this workspace may do. This one is as small as it
can be for our target, and every line is needed:
proc.runlists the programs a build may run. Here that issortand nothing else.fs.readlists the folders a build may read, relative to the workspace."."is the whole workspace, which is wherenames.inlives.fs.writelists the folders a build may write.outis where finished outputs go, and.buildlis wherebuildlkeeps its cache.
Leave any of them out and buildl build stops before running anything, naming what was missing.
Asking Permission covers the ceiling in full.
Last, build.lua:
local b = buildl
b.target("names.txt", {
inputs = { "names.in" },
run = { "sort", "-o", "$out", "$in" },
})
buildl is a table of functions that every build file can use, and the first line gives it a
shorter name. b.target declares one target, named names.txt. Its inputs are the files it
reads, and run is the command that makes it, as a list of arguments.
$in and $out are placeholders. Your build file never sees a real path: buildl puts the
paths in when it runs the command. $in becomes the target's inputs and $out becomes the file
it must make, which by default is named after the target.
Check it
buildl check reads every build file and runs nothing. It is the quickest way to find a mistake
in a build file:
$ buildl check
ok: 1 declaration in 1 build file
Build it
$ buildl build
1 built
The result is under out/, named after the target:
$ ls out
names.txt
$ cat out/names.txt
ada
mia
zoe
out/names.txt is read-only. buildl keeps the bytes in its own store, under .buildl, and
the file in out/ is a link to them. To change the output, change the input.
Build it again
$ buildl build
1 cached
Nothing ran. buildl saw that names.in, the command and everything else the target depends on
are the same as last time, so it already has the answer. The next page asks buildl how it knew.
What Did It Do?
buildl keeps no secrets about what it does. This page asks it three questions about the
workspace from the last page: what a build would run, what a target printed, and what the
workspace allows.
What would a build run?
buildl plan works out everything a build would, then stops before running anything:
$ buildl plan
clean //:names.txt
run programs: sort
write into: .buildl, out
0 to run, 0 conditional, 1 clean
//:names.txt is the target's full name, its label: // is the top of the workspace, and
names.txt is the name after the colon. clean means nothing it depends on has changed since it
was built, so a build would leave it alone. The two indented lines are what the build would be
allowed to do: run sort, and write into .buildl and out.
Now change the input, and ask again:
$ echo "bob" >> names.in
$ buildl plan
run //:names.txt: input names.in changed
run programs: sort
write into: .buildl, out
1 to run, 0 conditional, 0 clean
The target would run, and plan says why: names.in changed. buildl noticed by hashing the
contents of every input, not by looking at file times, so saving a file without changing it does
not cause a rebuild. Conditional counts targets that depend on one that is about to run, and that
may or may not need to run themselves; Caching explains them.
Build, and the plan is clean again:
$ buildl build
1 built
$ cat out/names.txt
ada
bob
mia
zoe
$ buildl plan
clean //:names.txt
run programs: sort
write into: .buildl, out
0 to run, 0 conditional, 1 clean
plan takes the same targets build does, because it is that build's dry run.
What did it print?
buildl log shows what a target printed the last time it ran:
$ buildl log names.txt
//:names.txt: built at 2026-10-28 13:25:04 UTC
sort -o writes its result to the file and prints nothing, so all there is to show is when it
ran. The time on your machine will be your own. For a target that does print, such as a test, the
lines it printed follow; A First Project shows one.
What may the workspace do?
buildl doctor prints the workspace's settings, and what its build wants next to what
buildl.toml allows:
$ buildl doctor
workspace /private/tmp/buildl-book/hello
approver manifest
execution workers 0 (one per core), timeout 10m, strategy sandbox
remote: none
ceiling
proc.run sort
env.read -
env.unkeyed -
fs.read .
fs.write .buildl, out
wants ceiling approved
run sort allowed yes
write .buildl allowed yes
write out allowed yes
The first line is the folder the workspace is in, so on your machine it names your own folder. The
next three are settings our short buildl.toml left at their defaults: who approves a build
(manifest, which approves whatever the ceiling allows), how actions run (as many at once as there are
cores, at most ten minutes each, in a sandbox), and no remote cache. Then comes the ceiling, and last the
wants: everything the declared targets need, each checked against the ceiling. doctor only
reports. It runs nothing and refuses nothing, so it is the command to reach for when a build is
refused and you want to see why. Approvers covers the approved column.
Each command stops somewhere
Every command that reads the build files runs the same pipeline, and stops at a different point in it:
| Step | What happens | Commands that stop here |
|---|---|---|
| Load | Lua evaluates every build file | check |
| Resolve | the declarations become one graph of targets | graph, query, doctor |
| Plan | every input is hashed, and each target is marked clean or to run | plan |
| Execute | the targets to run are run, in parallel | |
| Record | outputs, the cache and the log are written | build, test |
So check is quick and runs nothing on any workspace, and plan tells you exactly what build
would do without running any of it.
With an AI Agent
An AI coding agent can write build.lua, run buildl and read what it says. To do that well it
needs to know how buildl works: that nothing is allowed unless buildl.toml allows it, what each
exit code means, and which questions are the user's to answer. The repository ships two skills
that tell it.
| Skill | What it is for |
|---|---|
buildl | writing, editing and debugging build.lua and buildl.toml, and reading what buildl reports |
buildl-migrate | moving a Makefile, justfile, shell scripts or npm scripts to buildl, and proving the new build matches the old |
A skill is a folder holding a SKILL.md file, and sometimes scripts and reference pages the agent
reads when it needs them. Both skills follow the
Agent Skills format, so any agent that
reads that format can use them. Claude Code installs them as a plugin; other agents read them from
a skills folder.
Installing the skills
The skills come with an installer, skills/install.sh. It installs the buildl and airsl programs
if they are missing, then the skills. A program already on your PATH is left alone, so the script
never upgrades a buildl you installed on purpose. It prints each command before it runs it, and
needs no sudo.
For Claude Code, download the script, read it, then run it:
$ curl -fsSLO https://raw.githubusercontent.com/airsstack/buildl/main/skills/install.sh
$ sh install.sh --claude
For another agent, give --dir the folder that agent reads skills from. If you have cloned the
repository, run the script from the clone:
$ sh skills/install.sh --dir ~/.codex/skills
--dir copies buildl and buildl-migrate into that folder and replaces only those two, so your
other skills there stay. Running it again gives the same result.
| Option | Meaning | Default |
|---|---|---|
--claude | install the skills as a Claude Code plugin, buildl@buildl | |
--dir PATH | copy the two skills into PATH | |
--ref BRANCH | the branch of the skills and, when it is not main, of the buildl built from it. --dir from a clone ignores it | main |
--dry-run | print every command and run none | off |
Give exactly one of --claude and --dir. --dry-run shows what would happen before you let it.
It needs no Rust by default. When buildl is missing, the script runs the same installer as
Installation, https://airsstack.github.io/buildl/install.sh, which
downloads the latest prebuilt release in seconds. airsl comes the same way, from
https://airsstack.github.io/airsl/install.sh. If buildl and airsl are already installed, only
the skills are installed and it finishes quickly.
Cargo builds buildl in two cases, and then it takes several minutes on a machine with nothing
cached. With --dir from a clone, the script builds the buildl in that clone, so the program and
the skills come from the same source. With a --ref other than main, it runs
cargo install --locked --git https://github.com/airsstack/buildl --branch BRANCH buildl-cli, so
the buildl matches the skills on that branch.
The script needs Rust (from https://rustup.rs) only for those two cases, and only when buildl is
not already installed. It needs curl to fetch the installer of whichever of buildl and airsl is
missing, the claude command for --claude, and curl and tar for --dir from GitHub. When one
is missing it says so and stops.
What the agent does with the buildl skill
With the buildl skill loaded, the agent works in a loop and lets the exit code of each command say
where to go next:
flowchart TD
edit["edit build.lua or buildl.toml"] --> check["buildl check"]
check -- "exit 5" --> fixfile["fix the file at the line the error names"]
fixfile --> check
check -- "exit 0" --> plan["buildl plan"]
plan -- "exit 5" --> fixfile
plan -- "exit 4" --> refused["buildl doctor, then explain and ask you"]
plan -- "exit 0" --> build["buildl build, then buildl test"]
build -- "exit 1" --> log["buildl log target, then fix the code being built"]
log --> edit
build -- "exit 4" --> refused
build -- "exit 0" --> done["done"]
check only reads declarations, so it passes even when a build would be refused. plan is where
a missing permission first shows, before anything runs.
A refusal is answered by asking you
When a build is refused (exit code 4), the agent does not make the refusal go away. Whether a build
may run a program or touch a folder is your decision, so the agent runs buildl doctor, quotes the
error line buildl printed, says which key in buildl.toml would allow it, and asks along these
lines:
buildl refused the build:
//:x.txt: program sh is outside the ceiling (proc.run allows: python3)
To allow it, buildl.toml's [ceiling] proc.run needs "sh". Should I add it?
On a yes it makes exactly that change. Without one it changes nothing. A refusal has three causes, and the agent tells you which: the ceiling, a plugin's own limits (How buildl Decides), or the approver. The skill forbids two changes outright, even if they would get a build to run:
- changing
[approver]to get past a refusal - setting
strategy = "bare"to get past a sandbox failure, since that drops the sandbox when the real fix is a missing declared input
Two more need you first:
- widening the ceiling, a plugin's cap, or a plugin's
extension.tomlhappens only on your yes to that exact change - deleting an old build,
outor.buildlhappens only after the agent asks
Moving a build to buildl
Ask the agent to migrate a project and the buildl-migrate skill takes over. It reads the old build,
writes build.lua and buildl.toml, and then proves the new build matches the old one. It never
edits or deletes the old build files.
The proof is a parity check in three steps. The agent writes parity.json first. That file maps
every old recipe to the buildl target that replaces it (or says why it was dropped), lists the
output files to compare, and lists what the old build uses: programs, environment variables and
whether it touches the network.
flowchart LR
prepare["prepare: copy the project to old-1, old-2 and new"] --> run["run: the old build twice, buildl build and test once"]
run --> compare["compare: print the table"]
| Step | What happens |
|---|---|
| prepare | copies the project three times into a work folder outside the project: old-1, old-2 and new. It runs nothing |
| run | runs the old build in old-1 and old-2, the old tests in old-1 when the project has them, and buildl build, buildl test, buildl graph and buildl doctor in new, saving each exit status and output. This is the agent's own shell, not the script |
| compare | reads the results and prints a table. It runs nothing and writes nothing, and exits non-zero if any row is FAIL |
The old build runs twice so the check can tell a build that is not repeatable from one that
is. If old-1 and old-2 disagree about a file, the new build cannot be blamed for differing from
it.
The table ends with parity: PASS or parity: FAIL (n rows). A row's verdict is one of these:
| Verdict | What it means |
|---|---|
PASS | the check holds |
FAIL | the check does not hold. The row says which check. The agent fixes the new build, or the mistake in parity.json about the old one, and tells you when nothing can judge the file or the old build itself failed |
NOT REPEATABLE | the old build gives different bytes for this file on two runs, so the tests decide it instead |
JUDGED BY TESTS | the file is marked to be decided by the tests, with its reason shown |
NO TESTS | the project has no test command, so there are no test results to compare |
A FAIL is fixed in the new build. The agent never edits parity.json to make a row pass, for
example by dropping a recipe that does build. When it finishes, the old build files, parity.json
and the work folder stay where they are, and it tells you their paths. Deleting them is up to you.
With [approver] default = "interactive", buildl build in the work folder's new copy is refused,
since nobody approved that new place and the agent's shell has no terminal. The agent then asks you
to run the new lines of the run step in your own terminal, and compares afterwards. With deny,
nothing runs anywhere, so the parity check cannot run and the agent says so.
C and C++, compiled one file at a time
Many C projects compile each .c file to its own .o file and link them (%.o: %.c in a
Makefile). The agent moves that to the c plugin, which compiles each
source to its own object, so a change to one source or header rebuilds only the objects that read
it. It adds a [plugins.c] table to buildl.toml, runs buildl plugins fetch, and declares the
program with one call:
local c = buildl.use("c")
c.binary("app", {
srcs = { "src/main.c", "src/util.c" },
headers = { "src/util.h" },
})
The plugin's programs, and the PATH it reads, must be allowed by the ceiling and by the
[plugins.c] table. If they are not,
the agent asks you first, as it does for any refusal.
In parity.json, the old per-file recipes map to the plugin's object targets, and the old link to
the call's own target, app. When the old build compiles with -g, the compiler records the folder
it ran in, and buildl compiles in another one. The binary then differs from the old build's, byte
for byte, so the check marks that output judged by tests: the old tests and the buildl tests
decide it. A project with no test command cannot pass parity this way. Without -g an object does
not record the folder it was compiled in, so an object from buildl can match the old build's when
the compiler, the flags and the source match, and the output is compared as any other.
A First Project
The workspace in the last chapter sorted a list. This chapter builds and tests a real program: a
small Go command and its unit test. It is the Go starter that ships in the repository, in
examples/go, so you can copy that folder instead of typing the files out. You need the buildl
binary and Go 1.22 or newer.
The files
The folder holds a Go module (go.mod), a program (main.go), its test (main_test.go), and the
two files buildl reads. main.go prints one line:
package main
import "fmt"
// Greeting is the line the program prints.
func Greeting() string {
return "hello from go"
}
func main() {
fmt.Println(Greeting())
}
buildl.toml allows exactly what the build needs:
[workspace]
name = "go"
entry = "build.lua"
out = "out"
config = 1
[ceiling]
proc.run = ["go"]
env.read = ["HOME"]
env.unkeyed = ["HOME"]
fs.read = ["."]
fs.write = ["out", ".buildl"]
The [workspace] table spells out three settings the last chapter left at their defaults: the
build file to start from, the folder outputs go in, and the version of the config format. The
ceiling is new in two ways. env.read lets the build see one environment variable, HOME. The Go
toolchain keeps its build cache under your home folder, and without HOME it stops, because it
cannot find one. env.unkeyed lets that variable be left out of the target's cache key, which the
build file below puts to use.
build.lua declares two targets:
local b = buildl
local sources = { "go.mod", b.sources("*.go") }
-- The Go toolchain keeps its build cache under $HOME, so both actions read HOME.
b.target("hello", {
inputs = sources,
run = { "go", "build", "-o", "$out", "." },
env = { HOME = "unkeyed" },
})
b.test("unit", {
inputs = sources,
run = { "go", "test", "./..." },
env = { HOME = "unkeyed" },
})
b.sources("*.go") lists the files in this folder that match the pattern, sorted by name. It is
the only way a build file can look at the disk, and buildl does the looking for it. A list inside
a list is flattened, so sources is go.mod followed by every .go file.
hello builds the program into $out, which is out/hello. unit is declared with b.test
instead of b.target: it makes no file, and what buildl keeps for it is whether it passed and
what it printed. Both name HOME in env. A command sees only the variables its target lists, plus
a few that buildl pins itself (The Sandbox), so a build cannot read the rest of
your environment by accident.
env is a table from a variable's name to a mark, and every variable has one. HOME is marked
"unkeyed": go is given its value, but only the name HOME goes into the target's cache key. The
value is a folder on your machine, and a key that held it would be a different key on every other
machine, though the build is the same. The other mark, "key", puts the value in the key as well; it
is for a variable that changes what the build makes, such as RUSTFLAGS. The Action
Key has the details. env.unkeyed in the ceiling is the permission that lets
a target use the "unkeyed" mark.
Go is already good at deciding what to recompile. buildl does not try to do that job again: it
runs the whole go build as one action, and adds what Go lacks, such as a cache shared by every
language in the workspace, and a list of what the build may touch.
Build and run
$ buildl build
1 built
$ ./out/hello
hello from go
With no target named, build builds every target except the tests.
Test
$ buildl test
tests: 1 passed
With no target named, test runs every test, and builds whatever those tests depend on first.
Change a file
Make a change to main.go that Go will not mind, and ask what a build would do:
$ echo "// an edit" >> main.go
$ buildl plan
run //:hello: input main.go changed
run programs: go
unkeyed variables: HOME
write into: .buildl, out
1 to run, 0 conditional, 0 clean
plan names the file that changed. It lists only //:hello, because like build it leaves the
tests out when no target is named. The list under it now includes unkeyed variables: HOME, from
the targets' env. A variable marked "key" would be on a line of its own, read variables:.
main.go is an input of unit too, so the next test run runs it again. The run after that has
nothing new to test:
$ buildl test
tests: 1 passed
$ buildl test
tests: 1 passed (1 cached)
A passing test whose inputs have not changed is not run again; its result comes from the cache.
When you want it run anyway, buildl test --rerun runs it.
What the test printed
buildl log shows what the test printed the last time it actually ran:
$ buildl log //:unit
//:unit: cached at 2026-10-28 13:25:24 UTC
ok example.com/hello (cached)
The first line says the latest result came from buildl's cache; the time on your machine will be
your own. The second is go test's own output, from the run before. The (cached) on it is Go's
cache, not buildl's: Go keeps test results under HOME, and found this one already there. That is
two caches working side by side. buildl decides whether go runs at all, and when it
does, Go decides how little it has to redo.
The same project in Rust and Python
The repository has two more starters, examples/rust and examples/python. Each is the same
project: a program that prints a greeting, and a test, with its steps in its README.md.
| Starter | The program | The test | The ceiling allows |
|---|---|---|---|
examples/go | go build -o $out ., giving out/hello | go test ./... | go; HOME, unkeyed |
examples/rust | rust.binary, giving out/hello | rust.test, which runs cargo test | sh, rustc; HOME, PATH, both unkeyed |
examples/python | python3 -m zipapp app -o $out, giving out/app.pyz | python3 -m unittest discover -s tests | python3; no variables |
The Rust starter is the one that loads a plugin. Running cargo as a plain target takes some
care: cargo build writes its binary under target/, where buildl does not look for the
output, and cargo needs HOME for its registry and PATH to find the linker. The rust plugin
does that part, so the build file is two lines:
local rust = buildl.use("rust")
rust.binary("hello", { profile = "release" })
rust.test("unit")
rust.binary runs cargo build for the binary hello and copies the file cargo wrote to
out/hello, and rust.test runs cargo test. Both take every file in the folder as inputs, and
HOME and PATH are given as unkeyed variables. The plugin is named in buildl.toml, with the
programs and variables it may use, and fetched once with buildl plugins fetch;
The Rust Plugin shows the table and everything the plugin does.
The next chapter looks at build files properly: labels, dependencies between targets, more than
one folder, and the functions buildl gives you to write them with.
Build Files
A build file is a Lua file named build.lua. It says what can be built: which files go in, which
command runs, and what comes out. It never runs that command itself. buildl reads every build file
first, and only then decides what to run.
This chapter covers:
- Targets and Labels: the four ways to declare something, and how targets name each other.
- Inputs, Outputs and Dependencies: what a command reads and
writes, and the
$in,$outand$depsplaceholders. - The Toolbox: the helper modules a build file can call.
- Many Directories: one build file per directory, joined by labels.
- Build Settings: values you choose when you run a build.
What a build file sees
A build file starts with two globals:
| Global | What it holds |
|---|---|
buildl | the declaration functions: buildl.target, buildl.test, buildl.rule and the rest |
airsstack | the helper modules json, path, regex, hash and glob, and buildl again |
They are not two copies. buildl and airsstack.buildl are one table with two names, so most build
files begin with a short local name for it:
local b = buildl
What a build file does not see
A build file must declare the same targets every time it is read, on every machine. So the parts of Lua that could make it answer differently are not there:
printis gone. A build file has nowhere to write to.math.randomandmath.randomseedare gone. A random name would change on every run.os,io,loadanddofileare gone. A build file cannot read the clock, the environment or a file.requireanswers onlyairsstackitself, so it cannot load another build file's code either.
Calling one of them is an ordinary Lua error, and the build file fails:
-- build.lua
print(buildl == airsstack.buildl)
$ buildl check
error: build.lua: runtime error: lua error in build.lua: runtime error: build.lua:1: attempt to call a nil value (global 'print')
stack traceback:
[C]: in global 'print'
build.lua:1: in main chunk
buildl check reads every build file and runs nothing, which makes it the quickest way to see
whether your build files are well formed. A build file that fails exits with code 5.
The one way a build file looks at the disk is buildl.sources, which lists files in its own
directory. Inputs, Outputs and Dependencies covers it.
Targets and Labels
This page builds a two-directory workspace that joins two text files, and uses it to show the four things a build file declares and how they name each other.
hello/
buildl.toml
build.lua
hello.txt "hello"
lib/
build.lua
name.txt "world"
-- lib/build.lua
local b = buildl
b.target("name", {
inputs = { "name.txt" },
run = { "cp", "$in", "$out" },
})
-- build.lua
local b = buildl
b.subdir("lib")
b.rule("join", {
run = { "cat", "$in", "$deps" },
desc = "join $in and $deps",
})
b.target("greeting", {
rule = "join",
inputs = { "hello.txt" },
deps = { "//lib:name" },
stdout = true,
})
b.alias("default", "greeting")
b.test("greeting_test", {
deps = { "greeting" },
run = { "grep", "-q", "world", "$deps" },
})
buildl.toml lets the build run cat, cp and grep;
buildl.toml, the Ceiling explains why it has to.
The four declarations
| Call | Declares |
|---|---|
buildl.target(name, { … }) | something to build: a command, what it reads, what it writes |
buildl.test(name, { … }) | a target that buildl test runs; it passes when its command exits 0 |
buildl.rule(name, { run, desc }) | a command shared by many targets, which name it with rule = "…" |
buildl.alias(name, target) | a second name for a target |
A target and a test take the same table. Every field is optional:
| Field | Meaning |
|---|---|
run | the command, a list of arguments; or rule, the name of a rule whose run is used |
inputs | the files the command reads, relative to the build file's directory |
deps | the targets whose outputs the command reads, by label |
outputs | what the command writes; a target defaults to its own name, a test to nothing |
env | the environment variables the command may see, each marked "key" or "unkeyed": { HOME = "unkeyed" } |
network | true says the command reaches the network; plan and the approver show it |
stdout | true makes what the command prints the target's one output (not for tests) |
always | true runs the command every time, never from the cache |
A rule takes run and desc. desc is the line a terminal shows for the action while it runs, so
join hello.txt and out/lib/name here.
The table is closed. A field buildl does not know is an error that names the line, so a misspelling cannot quietly drop an input:
$ buildl check
error: build.lua: unknown field "srcs": line 10: buildl.target 'greeting': unknown field 'srcs'
buildl.discover, buildl.option, buildl.subdir and buildl.use are declarations too. They
have their own pages: Discovery Targets,
Build Settings, Many Directories and
Plugins.
Labels
Every target has a label: //, the directory of its build file, :, and its name. The target
name in lib/build.lua is //lib:name. The root directory is empty, so greeting is
//:greeting.
Inside one build file you can write a label two shorter ways, both read against the build file's own directory:
| Written | In lib/build.lua means | In build.lua means |
|---|---|---|
//lib:name | //lib:name | //lib:name |
:name | //lib:name | //:name |
name | //lib:name | //:name |
That is why the test above can write deps = { "greeting" }. On the command line, plan, build,
test and query take the same three forms.
A label always names one target. //lib names a directory, and buildl will not guess that you
meant //lib:lib:
$ buildl check
error: build.lua: declaration #2: invalid dep: invalid label: "//lib" — must hold ':' and a target name
The command exits with code 5, the code for a mistake in a build file.
Looking at the graph
The targets and their deps form a graph. buildl graph prints it. Its default is JSON with sorted keys, the same bytes every time,
the same bytes buildl keeps in .buildl/graph.json; --dot prints it for Graphviz instead:
$ buildl graph --dot
digraph buildl {
"//:greeting";
"//:greeting_test";
"//lib:name";
"//:greeting" -> "//lib:name";
"//:greeting_test" -> "//:greeting";
"//:default" [shape=plaintext];
"//:default" -> "//:greeting" [style=dashed];
}
The alias is the dashed line: //:default is not a target of its own, only another way to say
//:greeting.
buildl query answers one question about the graph. deps(…) lists what a target needs, all the
way down, and rdeps(…) lists everything that needs it:
$ buildl query 'deps(greeting)'
//lib:name
$ buildl query 'rdeps(//lib:name)'
//:greeting
//:greeting_test
rdeps is the one to reach for before an edit: it lists every target the edit can affect.
Neither command runs anything, and neither does check. build and test do:
$ buildl build
--- //:greeting
hello
world
2 built
$ buildl test
--- //:greeting (cached)
hello
world
tests: 1 passed
buildl build with no targets builds everything but tests, and buildl test runs every test,
building what they need first. Under --- and a label, buildl shows what that command printed. For
a stdout = true target that is its output, which is why hello and world appear. The next
page looks at what $in, $out and $deps turned into.
Inputs, Outputs and Dependencies
A build file never handles a real path to a built file. It writes placeholders in its commands, and
buildl puts the paths in just before the command runs. This page shows what each placeholder turns
into, using a workspace whose commands only echo and touch:
-- build.lua
local b = buildl
b.target("pair", {
outputs = { "left.txt", "right.txt" },
run = { "touch", "$out" },
})
b.target("show", {
inputs = { b.sources("notes/*.txt"), "README" },
deps = { "pair" },
run = { "echo", "in:", "$in", "deps:", "$deps", "joined: $in" },
stdout = true,
})
$ buildl build
--- //:show
in: notes/a.txt notes/b.txt README deps: out/left.txt out/right.txt joined: notes/a.txt notes/b.txt README
2 built
The three placeholders
| Placeholder | Becomes |
|---|---|
$in | the target's inputs |
$out | the target's own outputs, under out/ |
$deps | every output of every target in deps |
Each one is a list of paths, and the paths are read from the workspace root. An argument that is
exactly one placeholder becomes one argument per path, or no argument when the list is empty. So
{ "touch", "$out" } above ran touch out/left.txt out/right.txt, two arguments. Inside longer text
the paths are joined by one space instead, as "joined: $in" shows: that was a single argument.
Lists keep the order you wrote them in, with repeats dropped. $in lists the two notes, then
README, because that is the order of inputs.
Inputs, and buildl.sources
An input is a file in your workspace, written relative to the build file's directory. buildl reads it, hashes it, and rebuilds the target when its bytes change.
A build file cannot look at the disk to find its inputs. buildl.sources(pattern) does that for it:
buildl walks the build file's directory, and returns the regular files that match, relative to that
directory and sorted, so every machine gets the same list. It never enters out/ or .buildl/,
never lists a path a .buildlignore leaves out (below), and
never follows a symbolic link. * stays inside one directory and **/ crosses any number
of them.
A list field takes one level of nesting, spliced in where it stands. That is why
{ b.sources("notes/*.txt"), "README" } above is one flat list of three files.
An input stays inside its build file's directory. A build file in lib/ cannot reach up with ..
to read a file that belongs to the directory above:
-- lib/build.lua
local b = buildl
b.target("readme", {
inputs = { "../README" },
run = { "echo", "$in" },
stdout = true,
})
$ buildl check
error: lib/build.lua: declaration #0: invalid input: invalid source path: "lib/../README" — must not contain a '.' or '..' segment
If a target needs a file from another directory, the build file there declares a target for it,
and this one lists that target in deps. Many Directories shows how.
Leaving paths out: .buildlignore
Some folders hold files no target should read: notes, drafts, generated documentation. A file named
.buildlignore marks such paths as outside the build. It is written the way a .gitignore is, and
it may sit in any folder of the workspace: its patterns apply to that folder and everything below
it. Where a nested file and one above it disagree, the deeper file wins.
Here the workspace keeps its notes in notes/, and the root .buildlignore leaves them out. It
holds one line:
notes/
-- build.lua
local b = buildl
b.target("bundle", {
inputs = { b.sources("**/*.txt") },
run = { "cat", "$in" },
stdout = true,
})
The workspace holds src/a.txt, src/b.txt and notes/todo.txt, and buildl.toml lets the build
run cat. The target reads the two files in src/. Editing a note changes nothing it reads, so
the target stays clean; editing a source does not:
$ buildl build
--- //:bundle
a
b
1 built
$ echo more >> notes/todo.txt
$ buildl plan
clean //:bundle
run programs: cat
write into: .buildl, out
0 to run, 0 conditional, 1 clean
$ echo more >> src/a.txt
$ buildl plan
run //:bundle: input src/a.txt changed
run programs: cat
write into: .buildl, out
1 to run, 0 conditional, 0 clean
Three parts of buildl read the files, and all three give the same answer for a path:
| Where | What an ignored path does |
|---|---|
buildl.sources | is not listed. An ignored folder is not entered, so it costs nothing against [declaration] walk_entries |
inputs and subdir | is refused: a target cannot read a path the workspace has left out, and a build file cannot add an ignored folder. The exit code is 5, as Exit Codes shows |
buildl watch | a change there starts no build |
The syntax
The lines mean what they mean in a .gitignore:
| Line | Meaning |
|---|---|
# text | a comment |
| an empty line | skipped |
notes/ | a folder named notes, at any depth, and everything in it; a trailing / matches folders only |
*.log | a pattern with no / matches at any depth below the file |
/a.log | a.log in the folder that holds this .buildlignore, and not deeper: a leading / anchors the pattern |
gen/* | a / in the middle anchors the pattern the same way; * stays inside one folder name |
!keep.log | puts back a path an earlier line left out; within a file the last matching line decides |
Spaces at the end of a line are dropped unless escaped with a backslash, and matching is
case-sensitive on every platform. A byte-order mark at the start of the file is dropped. { and
} are plain characters, as in git: {a,b} names a file called {a,b}, and is not two
alternatives as it would be in a pattern given to buildl.sources.
A path is decided from the workspace root down. buildl asks about each folder on the way to the
path, then about the path itself, and the first one a pattern ignores ends the question: nothing
below an ignored folder can be put back. With this root .buildlignore:
notes/
!notes/keep/
notes/keep/b.md is ignored. notes/ already left out the folder it sits in, and the
!notes/keep/ line is never reached. To keep a file inside a folder, ignore the folder's contents
(notes/*) and not the folder.
Here is that root file in a workspace where src/.buildlignore holds gen/* and !gen/keep.rs,
beside notes/a.md, notes/keep/b.md, src/main.rs, src/gen/g.rs and src/gen/keep.rs. A
target whose inputs are buildl.sources("**/*") reads:
$ buildl build
--- //:files
.buildlignore build.lua buildl.toml src/.buildlignore src/gen/keep.rs src/main.rs
1 built
Both files of notes/ are gone, src/gen/g.rs is gone, and src/gen/keep.rs was put back by the
nested file. A .buildlignore is an ordinary file in every other way: it is listed, as above, and
a target that reads one is dirty when it changes. A pattern that ignores a .buildlignore hides it
from the listing, and the rules it holds still apply.
What is and is not read
- Only a
.buildlignoreat or below the workspace root is read. One above the root never applies. - No other ignore file is read: not
.gitignore, not.ignore, not git's global file. out/and.buildl/stay out of the build whatever the patterns say, so a!out/line changes nothing.- A pattern that names
build.luaorbuildl.tomldoes not stop buildl reading it. The rules apply only toinputs,subdir,sourcesandwatch. Underwatch, though, a change to an ignoredbuild.luaorbuildl.tomlis dropped like any other ignored path, so editing it starts no cycle; the next cycle, started by something else, reads it. - A
.buildlignorebuildl cannot use is refused, never skipped: a pattern that does not parse, a file that is not UTF-8, a file that cannot be read, or one that is a symbolic link. The exit code is 5 and the message names the file, with the line where there is one.
Outputs, and out/
Every output lands at out/<directory>/<name>: the directory of the target's label, then the
output's name. //:show writes out/show, and a target //lib:text would write out/lib/text.
An output may be one file or a whole directory of files.
$ ls -R out
left.txt
right.txt
show
outputs defaults to the target's own name, which is why show needs no outputs line. When the
command starts, the directory each output goes into exists and the output itself does not: the
command creates it. Two targets may not claim the same path; buildl refuses that before anything
runs.
out/ is buildl's to write. Each file in it is read-only. A file that may be run is a copy; any
other is a link into buildl's store under .buildl/ where linking is possible. Delete out/ whenever you like: buildl clean does exactly
that, and the next build puts it back from the store without running anything:
$ buildl clean
clean: removed out
$ buildl build
--- //:show (cached)
in: notes/a.txt notes/b.txt README deps: out/left.txt out/right.txt joined: notes/a.txt notes/b.txt README
2 cached
Dependencies
deps names targets, and does two things at once:
- it orders the build:
pairruns beforeshow; - it hands over files:
$depsinshowbecame the outputs ofpair.
A target can only read another target's outputs through deps. Under the default sandbox, a
command sees copies of its declared inputs and its dependencies' outputs and nothing else from the
workspace, so a forgotten dependency fails the build instead of working by luck.
The Sandbox explains how.
What a dependency produced, its outputs' bytes, is part of what decides whether a target is up to date. Caching takes that up.
The Toolbox
Build files are often loops: one target per source file, a name worked out from a path, a list
filtered by a pattern. The airsstack table holds five helper modules for that work. They come
from airsl, the Lua runtime buildl evaluates build files on.
A build file can list them itself. This one sorts the names in airsstack and raises them as an
error, the only way a build file can show you something:
-- build.lua
local names = {}
for name in pairs(airsstack) do
names[#names + 1] = name
end
table.sort(names)
error(table.concat(names, ", ") .. "; one table: " .. tostring(buildl == airsstack.buildl), 0)
$ buildl check
error: build.lua: runtime error: lua error in build.lua: runtime error: buildl, glob, hash, json, path, regex; one table: true
stack traceback:
[C]: in ?
[C]: in function 'error'
build.lua:6: in main chunk
Five modules, and buildl itself. In a build file they work only on the values you pass in: none
of them can read a file, the clock or the environment.
One build file using all five
This build file turns each Markdown page in pages/ into a target, skips the drafts, and writes an
index of what it built:
-- build.lua
local b = buildl
local glob, hash, json, path, regex =
airsstack.glob, airsstack.hash, airsstack.json, airsstack.path, airsstack.regex
local pages = {}
for _, src in ipairs(b.sources("pages/*")) do
local file = path.basename(src)
if glob.match("*.md", file) and not regex.is_match("^draft-", file) then
local name = path.stem(file) .. ".txt"
b.target(name, { inputs = { src }, run = { "cp", "$in", "$out" } })
pages[#pages + 1] = name
end
end
local stamp = hash.sha256(table.concat(pages, "\n")):sub(1, 12)
b.target("index.json", {
run = { "echo", json.encode({ pages = pages, stamp = stamp }) },
stdout = true,
})
With pages/ holding draft-ideas.md, guide.md, intro.md and notes.txt:
$ buildl build
--- //:index.json
{"pages":["guide.txt","intro.txt"],"stamp":"c00644b5f375"}
3 built
$ ls out
guide.txt
index.json
intro.txt
What each module did:
| Module | Call | Did |
|---|---|---|
path | path.basename(src), path.stem(file) | pages/intro.md to intro.md, then to intro |
glob | glob.match("*.md", file) | kept the Markdown files, so notes.txt got no target |
regex | regex.is_match("^draft-", file) | dropped draft-ideas.md |
hash | hash.sha256(text) | a SHA-256 of the page list, as hex |
json | json.encode(value) | a table to JSON text, keys sorted |
json.decode goes the other way, and is how a build file reads what a discovery target found
(Discovery Targets).
What is held back
The modules are airsl's, with the parts that would reach outside the build file switched off:
| Function | In a build file |
|---|---|
glob.walk, hash.hash_file | refused: they read the disk, and a build file holds no grant to read with |
path.absolute | removed: it would answer differently depending on where you ran buildl |
A refused call is an error, never an empty answer, so a build file cannot mistake "not allowed to look" for "nothing there":
-- build.lua
local found = airsstack.glob.walk(".", "*.md")
$ buildl check
error: build.lua: operation refused: lua error in build.lua: glob.walk denied: `/private/tmp/buildl-book/toolbox-walk` is outside the granted read roots: none are granted
stack traceback:
[C]: in field 'walk'
build.lua:1: in main chunk
buildl.sources is the way to list files, as the build file above does. buildl does the walk
itself, inside the build file's directory, and sorts what it finds.
Every other function is as airsl documents it. The airsl book's module reference lists them all.
Many Directories
A real project has more than one directory, and each directory knows best how to build itself.
buildl gives each one its own build.lua, and joins them with labels. This page walks through
examples/polyglot in the buildl repository: one schema, and a Go, a Rust and a Python program
built from it.
polyglot/
buildl.toml
build.lua
schema/ build.lua generate.py schema.json
go/ build.lua go.mod main.go
rust/ build.lua Cargo.toml Cargo.lock src/main.rs
python/ build.lua pack.py tool/__main__.py
buildl.subdir
The root build file declares no targets. It names the four directories:
-- build.lua
local b = buildl
-- Each directory declares its own targets; they reach each other by label.
b.subdir("schema")
b.subdir("go")
b.subdir("rust")
b.subdir("python")
buildl.subdir("go") asks buildl to evaluate go/build.lua, on its own, with go/ as its
directory. Its targets are labelled //go:…, its inputs are read from go/, and its outputs land
in out/go/.
This is the only way a build file gets read. buildl does not search the workspace for build.lua
files: it reads the root one, then each one a build file it read has named, and nothing else. A
build.lua that nobody names is never evaluated. Here extra/build.lua sits in the hello
workspace from Targets and Labels, unnamed:
$ buildl check
ok: 5 declarations in 2 build files
$ buildl query 'deps(//extra:unseen)'
error: target //extra:unseen was asked for but is not declared
So what is in the build is exactly what the build files say is in it, never what happens to be on disk.
Labels across directories
The schema directory holds one target that writes all four generated files:
-- schema/build.lua
local b = buildl
b.target("gen", {
inputs = { "generate.py", "schema.json" },
outputs = { "gogen/gen.go", "gogen/go.mod", "gen.rs", "gen.py" },
run = { "python3", "$in", "$out" },
})
Each program lists it by its full label. The Go one:
-- go/build.lua
local b = buildl
b.target("service", {
inputs = { "go.mod", b.sources("*.go") },
deps = { "//schema:gen" },
run = { "go", "build", "-C", "go", "-o", "../$out", "." },
env = { HOME = "unkeyed" },
})
python/build.lua does the same with python3. rust/build.lua asks the rust plugin
(The Rust Plugin) for a binary and a test, which run cargo in
rust/, and lists the same dependency:
-- rust/build.lua
local rust = buildl.use("rust")
rust.binary("cli", { deps = { "//schema:gen" }, profile = "release" })
rust.test("cli_test", { deps = { "//schema:gen" } })
The workspace's buildl.toml names the plugin and lets it run sh; that chapter shows the table.
A command runs from the workspace root, so the Go target builds with go build -C go, and each
language finds the generated files under out/schema/.
The graph has one target in the middle and four around it, the Rust test being the fourth:
$ buildl graph --dot
digraph buildl {
"//go:service";
"//python:tool.pyz";
"//rust:cli";
"//rust:cli_test";
"//schema:gen";
"//go:service" -> "//schema:gen";
"//python:tool.pyz" -> "//schema:gen";
"//rust:cli" -> "//schema:gen";
"//rust:cli_test" -> "//schema:gen";
}
$ buildl query 'rdeps(//schema:gen)'
//go:service
//python:tool.pyz
//rust:cli
//rust:cli_test
rdeps names one target per language and the Rust test: an edit to the schema can affect all
three programs and that test, and nothing else.
$ buildl build
--- //rust:cli
Compiling cli v0.1.0 (/private/var/folders/8w/4ccj7cw90nx4d32s72tqf5nw0000gn/T/buildl-4a04b4d480388c7fb246c52f872863b3/709bb78cafdc4445f4217a9db757a876/rust)
Finished `release` profile [optimized] target(s) in 1.18s
4 built
$ ./out/go/service
go service 1.0: hello from the schema
$ ./out/rust/cli
rust cli 1.0: hello from the schema
$ python3 out/python/tool.pyz
python tool 1.0: hello from the schema
The path cargo printed is the sandbox: a directory outside the workspace, laid out like it,
where the command ran (The Sandbox). The schema ran first because all three
programs depend on it; the three programs then ran side by side.
The same shape, bigger
A larger monorepo looks the same: code generators in the middle, each language's build around them, and packaging steps on top.
%% Cross-stack monorepo DAG
graph TD
PG["//proto:go<br/>protoc codegen"] --> API["//services/api:server<br/>go build"]
PT["//proto:ts<br/>protoc codegen"] --> WEB["//web:bundle<br/>bun build"]
API --> AIMG["//deploy:api_image<br/>docker build"]
WEB --> WIMG["//deploy:web_image<br/>docker build"]
AIMG --> STACK["//deploy:stack"]
WIMG --> STACK
An arrow here points from what is built first to what uses it. One .proto edit rebuilds both
columns in the right order, side by side. A web-only edit leaves the Go column alone, and go is
never started. Every box is an ordinary buildl.target with inputs, deps and run.
Build Settings
Sometimes you want to change one thing for one run: a different flag, a test filter, another compiler. A build file cannot read the environment to find out, on purpose. Instead it declares a build setting: a named value with a default, which you can override on the command line.
-- build.lua
local b = buildl
b.option("greeting", { default = "hello" })
b.target("message", {
run = { "echo", "$opt:greeting", "world" },
stdout = true,
})
buildl.option(name, { default = "…" }) declares the setting. default is required, and is the
only field. A command uses the value by writing $opt:greeting.
Overriding a setting
--set NAME=VALUE gives a setting another value for one run. plan, build, test, verify and
watch all take it, and it may be repeated.
$ buildl build
--- //:message
hello world
1 built
$ buildl plan --set greeting=goodbye
run //:message: setting greeting changed
run programs: echo
write into: .buildl, out
1 to run, 0 conditional, 0 clean
$ buildl build --set greeting=goodbye
--- //:message
goodbye world
1 built
plan names the reason: the setting changed. A setting's value is part of what decides whether a
target is up to date, but only for the targets whose commands name it. Change a setting no command
uses, and nothing runs again.
The value of every setting is fixed when the plan is made, so the run is the one that was planned. Going back to the default is a change too:
$ buildl plan
run //:message: setting greeting changed
run programs: echo
write into: .buildl, out
1 to run, 0 conditional, 0 clean
Only declared settings
An override must name a setting some build file declared. A misspelt name is refused rather than quietly ignored:
$ buildl plan --set colour=blue
error: setting colour is overridden but not declared
That exits with code 2, the code for a mistake on the command line. Every setting and its default
appear in buildl graph, under "settings":
$ buildl graph
{"aliases":{},"settings":{"greeting":"hello"},"targets":{"//:message":{"deps":[],"description":null,"env":{},"freshness":"Cached","inputs":[],"network":"Sealed","origin":"BuildFile","output_source":"Stdout","outputs":["message"],"provenance":{"directory":"","file":"build.lua"},"role":"Build","run":["echo","$opt:greeting","world"]}}}
So everything that shapes a build is written down: in a build file, or on the command line that ran it.
A setting can choose the program
A setting may stand for the whole first argument:
b.option("compiler", { default = "cc" })
b.target("main.o", { inputs = { "main.c" }, run = { "$opt:compiler", "-c", "$in", "-o", "$out" } })
Once the value is put in, buildl treats the program exactly as if it were written out. Running
with --set compiler=clang means clang must be allowed by the workspace's ceiling
(buildl.toml, the Ceiling), must be found on PATH, and its contents
become part of what decides whether main.o is up to date.
When to reach for one
A setting is for a choice made per run. If you find yourself setting the same value every time,
it belongs in the build file. And if you want to run part of a test suite, consider one test
target per package instead: then buildl test //services/api:auth_test runs just that part, and
buildl query 'rdeps(…)' can tell you which tests an edit touches.
Asking Permission
A build runs programs on your machine. Most build tools let a build file run whatever it likes, and you find out what it did afterwards. buildl works the other way round: before anything runs, it works out everything the build will need, holds that against a list you wrote, and stops if anything is missing from the list.
This chapter covers:
- Nothing Is Ambient: how buildl works out what a build needs, and why a build file never asks for permission itself.
buildl.toml, the Ceiling: the file that says the most any build in the workspace may do.- Approvers: who says yes once a build fits under the ceiling, and
buildl doctor, which shows you the whole picture.
Nothing Is Ambient
"Ambient" authority is power a program has just because it is running: it can open any file you
can, run any program on your PATH, read any environment variable. A build file in buildl has none
of that. It runs with no permission at all, and it never asks for any. It only declares targets.
So where does a build's permission come from? From the targets themselves.
The build is the request
Every target says which program it runs, which variables it reads, which files it reads and where its outputs go. After reading the build files, buildl collects all of that into the wanted set:
| Want | Comes from |
|---|---|
| programs | the first argument of every command, after $opt:, $in, $out and $deps are put in |
| variables | every name in an env table, the "key" ones and the "unkeyed" ones apart |
| reads | every declared input |
| writes | the output directory (out unless [workspace] out names another) and .buildl, where outputs and buildl's own state go |
| network | every target with network = true |
buildl plan prints the wanted set under its list of targets:
$ buildl plan
run //:report: never built
run //tools:hello: never built
run programs: go
unkeyed variables: HOME
write into: .buildl, out
2 to run, 0 conditional, 0 clean
The plan lists every want but the reads, which stay with the targets that declare them; each
input is still checked. A variable marked "key" is listed as read variables:, one marked
"unkeyed" as unkeyed variables:, and the ceiling holds the two apart too: env.read and
env.unkeyed (the ceiling). Then buildl holds each want against the
workspace's ceiling, the lists in buildl.toml. Anything outside the ceiling stops the build before
anything runs. Anything inside goes to the approver, which can only say yes or no:
%% Grant negotiation
graph LR
W["Wanted set<br/>derived from the DAG"] --> C["Held to the ceiling<br/>buildl.toml"]
C -- "a want outside: refused" --> X["Error, nothing runs"]
C --> A["Approver<br/>manifest / interactive / deny"]
A -- "denied" --> X
A --> G["Granted: the build runs"]
Three rules hold all the way through. The ceiling is never widened: a want outside it is refused, never added. The approver only narrows: it can turn a build down, never let more in. And every failure is a refusal: when in doubt, nothing runs.
Nobody writes the wanted set by hand, so it cannot drift away from the truth. It is worked out from the same targets buildl is about to run.
Tools are dependencies too
The ceiling lists the programs from your machine that a build may run. A program the build made
itself is different: you can see where it came from in the graph. So a command whose program is
the output of one of its own deps runs it with no proc.run entry.
-- tools/build.lua
local b = buildl
b.target("hello", {
inputs = { "go.mod", "main.go" },
run = { "go", "build", "-C", "tools", "-o", "../$out", "." },
env = { HOME = "unkeyed" },
})
-- build.lua
local b = buildl
b.subdir("tools")
-- The program is whatever //tools:hello built; $deps is its path, out/tools/hello.
b.target("report", {
deps = { "//tools:hello" },
run = { "$deps", "from a tool the build made" },
stdout = true,
})
The ceiling lists one program, go. The plan above wants only go, though //:report runs a
program too, and the build runs:
$ buildl build
--- //:report
hello from a tool the build made
2 built
Declaring the dependency is the permission. It also ties the tool into caching: when an edit to
main.go changes the program, report runs again with the new one.
A program from your machine is tied in the same way. buildl finds it on its own PATH when it
plans, hashes the file, and makes that hash part of each target's action key, so upgrading go
rebuilds what go built. The Action Key has the details.
An untrusted clone
This is where it pays off. You clone someone's fork of your project, and their change adds a step
to tools/build.lua:
-- A contributor's new step.
b.target("setup", {
run = { "curl", "-fsSL", "https://example.com/setup.sh" },
stdout = true,
})
Reading the build files is safe, because reading them grants nothing:
$ buildl check
ok: 3 declarations in 2 build files
Asking for a plan is safe too. The new step wants curl, and the ceiling does not list it:
$ buildl plan
error: tools/build.lua: //tools:setup: program curl is outside the ceiling (proc.run allows: go)
$ buildl build
error: tools/build.lua: //tools:setup: program curl is outside the ceiling (proc.run allows: go)
Both exit with code 4, the code for a refusal. Nothing ran: not curl, and not the go build
that was fine on its own. The error names both sides, what was wanted and what the ceiling allows,
and the build file and target that wanted it.
%% Untrusted clone — grant negotiation sequence
sequenceDiagram
participant Dev as Developer
participant Host as buildl host — Rust
participant Lua as airsl engine — confined
Dev->>Host: buildl plan
Host->>Host: parse buildl.toml — the ceiling
Host->>Lua: evaluate build files<br/>no grant — sources listed host-side
Note over Lua: contributor's file calls<br/>b.target with run curl
Lua-->>Host: staging list — declarations only<br/>nothing executed
Host->>Host: Resolve DAG, derive wanted set<br/>wanted includes curl
Host->>Host: hold to the ceiling<br/>curl not in proc.run
Host-->>Dev: refused, exit 4<br/>tools/build.lua: //tools:setup:<br/>program curl is outside the ceiling (proc.run allows: go)
Note over Dev: nothing ran — the new<br/>step never had authority
Most build tools read their build files with the full power of the user running them, so even
looking at an untrusted project's build can run its code. In buildl, reading the build files grants
nothing at all. The only way for the build to get curl is for you to add it to buildl.toml.
buildl.toml, the Ceiling
buildl.toml sits at the root of the workspace. buildl reads it before any build file, and it is
plain TOML, not Lua, so nothing in it can run. Its [ceiling] table is the most any build in the
workspace may ever do. A build file cannot raise it; only you can, by editing this file.
The file is also what makes a directory a workspace. buildl looks for it in the current directory
and the ones above, and a directory with no buildl.toml in or above it is an error, never a
default.
This page explains each table with one example. Appendix B lists every key.
Read strictly
Every table and every key is optional. A key buildl does not know, though, is an error with its line and column, so a typo cannot quietly drop a permission:
fs.wirte = ["out", ".buildl"]
$ buildl check
error: manifest: buildl.toml:9:4: unknown field `wirte`, expected `read` or `write`
[workspace]
[workspace]
name = "ambient"
entry = "build.lua"
out = "out"
config = 1
name is for people. entry is the file name of every directory's build file, build.lua unless
you say otherwise. out is where outputs go, out by default. config is the version of this
file's format, and must be 1.
[ceiling]
[ceiling]
proc.run = ["go"]
env.read = ["HOME"]
env.unkeyed = ["HOME"]
fs.read = ["."]
fs.write = ["out", ".buildl"]
| Key | Lists |
|---|---|
proc.run | the programs from your machine a command may run |
env.read | the environment variables a target may name in env |
env.unkeyed | the ones among them a target may mark "unkeyed", so that only the name, not the value, is in its action key |
fs.read | the directories inputs may come from; "." is the whole workspace |
fs.write | the directories a build may write into |
Directories are relative to the workspace root, and buildl, never Lua, works out what they mean.
Each list starts empty. An empty ceiling, even an empty buildl.toml, still lets check, graph
and query work, since they run nothing, but every plan is refused:
$ buildl plan
error: directory .buildl is outside the ceiling (fs.write allows: nothing)
A build always writes into .buildl, where buildl keeps its state, and the output directory,
out here, so fs.write needs both. An input outside fs.read is refused the same way, naming the target. Here the ceiling
writes fs.read = ["lib"] and the root build file reads hello.txt:
$ buildl plan
error: build.lua: //:greeting: input hello.txt is outside the ceiling (fs.read allows: lib)
There is no network list. A target that reaches the network says so with network = true, and
the approver and buildl doctor show it.
Unkeyed variables
A target marks each variable it reads, "key" or "unkeyed" (see Targets and
Labels). A "key" variable is held to env.read. An "unkeyed" one
must be in env.unkeyed as well, and env.unkeyed only narrows env.read: it holds names that
env.read already holds. A list left out is empty, so a variable may be unkeyed only when
env.unkeyed names it. Here a target marks HOME "unkeyed" under a ceiling with env.read and no
env.unkeyed:
$ buildl plan
error: build.lua: //:hello: unkeyed variable HOME is outside the ceiling (env.unkeyed allows: nothing)
That is a refusal, exit code 4, as for any want outside the ceiling. A name in env.unkeyed that
env.read does not hold is a fault in the file instead, found when buildl reads it, exit code 5:
$ buildl check
error: buildl.toml: ceiling env.unkeyed lists HOME, which env.read does not
The same pair of keys, with the same rule, is in each plugin's table and manifest (How buildl Decides).
[declaration]
[declaration]
memory = "16MB"
instructions = 10_000_000
walk_entries = 100_000
The limits one build file is evaluated under: how much memory it may use, how many Lua
instructions it may run, and how many directory entries buildl.sources may visit. The values
above are the defaults. A build file that goes over a limit fails.
[execution]
[execution]
workers = 4
timeout = "2m"
strategy = "sandbox"
| Key | Means | When left out |
|---|---|---|
workers | how many actions run at once; 0 is one per core | 0 |
timeout | how long one action may run: 500ms, 90s, 10m, 2h | "10m" |
strategy | how actions are isolated: bare, sandbox, os-sandbox or container | "sandbox" |
build and test run bare and sandbox, and refuse the other two rather than run with less
isolation than you asked for. The Sandbox explains the difference. None of
these change what an action produces, so none of them is part of a target's action key.
[approver]
[approver]
default = "manifest"
Who has the last word once a build fits under the ceiling: manifest, interactive or deny.
Approvers covers all three.
[plugins.<name>]
[plugins.gobin]
path = "plugins/gobin"
proc.run = ["go"]
env.read = ["HOME"]
env.unkeyed = ["HOME"]
One table per plugin: where its files come from (path in the workspace, or git or github with
a rev), and the most its targets may want, env.unkeyed included. A plugin's targets are held to
its own lists first, then to the ceiling, so these lists can narrow what a plugin gets but never
widen it.
Plugins covers them.
[remote]
[remote]
url = "grpcs://cache.example.com:443"
instance = "ci"
token = { env = "BUILDL_REMOTE_TOKEN" }
A shared cache, and optionally machines to build on, that speak the Remote Execution API. The
token itself is never written here, since this file is committed: token names the environment
variable or the file to read it from. A workspace without this table never uses a remote.
Remote Cache and Execution covers it.
Seeing what you wrote
buildl doctor prints the manifest as buildl understood it, with every default filled in, and
connects to nothing. For the manifest built from the examples on this page:
$ buildl doctor
workspace /private/tmp/buildl-book/full
approver manifest
execution workers 4, timeout 2m, strategy sandbox
remote
url grpcs://cache.example.com:443
instance ci
ca -
header authorization
timeout 30s
token not set
upload off
strict off
execute off in buildl.toml, BUILDL_REMOTE_EXECUTE not set
jobs 128
queue_timeout 1h
retries 5
properties: none
--remote-upload and --remote-strict turn either on for one run
--remote-execute and --no-remote-execute change execute, and --remote-jobs changes jobs, for one run
ceiling
proc.run go
env.read HOME
env.unkeyed HOME
fs.read .
fs.write .buildl, out
wants ceiling approved
run go allowed yes
read HOME unkeyed allowed yes
write .buildl allowed yes
write out allowed yes
The last part, the wants, is the subject of the next page. A variable a target marks "key" has the
row read HOME, and one marked "unkeyed" the row read HOME unkeyed.
Approvers
The ceiling says what a build may want. Once a build's wants all fit under it, one more question is left: should this build run now? The approver answers it, with yes or no. It cannot grant anything the ceiling does not, and it is never asked about a build the ceiling already refused.
build, test and verify ask the approver after planning and before anything runs. plan never
asks, so you can always look before you leap.
The three approvers
buildl.toml picks one:
[approver]
default = "interactive"
default | Answer |
|---|---|
manifest (when left out) | yes: the ceiling is the whole decision |
interactive | asks you on the terminal once, and remembers a yes |
deny | no, always |
manifest
The default. If the wants fit under the ceiling, the build runs. This suits a workspace whose ceiling you keep short and review like code, and it suits CI, where nobody is there to ask.
deny
Nothing runs, ever, even when every target could come from the cache. plan, check, graph and
query still work, so a workspace can be read and studied without any chance of running it:
$ buildl plan
run //:report: never built
run //tools:hello: never built
run programs: go
unkeyed variables: HOME
write into: .buildl, out
2 to run, 0 conditional, 0 clean
$ buildl build
error: the workspace's approver is deny
run programs: go
unkeyed variables: HOME
write into: .buildl, out
The build exits with code 4, as a want outside the ceiling does. The error lists what the build wanted, so you can see what you turned down.
interactive
The first time a build runs, buildl writes the question on standard error: this build wants to,
then the same list plan prints, then allow? [y/N]. It reads one line from standard input, and
y or yes, in any case, is a yes. Anything else, an empty line included, is a no, and the build
is refused with exit code 4.
A yes is remembered, and the next build whose wants are all covered by remembered yeses asks
nothing. If a later build wants something new, say a build file starts running protoc, buildl
asks again about the new wants only. A variable read as "key" and the same variable read as
"unkeyed" are two wants: a yes to read variables: HOME does not cover unkeyed variables: HOME,
so a build file that changes a mark is asked about once more. When a plugin's targets are behind a
new want, a line under the list names the plugin.
The remembered yeses live outside the workspace, in
$XDG_DATA_HOME/buildl/approved/, in a JSON file named for the workspace's location, or under
$HOME/.local/share when
XDG_DATA_HOME is not set to an absolute path. That is on purpose: a repository can ship its own
.buildl/ directory, and an approval kept inside the workspace would arrive with the code it is
meant to approve.
interactive only asks when both standard input and standard error are terminals. In a pipe or
in CI there is nobody to answer, so the build is refused, never quietly allowed:
$ buildl build
error: no terminal to ask on; run the build in a terminal once to approve, or set [approver] default = "manifest"
run programs: go
unkeyed variables: HOME
write into: .buildl, out
Run the build once in a terminal and answer yes, and later runs in a pipe go through, as long as they want nothing new.
buildl doctor
buildl doctor shows the whole picture in one place: the ceiling, the approver, the execution
settings, the remote, and every want of the build with what the ceiling and the approver say about
it. It refuses nothing and runs nothing, so it is safe in any workspace:
$ buildl doctor
workspace /private/tmp/buildl-book/ambient
approver manifest
execution workers 0 (one per core), timeout 10m, strategy sandbox
remote: none
ceiling
proc.run go
env.read HOME
env.unkeyed HOME
fs.read .
fs.write .buildl, out
wants ceiling approved
run go allowed yes
read HOME unkeyed allowed yes
write .buildl allowed yes
write out allowed yes
The same workspace under deny says no to every want, though each is inside the ceiling:
$ buildl doctor
workspace /private/tmp/buildl-book/denied
approver deny
execution workers 0 (one per core), timeout 10m, strategy sandbox
remote: none
ceiling
proc.run go
env.read HOME
env.unkeyed HOME
fs.read .
fs.write .buildl, out
wants ceiling approved
run go allowed no
read HOME unkeyed allowed no
write .buildl allowed no
write out allowed no
And the untrusted clone from Nothing Is Ambient, whose plan is
refused, shows the refused want beside the others:
$ buildl doctor
workspace /private/tmp/buildl-book/untrusted
approver manifest
execution workers 0 (one per core), timeout 10m, strategy sandbox
remote: none
ceiling
proc.run go
env.read HOME
env.unkeyed HOME
fs.read .
fs.write .buildl, out
wants ceiling approved
run curl REFUSED -
run go allowed yes
read HOME unkeyed allowed yes
write .buildl allowed yes
write out allowed yes
doctor exits 0 in all three. It reports; plan and build decide.
Caching
Run buildl build twice and the second run does nothing. That is not because buildl looked at
file times. Before it runs an action, it works out a fingerprint of everything that action could
depend on, and if it has run an action with the same fingerprint before, it puts the old outputs
back instead of running it again.
This chapter covers how that works and the commands built on it:
- The Action Key: what goes into the fingerprint, and how
buildl plantells you why a target has to run - Early Cutoff: why a target whose dependency was rebuilt to the same bytes is left alone
- Tests:
buildl test, and tests that are not run again when nothing they depend on changed clean,gcandverify: removing outputs, trimming the store, and checking that what the cache holds is what the action really makes
The Action Key
Every target that runs something has an action key: one SHA-256 digest of everything that could
change what its action produces. buildl keeps the key of each action it has run next to the
outputs it made. When a build comes to a target, it works out the key again. Same key, and the old
outputs are put back. A different key, and the action runs.
%% Action key composition
graph TD
CMD["Command<br/>argv template"] --> KEY["Action key<br/>sha256 of all five"]
IN["Input hashes<br/>via the stat cache"] --> KEY
DEP["Dep output hashes<br/>early cutoff built in"] --> KEY
ENV["Env: values of key variables,<br/>names of unkeyed ones"] --> KEY
SET["Tool fingerprints, settings,<br/>network, output source, os/arch"] --> KEY
KEY --> CMP{"equals cached key?"}
CMP -- yes --> CLEAN["Clean — served from cache"]
CMP -- no --> DIRTY["Dirty — plus the reason why"]
CMP -- "a dep is not clean" --> COND["Conditional — runs only if<br/>that dep's output changes"]
Why does it have to run?
buildl keeps the pieces of each key, not only the digest. So when a key changes, it can compare
the old pieces with the new ones and tell you which one moved. Here is the Go project from
A First Project, with an edit to main.go. The edits in this chapter
use sed -i '', the macOS form; on Linux, drop the '':
$ buildl plan
clean //:hello
run programs: go
unkeyed variables: HOME
write into: .buildl, out
0 to run, 0 conditional, 1 clean
$ sed -i '' 's/hello from go/hello again from go/' main.go
$ buildl plan
run //:hello: input main.go changed
run programs: go
unkeyed variables: HOME
write into: .buildl, out
1 to run, 0 conditional, 0 clean
$ buildl build
1 built
$ buildl plan
clean //:hello
run programs: go
unkeyed variables: HOME
write into: .buildl, out
0 to run, 0 conditional, 1 clean
What goes in
buildl plan --json prints the plan as JSON, with every piece of every key spelled out. One more
edit, and a look:
$ echo '// a comment' >> main.go
$ buildl plan --json | python3 -m json.tool
{
"attribution": {
"env": {},
"network": {},
"programs": {},
"unkeyed": {}
},
"settings": {},
"stale_discovery": [],
"targets": {
"//:hello": {
"key": {
"components": {
"deps": [],
"own": {
"command": [
"go",
"build",
"-o",
"$out",
"."
],
"env": {},
"inputs": [
{
"digest": "d38681ddfea2335850882acc2698e6d7774a756145aa33b2a609a7e017557758",
"path": "go.mod"
},
{
"digest": "ad15ae8cfe78c99215787abf757440d2fabff96c116a6f0c93730308833dd9f9",
"path": "main.go"
},
{
"digest": "5d3a28044a10bc204ee388b2d16bc160f4c723b69e0a8bb80b1d0c1532f80a25",
"path": "main_test.go"
}
],
"network": "Sealed",
"output_source": "Command",
"outputs": [
"hello"
],
"platform": "macos/aarch64",
"settings": {},
"tool": {
"fingerprint": "45bd4639e304aed73901b60255c0eaffbf35ef0b2f23775fbb0a415a3618cfb6",
"program": "go"
},
"unkeyed": [
"HOME"
]
}
},
"digest": "3ce0dd2ff689ab3da2a054836c76a059102e470fd56ed3c6fa2a47cd6253d5d7"
},
"reason": {
"Changed": [
{
"Input": "main.go"
}
]
},
"unfinished": null,
"verdict": "Dirty"
}
},
"wanted": {
"env": [],
"network": [],
"programs": [
"go"
],
"unkeyed": [
"HOME"
],
"write": [
".buildl",
"out"
]
}
}
components is what the key is made of, digest is the key itself, and reason is the piece that
differs from the last build: the words input main.go changed come from it. The digests and the
platform will be your own. env is empty and unkeyed holds HOME: more on that below.
| Component | What it holds |
|---|---|
command | the command as written, before $out and the others are filled in |
inputs | the path and a SHA-256 of the contents of every input file |
deps | for each dependency, a digest of each output it produced: its name, a hash of its bytes and whether it is executable |
env | the name and value of each variable the target marked key, and nothing of the rest of the environment |
unkeyed | the name, and only the name, of each variable the target marked unkeyed |
tool | the program the command runs, and a fingerprint of that program's file |
settings | the build settings the target uses, with their values for this run |
network, output_source, outputs | whether it may reach the network, whether its output is a file it writes or what it prints, and the names of its outputs |
platform | the operating system and the processor |
So a new Go toolchain is a new tool fingerprint and rebuilds everything that runs go, and a
cache filled on a Mac is never used on Linux. Some things are left out on purpose. How many actions
run at once, the timeout, and whether actions run in the sandbox change how a
build runs, not what an action is given, so none of them is part of this key. The timeout is part of
the name a remote server knows an action by, which is a
different thing from this key.
Variables that only find files
A command is given only the variables its target names, and env marks each one:
| Mark | The command gets | The key holds | Sent to a remote server |
|---|---|---|---|
"key" | its value | its name and value | name and value |
"unkeyed" | its value | its name | no |
go needs HOME to find its build cache, but the value is a folder on one machine. Keyed, the same
target would have another key for every user and every machine, and nothing one made could be used
by another. Marked unkeyed, HOME still reaches go, and the key holds the word HOME and no
more. Use unkeyed for a variable that only finds programs or files: HOME, PATH, a cache
folder. Use key for one that changes what the action makes, such as a compiler flag.
unkeyed is something the workspace has to allow, as reading a variable is. The ceiling lists the
names that may be marked so in env.unkeyed, and every name in it has to be in env.read too (the
buildl.toml appendix has the table).
Mark GOCACHE key, point it at a folder, build, then point it at another folder:
$ GOCACHE=/tmp/buildl-book/keys/cache-a buildl build
1 built
$ GOCACHE=/tmp/buildl-book/keys/cache-b buildl plan
run //:hello: environment variable GOCACHE changed
run programs: go
read variables: GOCACHE
unkeyed variables: HOME
write into: .buildl, out
1 to run, 0 conditional, 0 clean
The folder is in the key, so the target runs again for nothing. Change the mark to unkeyed, and add
GOCACHE to env.unkeyed in buildl.toml. The change is in the key, so plan says so once, and a
build stores the new key:
$ GOCACHE=/tmp/buildl-book/keys/cache-b buildl plan
run //:hello: variable GOCACHE is now unkeyed
run programs: go
unkeyed variables: GOCACHE, HOME
write into: .buildl, out
1 to run, 0 conditional, 0 clean
$ GOCACHE=/tmp/buildl-book/keys/cache-b buildl build
1 built
$ GOCACHE=/tmp/buildl-book/keys/cache-a buildl plan
clean //:hello
run programs: go
unkeyed variables: GOCACHE, HOME
write into: .buildl, out
0 to run, 0 conditional, 1 clean
Now a different folder is no change at all. What plan says when the set of variables or a mark
changes:
| Change | plan prints |
|---|---|
a key variable's value, added or removed | environment variable X changed |
an unkeyed variable added | unkeyed variable X added |
an unkeyed variable removed | unkeyed variable X removed |
key to unkeyed | variable X is now unkeyed |
unkeyed to key | variable X is now keyed |
an unkeyed variable's value | nothing: the key does not change |
The other way a machine gets into a key is a folder written into a command, a key variable's value,
a setting's value or a discovery output. buildl refuses those with exit code 5 instead of letting
the key split. What buildl Promises lists what is checked, and Discovery
Targets shows one refusal.
What a dependency produced, not its key
The deps list above is empty, because //:hello depends on nothing. In the polyglot workspace
from Many Directories, //go:service depends on //schema:gen, and
its key holds a digest of each file //schema:gen wrote. That digest covers the file's name, a
hash of its bytes and whether it is executable, so it is not the same number shasum prints:
$ buildl plan --json //go:service | python3 -c 'import json,sys; t=json.load(sys.stdin)["targets"]["//go:service"]; print(json.dumps(t["key"]["components"]["deps"], indent=2))'
[
{
"label": "//schema:gen",
"outputs": [
{
"digest": "48497628d8cd57a7717a79ccd4d81becd7b149564ec060ebb5e99fd9f2588e2b",
"name": "gogen/gen.go"
},
{
"digest": "088cae078ec9a96c4f9b03ab629306aa133d69aa685092d0b99dd8a08f0cb12a",
"name": "gogen/go.mod"
},
{
"digest": "9d1e8a75aa2175d3e82a7b96fd399b975d0af6d42da73298186453978d49edd3",
"name": "gen.rs"
},
{
"digest": "343fea850093120344f9469cccb363ec52a8690d84e651d8faa0e3dfa8d85e94",
"name": "gen.py"
}
]
}
]
It holds what the dependency made, not the dependency's own key. That one choice is what the next page, Early Cutoff, is about.
The same choice has a cost when a dependency is built somewhere else. If it is built on another machine or in another workspace and comes out with other bytes, its output digests change, and so do the keys of the targets that use it. Above those, the change goes on only as far as their rebuilt outputs differ too. A tool that writes the folder it ran in into its output is one cause, because the folder an action runs in is named for the workspace's path and the temporary directory. The result is still correct, only not shared. Who should upload says how a team keeps those bytes the same for everyone.
One edit, start to finish
Put together, this is everything that happens between saving main.go and the build finishing:
%% One edit traced through the rebuilder
flowchart TD
EDIT["Edit main.go"] --> STAT["Stat cache check<br/>mtime changed — rehash the file"]
STAT --> H["New content hash<br/>for main.go"]
H --> KEY["Action key recomputed<br/>argv + input hashes + key variables<br/>+ unkeyed names + tool fingerprint + os/arch"]
KEY --> CMP{"Equals cached key<br/>for //:hello?"}
CMP -->|no| DIRTY["Dirty — reason recorded:<br/>input main.go changed"]
DIRTY --> EXEC["Worker runs go build<br/>outputs to temp dir"]
EXEC --> CAS["Hash output into cas<br/>then write cache row"]
CAS --> CUT{"Output binary<br/>byte-identical to before?"}
CUT -->|yes| CLEAN["Early cutoff —<br/>downstream stays clean"]
CUT -->|no| PROP["Downstream keys change —<br/>dependents run"]
The stat cache is how buildl avoids reading every input on every run: when a file's size and
modification time are what they were last time, the hash recorded then is used again. The cas is
the store under .buildl/ that holds every output by the hash of its contents. The output goes
into the cas first and the cache row is written after it, so a build stopped half way never leaves
a row that points at nothing; Crash Safety and the Store has the rest.
Early Cutoff
A target's key holds what its dependencies produced, not their keys. So when a dependency runs again and writes exactly the bytes it wrote last time, nothing downstream of it has a new key, and nothing downstream runs. This is called early cutoff: the ripple of an edit stops at the first target whose output did not change.
The polyglot workspace
examples/polyglot builds a Go service, a Rust program and a Python tool, all from one generated
file. //schema:gen runs generate.py over schema.json and writes a source file for each
language; the three programs depend on it.
%% Polyglot workspace — edit ripple analysis
graph TD
SCHEMA["schema/schema.json<br/>source of truth"] --> GEN["//schema:gen<br/>python3 generate.py"]
GEN --> GO["//go:service<br/>go build"]
GEN --> RS["//rust:cli<br/>rust.binary, cargo build"]
GEN --> PY["//python:tool.pyz<br/>python3 pack.py"]
schema.json has a comment field, and the generator never copies it into what it writes:
{
"comment": "The values every program prints. The generator ignores this line.",
"version": "1.0",
"greeting": "hello from the schema"
}
Editing the comment
Build once, then edit only the comment. (The first build's cargo lines are left out here; you
will see them in full below.)
$ buildl build
4 built
$ sed -i '' 's/ignores this line\./ignores this line. Edited./' schema/schema.json
$ buildl plan
maybe //go:service: runs only if //schema:gen produces something else
maybe //python:tool.pyz: runs only if //schema:gen produces something else
maybe //rust:cli: runs only if //schema:gen produces something else
run //schema:gen: input schema/schema.json changed
run programs: go, python3, sh
unkeyed variables: HOME, PATH
write into: .buildl, out
reach the network: //rust:cli
sh: declared by plugin rust@0.2.1 for //rust:cli
HOME (unkeyed): declared by plugin rust@0.2.1 for //rust:cli
PATH (unkeyed): declared by plugin rust@0.2.1 for //rust:cli
//rust:cli: declared by plugin rust@0.2.1 for //rust:cli
1 to run, 3 conditional, 0 clean
//schema:gen has to run: one of its inputs changed. The three programs are neither clean nor to
run. Their keys hold //schema:gen's outputs, and those do not exist yet, so plan cannot know
their keys. It calls them conditional and prints them as maybe. In buildl plan --json they
have the verdict Conditional, no key, and an unfinished entry that names the target they are
waiting on.
Now build:
$ buildl build
--- //rust:cli (cached)
Compiling cli v0.1.0 (/private/var/folders/8w/4ccj7cw90nx4d32s72tqf5nw0000gn/T/buildl-4a04b4d480388c7fb246c52f872863b3/709bb78cafdc4445f4217a9db757a876/rust)
Finished `release` profile [optimized] target(s) in 1.18s
1 built, 3 cached
$ buildl plan
clean //go:service
clean //python:tool.pyz
clean //rust:cli
clean //schema:gen
run programs: go, python3, sh
unkeyed variables: HOME, PATH
write into: .buildl, out
reach the network: //rust:cli
sh: declared by plugin rust@0.2.1 for //rust:cli
HOME (unkeyed): declared by plugin rust@0.2.1 for //rust:cli
PATH (unkeyed): declared by plugin rust@0.2.1 for //rust:cli
//rust:cli: declared by plugin rust@0.2.1 for //rust:cli
0 to run, 0 conditional, 4 clean
1 built, 3 cached. The generator ran and wrote the same four files, so the three programs had the
keys they had before and came from the cache. go, cargo and the Python packer never started.
The cargo lines are not a run. A target served from the cache shows what it printed when it last
ran, marked (cached), so a warning does not vanish just because the build was fast the second
time. The long folder names are the sandbox directory where cargo ran; on
your machine they will differ, and so will the time.
Editing a value
Change a value the generator does copy, and the ripple goes all the way:
$ sed -i '' 's/hello from the schema/hello again from the schema/' schema/schema.json
$ buildl plan
maybe //go:service: runs only if //schema:gen produces something else
maybe //python:tool.pyz: runs only if //schema:gen produces something else
maybe //rust:cli: runs only if //schema:gen produces something else
run //schema:gen: input schema/schema.json changed
run programs: go, python3, sh
unkeyed variables: HOME, PATH
write into: .buildl, out
reach the network: //rust:cli
sh: declared by plugin rust@0.2.1 for //rust:cli
HOME (unkeyed): declared by plugin rust@0.2.1 for //rust:cli
PATH (unkeyed): declared by plugin rust@0.2.1 for //rust:cli
//rust:cli: declared by plugin rust@0.2.1 for //rust:cli
1 to run, 3 conditional, 0 clean
$ buildl build
--- //rust:cli
Compiling cli v0.1.0 (/private/var/folders/8w/4ccj7cw90nx4d32s72tqf5nw0000gn/T/buildl-4a04b4d480388c7fb246c52f872863b3/709bb78cafdc4445f4217a9db757a876/rust)
Finished `release` profile [optimized] target(s) in 1.08s
4 built
The plan is the same as before, because before the generator runs nobody can tell the two edits
apart. Only its output decides.
Edits that never reach a tool
The three edits this workspace can see, side by side:
| You edit | What runs | Why |
|---|---|---|
the comment in schema.json | //schema:gen only | its outputs are byte-for-byte the same, so the programs' keys are too |
the greeting in schema.json | all four | the generated files differ, so every program's key changes |
go/main.go | //go:service only | the other programs do not depend on it; cargo and the packer are never started |
Early cutoff is why it pays for a generator to write only what it was asked for: anything it copies blindly, such as a comment or a time stamp, turns every edit into a full rebuild.
Tests
A test target is declared with buildl.test instead of buildl.target. It has inputs and a
command like any target, but no outputs unless it names some: what it produces is a pass or a fail. The Go project
declares one:
b.test("unit", {
inputs = sources,
run = { "go", "test", "./..." },
env = { HOME = "unkeyed" },
})
buildl build leaves test targets out. buildl test runs them, and builds whatever they depend on
first, as build would. With no targets named it runs every test; name one, and it runs just that
one. Naming a target that is not a test is a usage error.
A test is cached like anything else
A test target has an action key, worked out exactly as a build target's is. If nothing in the key changed since the test last passed, the test is not run again:
$ buildl test
tests: 1 passed
$ buildl test
tests: 1 passed (1 cached)
The last line always has the same shape: tests: N passed, with how many of those came from the
cache in brackets, and the failures after it. The second time, go test was never started:
nothing it could see had changed.
When you want the tests run anyway, say so:
$ buildl test --rerun
tests (rerun): 1 passed
A failing test
Break the greeting the test checks:
$ sed -i '' 's/hello from go/hello, tests/' main.go
$ buildl test
--- //:unit
--- FAIL: TestGreeting (0.00s)
main_test.go:7: Greeting() = "hello, tests"
FAIL
FAIL example.com/hello 0.532s
FAIL
FAILED //:unit: action failure (exit status 1)
declared in build.lua
command: go test ./...
tests: 1 failed
buildl shows what the failing test printed, names the target, the build file that declared it
and the command, and exits with code 1. A passing test prints nothing unless you ask with
--verbose. The time go test reports will be different on your machine.
A failure is never cached. Put the line back:
$ sed -i '' 's/hello, tests/hello from go/' main.go
$ buildl test
tests: 1 passed (1 cached)
The failed run recorded nothing in the cache. main.go is back to the bytes it held when the test
last passed, so the key is that run's key again, and the pass recorded then still stands.
Other ways to run them
| Flag | What it does |
|---|---|
--rerun | run the selected tests even when nothing they depend on changed |
--verbose | show what every test printed, not only the failing ones |
--stop | start nothing new after the first failure |
--stream | show one running action's output as it is printed |
buildl log //:unit shows what the test printed the last time it ran, cached or not.
clean, gc and verify
Three commands look after what the cache holds. clean throws away the copies in out/, gc
throws away what no target needs any more, and verify checks that what the cache holds is what
the actions really make.
buildl clean
clean removes the output directory and nothing else:
$ ls out
hello
$ buildl clean
clean: removed out
$ ls
assert.sh
build.lua
buildl.toml
go.mod
main_test.go
main.go
README.md
$ buildl build
1 cached
$ ls out
hello
The cache rows and the store under .buildl/ are untouched, so the next build runs nothing. It
puts every output back from the store, and says cached. out/ is only ever a copy.
buildl gc
The store keeps every output it was given. Over time it fills with outputs of targets that were
renamed, removed, or rebuilt to something new. gc drops the cache rows of targets that are no
longer declared, then removes every stored file that no remaining row and no target's last run
needs.
Rename hello to greeter in build.lua, build, and collect:
$ sed -i '' 's/"hello"/"greeter"/' build.lua
$ buildl build
1 built
$ buildl gc
gc: dropped 1 row, removed 4 blobs (4059395 bytes)
$ buildl gc
gc: dropped 0 rows, removed 0 blobs (0 bytes)
//:hello is gone from the build files, so its row was dropped and what only it needed was
removed. A blob is one stored file. A second gc finds nothing left to do. gc reads the build
files first, so run it from a checkout whose build files declare everything you want to keep.
buildl verify
The action key promises that the same inputs give the same key, and so a cache hit. It cannot promise that the command gives the same bytes. A tool that writes the time, a random number or the order a hash table happened to iterate in will not. If such an output reaches the cache, every later build trusts it.
verify checks. It plans as build does, takes the targets that are cached, puts their outputs
back, runs their actions again in the sandbox, and compares each new output
with the one the cache holds:
$ buildl verify
verified //:hello
1 verified, 0 mismatched, 0 failed, 0 skipped, 0 not cached, 0 not sampled
Go writes the same binary every time, so it passes. To see a failure, here is a small workspace
with two targets: copy.txt copies a file, and stamp.txt writes the time it ran.
-- build.lua
local b = buildl
b.target("copy.txt", {
inputs = { "copy.py", "notes.txt" },
run = { "python3", "$in", "$out" },
})
b.target("stamp.txt", {
inputs = { "stamp.py" },
run = { "python3", "$in", "$out" },
})
# stamp.py
import sys, time
with open(sys.argv[1], "w") as f:
f.write(f"built at {time.time()}\n")
$ buildl build
2 built
$ buildl verify
verified //:copy.txt
MISMATCH //:stamp.txt: output stamp.txt differs: bytes
1 verified, 1 mismatched, 0 failed, 0 skipped, 0 not cached, 0 not sampled
verify names the target, the output and the first thing that differs, and exits with code 1.
It repairs nothing and records nothing: no cache row is written or forgotten, nothing goes in the
log, and the new bytes never reach out/. The build after it is served from the cache as before:
$ buildl build
2 cached
The summary counts:
| Count | Meaning |
|---|---|
| verified | ran again and gave the same output |
| mismatched | ran again and gave a different output |
| failed | the second run failed |
| skipped | depends on a target that is not cached, so it could not be run |
| not cached | not clean in the plan, or its stored output is gone |
| not sampled | left out by --sample |
Checking a sample
Running every action again costs as much as a full build. --sample N runs only N of them:
$ buildl verify --sample 1
MISMATCH //:stamp.txt: output stamp.txt differs: bytes
0 verified, 1 mismatched, 0 failed, 0 skipped, 0 not cached, 1 not sampled
The sample is not random. It takes the N targets whose keys sort lowest, so the same keys pick the
same targets on every run and every machine, and a target moves in or out of the sample only when
its key changes. With no targets named, verify takes every target but the tests; name targets to
check those.
verify runs actions only in the sandbox. A workspace whose buildl.toml says
strategy = "bare" is refused, and the next chapter shows why that matters.
The Sandbox
The action key folds in every input a target declares. A tool that quietly reads a file nobody
declared breaks that: edit the file, and the key does not change, so buildl serves the old output
as if nothing happened. The sandbox is there so such a target fails loudly instead.
The isolation ladder
How much an action can reach is a ladder of four steps, set by strategy under [execution] in
buildl.toml:
%% Execution isolation ladder
graph TD
T1["Tier 1 — Bare process<br/>filtered env, no shell<br/>strategy = bare"] --> T2["Tier 2 — Input sandbox<br/>temp dir, declared inputs only<br/>strategy = sandbox, the default"]
T2 --> T3["Tier 3 — OS sandbox<br/>namespaces or sandbox-exec: no network<br/>strategy = os-sandbox, refused today"]
T3 --> T4["Tier 4 — Container<br/>pinned toolchain image in the key<br/>strategy = container, refused today"]
This version of buildl runs the first two. Tier 2, sandbox, is what you get when buildl.toml
says nothing.
Tier 2: the input sandbox
Each action runs in a directory of its own, outside the workspace, made fresh for it. Into it
buildl copies the action's declared inputs and the outputs of its dependencies, each at its path
in the workspace, and makes the folders its outputs go in. Nothing else of the workspace is there.
The environment holds the variables the target declared, each with its value, marked "key" or
"unkeyed" alike, and three that the sandbox sets itself:
| Variable | Value | Why |
|---|---|---|
TZ | UTC | local time is the same everywhere |
LC_ALL | C | sorting, messages and number formats do not follow the machine's language |
SOURCE_DATE_EPOCH | 315532800 | the time a tool stamps into what it writes: 1980-01-01, the earliest a ZIP file can hold |
Every file and folder copied in carries that same time, 1980-01-01, as the time it was last changed. A tool that records file times, such as a ZIP packer, then writes the same times on every run and every system.
When the action is done, buildl reads its outputs into the store and removes the directory.
The directory is outside the workspace on purpose. Tools such as go, cargo and node search
upward for a go.mod, a Cargo.toml or a node_modules; from inside the workspace they would
find the real ones and read what the action never declared.
Where the folder is
The folder sits below the system's temporary directory (TMPDIR, or /tmp), in two parts:
buildl- and a digest of the workspace's path, and inside it one folder per target, named by a
digest of the target's label. The label part depends on the label only, so it is the same
everywhere. The workspace part changes with the workspace's path and the temporary directory:
another workspace, or a machine where either differs, has a folder with another name.
That is on purpose. Each workspace, a git worktree included, keeps a folder of its own, so it never shares one with another workspace and never waits on it.
This matters for a tool that writes the folder it ran in into its output. Rust's include! of a
file from OUT_DIR, and the build directory a compiler writes into debug information, are two
examples. Run in another folder, such a tool gives other bytes. This is correct: the output
really does differ, and the cache is not wrong. What it means for a cache shared between
workspaces is on Who should upload.
An input nobody declared
This target runs copy.py notes.txt, but declares only copy.py:
b.target("report.txt", {
inputs = { "copy.py" },
run = { "python3", "copy.py", "notes.txt", "$out" },
})
In the sandbox, notes.txt is simply not there:
$ buildl build report.txt
--- //:report.txt
Traceback (most recent call last):
File "/private/tmp/buildl-book/tmp/buildl-da4d7d2517e4eb80af55e5b005ab65a7/94e5f4daefe263b293863d95170ab5bc/copy.py", line 4, in <module>
with open(src) as f, open(dst, "w") as g:
^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'notes.txt'
FAILED //:report.txt: action failure (exit status 1)
declared in build.lua
command: python3 copy.py notes.txt out/report.txt
1 failed
The error is the tool's own. buildl cannot know which file the tool went looking for, only that
the action failed. The temporary folder in the traceback will have another name on your machine.
The fix is to add notes.txt to inputs.
Tier 1: bare
Some tools read files they have no way to declare. For those, buildl.toml can step down a rung:
[execution]
strategy = "bare"
Now the action runs as a plain process in the workspace itself, and it finds notes.txt:
$ buildl build report.txt
1 built
$ cat out/report.txt
some notes
bare still starts the command without a shell, gives it only the variables the target declared,
and stops it at the timeout. But it confines nothing: the action can read and write anything you
can, and an undeclared input is a silent mistake again.
The strategy is not in the key
Switching strategy does not rebuild anything, because it changes where an action runs, not what
it is given. So report.txt, built under bare with its hidden input, is still a cache hit after
switching back to sandbox:
$ buildl build report.txt
1 cached
The sandbox never ran it, so the sandbox never caught it. That is what
buildl verify is for. It runs cached actions again in the sandbox:
$ buildl verify report.txt
--- //:report.txt
FAILED //:report.txt: action failure (exit status 1)
Traceback (most recent call last):
File "/private/tmp/buildl-book/tmp/buildl-da4d7d2517e4eb80af55e5b005ab65a7/94e5f4daefe263b293863d95170ab5bc/copy.py", line 4, in <module>
with open(src) as f, open(dst, "w") as g:
^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'notes.txt'
0 verified, 0 mismatched, 1 failed, 0 skipped, 0 not cached, 0 not sampled
verify itself runs only in the sandbox. Under bare it is refused, with exit code 5:
$ buildl verify report.txt
error: manifest: buildl.toml: [execution] strategy is "bare", and verify re-runs actions in the input sandbox only: write strategy = "sandbox" under [execution]
What an action sees
You can watch the difference from inside an action. This target writes down the files in the folder it runs in, and its whole environment:
b.target("where.txt", {
inputs = { "where.py" },
run = { "python3", "$in", "$out" },
})
# where.py
import os, sys
with open(sys.argv[1], "w") as f:
f.write(f"files: {sorted(os.listdir('.'))}\n")
for name in sorted(os.environ):
f.write(f"{name}={os.environ[name]}\n")
Under bare it sees the whole workspace:
$ buildl build where.txt
1 built
$ cat out/where.txt
files: ['.buildl', 'build.lua', 'buildl.toml', 'copy.py', 'notes.txt', 'out', 'where.py']
LC_CTYPE=C.UTF-8
__CF_USER_TEXT_ENCODING=0x1F5:0x0:0x0
Now switch to sandbox. Because the strategy is not in the key, a plain build would serve the
bare result from the cache, so start from an empty state first:
$ rm -rf out .buildl
$ buildl build where.txt
1 built
$ cat out/where.txt
files: ['out', 'where.py']
LC_ALL=C
SOURCE_DATE_EPOCH=315532800
TZ=UTC
__CF_USER_TEXT_ENCODING=0x1F5:0x0:0x0
Only its one input and the folder for its output, and the three pinned variables. LC_CTYPE and
__CF_USER_TEXT_ENCODING are not from buildl: Python and macOS set them as the process starts,
and on Linux you will not see the second. Neither run got anything of your own environment, not
even PATH or HOME, because the target declared no variables. Had it declared HOME, marked
"key" or "unkeyed", the command would have been given HOME with its value either way: the mark
only decides whether the value is in the action key and whether it is sent
to a remote server. A variable marked "unkeyed" that is not set is not given to the command at
all.
Tiers that are not built yet
os-sandbox and container are accepted names, but this version cannot run them. Rather than run
your actions with less isolation than you asked for, build, test and verify refuse, with exit
code 5:
$ buildl build
error: manifest: buildl.toml: [execution] strategy is "container", and this version of buildl runs "bare" and "sandbox" only: write strategy = "sandbox" under [execution]
$ buildl plan
run //:report.txt: never built
clean //:where.txt
run programs: python3
write into: .buildl, out
1 to run, 0 conditional, 1 clean
Commands that run no action, like plan, check and graph, work under any strategy.
Guarantee, mitigate, verify
Tier 2 stops an action reading a workspace file it did not declare, and nothing more. An action
can still name a file by its full path, climb out with .., read /usr or your home folder, reach
the network, and leave processes running after it ends. Closing those is tier 3's job. What each
part of buildl can promise:
| Property | Status |
|---|---|
| same declared inputs, same action | guaranteed by the action key |
| an action sees only its declared inputs | enforced from tier 2, for the files of the workspace |
| time zone, language and clock differ between machines | mitigated from tier 2 by the three pinned variables |
| the network as a hidden input | removed at tier 3, not built yet |
| the same action gives the same bytes | up to the tool: not promised, but checked by verify |
buildl cannot make a compiler reproducible. It can pin every input the compiler sees, and then
verify turns whatever is left into a named target with a named output, instead of a wrong file
quietly shared from the cache.
Discovery Targets
Sometimes the build files cannot know their targets until a tool has looked at the sources. A Go
module wants one test target per package, and the packages are whatever go list says they are.
You could write the list out by hand, and keep it up to date by hand.
Or the build file could ask go list. But a build file cannot run anything. Lua only declares
targets; buildl runs them later, after it has planned the whole build and the approver has seen
everything the build wants. A build file that ran go list while it was being read would run a
program before any of that, and the same door would let it run anything else. So it cannot.
What it can do is declare a discovery target: an ordinary action, keyed, cached, sandboxed and approved like any other, whose output the build files read back the next time they are evaluated.
Three functions
| Function | What it does |
|---|---|
buildl.discover(name, { ... }) | declares a discovery target. It takes the same table as buildl.target, without outputs and always. Its one output is <name>.json, which must be a file |
buildl.discovered(label) | the output of that target's last successful run, as a string, or nil if it has never run |
buildl.decode_all(text) | reads text holding several JSON values back to back, and returns them as a list |
The example
examples/go-discovery is a Go module with three packages and no list of them anywhere:
$ find . -name '*.go' | sort
./greet/greet_test.go
./greet/greet.go
./mathx/mathx_test.go
./mathx/mathx.go
./text/words/words_test.go
./text/words/words.go
Its build file:
local b = buildl
-- The module line of go.mod.
local module = "example.com/discovery"
b.discover("pkgs", {
run = { "go", "list", "-json=ImportPath", "./..." },
inputs = { "go.mod", b.sources("**/*.go") },
env = { HOME = "unkeyed" },
stdout = true,
})
local listed = b.discovered(":pkgs")
if listed == nil then
return
end
for _, pkg in ipairs(b.decode_all(listed)) do
local dir = pkg.ImportPath:sub(#module + 2)
b.test((dir:gsub("/", ".")), {
inputs = { "go.mod", b.sources(dir .. "/*.go") },
run = { "go", "test", "./" .. dir },
env = { HOME = "unkeyed" },
})
end
Three details make it work:
stdout = true.go listprints what it finds and has no flag to write it to a file. Withstdout = true, what the command prints is the target's output.decode_all.go list -jsonprints one JSON object per package, one after the other. That is not one JSON value, soairsstack.json.decodewould refuse it;decode_allreturns the list.-json=ImportPath. The full objects also hold absolute paths, which name the folder the action ran in and so differ between machines. Asking for one field keeps the output the same everywhere. A folder in the output shows what happens without it.
A target name cannot hold /, so the package text/words becomes the test //:text.words.
Two passes
Before anything has run, discovered returns nil, and the build file declares only //:pkgs.
Commands that run nothing say so:
$ buildl graph
//:pkgs has not run; run buildl build
{"aliases":{},"settings":{},"targets":{"//:pkgs":{"deps":[],"description":null,"env":{"HOME":"unkeyed"},"freshness":"Cached","inputs":["go.mod","greet/greet.go","greet/greet_test.go","mathx/mathx.go","mathx/mathx_test.go","text/words/words.go","text/words/words_test.go"],"network":"Sealed","origin":"BuildFile","output_source":"Stdout","outputs":["pkgs.json"],"provenance":{"directory":"","file":"build.lua"},"role":"Discovery","run":["go","list","-json=ImportPath","./..."]}}}
$ buildl plan
write into: .buildl, out
//:pkgs is not up to date; targets declared from it may change
0 to run, 0 conditional, 0 clean
build and test are the only commands that run discovery targets. They read the build files,
run the discovery targets, then read the build files a second time with the results:
%% build and test when the workspace declares discovery targets
flowchart TD
L1["Load<br/>no discovery results"] --> R1["Resolve, narrow<br/>the discovery targets and what they need"]
R1 --> X1["Plan, approve, Execute, Record<br/>the discovery targets only"]
X1 --> L2["Load again<br/>with the results just recorded"]
L2 --> X2["The command as before<br/>Resolve, narrow, Plan, approve, Execute, Record"]
$ buildl build
--- //:pkgs
{
"ImportPath": "example.com/discovery/greet"
}
{
"ImportPath": "example.com/discovery/mathx"
}
{
"ImportPath": "example.com/discovery/text/words"
}
1 built
nothing to build
There are two summaries because there were two runs. 1 built is the discovery run. nothing to build is the build proper: this workspace's only other targets are tests, which build leaves
out. The output is in out/pkgs.json, and now the graph holds a test per package:
$ buildl graph | python3 -c 'import json,sys; [print(l, t["role"]) for l,t in sorted(json.load(sys.stdin)["targets"].items())]'
//:greet Test
//:mathx Test
//:pkgs Discovery
//:text.words Test
$ buildl test
--- //:pkgs (cached)
{
"ImportPath": "example.com/discovery/greet"
}
{
"ImportPath": "example.com/discovery/mathx"
}
{
"ImportPath": "example.com/discovery/text/words"
}
1 cached
tests: 3 passed
$ buildl test
--- //:pkgs (cached)
{
"ImportPath": "example.com/discovery/greet"
}
{
"ImportPath": "example.com/discovery/mathx"
}
{
"ImportPath": "example.com/discovery/text/words"
}
1 cached
tests: 3 passed (3 cached)
Each run shows what //:pkgs printed, marked (cached) because nothing it reads had changed.
Adding a package
Add a fourth package, shout, with a .go file and a test. No build file changes:
$ ls shout
shout_test.go
shout.go
$ buildl plan
write into: .buildl, out
//:pkgs is not up to date; targets declared from it may change
0 to run, 0 conditional, 0 clean
$ buildl test
--- //:pkgs
{
"ImportPath": "example.com/discovery/greet"
}
{
"ImportPath": "example.com/discovery/mathx"
}
{
"ImportPath": "example.com/discovery/shout"
}
{
"ImportPath": "example.com/discovery/text/words"
}
1 built
tests: 4 passed (3 cached)
//:pkgs reads every .go file, so the new files changed its key and go list ran again. The
second pass declared //:shout, which ran, and the three old tests came from the cache.
A folder in the output
A discovery output decides which targets exist, so one that holds a path of this machine would give
every machine its own graph. When the second pass reads the output, buildl looks for this
machine's folders in it: the home folder, the workspace and the action's folder. Change
-json=ImportPath to -json in the build file above, and go list prints the full objects, with
the Dir of each package:
$ buildl build 2>&1 | tail -n 2
1 built
error: build.lua: //:pkgs: its output holds this machine's path /private/tmp/buildl-book/keys/tmp/buildl-d40680c030c69f01d404b0ac8609d069
The command exits with code 5, a fault in the build files, and Dir is why: it names the folder the
action ran in. The path in the message is the longest of this machine's folders the output holds,
and it will be your own. The output was stored as any output is, so it is read and refused again
on every run, 1 cached this time, until the discovery's command changes:
$ buildl build 2>&1 | tail -n 2
1 cached
error: build.lua: //:pkgs: its output holds this machine's path /private/tmp/buildl-book/keys/tmp/buildl-d40680c030c69f01d404b0ac8609d069
Put -json=ImportPath back, and the command is a different key, so it runs again. Under
watch the refusal is printed and the watch goes on waiting. The
same check covers a command, a key variable and a setting; What buildl
Promises has the list.
The rules
| Rule | Detail |
|---|---|
| a target like any other | keyed, cached, run in the sandbox, held to the ceiling and approved, and logged. buildl verify //:pkgs re-runs it |
| default scope | build and test leave discovery targets out of what they run by default; buildl build //:pkgs builds just that one |
| two approvals | the discovery run and the build proper are each put to the approver. interactive asks the second time only about what the first yes did not cover |
| no machine folder | the output may not hold this machine's home, workspace or action's folder: it is refused with exit code 5 when the second pass reads it, whether it was just run, cached or fetched |
| a failure stops it | a discovery target that fails ends the command, and nothing is declared from it |
| other commands | plan, graph, check, query, doctor, verify and gc never run a discovery target to get the targets it declares. They read the last result this checkout recorded |
| no discovery from discovery | the second pass must declare exactly the discovery targets the first did. One added, removed or changed is refused, with exit code 5 |
The second load, and what each step does when something goes wrong, in more detail:
%% build and test — the two passes, with the discovery run between them
flowchart TD
L1["load the build files,<br/>no results yet"] --> Q{"a discovery<br/>target?"}
Q -- no --> R1["check the graph, save it"] --> RUN
Q -- yes --> R0["check the graph, save it<br/>keep only the discovery targets"]
R0 --> D["plan · ask the approver · run<br/>its own approval and summary"]
D --> F{"all succeeded?"}
F -- no --> STOP["report the discovery run<br/>and stop"]
F -- yes --> RES["read what they printed<br/>unreadable: exit code 3"]
RES --> L2["load again with the results<br/>other discovery targets: exit code 5"]
L2 --> R2["check the graph, save it"] --> RUN
RUN["keep the targets asked for · plan · ask the approver · run"]
The depfile gap
Many build systems learn some inputs only while an action runs. A C compiler is the classic case:
main.c includes util.h, and nobody wrote that down. Ninja and Make let the compiler write a
depfile listing the headers it actually read. A build file that compiles one .c file per target
and declares only the .c file has a hole in its graph:
%% The missing edge — declared graph vs true graph
graph TD
subgraph DECLARED["Graph buildl sees — from declarations"]
MC1["main.c"] --> MO1["main.o"]
UC1["util.c"] --> UO1["util.o"]
MO1 --> APP1["app"]
UO1 --> APP1
end
subgraph TRUE["True dependency graph"]
MC2["main.c"] --> MO2["main.o"]
UC2["util.c"] --> UO2["util.o"]
UH["util.h<br/>NOT DECLARED"] -.->|"missing edge"| MO2
UH -.->|"missing edge"| UO2
MO2 --> APP2["app"]
UO2 --> APP2
end
Edit util.h, and no declared input changed. What happens next depends on the strategy:
%% What happens per isolation tier when util.h is undeclared
flowchart TD
EDIT["Edit util.h — undeclared input"] --> T{"Execution tier?"}
T -->|"Tier 1 — Bare"| STALE["SILENT STALENESS<br/>compile reads util.h from workspace<br/>key never sees it — wrong cache hits forever"]
T -->|"Tier 2 — Input sandbox"| LOUD["LOUD FAILURE<br/>util.h absent from exec dir<br/>first compile fails: file not found"]
STALE --> BAD["Worst outcome —<br/>a shared remote cache<br/>would amplify it"]
LOUD --> OK["Correct but unusable —<br/>a target declaring only<br/>the .c file cannot work"]
The sandbox turns the wrong answer into a loud one, which is its job, but that only proves the
pattern cannot be written, not that it works. buildl reads no depfiles, so it closes the gap
another way: a discovery target runs the compiler with -MM before the compile, one per source,
and prints the project headers that source reads. The second pass reads that output and declares
each object with the source and those headers as its inputs. The headers are declared once for the
call, and discovery gives each object only those it read: edit util.h and only the objects that
read it rebuild.
The c plugin writes this for you, one object per source. The C and C++
Plugin shows it.
The gap is narrower than it looks. Go, Cargo, Bun and the rest track their own sources, so a target
that hands a whole toolchain all of its sources, as the Go, Rust and Python examples do, has no
hole. The Rust Plugin writes that target for Cargo.
And where a build does need a tool to tell it what exists, the discovery target is the answer: not
a file a compiler happened to drop, but a target with its own key, its own approval and its own
line in the plan, like everything else buildl runs.
What a discovery target cannot do is feed an action while it runs; its output reaches the next declaration pass. If that is ever needed, it will be an extension of discovery targets, not a depfile side door.
Plugins
Write the same three targets for every Go program in a repository and you soon want a function
for it. In buildl that function lives in a plugin: Lua that runs while build files are read,
and declares targets for you. A plugin cannot run anything. All it can do is call the same
buildl.target a build file calls, so whatever it declares is planned, held to the ceiling,
cached and shown by buildl graph like a target you wrote by hand.
A plugin is not trusted just because it is code you loaded. Every target it declares carries its name, and is held to what the plugin said it needs before it is held to the ceiling.
This chapter covers:
- Writing a Plugin:
extension.toml,buildl.use, and where your own logic should live - Plugins from Git: a plugin kept in another repository,
buildl plugins fetch, andbuildl.lock - How buildl Decides: what a plugin's targets may want, and
how
plan,doctor, the approver andgraphtell you which plugin wanted it - The C and C++ Plugin: the
cplugin kept in this repository, compiling one object per source with each object declaring the headers it read - The Rust Plugin: the
rustplugin kept in this repository, running plaincargofor a binary, a library or a test - cargo buildl: the cargo subcommand that sets a Cargo project up
for the
rustplugin and keeps itsbuild.luain line withCargo.toml
Writing a Plugin
A plugin is a folder with two things in it: a manifest called extension.toml, and a Lua entry
script. The examples/plugins workspace keeps one, gobin, beside a Go module with two programs:
plugins/
├── buildl.toml
├── build.lua
├── go.mod
├── hello/main.go
├── bye/main.go
└── plugins/gobin/
├── extension.toml
└── main.lua
The entry script
-- plugins/gobin/main.lua
local module = {}
-- Declares a target building the Go program in directory `dir` of the module whose go.mod sits
-- beside the calling build file. The Go toolchain keeps its build cache under $HOME, so the target
-- reads HOME, as `unkeyed`: the value goes to `go`, only the name enters the key.
function module.binary(name, dir)
buildl.target(name, {
inputs = { "go.mod", buildl.sources(dir .. "/*.go") },
run = { "go", "build", "-o", "$out", "./" .. dir },
env = { HOME = "unkeyed" },
})
end
return module
It is an ordinary Lua module. It returns a table of functions, and each function calls
buildl.target, the same one a build file calls. A plugin has no other way to make a target, and
no way to run anything: the work happens later, when buildl runs the targets.
The manifest
# plugins/gobin/extension.toml
[extension]
name = "gobin"
version = "0.1.0"
entry = "main.lua"
api = 1
# The most the plugin's targets may want; the workspace can narrow it further.
[capabilities]
proc.run = ["go"]
env.read = ["HOME"]
env.unkeyed = ["HOME"]
The format is airsl's, so buildl has no manifest grammar of its own. buildl reads these keys:
| Key | Says |
|---|---|
name | the plugin's name; it must be the name buildl.toml gives it |
version | text to show, such as 0.1.0; never compared |
entry | the file buildl.use runs, inside the plugin's folder |
api | which version of the plugin API it was written for |
proc.run | the programs its targets may run |
env.read | the variables its targets may read |
env.unkeyed | the ones among them its targets may mark "unkeyed"; each must be in env.read too |
airsl's manifest can say more than that: fs.read, fs.write, a module flag, a
[capabilities.optional] block, a [limits] value. buildl refuses a manifest that holds any of
them, naming the file. A request that is quietly ignored reads like a request that was granted.
The workspace names it
A build file cannot load whatever plugin it likes. buildl.toml names each one:
[ceiling]
proc.run = ["go"]
env.read = ["HOME"]
env.unkeyed = ["HOME"]
fs.read = ["."]
fs.write = ["out", ".buildl"]
# A plugin kept in the workspace. Its targets may want at most what this table
# allows, and what its own extension.toml allows, and what the ceiling allows.
[plugins.gobin]
path = "plugins/gobin"
proc.run = ["go"]
env.read = ["HOME"]
env.unkeyed = ["HOME"]
path is a folder of the workspace. The proc.run, env.read and env.unkeyed beside it are the
workspace's own limit for this plugin, its cap.
How buildl Decides shows the manifest, the cap and the ceiling at
work.
Using it
-- build.lua
local gobin = buildl.use("gobin")
-- Each call declares one target building a Go program of this module.
gobin.binary("hello", "hello")
gobin.binary("bye", "bye")
buildl.use runs the entry script and hands back what it returned. From there it is two function
calls:
$ buildl plan
run //:bye: never built
run //:hello: never built
run programs: go
unkeyed variables: HOME
write into: .buildl, out
go: declared by plugin gobin@0.1.0 for //:bye
HOME (unkeyed): declared by plugin gobin@0.1.0 for //:bye
2 to run, 0 conditional, 0 clean
$ buildl build
2 built
$ ./out/hello
hello from a plugin
$ ./out/bye
bye from a plugin
The two declared by lines are the plugin's name on its wants; (unkeyed) marks the variable the
plugin reads as "unkeyed". A build file cannot hide a program behind a plugin: you see which
plugin wanted it, and for which target.
What a plugin sees
Each use of a plugin runs in a fresh set of globals, not the build file's:
| Name | Holds |
|---|---|
buildl | a new table of the declaration functions; what is declared through it carries the plugin's name |
airsstack | copies of the toolbox modules (json, path, regex, hash, glob), and this same buildl |
require | loads a/b.lua of the plugin's folder for require("a.b"), and nothing outside it |
string, table, math and the rest | copies, so a plugin that changes string changes only its own |
A plugin could otherwise reach the build file's own buildl table and declare targets with no
name on them. Its Lua counts toward the build file's limits, and an error in it names the plugin's
file and line.
One call, many targets
gobin.binary makes one target per call. A richer plugin makes several. Here is a sketch of a
go plugin whose one call declares a build, a test and a vet target:
%% Plugin declaration expansion
graph LR
CALL["go.binary — one call"] --> T1["server<br/>go build, full input set"]
CALL --> T2["server_test<br/>go test, cached by key"]
CALL --> T3["server_vet<br/>go vet, same inputs"]
Whatever a plugin declares, buildl graph shows the plain targets, so you can always read what a
plugin did.
Three places for your own logic
A plugin is a convenience, not the only way to say something. Custom logic has three homes, each more your own than the last:
| Layer | What you write |
|---|---|
| Options on a plugin call | go.test("auth_test", { run = "TestLogin" }): the plugin turns options into the command, and since the command is in the action key, each variation is cached apart |
| Plain targets beside it | a buildl.target next to the generated ones, for a case the plugin never thought of. Same graph, same cache, same permissions. Nobody waits for a plugin release |
| A plugin of your own on top | a plugin in your repository that calls buildl.use("go") and adds your house rules. What it declares is held to both plugins |
-- plugins/ourgo/main.lua, the entry its extension.toml names
local go = buildl.use("go")
local M = {}
function M.service(name)
go.binary(name, { main = "./cmd/" .. name })
go.test(name .. "_unit", { packages = { "./internal/..." }, short = true })
end
return M
What a stack plugin knows
A plugin for one toolchain is mostly the know-how of wrapping that toolchain. buildl ships no stack
plugins today; the design sketches a set (go, bun, rust, docker, proto, python), and
the same few habits turn up in every one:
| Habit | go | bun | rust | docker | python |
|---|---|---|---|---|---|
| a lock file pins the environment | go.sum | bun.lock | Cargo.lock | base image digest | uv.lock |
| a stamp file stands for a tree its lock file pins | — | node_modules | — | — | .venv |
| a digest file as the output | — | — | — | --iidfile | — |
| a filter as a build setting | -run | --test-name-pattern | --test | — | -k |
| one target per unit | per package | per workspace package | per crate | per Dockerfile | per module |
A new stack plugin is these five habits for one more toolchain. That is why the plugin API can stay small, and why buildl itself never needs to know a language exists.
Versions
api is airsl's key, and airsl checks it before any of the plugin's code runs:
$ buildl check
error: build.lua: operation refused: line 1: buildl.use 'gobin': plugins/gobin/extension.toml: manifest declares api 2; this runtime supports api 1
That exits with code 5, a build definition to fix. Within api = 1 the buildl table a plugin
sees only ever gains names, never loses or changes one. buildl has no second version number for
plugins.
Plugins from Git
A plugin you share between repositories lives in a git repository of its own. The workspace names
the repository and a version of it, buildl plugins fetch downloads it once, and from then on no
command reaches the network to load it.
Naming the repository
Instead of path, the plugin's table in buildl.toml gives git and rev:
[plugins.gobin]
git = "file:///tmp/buildl-book/p05/git/gobin.git"
rev = "v0.1.0"
proc.run = ["go"]
env.read = ["HOME"]
env.unkeyed = ["HOME"]
| Key | Says |
|---|---|
git | any URL git can clone: https://, ssh://, or file:// as here |
github | instead of git: owner/repo, short for the GitHub URL |
rev | a tag or a full commit |
dir | optional: the folder of the repository that holds the plugin, such as plugins/gobin; left out, the plugin is the repository root |
dir is for a repository that holds more than one plugin, or a plugin beside other files. It is
written relative to the repository root, with / between folders, and takes no .., no leading
/ and no empty part. Only that folder is stored and digested: the plugin's extension.toml sits
directly in it, and the rest of the repository plays no part. A plugin that comes from a path has
no dir.
The cap, proc.run, env.read and env.unkeyed, works as it does for a plugin kept in the
workspace. For this page the repository is a bare one made on the same machine, holding the gobin
plugin from Writing a Plugin under the tag v0.1.0, so nothing here
needs the network.
Nothing loads until it is fetched
A build does not fetch. It refuses, and says what to run:
$ buildl build
error: plugin gobin is not fetched: buildl.lock does not pin file:///tmp/buildl-book/p05/git/gobin.git at v0.1.0; run `buildl plugins fetch`
That exits with code 5.
buildl plugins fetch
$ buildl plugins fetch
fetched gobin b9d7c9afdd7177719d6d1fca8d65a4f4bca46137
It takes no flags of its own beyond --color. For each plugin that comes from git, in name order,
it runs your own git to fetch the one commit the tag names, at depth 1, drops the .git folder,
and works out one digest over the files. It reads no build file and asks no approver: fetching runs
no plugin code.
The commit shown is the one the tag named in this capture; yours will be another.
buildl.lock
The fetch writes buildl.lock in the workspace root:
$ cat buildl.lock
{"gobin":{"commit":"b9d7c9afdd7177719d6d1fca8d65a4f4bca46137","dir":"","git":"file:///tmp/buildl-book/p05/git/gobin.git","rev":"v0.1.0","sha256":"232d8abc6a17a467574ea0f57bd5b5cd76e6b05084afc76a02fc77a2b989cb4a"}}
| Field | Records |
|---|---|
git, rev | what buildl.toml asked for when it was fetched |
dir | the folder buildl.toml named, or "" for the repository root |
commit | the commit rev named then |
sha256 | the digest of the plugin's files: those of dir, when it is set |
Commit it with the workspace. Someone who clones the repository then fetches the very commit and files you did, or is refused.
Kept in the store
The files go under the state directory, one folder per plugin and commit:
$ ls .buildl/plugins/gobin
b9d7c9afdd7177719d6d1fca8d65a4f4bca46137
$ ls .buildl/plugins/gobin/b9d7c9afdd7177719d6d1fca8d65a4f4bca46137
extension.toml
main.lua
Now the build loads it from there:
$ buildl build
2 built
$ ./out/hello
hello from a plugin
A second fetch with nothing changed runs no git at all:
$ buildl plugins fetch
unchanged gobin b9d7c9afdd7177719d6d1fca8d65a4f4bca46137
Checked every time
Every command that reads build files first checks each git plugin against buildl.lock and the
store, and never against the network. Add a line to the stored main.lua, and the digest no
longer matches:
$ buildl build
error: plugin gobin was changed after it was fetched: its files digest to 4f44f261367f027f0988af25deb94e3bc5db2ba2f3c46f0f4ca4f633e7a5ce06 and buildl.lock pins 232d8abc6a17a467574ea0f57bd5b5cd76e6b05084afc76a02fc77a2b989cb4a
$ buildl plugins fetch
fetched gobin b9d7c9afdd7177719d6d1fca8d65a4f4bca46137
$ buildl build
2 cached
The build exits with code 6: what is on disk is not what buildl wrote. Fetching again brought back the files the lock pins.
A tag that moves is caught the same way. When the lock already pins a git and rev, and a fetch
of them brings another commit or other files, the fetch is refused rather than quietly pinning the
new ones. Moving a plugin on is a change you make: a new rev in buildl.toml, then a fetch.
How buildl Decides
A plugin is code someone else wrote, and a new release of it might want more than the last. So before the ceiling ever sees a want of a plugin's target, buildl holds it to two lists that belong to the plugin.
Three lists, in order
what the target wants
│
▼
the plugin's extension.toml ── not listed? refused, exit 4
│
▼
[plugins.<name>] in buildl.toml, the workspace's cap ── not listed? refused, exit 4
│
▼
[ceiling] in buildl.toml ── not listed? refused, exit 4
│
▼
the approver
| Want | Allowed by the plugin when |
|---|---|
| a program | its manifest's proc.run and its cap's proc.run both list it |
a variable marked "key" | its manifest's env.read and its cap's env.read both list it |
a variable marked "unkeyed" | its manifest's env.unkeyed and its cap's env.unkeyed both list it |
| the network | its cap says network = true |
env.unkeyed narrows env.read at each of the three levels, the plugin's manifest, its cap and the
ceiling: a name in an env.unkeyed that the env.read beside it does not list is a fault in the
file, found when buildl reads it, exit code 5. A list left out is empty, so a plugin's targets may
leave a variable out of the key only when the manifest, the cap and the ceiling all say so.
A plugin whose table gives no cap allows its targets nothing. Inputs and the folders a build writes into are not narrowed per plugin, and a program a dependency built is no want at all (see Nothing Is Ambient).
When a plugin uses another plugin, a target is held to every plugin in the chain. A wrapper ourgo
that calls go.binary needs both ourgo and go to allow what the target runs.
The workspace narrows
Take the examples/plugins workspace from Writing a Plugin, and
give the plugin no variables in its cap. The ceiling still allows HOME. The plugin's targets mark
HOME "unkeyed", so the cap has to say so in env.unkeyed, and env.unkeyed may not name what
env.read leaves out. Taking HOME out of env.read alone is therefore a fault in the file:
[plugins.gobin]
path = "plugins/gobin"
proc.run = ["go"]
env.read = []
env.unkeyed = ["HOME"]
$ buildl build
error: buildl.toml: [plugins.gobin] env.unkeyed lists HOME, which env.read does not
That is exit code 5, the same as for the ceiling's own pair of lists. Take HOME out of both:
[plugins.gobin]
path = "plugins/gobin"
proc.run = ["go"]
env.read = []
env.unkeyed = []
$ buildl build
error: build.lua: //:bye (plugin gobin@0.1.0): unkeyed variable HOME is outside plugin gobin@0.1.0 (env.unkeyed allows: nothing)
The build exits with code 4, before anything runs, as a want outside the ceiling would. The message
names the build file, the first target refused, the plugin chain in brackets, and what the plugin
does allow. A "key" variable the cap does not list is refused the same way, as environment variable X is outside plugin … with env.read allows.
The manifest narrows
Now put the cap back and take go out of the plugin's own manifest:
# plugins/gobin/extension.toml
[capabilities]
proc.run = []
env.read = ["HOME"]
env.unkeyed = ["HOME"]
$ buildl build
error: build.lua: //:bye (plugin gobin@0.1.0): program go is outside plugin gobin@0.1.0 (proc.run allows: nothing)
Exit code 4 again. The workspace and the ceiling would both allow go; the plugin did not ask for
it, so its targets cannot have it. This is the case that matters: a plugin update that starts
running curl is stopped by its own manifest, then by your cap, then by the ceiling.
Every view names the plugin
A declaration made through a plugin carries its origin: the chain of plugins that made it,
each as name@version with what its manifest allows. The origin is for showing and for checking.
It is not part of the action key, so a target moved out of a plugin into a
plain buildl.target with the same fields stays cached.
plan prints, after the wanted set, each want a plugin's targets have, with the lowest label
that wants it:
$ buildl plan
run //:bye: never built
run //:hello: never built
run programs: go
unkeyed variables: HOME
write into: .buildl, out
go: declared by plugin gobin@0.1.0 for //:bye
HOME (unkeyed): declared by plugin gobin@0.1.0 for //:bye
2 to run, 0 conditional, 0 clean
doctor puts the same line under each want's row, and ends with a plugin violations section
worded as the build's refusal would be. Here it is in the workspace whose cap gives no variables;
the lines above wants are left off:
$ buildl doctor | sed -n '/^wants/,$p'
wants ceiling approved
run go allowed yes
declared by plugin gobin@0.1.0 for //:bye
read HOME unkeyed allowed yes
declared by plugin gobin@0.1.0 for //:bye
write .buildl allowed yes
write out allowed yes
plugin violations
build.lua: //:bye (plugin gobin@0.1.0): unkeyed variable HOME is outside plugin gobin@0.1.0 (env.unkeyed allows: nothing)
build.lua: //:hello (plugin gobin@0.1.0): unkeyed variable HOME is outside plugin gobin@0.1.0 (env.unkeyed allows: nothing)
read HOME unkeyed is allowed in the ceiling column, because the ceiling does allow it; the
violation is the plugin's. Like the rest of doctor, it refuses nothing and exits 0.
The approver. The interactive approver puts a line under its question naming the plugin
behind a new want, as plan does (see Approvers).
graph gives every target its origin. A target a build file wrote has "origin":"BuildFile";
these two have the plugin:
$ buildl graph | python3 -c 'import json,sys; g=json.load(sys.stdin)["targets"]; [print(l, json.dumps(t["origin"])) for l,t in sorted(g.items())]'
//:bye {"Plugins": [{"env": ["HOME"], "name": "gobin", "run": ["go"], "unkeyed": ["HOME"], "version": "0.1.0"}]}
//:hello {"Plugins": [{"env": ["HOME"], "name": "gobin", "run": ["go"], "unkeyed": ["HOME"], "version": "0.1.0"}]}
Where it is checked
The order of the checks is the order of the commands' work:
| When | What is checked | Failure |
|---|---|---|
| before any build file opens | each [plugins.<name>] is a folder of the workspace, or is pinned in buildl.lock and digests to the pin; its env.unkeyed is inside its env.read | exit 5 if not fetched or the lists disagree, exit 6 if changed |
when buildl.use runs | the manifest: its name, api, entry, and that it asks for nothing but proc.run, env.read and env.unkeyed, and that env.unkeyed is inside env.read | exit 5 |
| at plan | every want of every plugin target, against each plugin in its chain, then the ceiling | exit 4 |
No plugin can do anything a build file cannot. It holds no permission of its own: it can only narrow what the workspace already allows.
The C and C++ Plugin
A C compiler learns which headers a source reads only while it compiles it, so a build file that
lists a .c file and nothing else has a hole in its graph (see The depfile
gap). The c plugin closes it. It compiles each
source to its own object, finds that source's headers with a discovery
target, and links, archives or tests the result. Edit one header
and only the objects that read it rebuild; edit one source and only its object does.
It builds programs, static libraries, shared libraries and tests on Linux and macOS, with gcc or
clang and ar. It is a plugin like the one in Writing a Plugin:
Lua, held to its manifest and your cap, adding nothing a build file could not declare itself.
Every command and output on this page was taken from a real run on macOS with Apple clang. The
first program and the case without sh come from a small two-source project made for this page;
the error and version-probe outputs come from edited copies of examples/c and examples/cpp in
the buildl repository; the rest come from those examples as they are. Two things in the outputs are
test details. The plugin was
fetched from a local git repository instead of GitHub, so the commit in fetched c <commit> is
that repository's; and the compiler messages are clang's. The tables in buildl.toml are the ones
you would write.
Setting it up
The plugin lives in the buildl repository, in the folder plugins/c, and is fetched by git tag
(see Plugins from Git). Name it in buildl.toml, give it the
program and the variable it may use, and let the ceiling allow them too:
[ceiling]
proc.run = ["cc"]
env.read = ["PATH"]
env.unkeyed = ["PATH"]
fs.read = ["."]
fs.write = ["out", ".buildl"]
[plugins.c]
github = "airsstack/buildl"
rev = "plugin-c-v0.2.0"
dir = "plugins/c"
proc.run = ["cc"]
env.read = ["PATH"]
env.unkeyed = ["PATH"]
PATH is there because a compiler driver finds the linker through it. The plugin reads it as
"unkeyed": the compiler is given the value, but only the name is in the action key, so the same
link has the same key on every machine. That is why env.unkeyed lists it beside env.read, in the
ceiling and in the plugin's table, as the plugin's own manifest does. sh is on neither list
yet: a workspace needs it only for c.library, whose archive step runs through it, and for a
c.test with deps (see Libraries and tests). Allowing sh lets a target
run any program through sh -c, so the ceiling's program list then limits less. Start from cc
and add sh when you declare one of those two.
Fetch the plugin once. A build does not fetch:
$ buildl plugins fetch
fetched c ae08f395e6fdf8aedb9eed40f3989ee1f1ba9878
A first binary
A project with two sources and a header:
buildl.toml
build.lua
include/util.h
src/main.c
src/util.c
include/util.h declares int util_add(int a, int b);, src/util.c defines it, and src/main.c
prints 2 + 3 = followed by util_add(2, 3); both sources include util.h.
build.lua loads the plugin with buildl.use and declares one binary:
local c = buildl.use("c")
c.binary("app", {
srcs = { "src/main.c", "src/util.c" },
headers = { "include/util.h" },
cflags = c.includes({ "include" }),
})
srcs and headers are written relative to the build file. headers lists every header a source
may include; the plugin does not search for them. cflags are compiler arguments, and
c.includes writes -Iinclude for you.
check reads the build file once and tells you the targets that wait on a discovery:
$ buildl check
ok: 2 declarations in 1 build file
//:app.src.main.c.deps has not run; run buildl build
//:app.src.util.c.deps has not run; run buildl build
build runs those two first, shows what they printed, and then builds:
$ buildl build
--- //:app.src.util.c.deps
obj: src/util.c include/util.h
--- //:app.src.main.c.deps
obj: src/main.c include/util.h
2 built
3 built
$ ./out/app
2 + 3 = 5
The first summary is the two discovery targets; the second is the two objects and the link. Each
discovery line is a Make rule from the compiler's -MM flag: the source, then the headers it reads
and nothing the system provides.
Edit a header and look at the plan:
$ echo '/* edited */' >> include/util.h
$ buildl plan
maybe //:app: runs only if //:app.src.main.c.o, //:app.src.util.c.o produces something else
run //:app.src.main.c.o: input include/util.h changed
run //:app.src.util.c.o: input include/util.h changed
run programs: cc
unkeyed variables: PATH
write into: .buildl, out
cc: declared by plugin c@0.2.0 for //:app
PATH (unkeyed): declared by plugin c@0.2.0 for //:app
//:app.src.main.c.deps is not up to date; targets declared from it may change
//:app.src.util.c.deps is not up to date; targets declared from it may change
2 to run, 1 conditional, 0 clean
Both sources include util.h, so both objects run. The link is conditional: if the objects come
out the same, it is not run. A comment changes no object code, so:
$ buildl build
--- //:app.src.util.c.deps
obj: src/util.c include/util.h
--- //:app.src.main.c.deps
obj: src/main.c include/util.h
2 built
2 built, 1 cached
Now change only src/util.c:
$ buildl plan
maybe //:app: runs only if //:app.src.util.c.o produces something else
clean //:app.src.main.c.o
run //:app.src.util.c.o: input src/util.c changed
run programs: cc
unkeyed variables: PATH
write into: .buildl, out
cc: declared by plugin c@0.2.0 for //:app
PATH (unkeyed): declared by plugin c@0.2.0 for //:app
//:app.src.util.c.deps is not up to date; targets declared from it may change
1 to run, 1 conditional, 1 clean
One object runs. That is what the plugin is for; with one target for the whole program, every edit would rerun every compile.
What one call declares
A call declares targets in two passes, as Discovery Targets describes. The first pass cannot name the objects' inputs, because the headers are not known yet.
%% What one c.binary call with two sources declares
graph TD
subgraph P1["First pass"]
D1["app.src.main.c.deps<br/>cc -MM src/main.c"]
D2["app.src.util.c.deps<br/>cc -MM src/util.c"]
V["app.version.c<br/>only with version_probe"]
end
subgraph P2["Second pass, from what the discovery targets printed"]
O1["app.src.main.c.o<br/>inputs: the source and the headers it read"]
O2["app.src.util.c.o<br/>inputs: the source and the headers it read"]
L["app<br/>cc -o out/app, objects in srcs order, then deps"]
end
D1 -.->|"headers read"| O1
D2 -.->|"headers read"| O2
O1 --> L
O2 --> L
HD["header_deps targets<br/>a generated config.h"] --> D1
HD --> D2
HD --> O1
HD --> O2
V -.-> O1
V -.-> O2
| Target | What it is | Runs |
|---|---|---|
<name>.<source>.deps | a discovery target; <source> is the source's path with / turned into ., extension kept | the compiler with -MM, its output is the headers |
<name>.<source>.o | the object; inputs are the source and the headers it read | the compiler with -c |
<name> | the last step: the binary, archive or library; for c.test, the test target, whose binary is <name>.bin | the linker, or sh running ar |
<name>.version.c, <name>.version.cpp | only with version_probe, see below | the compiler with --version |
The names keep the extension, so main.c and main.cc in one folder do not collide. buildl graph shows all of them as plain targets, with the plugin as their origin.
A .c source is C. .cc, .cpp and .cxx are C++: they use cxx and cxxflags, both for the
compile and for the discovery. A call can hold both, and its link uses cxx. Every other
extension is refused.
Options
Each function takes (name, options) and returns nothing. An option it does not know is refused,
and the message names it.
| Option | Type | Meaning | Default |
|---|---|---|---|
srcs | list of strings | the sources | required, not empty |
headers | list of strings | the headers a source may include | {} |
header_deps | list of labels | targets whose outputs the compiles read, such as a generated config.h | {} |
cflags | list of strings | arguments of C compiles and of the discovery of C sources | {} |
cxxflags | list of strings | arguments of C++ compiles and of the discovery of C++ sources | {} |
ldflags | list of strings | link arguments before the objects | {} |
ldlibs | list of strings | link arguments after the objects, such as -lm | {} |
deps | list of labels | targets linked in, after the objects; for a test, also present when it runs | {} |
cc | string | the C compiler | "cc" |
cxx | string | the C++ compiler | "c++" |
linker | string | the program that links | cxx when a source is C++, else cc |
output | string | the file the last step writes | name (c.test: name .. ".bin") |
version_probe | boolean | see below | false |
Paths in cflags, cxxflags, ldflags and ldlibs are written from the workspace root, as every
command's paths are (see Many Directories); c.includes writes
include folders that way for you. The libraries go in ldlibs, after the objects, since the
linker reads in command order.
Headers
Every header in headers is an input of every discovery target, so a header that a source reads
must be listed, or the discovery cannot see it. Leave one out and the sandbox shows it at once:
$ buildl build
--- //:hello.src.main.c.deps
src/main.c:3:10: fatal error: 'banner.h' file not found
#include "banner.h"
^~~~~~~~~~
1 error generated.
FAILED //:hello.src.main.c.deps: action failure (exit status 1)
declared in build.lua
command: cc -Iinclude -Iout -MM -MT obj src/main.c
1 failed
(The build file here listed only include/util.h for a source that includes banner.h too.)
buildl.sources("include/*.h") lists a folder's headers in one call and is what the examples use.
Once the discovery has run, each header the compiler names is placed by these rules, in order:
| The header | Becomes |
|---|---|
| an absolute path | an error naming it: a header outside the workspace belongs in an -isystem folder, whose headers -MM leaves out |
inside the build file's folder and in headers | an input of the object |
anything else, when the call has header_deps | nothing: it is an output of one of those targets, and the compile depends on them already |
| anything else | an error naming it: a header outside the build file's folder cannot be declared, and one inside it is refused when it is missing from headers |
A path is tidied first: . parts go and each .. removes the part before it. One that climbs
above the workspace root is an error naming it.
A generated header
A header another target writes belongs in header_deps, not in headers. From examples/c:
buildl.target("config.h", {
run = { "sh", "-c", [[printf '#define GREETING "hello from buildl"\n' > "$0"]], "$out" },
})
c.binary("hello", {
srcs = { "src/main.c" },
headers = headers,
header_deps = { ":config.h" },
cflags = cflags, -- includes -Iout, where config.h is written
deps = { ":util", ":blob.o" },
})
The compile of src/main.c reads out/config.h; -MM names it that way, and with header_deps
that is not an error. The header_deps targets are dependencies of the discovery and the compile,
so the header exists when either runs.
One build file per project
An input cannot name a file outside its build file's folder, so a header another folder's build file holds cannot be declared. A call reads the headers of its own build file's folder, and so a C or C++ project is declared in one build file. The build files of other languages in the same workspace are not affected.
Platforms and the two passes
A shared library has a different file name on Linux and macOS, and a different way to say where it
can be found. The plugin's helpers answer from the compiler's target triple. This is
examples/cpp, a shared library, a program that loads it and a test:
local c = buildl.use("c")
local platform = c.platform() -- nil on the first pass
local lib = c.shared_name("greet", platform) -- nil on the first pass
local headers = buildl.sources("include/*.h")
local cxxflags = c.includes({ "include" })
cxxflags[#cxxflags + 1] = "-fPIC"
c.shared_library("greet", {
srcs = { "lib/greet.cc" },
headers = headers,
cxxflags = cxxflags,
ldflags = c.soname(lib, platform),
output = lib,
})
c.binary("hello", {
srcs = { "src/main.cc" },
headers = headers,
cxxflags = cxxflags,
ldflags = c.rpath(platform),
deps = { ":greet" },
})
c.test("greet_test", {
srcs = { "test/greet_test.cc" },
headers = headers,
cxxflags = cxxflags,
ldflags = c.rpath(platform),
deps = { ":greet" },
})
The first c.platform() call declares a discovery target, :c.platform, which runs
cc -dumpmachine. Its result is not known on the first pass, so the call returns nil there, and
the helpers that take it give nil or {}:
%% The two passes of examples/cpp
sequenceDiagram
participant B as build.lua
participant H as buildl
B->>H: first pass: platform is nil, so lib is nil
Note over B: declares c.platform and one .deps target per source
H->>H: runs cc -dumpmachine, and c++ -MM once per source
H->>B: second pass, with their output
Note over B: platform is macos, lib is libgreet.dylib
B->>H: declares the objects and the last steps
$ buildl check
ok: 4 declarations in 1 build file
//:c.platform has not run; run buildl build
//:greet.lib.greet.cc.deps has not run; run buildl build
//:greet_test.test.greet_test.cc.deps has not run; run buildl build
//:hello.src.main.cc.deps has not run; run buildl build
$ buildl build
--- //:c.platform
arm64-apple-darwin25.3.0
--- //:greet.lib.greet.cc.deps
obj: lib/greet.cc include/greet.h
--- //:hello.src.main.cc.deps
obj: src/main.cc include/banner.h include/greet.h
--- //:greet_test.test.greet_test.cc.deps
obj: test/greet_test.cc include/greet.h
4 built
6 built
$ ls out
c.platform.json
greet_test.bin
greet_test.test.greet_test.cc.deps.json
greet_test.test.greet_test.cc.o
greet.lib.greet.cc.deps.json
greet.lib.greet.cc.o
hello
hello.src.main.cc.deps.json
hello.src.main.cc.o
libgreet.dylib
$ ./out/hello
== greet ==
hello, buildl
On Linux the same build file writes libgreet.so.
The first pass's discovery targets must be the same as the second's, so what they hold must not
depend on anything discovered. name, srcs, headers, header_deps, cflags, cxxflags, cc
and cxx feed them; ldflags, ldlibs, deps, output and linker reach only the last step
and may use the platform. Put a platform in cxxflags and buildl stops, with exit code 5:
$ buildl build
--- //:c.platform (cached)
arm64-apple-darwin25.3.0
--- //:greet.lib.greet.cc.deps (cached)
obj: lib/greet.cc include/greet.h
--- //:greet_test.test.greet_test.cc.deps (cached)
obj: test/greet_test.cc include/greet.h
--- //:hello.src.main.cc.deps (cached)
obj: src/main.cc include/banner.h include/greet.h
4 cached
error: build.lua: discovery target //:greet.lib.greet.cc.deps differs once discovery results are read; a discovery target may not depend on a discovery result
The helpers
Each returns a value and declares nothing, except c.platform. Put the value where you want it.
| Helper | Returns |
|---|---|
c.includes(dirs) | -I<folder>/<dir> for each directory, folder being the build file's folder; -I<dir> at the root |
c.defines(map) | sorted by key: -D<key> for true, nothing for false, -D<key>=<value> for a string or a number |
c.platform(options?) | "linux" or "macos", or nil before the discovery has run |
c.shared_name(name, platform) | lib<name>.so or lib<name>.dylib; nil when platform is nil |
c.soname(file, platform) | the flags that give a shared library its runtime name: -Wl,-soname,<file> on Linux, -install_name @rpath/<file> on macOS; {} when platform is nil |
c.rpath(platform) | the flags that make a binary look for shared libraries in its own folder: -Wl,-rpath,$ORIGIN on Linux, -Wl,-rpath,@loader_path on macOS; {} when platform is nil |
c.depfile.parse(text) | the rules of Make-style output, for a discovery target of your own |
c.platform takes { cc = "clang" } to ask another compiler; a later call whose cc differs from
the first is an error. A triple that is neither Linux nor macOS is an error naming it.
examples/c uses c.depfile.parse for a data-only assembly file, src/blob.S, which the plugin
does not compile: a discovery target of the build file runs cc -MM over it, and the object's
inputs are the headers the rules name.
Libraries and tests
| Function | Declares |
|---|---|
c.binary(name, o) | an executable |
c.library(name, o) | a static library, ar rcs over the objects, run through sh |
c.shared_library(name, o) | a shared library; -shared is the one flag the plugin adds, and -fPIC, the file name and the soname are yours |
c.test(name, o) | a test binary <name>.bin, then a test target name that runs it |
c.library refuses ldflags, ldlibs, linker and deps: an archive is not linked, and a library
another library needs is given to the binary that links them both.
The archive step is sh -c 'ZERO_AR_DATE=1 exec ar rcs "$0" "$@"' $out $deps, because macOS ar
writes the time it ran into the archive, and the archive would differ on every run. With
ZERO_AR_DATE set it does not; GNU ar gives the same bytes either way. ar runs inside sh, so
it needs no proc.run entry of its own, but sh does. Without it:
$ buildl build
--- //:util.src.util.c.deps
obj: src/util.c include/util.h
1 built
error: build.lua: //:util (plugin c@0.2.0): program sh is outside plugin c@0.2.0 (proc.run allows: cc)
That is exit code 4, and the fix is sh in the ceiling and in the plugin's proc.run, as
examples/c has it:
[ceiling]
proc.run = ["cc", "sh"]
env.read = ["PATH"]
env.unkeyed = ["PATH"]
fs.read = ["."]
fs.write = ["out", ".buildl"]
[plugins.c]
github = "airsstack/buildl"
rev = "plugin-c-v0.2.0"
dir = "plugins/c"
proc.run = ["cc", "sh"]
env.read = ["PATH"]
env.unkeyed = ["PATH"]
%% A test that lists a library in deps, beside the library
graph LR
LIB["util<br/>libutil.a"]
TO["util_test.test.util_test.c.o"] --> TB["util_test.bin<br/>cc, links the objects and the library"]
LIB --> TB
TB --> TT["util_test<br/>test target, runs the binary"]
LIB --> TT
A test is two targets: a binary, and a test target that runs it. The sandbox holds only the outputs
of the targets a step names, so a test lists in deps every library its binary loads. With deps,
the test runs through sh -c 'exec "$0"', so the binary runs alone and not with the libraries as
arguments; that is the second reason a workspace allows sh. The binary is a program a dependency
built, so it needs no proc.run entry of its own.
In examples/c:
$ buildl test
--- //:blob.deps (cached)
obj: src/blob.S include/blob.h
--- //:util.lib.util.c.deps (cached)
obj: lib/util.c include/util.h
--- //:util_test.test.util_test.c.deps (cached)
obj: test/util_test.c include/util.h
--- //:hello.src.main.c.deps (cached)
obj: src/main.c include/banner.h out/config.h include/util.h
5 cached
tests: 1 passed
With a shared library, as in examples/cpp, the test lists it in deps and uses c.rpath so the
binary finds the library beside itself.
The compiler and its version
An action key records the program file, and /usr/bin/cc is one launcher
file that stays the same when the compiler behind it changes. Update the compiler and the key does
not move, so objects built by the old one are served from the cache.
version_probe = true closes that. The call declares <name>.version.c, the call's cc with
--version, for its C sources, and <name>.version.cpp, its cxx with --version, for its C++
sources. Each is an always-run target, and every object of that language depends on its probe: a
new compiler prints a new version, and the objects rebuild. In examples/c, after a build
without the probe, turn on version_probe = true for hello. The first build then has two things
to run, the probe and hello's object, which now depends on it:
$ buildl build
--- //:blob.deps (cached)
obj: src/blob.S include/blob.h
--- //:util.lib.util.c.deps (cached)
obj: lib/util.c include/util.h
--- //:util_test.test.util_test.c.deps (cached)
obj: test/util_test.c include/util.h
--- //:hello.src.main.c.deps (cached)
obj: src/main.c include/banner.h out/config.h include/util.h
5 cached
--- //:hello.version.c
Apple clang version 15.0.0 (clang-1500.3.9.4)
Target: arm64-apple-darwin25.3.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
2 built, 7 cached
Built again with nothing changed, the probe runs and the rest is cached; it prints the same version, so the object is served from the cache:
$ buildl build
--- //:blob.deps (cached)
obj: src/blob.S include/blob.h
--- //:util.lib.util.c.deps (cached)
obj: lib/util.c include/util.h
--- //:util_test.test.util_test.c.deps (cached)
obj: test/util_test.c include/util.h
--- //:hello.src.main.c.deps (cached)
obj: src/main.c include/banner.h out/config.h include/util.h
5 cached
--- //:hello.version.c
Apple clang version 15.0.0 (clang-1500.3.9.4)
Target: arm64-apple-darwin25.3.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
1 built, 8 cached
It is off by default for a reason that shows in plan. An always-run target leaves every compile
that depends on it conditional, and the plan of a tree with nothing changed is no longer all
clean:
$ buildl plan
clean //:blob.o
clean //:config.h
maybe //:hello: runs only if //:hello.src.main.c.o produces something else
maybe //:hello.src.main.c.o: runs only if //:hello.version.c produces something else
run //:hello.version.c: declared to run on every build
clean //:util
clean //:util.lib.util.c.o
clean //:util_test.bin
clean //:util_test.test.util_test.c.o
run programs: cc, sh
unkeyed variables: PATH
write into: .buildl, out
cc: declared by plugin c@0.2.0 for //:hello
sh: declared by plugin c@0.2.0 for //:util
PATH (unkeyed): declared by plugin c@0.2.0 for //:hello
1 to run, 2 conditional, 6 clean
A build still takes those objects from the cache when the probe prints what it printed before, as the second build above shows. Turn the probe on where a stale compiler would cost you.
What it may run
The plugin's manifest lists the programs its targets may run: cc, c++, gcc, g++, clang,
clang++ and sh. A program outside the list is refused even when your workspace allows it, and
your cap and ceiling narrow the list further (see How buildl Decides).
ar is not on it, because c.library runs it through sh. A versioned name, such as gcc-13 or
clang-18, is not on it either.
For one of those, keep a copy of plugins/c in your workspace, add the program to the proc.run of
its extension.toml, and name it as a path plugin; the calls name the program in their cc
option:
[plugins.c]
path = "plugins/c"
proc.run = ["gcc-13"]
env.read = ["PATH"]
env.unkeyed = ["PATH"]
Every link step and every archive step declares env = { PATH = "unkeyed" }, so they are given
PATH's value but only its name is part of their keys. Compiles and discovery declare no variable.
The archiver is fixed to ar; another one, such as llvm-ar, means editing graph.lua in the
copied folder.
When it goes wrong
A message names the function and the target, and carries the file and line of your call:
$ buildl check
error: build.lua: runtime error: lua error in build.lua: runtime error: build.lua:3: c.binary(hello): the option bogus is not known
The plugin's own frames follow in a traceback, with build.lua:3 last. The build file fails to load,
with exit code 5. The other messages that name a function are:
| The call | Refused when |
|---|---|
c.binary, c.library, c.shared_library, c.test | srcs is missing or empty; an option has the wrong type, is unknown, or is one c.library refuses; a source has another extension (.C counts as another) |
| the same four | a header is absolute, climbs above the root, or is outside headers with no header_deps |
c.includes, c.defines | a value that is not what they take |
c.platform, c.shared_name, c.soname, c.rpath | a triple that is neither Linux nor macOS, or a platform that is neither |
c.platform | the options are not a table, an option other than cc is given, or cc is not a string |
| a discovery target of the call | its output holds no rule for obj |
A compiler outside the plugin's manifest, your cap or your ceiling is refused with exit code 4, as
the sh case above is. A discovery target that differs between the two passes is refused with exit
code 5.
Limits
| The plugin | Because |
|---|---|
| builds on Linux and macOS | c.platform and the helpers know only Linux and macOS target triples |
| uses gcc or clang | the program list is fixed in the manifest |
| needs one build file per project | an input cannot leave its build file's folder |
| does not cross-compile | not supported |
| wraps no other build system | CMake, autotools and meson are a plain target's job |
| reads no depfile in the executor | the discovery target is the one mechanism, and its output is a target's own |
A byte-for-byte match with an older make build is not promised. An object compiled with -g
records the folder the compile ran in, and buildl compiles in its own, so it differs from the old
build's; without -g the bytes match. Test the program, not the object.
Try it
examples/c and examples/cpp in the buildl repository are the two builds above, each with a
README. From examples/, sh check.sh c and sh check.sh cpp run check, build, test,
verify and the example's own assertions on a copy:
$ buildl verify
verified //:blob.o
verified //:config.h
verified //:hello
verified //:hello.src.main.c.o
verified //:util
verified //:util.lib.util.c.o
verified //:util_test.bin
verified //:util_test.test.util_test.c.o
8 verified, 0 mismatched, 0 failed, 0 skipped, 0 not cached, 0 not sampled
That is examples/c; the archive is the same bytes on a second run because of ZERO_AR_DATE.
The Rust Plugin
Cargo already tracks its own sources, so a Rust crate has no hole in its graph to close, the way
a C project does. What a plain target needs is the plumbing around cargo: every file under the
crate as an input, HOME and PATH as unkeyed variables, network = true for the crates cargo
has to download, and a command that copies the file cargo wrote under target/ to the place
buildl looks for an output. The rust plugin writes that for you. rust.binary("hello") is one
call, and what runs is plain cargo.
It builds binaries, staticlib and cdylib libraries and tests, on Linux and macOS. It is a plugin
like the one in Writing a Plugin: Lua, held to its manifest and your
cap, adding nothing a build file could not declare itself. It is also as thin as c is: it changes
nothing about how Rust builds, and features, profiles and workspace members stay in Cargo.toml.
In a Cargo project, cargo buildl init writes a buildl.toml with the tables below and a
build.lua with one call per artifact, and cargo buildl sync keeps the calls in line with Cargo.toml: see cargo
buildl.
Every command and output on this page was taken from a real run on macOS, in a copy of
examples/rust in the buildl repository; the errors come from edited copies of it. Two things in
the outputs are test details. The plugin was fetched from a local git repository instead of GitHub,
so the commit in fetched rust <commit> is that repository's; and the folder in cargo's
Compiling line is the sandbox directory the build ran in, which is
different on your machine. The tables in buildl.toml are the ones you would write.
Setting it up
The plugin lives in the buildl repository, in the folder plugins/rust, and is fetched by git tag
(see Plugins from Git). Name it in buildl.toml, give it the
programs and variables it may use, and let the ceiling allow them too:
[ceiling]
proc.run = ["sh", "rustc"]
env.read = ["HOME", "PATH"]
env.unkeyed = ["HOME", "PATH"]
fs.read = ["."]
fs.write = ["out", ".buildl"]
[plugins.rust]
github = "airsstack/buildl"
rev = "plugin-rust-v0.2.1"
dir = "plugins/rust"
proc.run = ["sh", "rustc"]
env.read = ["HOME", "PATH"]
env.unkeyed = ["HOME", "PATH"]
network = true
| Entry | Why |
|---|---|
sh | each target is sh -c 'cargo …', so cargo needs no entry of its own, and the binary's target copies cargo's file in the same script |
rustc | what the plugin runs for version_probe and rust.platform; cargo itself finds rustc through PATH |
HOME, PATH | cargo keeps its registry and toolchains under HOME and finds the linker through PATH; both are unkeyed |
network = true | cargo downloads the crates it does not have yet; the ceiling has no network list, and the plugin's table says it |
Both variables are read as "unkeyed": the build is given the value, but only the name is in the
action key, so the same build has the same key on every machine (see The Action
Key). That is why env.unkeyed lists them
beside env.read, in the ceiling and in the plugin's table, as the plugin's manifest does.
Allowing sh lets a target run any program through sh -c, so the ceiling's program list then
limits less.
Fetch the plugin once. A build does not fetch:
$ buildl plugins fetch
fetched rust c97eb8836fddb2a1ed42248bee4315020957e2d2
A first binary
examples/rust is a crate with one binary and one test:
buildl.toml
build.lua
Cargo.toml
Cargo.lock
src/main.rs
src/main.rs has a greeting() function that returns hello from rust, a main that prints it,
and a test that checks it. Cargo.toml holds an empty [workspace] table so cargo treats the
folder as a workspace of its own wherever it is copied. build.lua loads the plugin with
buildl.use and declares the two targets:
local rust = buildl.use("rust")
-- The default profile, dev, keeps the absolute path of the folder it was built in as debug
-- info, so `buildl verify` would find the binary differing each time. release holds no path.
rust.binary("hello", { profile = "release" })
rust.test("unit")
The build file sits in the crate's folder, beside Cargo.toml and Cargo.lock. check reads it
once, and build runs the binary's target:
$ buildl check
ok: 2 declarations in 1 build file
$ buildl build
--- //:hello
Compiling hello v0.1.0 (/private/var/folders/8w/4ccj7cw90nx4d32s72tqf5nw0000gn/T/buildl-9c120668758364b5e50f553c0b89ad6e/fe4f9260c378e04a18415e3a241c26a7)
Finished `release` profile [optimized] target(s) in 1.14s
1 built
$ ./out/hello
hello from rust
build leaves the test out, as it does every test; buildl test runs it:
$ buildl test
tests: 1 passed
What cargo printed is shown with the target, as any program's output is. plan after the build
shows what the plugin declared. Everything is clean, and its declared by plugin rust@0.2.1 lines
say who wanted what:
$ buildl plan
clean //:hello
run programs: sh
unkeyed variables: HOME, PATH
write into: .buildl, out
reach the network: //:hello
sh: declared by plugin rust@0.2.1 for //:hello
HOME (unkeyed): declared by plugin rust@0.2.1 for //:hello
PATH (unkeyed): declared by plugin rust@0.2.1 for //:hello
//:hello: declared by plugin rust@0.2.1 for //:hello
0 to run, 0 conditional, 1 clean
Every file of the crate is an input of both targets, so an edit to src/main.rs runs both:
$ echo "// an edit" >> src/main.rs
$ buildl plan //:hello //:unit
run //:hello: input src/main.rs changed
run //:unit: input src/main.rs changed
run programs: sh
unkeyed variables: HOME, PATH
write into: .buildl, out
reach the network: //:hello, //:unit
sh: declared by plugin rust@0.2.1 for //:hello
HOME (unkeyed): declared by plugin rust@0.2.1 for //:hello
PATH (unkeyed): declared by plugin rust@0.2.1 for //:hello
//:hello: declared by plugin rust@0.2.1 for //:hello
//:unit: declared by plugin rust@0.2.1 for //:unit
2 to run, 0 conditional, 0 clean
What one call declares
%% What rust.binary and rust.test declare for examples/rust
graph LR
F["every file of the crate<br/>Cargo.toml, Cargo.lock, src/, build.rs, ...<br/>not target/ or .git/"] --> B
F --> T
B["hello<br/>sh -c: cargo build --locked --bin hello,<br/>then cp target/release/hello to out/hello"]
T["unit, a test target<br/>sh -c: cargo test --locked"]
A call declares one target, with no discovery pass: cargo finds what a crate reads. Each runs
through sh -c, and an action starts at the sandbox root. So in a folder other than the workspace
root the script runs cargo as (cd <folder> && cargo …), in a subshell, and nothing is added at
the root:
cargo <build or test> --locked … --profile <profile> --target-dir target <args>
For rust.binary, the same script then copies the binary cargo wrote under
<folder>/target/<profile folder>/ to the output, and for rust.library every file cargo wrote
for the crate types kind lists, under the names cargo gave them. The cd sits in the subshell so that the copy,
which comes after it, still reads the path from the root. rust.test copies nothing. --locked is why a
folder with a Cargo.toml and no Cargo.lock is refused.
| Function | Declares |
|---|---|
rust.binary(name, o) | a target that runs cargo build --locked --bin <name> and copies the binary to the output |
rust.library(name, o) | a target that runs cargo build --locked --lib and copies each file it wrote for kind to the outputs |
rust.test(name, o) | a test target name that runs cargo test --locked |
What every target gets, so a build file writes none of it:
| Setting | Value |
|---|---|
| inputs | every file below the build file's folder (buildl.sources("**/*")), except a target/ folder a plain cargo build left there and a .git/ folder, and any path a .buildlignore leaves out: sources, manifests, build.rs, toolchain files, and files read by include_str! or a build script |
| env | { HOME = "unkeyed", PATH = "unkeyed" } |
| network | network = true |
Options
Each function takes (name, options) and returns nothing; options may be left out. An option it
does not know is refused, and the message names it.
| Option | Type | Meaning | Default |
|---|---|---|---|
args | list of strings | arguments to cargo, after the plugin's own, as written on its command line | {} |
profile | string | --profile; it also names the folder the output is copied from: debug for dev and test, release for release and bench, else the profile's own name | "dev" |
deps | list of labels | targets whose outputs the build reads, such as a generated file | {} |
output | string | rust.binary only: the file the step writes | name |
kind | list of strings | rust.library only, required: the crate types to copy, as crate-type in Cargo.toml lists them: "staticlib", "cdylib" or both | none |
version_probe | boolean | see below | false |
output given to rust.library or rust.test is refused, and so is kind given to rust.binary
or rust.test. args go
where you would write them on the command line, so a flag cargo takes is passed as it is:
args = { "--no-default-features" }. A library's name is the name of the file cargo writes, so
it is the crate's library name: my-lib becomes my_lib.
Profiles
The profile is an option, not an argument, because it names the folder the output is copied from.
The default, dev, builds with debug info, and cargo records in it the absolute path of the folder
it compiled in. buildl verify runs each action again in a folder of its
own, so it finds a dev binary different from the cached one:
$ buildl verify
MISMATCH //:hello: output hello differs: bytes
0 verified, 1 mismatched, 0 failed, 0 skipped, 0 not cached, 0 not sampled
With profile = "release", which holds no path, the same crate verifies:
$ buildl verify
verified //:hello
1 verified, 0 mismatched, 0 failed, 0 skipped, 0 not cached, 0 not sampled
That is why both examples say profile = "release". A build that does not run verify can leave
dev as it is.
The helpers
Each returns a value and declares nothing, except rust.platform. Put the value where you want it.
| Helper | Returns |
|---|---|
rust.package(name) | { "-p", name } |
rust.features(list) | { "--features", "<the list joined with commas>" }; {} for an empty list |
rust.platform() | "linux" or "macos", or nil before the discovery has run (see below) |
rust.shared_name(name, platform) | lib<name>.so or lib<name>.dylib; nil when platform is nil |
The helpers compose into args, the way c.includes composes into cflags:
local rust = buildl.use("rust")
local args = rust.package("server")
for _, a in ipairs(rust.features({ "tls" })) do args[#args + 1] = a end
args[#args + 1] = "--no-default-features"
rust.binary("server", { args = args, profile = "release" })
No helper tries to cover every case: a flag cargo takes that none of them writes goes into the list as a string.
A Cargo workspace
A Cargo workspace has one build file at its root, beside Cargo.lock, and one call per artifact,
each naming its package with rust.package. Cargo reads Cargo.toml as always: members, profile
settings and feature definitions stay there.
local rust = buildl.use("rust")
rust.binary("server", { args = rust.package("server"), profile = "release" })
rust.binary("cli", { args = rust.package("cli") })
rust.library("codec", { kind = { "staticlib" }, args = rust.package("codec") })
rust.test("server-test", { args = rust.package("server") })
rust.test("codec-test", { args = rust.package("codec") })
The inputs are every file below the root, so a change in any member runs every target.
A crate in a folder of a workspace that is not the repository's root, like rust/ in
examples/polyglot, has its own build file there, and its own Cargo.toml and Cargo.lock. The
plugin runs cargo in that folder.
Crate types
rust.library gives the two crate types other languages use, staticlib and cdylib. An rlib
(the default lib), a Rust dylib and a proc-macro are read only by rustc. Cargo builds them
itself for any rust.binary or rust.test that depends on them, as a plain cargo build does, so
they have no function of their own. examples/rust-workspace builds a binary from an rlib and a
proc-macro this way, and copies only the binary to out/. To test one, use rust.test:
rust.test("codec-test", { args = rust.package("codec") })
A shared library and the two passes
A shared library has a different file name on Linux and macOS. The helpers answer from the target
triple rustc reports, as c.platform does from the compiler's:
local rust = buildl.use("rust")
rust.library("ffi", { kind = { "cdylib", "staticlib" } })
kind is the crate-type list of Cargo.toml. One cargo build --lib builds every crate type
it lists, as it does without buildl, and the target copies each file under the name cargo gave it:
libffi.so or libffi.dylib, and libffi.a. A library whose kind lists cdylib calls
rust.platform() itself for the shared library's name.
The first rust.platform() call declares a discovery target, :rust.platform, which runs rustc -vV; later calls return the same value and declare nothing. The host: line of its output holds
the triple, and a triple holding apple-darwin gives "macos" and one holding linux gives
"linux". A call returns nil until the discovery has run, which is on the first of the two passes
a build file is declared in (see Discovery Targets). So the
shared library's name waits too: on the first pass its output is named ffi, and the second pass has
libffi.dylib or libffi.so. The plugin copies a cdylib from
lib<name>.so when cargo wrote that file, else from lib<name>.dylib.
The discovery target is the same on both passes, because rust.platform() takes no option, so
the platform may go anywhere in a call's options.
A C program that links the library finds it at run time by the name the library carries. Left
alone, rustc names a cdylib by the path it was linked at, inside the sandbox, and the program
fails to start once that folder is gone. The crate names itself in a build.rs, which is cargo's
business and not the plugin's:
// greeter/build.rs, in examples/rust-ffi fn main() { match std::env::var("CARGO_CFG_TARGET_OS").as_deref() { Ok("linux") => println!("cargo:rustc-cdylib-link-arg=-Wl,-soname,libgreeter.so"), Ok("macos") => { println!("cargo:rustc-cdylib-link-arg=-Wl,-install_name,@rpath/libgreeter.dylib"); } _ => {} } }
examples/rust-ffi builds a static and a shared library from one Cargo workspace and links each
into a C program through the c plugin: c.binary's deps names
//rust:mathlib or //rust:greeter, and c.rpath points the program at out/rust/. It goes the
other way too: c.library builds out/c/libclamp.a, and rust.binary("calc", { deps = { "//c:clamp" } }) puts it in the sandbox, where the crate's build.rs tells rustc to link it with
cargo:rustc-link-search and cargo:rustc-link-lib=static=clamp. The c plugin declares its
library on the second pass, once its compiler discovery has run, so calc is declared on the
second pass as well. The Rust
crates and the C sources sit in folders of their own, since the plugin takes every file of its
folder as an input and a C header beside the crates would rerun cargo.
A target a build reads from another
deps lists targets whose outputs the build reads, so they are in the sandbox when cargo runs.
examples/polyglot has a Rust program that includes a file another target generates:
-- rust/build.lua, in examples/polyglot
local rust = buildl.use("rust")
rust.binary("cli", { deps = { "//schema:gen" }, profile = "release" })
rust.test("cli_test", { deps = { "//schema:gen" } })
The binary and its test each list //schema:gen, because the test compiles the same sources and
the sandbox holds only the outputs of the targets an action names. Many
Directories walks through the workspace.
The toolchain and its version
Each target runs sh, so its action key records the sh program file and
neither cargo nor rustc, whether or not they are links to the rustup launcher. A toolchain
change moves no key: a target built by the old toolchain would be served from the cache.
version_probe = true closes that. The call declares <name>.version, rustc -vV as an always-run
target, and makes its target depend on it, so a new toolchain prints a new version and the target
rebuilds. It is off by default for a reason that shows in plan: an always-run target leaves every
target that depends on it listed as conditional, even right after a full build, because plan never
runs the probe. A build still takes the target from the cache when the probe prints what it printed
before.
What it may run
The plugin's manifest lists sh and rustc. cargo runs inside sh, as ar runs inside sh in
the c plugin, so it is not on the list; rustc is for version_probe
and rust.platform. A program outside the list is refused even when the workspace allows it, and
your cap and ceiling narrow the list further (see How buildl
Decides). Take sh out of the plugin's proc.run, and the build
stops with exit code 4:
$ buildl build
error: build.lua: //:hello (plugin rust@0.2.1): program sh is outside plugin rust@0.2.1 (proc.run allows: rustc)
Programs cargo starts itself, that is rustc, the linker and build scripts, are not seen by the
ceiling: cargo runs them as its own children, and the approver sees the sh that started cargo.
When it goes wrong
A message names the function and the target, and carries the file and line of your call:
$ buildl check
error: build.lua: runtime error: lua error in build.lua: runtime error: build.lua:3: rust.binary(hello): the option bogus is not known
stack traceback:
[C]: in ?
[C]: in function 'error'
...ns/rust/d6dce47e11479c6b66f8ec41fa6a73691822d46b/api.lua:23: in upvalue 'relocate'
...ns/rust/d6dce47e11479c6b66f8ec41fa6a73691822d46b/api.lua:45: in field 'binary'
build.lua:3: in main chunk
The plugin's own frames come first in the traceback, with build.lua:3 last. The build file fails
to load, with exit code 5. The same goes for a crate with no lock file:
$ buildl check
error: build.lua: runtime error: lua error in build.lua: runtime error: build.lua:5: rust.binary(hello): no Cargo.lock beside Cargo.toml; run cargo generate-lockfile
The other messages:
| Case | Message |
|---|---|
no Cargo.toml in the build file's folder | rust.binary(hello): no Cargo.toml in <folder> (. at the root) |
| options that are not a table | rust.binary(hello): the options must be a table |
kind given to rust.binary or rust.test | rust.binary(hello): the option kind is refused |
output given to rust.test | rust.test(unit): the option output is refused |
| a wrong type | rust.binary(hello): the option args must be a list of strings |
rust.library without kind, or a kind listing another value | rust.library(mylib): kind must list "staticlib", "cdylib" or both |
a kind listing a crate type twice | rust.library(mylib): kind lists cdylib twice |
output given to rust.library | rust.library(mylib): the option output is refused |
rust.platform on a host that is neither | rust.platform: the target triple <triple> is neither macos nor linux |
rustc -vV without a host: line | rust.platform: the output of rustc -vV has no host line |
rust.package without a string | rust.package: the name must be a string |
rust.shared_name without a string | rust.shared_name: the name must be a string |
rust.features without a list of strings | rust.features: the features must be a list of strings |
What cargo itself refuses (a bad Cargo.toml, a path dependency outside the folder, a failed
download) fails the action with cargo's own message, as a build failure. A program outside the
plugin's manifest, your cap or your ceiling is refused with exit code 4, as the sh case above is.
Limits
| The plugin | Because |
|---|---|
| builds on Linux and macOS | rust.platform and the helpers know only Linux and macOS target triples |
| compiles the dependencies again when an input changes | each build runs in a fresh sandbox, with a target/ of its own; plain cargo keeps its target/ and is faster for an edit loop on one crate |
| keeps crates in cargo's cache, outside buildl's store | cargo finds them under HOME (~/.cargo), which is unkeyed |
| does not see the programs cargo starts | the ceiling sees the sh that started cargo, not the rustc, linker or build scripts under it |
builds staticlib and cdylib only as libraries | the other crate types are read only by rustc, and cargo builds them for the binary that needs them |
| does not cross-compile | cargo would need --target, and the plugin copies the file from target/<profile folder>/, where cargo writes only without it |
| wraps no registry, vendoring or lock-file tool | cargo does its own; the plugin changes nothing about how Rust builds |
See What buildl Can and Cannot Promise for what the first three mean for a build's repeatability.
Try it
examples/rust, examples/rust-workspace, examples/rust-ffi and examples/polyglot in the
buildl repository are the builds above, each with a README. From examples/, sh check.sh rust
(or rust-workspace, rust-ffi, polyglot) runs check, build,
test, verify and the example's own assertions on a copy. The copy first runs prepare.sh,
which commits this checkout's plugins/rust to a temporary git repository, tags it
plugin-rust-v0.2.1 and points the copy's buildl.toml at it, so the check runs the plugin as the
checkout holds it instead of the published tag.
cargo buildl
A Cargo project that uses the rust plugin needs a buildl.toml with
the plugin's table, a build.lua with one call per artifact, and a .gitignore that keeps out/
and .buildl/ out of git. cargo buildl writes those, and keeps the calls in line with
Cargo.toml as packages and binaries come and go. It is a second program, cargo-buildl, from the
crate buildl-cargo. Cargo runs any cargo-<name> program it finds on PATH for cargo <name>
(see References, 29), so it needs no setup beyond installing it.
It adds two commands, init and sync, and passes every other command to the buildl command
line, so cargo buildl build is buildl build.
Install
buildl-cargo is published to crates.io. It depends on the buildl library, so cargo install
builds it from source; no prebuilt cargo-buildl is shipped. It does not need the buildl
program: the commands it passes on run in cargo-buildl itself.
cargo install --locked buildl-cargo
Starting a project: cargo buildl init
In a Cargo project that has a Cargo.lock:
$ cargo buildl init
init reads the project from cargo metadata --no-deps, which writes no Cargo.lock and fetches
nothing. It runs every check first and writes only when all of them pass:
%% cargo buildl init, in order
graph TD
M["Step 1: read the metadata"] --> E["Step 2: buildl.toml or build.lua already there?"]
E --> L["Step 3: a Cargo.lock beside Cargo.toml?"]
L --> G["Step 4: generate build.lua"]
G --> W["Step 5: write build.lua, buildl.toml, .gitignore"]
W --> F["Step 6: buildl plugins fetch"]
| Step | On failure |
|---|---|
| 1. read the metadata | cargo cannot be started: exit code 3. Cargo exits non-zero, a bad Cargo.toml for one: its stderr is shown, exit code 5 |
2. buildl.toml or build.lua is in the workspace root already | exit code 5, nothing written: init: <file> already exists; this folder is set up already, or remove <file> to start over |
3. no Cargo.lock in the workspace root | exit code 5, nothing written: init: no Cargo.lock beside Cargo.toml; run cargo generate-lockfile. The plugin builds with --locked and would fail without it |
4. generate build.lua | exit code 5, nothing written, if a target name is refused (see below) |
| 5. write the three files | an I/O error is exit code 3, and the files this run created are removed, so the folder is as it was |
| 6. fetch the plugin | the exit code of buildl plugins fetch, 3 when git is missing. The files stay, and the message says to run cargo buildl plugins fetch |
Step 6 runs buildl's plugins fetch inside cargo-buildl, with no buildl program needed, so its output and exit code are that command's own (see
Plugins from Git). On success, init prints this before the fetch
lines:
init: wrote build.lua, buildl.toml, .gitignore
Every message of init and sync goes to standard error. Run from a member's folder, init still
writes in the workspace root, the folder of the Cargo.toml that holds [workspace], and every
buildl command finds that workspace from any folder below it.
buildl.toml
init writes the tables the rust plugin page shows:
the ceiling, and [plugins.rust] pinned to the plugin tag this release of cargo-buildl was
tested with. [workspace]'s name is the last component of the workspace root's path; entry and
out are the defaults, and config = 1.
[workspace]
name = "my-project"
entry = "build.lua"
out = "out"
config = 1
[ceiling]
proc.run = ["sh", "rustc"]
env.read = ["HOME", "PATH"]
env.unkeyed = ["HOME", "PATH"]
fs.read = ["."]
fs.write = ["out", ".buildl"]
[plugins.rust]
github = "airsstack/buildl"
rev = "plugin-rust-v0.2.1"
dir = "plugins/rust"
proc.run = ["sh", "rustc"]
env.read = ["HOME", "PATH"]
env.unkeyed = ["HOME", "PATH"]
network = true
.gitignore gets the lines /out/ and /.buildl/, each added only when that exact line is
missing, and the file is created when there is none. sync never touches buildl.toml: from then
on it is yours.
The generated section of build.lua
build.lua has two parts, split by two comment lines. Lua ignores them, so the file is an
ordinary build file.
-- cargo-buildl: begin generated. `cargo buildl sync` rewrites this part from Cargo.toml.
local rust = buildl.use("rust")
rust.test("answer-test", { args = rust.package("answer") })
rust.binary("cli", { args = rust.package("cli") })
rust.test("cli-test", { args = rust.package("cli") })
rust.test("greeting-test", { args = rust.package("greeting") })
-- cargo-buildl: end generated
-- Your own targets go below. `cargo buildl sync` never changes them.
That is what init writes for examples/rust-workspace, a Cargo workspace of three packages: the
library greeting, the proc-macro answer and the binary cli. The section follows from
Cargo.toml alone, so the same manifest always gives the same bytes. Everything outside the two
marker lines belongs to you: add your own targets, a release binary, C code, whatever the build
needs, below the end marker.
| In the Cargo metadata | Generated |
|---|---|
a library target that builds cdylib, staticlib or both | rust.library("<target name>", { kind = { <those it builds, in Cargo's order> }, args = rust.package("<package>") }) |
a bin target with no required-features | rust.binary("<target name>", { args = rust.package("<package>") }) |
| every package | rust.test("<package>-test", { args = rust.package("<package>") }) |
lib (rlib), dylib, proc-macro, example, test, bench, custom-build, and a bin with required-features | no call: cargo builds them itself, or a plain cargo build skips them |
Packages are sorted by name; within a package the library comes first, then the binaries sorted by
name, then the test. No profile is written, so the plugin's default, dev, applies, and
buildl verify reports a dev build as differing
(rust plugin page). sync rewrites the generated lines, so
change the build where you own it: turn debug and incremental off under [profile.dev] in
Cargo.toml, as examples/cargo-buildl does, or declare a target of your own, under another
name, with profile = "release".
A target name outside buildl's rule (1 to 256 ASCII letters, digits, ., - and _, and neither
. nor ..), or two generated targets with the same name, is refused with exit code 5. The
message names the target and its package or packages, and nothing is written.
Keeping it in line: cargo buildl sync
Add a package or a binary, and sync brings the section up to date:
$ cargo buildl sync
sync: build.lua updated
It reads the project as init does, then replaces the lines from the begin marker to the end
marker and keeps every other byte of build.lua. When the section is already right it writes
nothing:
$ cargo buildl sync
sync: build.lua is up to date
A begin marker is any line that starts with -- cargo-buildl: begin generated, and an end marker
any line that starts with -- cargo-buildl: end generated; the rest of the line is free. Both
lines are kept as they are. To put the generated section in a build.lua you wrote by hand, add the
two lines where it should go and run sync.
| Case | Message, exit code 5 |
|---|---|
no build.lua | sync: no build.lua; run cargo buildl init |
| no markers | sync: build.lua has no generated section; add the lines "-- cargo-buildl: begin generated" and "-- cargo-buildl: end generated" where it goes |
| more than one of either marker, a begin with no end, an end with no begin, or the end before the begin | sync: build.lua must hold one begin line and, after it, one end line |
In CI
sync --check writes nothing. It exits 0 when build.lua is up to date, and 5 when it is not:
$ cargo buildl sync --check
sync: build.lua is out of date with Cargo.toml; run cargo buildl sync
Run it before cargo buildl build in CI, and a Cargo.toml that moved without its build.lua
fails the job, where the build alone would pass and leave a target out.
Every other command
cargo buildl build -k, cargo buildl test --stop, cargo buildl plan, cargo buildl watch and
the rest take buildl's own flags and give its output and exit codes, because the same code runs
them: the command line lives in the buildl library, and both programs call it. The BUILDL_REMOTE_*
variables and NO_COLOR are read as buildl reads them. An error raised while a buildl command
runs, such as a target that is not a label, keeps buildl's text and names buildl.
cargo buildl --version prints buildl-cargo's version, and cargo help buildl shows the help. A
usage error is clap's, exit code 2, and names cargo buildl.
Exit codes
cargo buildl uses buildl's exit codes and adds none:
| Code | init and sync |
|---|---|
| 0 | done; sync --check found build.lua up to date |
| 2 | a usage error |
| 3 | cargo cannot be started, its output cannot be read as metadata, the current directory cannot be read, build.lua cannot be read (sync), a file cannot be read or written, or the plugin fetch failed |
| 5 | cargo refused the manifest; files exist already (init); no Cargo.lock; a name refused or claimed twice; no build.lua or broken markers (sync); out of date (sync --check) |
What it does not do
| It does not | Because |
|---|---|
change buildl.toml after init | the ceiling is yours to set; sync rewrites only the generated lines of build.lua |
| build anything itself | it writes build files and hands the rest to buildl, so a build is the rust plugin's, with its limits |
| declare non-Rust targets | what a Cargo project needs besides cargo goes below the end marker |
| ship as a prebuilt binary | it is installed with cargo install --locked buildl-cargo |
Try it
examples/cargo-buildl in the buildl repository is a Cargo workspace of a library, a static library
and a binary. Its buildl.toml, build.lua and .gitignore are what cargo buildl init wrote,
and its checks add a binary and run sync and sync --check.
Remote Cache and Execution
Your cache only knows what your machine built. A remote cache is one a whole team shares: CI
builds main and stores its results there, and everyone's first build of the day is mostly
downloads. Remote execution goes a step further and runs the work on the server's machines.
buildl is a client of both. It speaks the Remote Execution API over gRPC, the protocol servers such as NativeLink, BuildBarn, Buildfarm and BuildBuddy speak. buildl does not ship a server.
Sharing results is only safe if every result depends on nothing but its declared inputs. That is
what the sandbox is for, and why some of what follows is refused under
strategy = "bare".
Where a result comes from
%% Cache lookup ladder
flowchart TD
KEY["Action key"] --> LC{"local cache?"}
LC -- hit --> REUSE["Reuse — link from local cas"]
LC -- miss --> RC{"remote cache?"}
RC -- hit --> DL["Download into local cas"]
RC -- miss --> EX["Execute — on the server's worker when remote execution is on, here otherwise"]
EX --> UP["Upload — seed the remote cache, when asked to"]
Naming the server
A [remote] table in buildl.toml names it. examples/remote points at a server on this machine:
[remote]
url = "grpc://127.0.0.1:50051"
url is the one key you must give. grpc:// is plain, grpcs:// is TLS. The others:
| Key | Says | When left out |
|---|---|---|
instance | the server's instance name, such as ci | the server's default |
ca | a PEM file of certificate authorities to trust as well as the system's | none |
token | { env = "NAME" } or { file = "path" }: where the secret is read from, never the secret itself | no login |
header | the request header the token travels in | authorization |
timeout | how long to wait to connect, for one call, or for one piece of a large transfer | 30s |
execute | true runs on the server what no cache holds | false |
jobs | how many targets may be with the server at once, 1 to 1024 | 128 |
queue_timeout | how long a job may wait to start on the server | 1h |
retries | how many times a failed call is tried again, 0 to 10 | 5 |
properties | names and values sent with every action, so the server can pick a worker | none |
None of these is in the action key: where a result is stored or run never
changes what it is. buildl doctor prints them without connecting:
$ buildl doctor | sed -n '/^remote/,/^ceiling/p'
remote
url grpc://127.0.0.1:50051
instance -
ca -
header authorization
timeout 30s
token -
upload off
strict off
execute off in buildl.toml, BUILDL_REMOTE_EXECUTE not set
jobs 128
queue_timeout 1h
retries 5
properties: none
--remote-upload and --remote-strict turn either on for one run
--remote-execute and --no-remote-execute change execute, and --remote-jobs changes jobs, for one run
ceiling
Only build and test (and watch, which runs builds) talk to the server.
When the server is not there
With a [remote] table, a build looks up there every target its own cache cannot serve. With no
server running, the lookup fails, and the build goes on without it:
$ buildl build
warning: remote cache lookup failed: grpc://127.0.0.1:50051: ActionCache.GetActionResult: cannot connect: transport error: tcp connect error: tcp connect error: Connection refused (os error 61) (after 6 calls); the build goes on without it
1 built
One warning, and the remote is off for the rest of the command. after 6 calls is the first call
and five retries (below). os error 61 is how macOS numbers a refused connection; Linux says 111. A remote that is down never stops you working.
If you would rather it did, as CI might, --remote-strict or BUILDL_REMOTE_STRICT=1 makes a
failed call fail the run:
$ buildl build --remote-strict
error: remote cache: lookup: grpc://127.0.0.1:50051: ActionCache.GetActionResult: cannot connect: transport error: tcp connect error: tcp connect error: Connection refused (os error 61) (after 6 calls)
That exits with code 3: the trouble is the machine or the network, not your build, and running
again may help. BUILDL_REMOTE_STRICT=1 buildl build prints the same and exits 3 too.
--no-remote leaves the remote out of one run entirely, whatever buildl.toml and the variables
say:
$ buildl build --no-remote
1 built
Sharing a result
The upload and the fetch, captured against examples/remote's server (docker compose up -d --build) in two fresh copies of the workspace. Copy 1 builds, and with --remote-upload sends what
it ran:
$ buildl build --remote-strict --remote-upload
1 built
$ buildl test --remote-strict --remote-upload
tests: 1 passed
Copy 2 has an empty cache of its own. It finds both results on the server:
$ buildl build --remote-strict
1 fetched
$ buildl test --remote-strict
tests: 1 passed (1 fetched)
$ python3 out/app.pyz
hello from python
$ buildl build --remote-strict
1 cached
out/app.pyz in copy 2 is byte for byte the one copy 1 built. The last build is cached: once
fetched, a result is in the local cache like any other.
buildl trusts a server for bytes and nothing else. Every blob it downloads is checked against the length and SHA-256 it was named by, and one that fails is never stored. A result is used only when its command exited 0 and it names each declared output exactly once, with no symbolic link. What passes goes into the local store first and the cache row is written after, so a crash in between leaves nothing half-recorded: the next build simply downloads again.
How a target is described
The server does not know buildl's action key. buildl describes each target in the API's own terms,
an Action holding its command, its environment, its sorted outputs, a tree of its inputs, its
timeout and its platform. The environment is the target's key variables with their values and the
sandbox's pinned variables; an unkeyed variable is not in it. buildl's key goes along as the
Action's salt. So two targets with different keys never share an entry, and nothing is shared
with Bazel or any other client of the same server.
Uploading
Uploading is off unless --remote-upload or BUILDL_REMOTE_UPLOAD=1 turns it on. Only an action
that ran here and succeeded is uploaded: never a failure, a result from the local cache, or one
fetched. Each variable is 1 or 0, and anything else is a usage error:
$ BUILDL_REMOTE_UPLOAD=yes buildl build
error: BUILDL_REMOTE_UPLOAD is "yes", and must be 1 or 0
Under strategy = "bare" an action can read files it never declared, so its result could depend on
more than its key. Sending that to every other machine is exactly the poisoning
verify exists to find, so it is refused, before anything runs:
$ buildl build --remote-upload
error: uploading to the remote cache needs actions to run in the input sandbox, but strategy is "bare"; set strategy to "sandbox", or stop uploading by unsetting BUILDL_REMOTE_UPLOAD or dropping --remote-upload
That exits with code 2. Reading from the cache works under any strategy.
Who should upload
The key of a target holds the digests of the files its dependencies produced. A computer that downloads a dependency gets the same bytes as the one that built it, so every key above it matches, and what is built on top is fetched too.
So the most reuse comes from one builder for the shared parts: CI with --remote-upload, or the
server itself under remote execution. Everyone else reads. buildl asks the remote cache only for
what the local cache cannot serve, so an engineer who already built a dependency themself keeps
their own bytes for it while their local cache holds it.
%% One builder uploads; the others fetch the same bytes
flowchart LR
CI["CI builds the dependency<br/>--remote-upload"] -->|"upload"| RC[("remote cache")]
RC -->|"fetch, same bytes"| A["Engineer A"]
RC -->|"fetch, same bytes"| B["Engineer B"]
A --> KA["keys above it match"]
B --> KB["keys above it match"]
When everyone uploads, it still works. But each computer runs an action in a folder of its own, named from the workspace's path and the target's label, and a tool may write that folder into what it makes (see where the folder is). Two computers that each build the same unchanged dependency can then get other bytes. The targets that use it then get other keys, and are built again instead of fetched.
A result is never wrong either way. It is only reused less.
Three more things decide whether two computers share a result, and all are in the build files and
buildl.toml, which everyone has the same copy of:
- Variables that find programs.
HOMEandPATHdiffer between users and machines, and a target that marks themkeyhas another key, and anotherAction, on each. Users and CI share only when those variables areunkeyed: the command still gets them when it runs here, but the key holds their names alone, and they are not sent to the server.examples/remotemarks both in its build file,env = { HOME = "unkeyed", PATH = "unkeyed" }, and lists them inenv.unkeyedin itsbuildl.toml. - The server's own environment. Because an
unkeyedvariable is not sent, a target that runs on the server runs with the server's environment, not yours, and the server decides how it finds a program. The program has to be there, and one of the same version. Akeyvariable is sent and set. - The timeout. The server's
Actionholds the action's timeout, because two actions with different timeouts are different actions to the API: a result found at a short timeout says nothing about a long one. So the timeout is part of the remote key, though not of the local key. It comes only from[execution] timeoutinbuildl.toml, with no flag or variable, so a team that commits onebuildl.tomlhas one timeout. A copy with another timeout fetches nothing the first one uploaded.
Running on the server
With execution on, a target neither cache can serve is sent to the server and run on one of its workers. The lookup still comes first, so a result someone else stored is fetched and nothing runs. Whether a run executes remotely comes from the first of these that says:
| Order | Source |
|---|---|
| 1 | --no-remote: the whole remote off, execution included |
| 2 | --remote-execute on, or --no-remote-execute off (the cache is still used) |
| 3 | BUILDL_REMOTE_EXECUTE=1 or =0 |
| 4 | execute = true in [remote] |
%% Remote execution flow
sequenceDiagram
participant B as buildl client
participant S as Server — CAS and Execution service
participant W as The server's worker
B->>S: GetCapabilities, once per build — execution enabled, SHA-256
B->>S: FindMissingBlobs — upload the inputs, Directory messages, Command and Action it lacks
B->>S: Execute — action digest, the server may answer from its cache
S->>W: queue, then assign the action
W->>S: fetch inputs, execute — declared inputs only, push outputs by digest
S-->>B: Operation stream until done — the ExecuteResponse
B->>S: download the blobs the answer names, each checked against its digest
The answer is checked and stored exactly as a fetched result is. How it ends the target:
| The server answers | The target |
|---|---|
| it ran the action, exit 0, every output there | remote |
| the result was already in its own cache | fetched |
| it ran, exit not 0 | fails as a local run with that exit would; nothing is cached |
| it gave up at the action's timeout | fails as a local timeout would, and is not run here |
| a retried status (below) | tried again |
| anything else, or a blob that fails its check | a failed call: a warning, or exit 3 under --remote-strict |
Execution is refused under strategy = "bare" for the same reason uploading is:
$ buildl build --remote-execute
error: executing on the remote needs actions to run in the input sandbox, but strategy is "bare"; set strategy to "sandbox", or stop executing by setting execute to false in [remote], unsetting BUILDL_REMOTE_EXECUTE or dropping --remote-execute
Exit code 2 again.
What it looks like
Remote execution could not be captured for this book: examples/remote's server only runs actions
for a Linux x86-64 client, and on a Mac the action waits in the server's queue until
queue_timeout. The example's README has the table of where it runs. The repository's CI
runs it on Linux against NativeLink. In run 40633614431, job "Remote example on NativeLink", the
example's assert.sh printed:
remote: a: the server runs the target
remote: a: the server runs the test
remote: b: a fresh copy fetches what the server ran
remote: c: an edited copy builds here and uploads
remote: d: a fresh copy with the same edit fetches what was uploaded
remote: ok
assert.sh does not print buildl's own lines. It checks that the last line of each is exactly what
it expects, and stops on the first that is not:
| Step | Command | Last line |
|---|---|---|
| a | buildl build --remote-strict --remote-execute | 1 remote |
| a | buildl test --remote-strict --remote-execute | tests: 1 passed (1 remote) |
| b | buildl build --remote-strict, in a fresh copy | 1 fetched |
| c | an edit, then buildl build --remote-strict --remote-upload | 1 built |
| d | the same edit in a fresh copy, buildl build --remote-strict | 1 fetched |
buildl does not upload what the server ran, even under --remote-upload. Step b fetched because
NativeLink stored the result itself.
The workers need the tools an action runs. buildl does not put them there: a toolchain declared as a dependency reaches a worker as any input does, and anything else is the server's to provide.
How many at once
[remote] jobs, or --remote-jobs N for one run, bounds how many targets are with the server at
once. [execution] workers still bounds how many actions run here, so a build that falls back to
local runs never runs more of them than it would without the remote. --remote-jobs means nothing
with execution off, and says so:
$ buildl build --remote-jobs 4
error: --remote-jobs needs remote execution, and it is off in this run
Retries
Every call to the server, the cache's and execution's alike, is tried again when it fails with
UNAVAILABLE, RESOURCE_EXHAUSTED, ABORTED or CANCELLED, and with no other code. A connection
that cannot be made, or a call that passes [remote] timeout, counts as UNAVAILABLE, which is why
the build above made six calls before giving up:
retries = 5 (default): the first call, then up to 5 retries
call ─✗─► 100 ms ─► retry 1 ─✗─► 200 ms ─► retry 2 ─✗─► 400 ms ─► ... ─✗─► failed call
(each pause doubles, at most 5 s, plus under 50 ms at random)
retries = 0: the first call only
A job on the server that keeps reporting progress is never given up: a stream that delivered
messages and then broke starts the count over, and buildl picks the job up again with
WaitExecution rather than running it twice.
Inside the client
The judging is done by buildl's core, which has no network; the remote adapter only moves bytes and encodes messages. Every check above can therefore be tested against a fake server:
%% The core judges; the adapter moves bytes and encodes
graph LR
subgraph CORE["buildl-core"]
RA["remote_action(task)"]
USE["usable(hit)"]
FET["fetch: length + SHA-256 per blob"]
DEC["decode_tree"]
UP["upload_of(run)<br/>RemoteUpload + BlobSource"]
end
subgraph AD["buildl: remote/"]
LK["encode, GetActionResult"]
RD["BatchRead / ByteStream Read"]
TR["Tree to files, or None"]
WR["FindMissingBlobs, uploads,<br/>UpdateActionResult"]
EX["upload the inputs, Execute,<br/>WaitExecution"]
end
RA -->|"RemoteAction, lookup"| LK
LK -->|"RemoteHit"| USE
RA -->|"RemoteAction, execute"| EX
EX -->|"Executed"| USE
FET -->|"download"| RD
DEC -->|"tree bytes"| TR
UP -->|"upload"| WR
One execution, from a worker thread's call to the answer the core judges:
%% execution::run: one Retry budget, streams resumed, blobs re-sent
sequenceDiagram
participant W as worker thread
participant A as Reapi (block_on)
participant S as server
W->>A: execute(RemoteAction)
A->>S: GetCapabilities (once per build)
A->>S: FindMissingBlobs, then BatchUpdateBlobs or ByteStream Write
A->>S: Execute(action digest)
S-->>A: Operation messages ...
Note over A,S: stream ends before done: WaitExecution(name)<br/>NOT_FOUND: Execute again<br/>FAILED_PRECONDITION with MISSING only: send those blobs, Execute again
S-->>A: Operation done, ExecuteResponse
A-->>W: Executed::{Ran, Cached, TimedOut, InputChanged}
The rest of buildl uses plain threads. The remote adapter alone owns an async runtime, and worker threads reach it by blocking on it; see Under the Hood.
Watch Mode
buildl watch builds, then waits, and builds again each time you change something the build
reads. Leave it running in a terminal while you edit.
buildl watch [target]...
It takes the same targets and flags as buildl build: --set, --keep-going, --stream and the
remote flags of the last chapter. Each time it builds, it is the buildl build you would have typed: it reads buildl.toml and the build files again, plans, asks the
approver, runs and records exactly as build does. An edit to buildl.toml, or to a plugin's
extension.toml, counts from the next build.
A session
In a copy of examples/python, buildl watch builds at once and waits. The lines starting with
# are what was done in another terminal; everything else is what watch printed:
$ buildl watch
watch: building
1 built
watch: waiting for changes
# echo '# an edit' >> app/greet.py
watch: app/greet.py changed
1 built
watch: waiting for changes
watch: app/greet.py changed
1 cached
watch: waiting for changes
# echo 'more' >> README.md
# echo 'x' > out/scratch.txt
# echo 'X = 1' > app/extra.py
watch: app/extra.py changed
1 built
watch: waiting for changes
watch: app/extra.py and 1 more changed
1 cached
watch: waiting for changes
# echo 'b.target(' >> build.lua
watch: build.lua changed
error: build.lua: syntax error: lua error in build.lua: syntax error: build.lua:16: unexpected symbol near <eof>
watch: waiting for changes
# the line removed from build.lua again
watch: build.lua changed
1 cached
watch: waiting for changes
# Ctrl-C
What happened at each step:
| Change | Why watch did what it did |
|---|---|
app/greet.py | a declared input of the last build: build again |
app/greet.py, a second time | the system reported the same save again; the build found nothing to do |
README.md | no target reads it, and the build files still declare the same graph: nothing at all is printed |
out/scratch.txt | the build's own output folder is never watched |
app/extra.py, a new file | b.sources("app/*.py") now matches one more file, so the graph is different: build |
app/extra.py and one more, again | events the system repeated; nothing to do |
build.lua broken | the build fails and prints what build prints; the watch goes on waiting |
build.lua fixed | build again; nothing had changed since the last good build, so it is all cached |
Timings vary, and so does how often the operating system repeats an event. watch can build once
too often; it never misses a change.
What starts a build
%% Watch mode loop
flowchart TD
EV["File events — from notify"] --> DB["Debounce — 50 ms window<br/>one batch of changed paths"]
DB --> DROP["Drop paths under out/,<br/>the state directory and .git,<br/>and paths a .buildlignore ignores"]
DROP --> E{"any path left?"}
E -- no --> WAIT
E -- yes --> Q{"no graph last cycle,<br/>or a path is a declared input<br/>or buildl.toml, buildl.lock,<br/>a plugin's extension.toml?"}
Q -- yes --> CYCLE
Q -- no --> CHECK["Check pass<br/>open the workspace again,<br/>load + resolve, no lock"]
CHECK --> G{"load failed, or<br/>graph differs from the<br/>graph the last build ran on?"}
G -- yes --> CYCLE["Cycle<br/>open the workspace again,<br/>then a whole build"]
G -- no --> WAIT["Wait for the next batch"]
CYCLE --> WAIT
WAIT --> EV
Changes arrive in batches: after the first, watch collects until 50 ms pass with no more. Then:
- Paths under
out/(or whatever[workspace] outnames), under.buildland under.gitare dropped. They are the build's own writes, or hold no source. So is a path a.buildlignoreignores (Inputs, Outputs and Dependencies): a file edited in an ignored folder, or a new one made there, starts nothing. A batch with nothing left does nothing and prints nothing. - A declared input of the last build,
buildl.toml,buildl.lockor theextension.tomlof a plugin kept in the workspace starts a build. So does any change after a build that failed before it had a graph. - Any other path, a README, an editor's swap file, a new source file, a build file, starts a check: the build files are read again, which runs nothing and writes nothing. If they declare the same graph as the last build ran on, nothing happens. If they fail to load or declare a different one, a build runs.
Apart from the .buildlignore files you write, there is no list of file names to ignore. A new
file can only reach a build through b.sources, and the check is exactly a reading of the build
files, so a new file that a pattern now matches is built, and a comment edited in a build file is
not.
The rules are those of the workspace as it was last opened, for a build or for a check. A
.buildlignore that is edited is a change like any other, unless a pattern ignores it. Each file is
read the first time a path below its folder is asked about, and a file that was read is kept until
the next open, so edited lines apply at the latest from the next open. Before the first open has
succeeded no path is dropped for being ignored.
watch: <path> changed names the first path of the batch in path order, and and N more counts
the others that were kept.
Between builds
watch holds the state lock only while it builds. While it waits, plan, log, graph and
doctor work in another terminal.
How it ends
| What happens | Exit code |
|---|---|
| Ctrl-C | ends watch as it ends buildl build; the shell reports 130 |
| a usage error, found before the first build | 2 |
buildl.toml cannot be read before the first build | 5, as buildl build ends |
| the file watcher cannot be set up or kept, or the system says it dropped events | 3 |
A wrong flag is caught before anything starts:
$ buildl watch --remote-upload
error: --remote-upload and --remote-strict need a [remote] table in buildl.toml, and this workspace has none
That exits with code 2. A build that fails, though, does not end the watch, not even one that asks for a target nothing declares:
$ buildl watch nosuch
watch: building
error: target //:nosuch was asked for but is not declared
watch: waiting for changes
You may be about to declare it. Exit code 3 is for a gap in the file events: rather than go on
with changes it may have missed, watch stops and prints watch: and the error.
Inside watch
Deciding between builds is buildl's core, which reads no files and no clock; noticing files and opening the workspace again are the adapters':
%% The loop in the core; the adapters notice files and open workspaces
graph LR
subgraph CORE["buildl-core: watch/"]
LOOP["watch(changes, cycles, layout)"]
KEPT["kept(batch, layout, rules)"]
REACT["react(batch, reference, None)"]
INP["watched_inputs(whole, scoped)"]
end
subgraph AD["buildl"]
NC["NotifyChanges<br/>watch/"]
RE["Reopening<br/>workspace/watching.rs"]
WS["Workspace::build_watched<br/>Workspace::graph"]
end
NC -->|"Changes::next: ChangeBatch"| LOOP
LOOP --> KEPT
LOOP --> REACT
RE -->|"Cycles::rules"| LOOP
LOOP -->|"Cycles::build, Cycles::graph"| RE
RE --> WS
WS -->|"Pipeline::build_watched"| INP
The loop first cuts the batch with kept, which drops the build's own paths and those the rules
ignore, using the rules of the workspace the last cycle opened; Reopening keeps them and hands
them back through Cycles::rules, refreshed after every successful reopen, whether for a build or
for a check. react then takes the batch that is left, what the last build left behind (its graph
and its inputs) and no rules, since kept has applied them, and answers build, check or ignore.
File events come from the notify crate: FSEvents on macOS, inotify on Linux. Each build is a
full reload of the workspace. That is fast enough that watch needs no long-lived Lua engine.
Under the Hood
This chapter is for the curious, and for anyone who wants to work on buildl itself. It explains
how the pieces you have used fit together, why they are shaped the way they are, and, just as
importantly, what buildl can and cannot promise.
You do not need any of it to use buildl.
| Section | What it covers |
|---|---|
| Declare, Then Execute | the five phases of a build, the value each hands to the next, and the scheduler |
| Crash Safety and the Store | the life of one action, and why a build stopped half way never leaves a broken cache |
| Five Crates, Ports and Adapters | how the code is split, and the rules that keep the logic of a build testable |
| Errors | how a failure is classified, and how that becomes an exit code |
| Determinism Rules | the engineering rules that keep the same inputs giving the same bytes |
| Decision Records | each choice that was settled, with its reason |
| Testing Layers | which kind of test lives where |
| Where buildl Sits | buildl placed among other build systems, in the terms of build-system theory |
| What buildl Can and Cannot Promise | what is out of scope, and what each isolation tier does not guarantee |
The pages name real types, modules and files. Where an older design note and the code disagree, these pages follow the code.
Declare, Then Execute
The most important decision in buildl is the split you met in the
Introduction: build files declare, and the host executes. Lua never runs a
compiler and never writes an artifact. It produces a description of the build, and the Rust side
schedules, sandboxes, runs in parallel and caches. The line between the two is airsl's boundary,
so the split is enforced, not just agreed on.
Three things follow from it:
- Declaring is safe on code you do not trust. The engine a build file runs in holds no grant
at all. Its one look at the filesystem,
buildl.sources, is done by the host and kept inside the declaring directory. - Parallelism lives where it works. One Lua state cannot run in parallel, but a pool of Rust workers can. Each build file gets an engine of its own, so even loading runs on the pool.
- Limits become a feature. A build file that loops forever is stopped by airsl's instruction limit while it declares, before it has wasted anyone's time.
Five phases
A build is five phases in a row, each with a clear edge:
%% Build workflow phases
flowchart TD
L["Load<br/>airsl evaluates build files"] --> R["Resolve<br/>assemble the target DAG"]
R --> P["Plan<br/>hash inputs, mark dirty"]
P --> X["Execute<br/>parallel workers run rules"]
X --> REC["Record<br/>write cache and log"]
REC -. "watch mode: a change that matters re-enters Load" .-> L
The phases do not call each other. Each one hands the next a plain value, and the Pipeline in
buildl-core (crates/buildl-core/src/pipeline/driver.rs) owns the order:
| Phase | Takes | Hands on | Defined in crates/buildl-core/src/ |
|---|---|---|---|
| Load | the workspace's build files | Vec<Declaration> | types/declaration.rs |
| Resolve | Vec<Declaration> | TargetGraph | types/target_graph.rs |
| Plan | TargetGraph | Plan | types/plan.rs |
| Execute | TargetGraph and Plan | Vec<ActionOutcome> | types/outcome.rs |
| Record | each ActionOutcome as it comes | cas blobs, a cache row, a log line | execute/record.rs |
Because every handoff is a value that can be written out, each phase can be tested alone, and
buildl graph and buildl plan are nothing more than a handoff printed.
Each command is the pipeline cut short
Every command runs the same pipeline and stops at one of those handoffs:
| Command | Stops after | What it shows |
|---|---|---|
buildl check | Load | that every build file evaluates; nothing runs |
buildl graph | Resolve | the target graph, as JSON or as DOT |
buildl query | Resolve | deps() or rdeps() of one target |
buildl doctor | Resolve | the wants of the whole graph, held up to the ceiling |
buildl plan | Plan | what would run, and why |
buildl build, buildl test | Record | the whole pipeline |
buildl verify | Plan, then a re-run with no Record | whether cached actions still give the same bytes |
buildl watch | Record, then waits | a build, then another each time something that matters changes |
buildl log | no phase | what a target printed when it last ran, read from the log and the cas |
clean, gc and plugins fetch are housekeeping around the pipeline rather than cuts of it.
Appendix A has every command and flag.
Not every module of buildl-core is a phase. A few hold what several phases need and may not
copy from one another: placement (where each output lives and what a command's $in and $out
stand for), grants (the wanted set, and which programs a dependency built), history (reading
the log back), discovery (loading the build files twice), suggest (the nearest name to one that
names nothing) and verify.
The core types
Every value that crosses a phase lives in buildl-core, and almost every one is a small type that
is checked when it is made, so an invalid one cannot exist. A Label is never a loose string, and
a path is never just a String. Here are the main ones and how they connect:
%% Core type relationships
classDiagram
class Label {
directory: Directory
name: TargetName
parse(s) Result~Label~
resolve(s, base) Result~Label~
}
class Provenance {
file: PathBuf
directory: Directory
}
class Origin {
<<enumeration>>
BuildFile
Plugins
}
class PluginChain {
Vec~PluginRef~
}
class Declaration {
provenance: Provenance
origin: Origin
item: Declared
}
class Declared {
<<enumeration>>
Target
Rule
Alias
Setting
}
class Target {
label: Label
role: TargetRole
action: Action
inputs: Vec~SourcePath~
deps: Vec~Label~
outputs: Vec~OutputName~
env: Vec~EnvName~
network: NetworkAccess
output_source: OutputSource
freshness: Freshness
}
class Rule {
label: Label
run: Command
description: Option~Description~
}
class Alias {
label: Label
target: Label
}
class Setting {
name: SettingName
default: SettingValue
}
class Node {
label: Label
provenance: Provenance
origin: Origin
narrowing: Vec~PluginRef~
role: TargetRole
run: Command
description: Option~Description~
inputs: Vec~SourcePath~
outputs: Vec~OutputName~
env: Vec~EnvName~
network: NetworkAccess
output_source: OutputSource
freshness: Freshness
}
class TargetGraph {
nodes: Vec~Node~
edges: Vec~Vec~NodeId~~
reverse: Vec~Vec~NodeId~~
by_label: BTreeMap~Label_NodeId~
aliases: BTreeMap~Label_NodeId~
settings: BTreeMap~SettingName_SettingValue~
}
class ActionKey {
digest: Digest
components: KeyComponents
}
class Digest {
sha256: 32_bytes
}
class Plan {
labels: Vec~Label~
verdicts: Vec~Verdict~
wanted: WantedSet
attribution: Attribution
settings: BTreeMap~SettingName_SettingValue~
stale_discovery: Vec~Label~
}
class Verdict {
<<enumeration>>
Clean
Dirty
Conditional
}
class ActionOutcome {
label: Label
role: TargetRole
class: OutcomeClass
diagnostic: Option~Diagnostic~
outputs: Vec~Produced~
stdout: Option~Digest~
stderr: Option~Digest~
}
Declaration --> Provenance
Declaration --> Origin
Origin --> PluginChain
Node --> Origin
Declaration --> Declared
Declared --> Target
Declared --> Rule
Declared --> Alias
Declared --> Setting
Target --> Label
TargetGraph --> Declaration : built from
TargetGraph --> Node
Plan --> Verdict
Verdict --> ActionKey
ActionOutcome --> Digest
A few choices in that picture carry a lot of weight:
Labelis the one name for a target,//dir:name. Every name a build file writes, whether//lib:text,:textortext, becomes an absoluteLabelduring Load. From Resolve on, a target is aNodeId, au32index into the graph. Strings appear only at the edges: when a label is parsed and when it is printed.ActionKeykeeps its pieces. The key is the digest of aKeyComponentsvalue, and the components are kept beside the digest. That is whybuildl plancan say which piece changed, as The Action Key showed: it compares two structs instead of guessing.Digestis SHA-256 everywhere: files, outputs, keys and log blobs. It is the digest the Remote Execution API uses too, so a remote cache is a transport, not a second way of naming things.Provenancetravels, it is never worked out again. It is attached when a declaration is made and carried into the graph, so every error can name the build file behind it.Origintravels the same way, and is never part of a key. It says whether a build file or a chain of plugins made the declaration. The same declaration built the same way has one key whoever wrote it, but an error names the plugin, because whoever reads it needs to know whose code to look at.Attributionexplains the wanted set and is never part of it. For each want it names the plugins whose targets want it, for the approver to show. What an approval remembers is the wanted set alone.
Load
Load turns build files into declarations. A queue of directories drives it, and each build file gets a fresh engine of its own, which is thrown away afterwards, so one file's stray globals can never leak into the next. An engine costs about 128 microseconds to make.
%% Load phase internals
flowchart TD
Q["Directory queue<br/>seeded with the workspace root"] --> ENG["Fresh airsl engine<br/>confined, no grant"]
ENG --> CALLS["buildl module calls<br/>target, rule, subdir"]
CALLS --> STAGE["Staging list<br/>declarations + provenance"]
CALLS -. "subdir(dir) enqueues a directory" .-> Q
The buildl module in buildl-lua stages what a build file declares: each call checks the shape
of its option table straight away, so an unknown field fails on the line that wrote it, and the
values are recorded exactly as written. buildl.subdir stages a request for another directory.
The adapter hands all of it back as one StagedFile. It is buildl-core that attaches the
provenance, checks every value, refuses a directory that escapes the workspace and queues the
rest. Lua never recurses into another directory, and the adapter never sees the queue.
A plugin a build file loads with buildl.use runs inside the same evaluation, in a table of its
own, and the declarations it makes carry its plugin chain as their origin. The results of
discovery targets reach every evaluation as one shared
Discovered value.
Loading in parallel
In a big monorepo the build files are many. Ten thousand of them at about 136 microseconds each is
about 1.4 seconds on one thread, so Load spreads them across the same worker pool that runs
actions, up to [execution] workers at once, each worker with an engine of its own. A directory
is handed out as soon as a result names it, so workers stay busy.
Results come back in whatever order the workers finish in, and that order must never show. So Load does not take its answer from arrival order:
- A serial replay walks the directories in the order a one-thread load would, reading each result when the walk reaches it. It alone decides the declarations and the error.
- The error, if there is one, is the one a serial load would have met first. A shared flag stops new evaluations once the replay meets it.
- The declarations are sorted by directory, then declared name, then the whole declaration, so parallel and serial loads give exactly the same list.
- If the worker pool says it finished, the replay met no error, and a build file is still without
a result, the load fails with
Error::LostBuildFilesand declares nothing.
Load is eager: it reads every build file the subdir calls reach, even when you asked for one
target. A label names its own directory, so loading only what a target needs looks like a small
change, but build settings are global, graph.json and the output-collision check cover the whole
graph, and a build file is read only because some subdir named it. Each of those would have to
change first.
Resolve
Resolve is plain Rust over memory. It turns the declarations into a TargetGraph, after three
checks, each of which names the build file at fault:
- duplicates: two declarations of one label, with both places named (
Error::DuplicateLabel); - unknown references: a dependency, rule or
$opt:setting that nothing declares, with the nearest name offered (Error::UnknownReference,Error::UnknownSetting); - cycles: the whole cycle path, not just the fact of one (
Error::DependencyCycle). The search keeps its own stack instead of recursing, so a very deep graph cannot overflow the call stack.
The graph is a set of arrays indexed by NodeId: nodes, edges (each target's dependencies, in
the order written), reverse (who depends on each target) and by_label. A Node is a target
with its rule filled in, so it holds the command it runs. buildl query walks edges for
deps() and reverse for rdeps(). graph.json is written with labels, never NodeIds, so
adding one target changes only that target's entry in the file.
Plan
Plan decides what each target needs. In order, it:
- fixes the value of every build setting for this run, its default or its
--set, and keeps those values on thePlanso Execute expands commands from exactly what was planned; - places every output and expands every command, so two outputs at one path fail here as
Error::OutputConflict; - holds each plugin's targets to that plugin's caps (
Error::PluginRefused), then every want to the ceiling (Error::Refused). A program a dependency built is no want; - refuses a target that declares a variable the sandbox sets itself (
Error::PinnedEnv); - works out each key: one fingerprint per program, one digest per input through the stat cache, one value per variable, and the platform;
- gives each target a
Verdict.
Verdicts are worked out from the bottom of the graph up. A target whose dependencies are all clean
has a finished key, and it is Clean when that key equals the one its last build recorded, or
Dirty with the pieces that differ. A target with a dependency that is not clean cannot finish its
key, because that dependency's output does not exist yet. It is Dirty if something already known
has changed, and Conditional otherwise: it runs only if the dependency produces something new.
That is early cutoff at plan time.
A plan that wants more than the ceiling or a plugin allows is an error, not a plan. Nothing has run yet.
Execute: the scheduler loop
Execute is a ready queue, a pool of workers and one counter per target:
%% Executor loop
graph TD
RQ["Ready targets<br/>every dependency succeeded"] --> SET{"settle:<br/>key stands, content held?"}
SET -- yes --> PUT["Cached<br/>outputs put back from the cas"]
SET -- no --> WP["Worker pool<br/>N parallel actions"]
WP --> CAS["cas/sha256<br/>outputs by digest"]
CAS --> ROW["Cache row<br/>written after the cas"]
PUT --> LOG["log.jsonl<br/>one event per target"]
ROW --> LOG
LOG --> DC["Dep counters<br/>decrement on finish"]
DC -- "counter hits zero" --> RQ
Every target in the build goes through that loop, clean ones included. When a target's dependencies have all succeeded, it is settled: its key is finished from what its dependencies' rows now hold, and if nothing forces it to run, the key equals the recorded one, and the cas still holds everything needed to put it back, it succeeds as cached without reaching a worker. So a conditional target gets its answer here, and a clean one whose content left the store runs again. A build of cached targets starts no thread at all.
The bookkeeping is one small state machine per target, Schedule in
crates/buildl-core/src/execute/schedule.rs:
%% Target states during execution
stateDiagram-v2
[*] --> Pending : every target, whatever its verdict
Pending --> Started : dep counter hits zero
Started --> Succeeded : cached, or built or fetched and recorded
Started --> Failed : action / infra failure
Started --> Skipped : the build stopped before a worker began it
Pending --> Skipped : upstream failed, or the build stopped
Succeeded --> [*]
Failed --> [*]
Skipped --> [*]
Succeeded covers cached, built, fetched and run on the remote; the outcome's class tells them
apart. Cached and skipped are the two results a plain task runner has no word for, and they are
why the summary can say 1 failed, 2 skipped, 2 built, 9 cached.
The scheduling thread is the only one that writes the counters, so they are plain integers, with
no locks to reason about. The threads themselves sit behind the Dispatcher port, which has one
method, dispatch(work, step):
workruns one task, on any thread, and can send messages back while it runs;stepruns on the calling thread, first withTurn::Begin, then with each message (Turn::Told) and each result (Turn::Done), and returns the tasks that became ready.
The port knows nothing about builds. Its adapter in buildl, ThreadPool, is plain threads and a
std::sync::mpsc channel, started only as tasks need them. Tests drive the same two closures on
one thread.
Some rules of the loop:
- Everything that can refuse a build is decided before the first task goes out. The last
guard holds every expanded command's program to the ceiling once more, and refuses a command that
names no program (
Error::NoProgram). - Workers never touch the terminal. One reporter on the scheduling thread prints everything, and a log event is written before anything is read for display.
- On failure,
buildstops handing out new work by default, and--keep-goingbuilds everything that does not depend on the failure.testkeeps going by default and stops with--stop. Actions already running are never cancelled, and what they produce is kept. - No target goes missing. A dispatcher that says it finished while some target has no outcome
fails the build with
Error::DispatcherFault, naming every such target. What finished before that keeps its blobs, its row and its log line. - Scheduling order cannot leak into results. An action's inputs are declared and in place before it starts, so where it fell in the schedule is invisible to it.
What happens inside one worker, and the order in which it is written down, is the subject of Crash Safety and the Store.
A second Load
A workspace with a discovery target runs Load twice. The first
load evaluates every build file with no results. build and test then run the discovery targets
as a small build of their own, with their own plan, approval and summary, read back what each
printed, and load every build file again with those results. The second load may not declare
different discovery targets than the first (Error::DiscoveryChanged).
Commands that run nothing, such as graph, query and plan, read the last results straight from
the log and the cas instead of running anything. The two passes are drawn out in the
Discovery Targets chapter.
Crash Safety and the Store
Builds get interrupted. Someone presses Ctrl-C, a laptop lid closes, a CI job hits its time limit.
Many build systems answer that with a ritual: "the cache looks corrupt, run a clean build." In
buildl there is no corrupt-cache state to get into, and no clean build to run. This page shows
why, by following one action from start to finish.
One action's life
%% Action lifecycle inside a worker
stateDiagram-v2
[*] --> Expand : take target from queue
Expand : Expand placeholders — workspace-relative paths
Spawn : Spawn process — granted env, no shell
Temp : Outputs written — in place at tier 1, in an exec dir from tier 2
Cas : Hash into cas — what it printed, its files, one manifest per output
Place : Place into out/ — clear the path, then link or copy from the cas
Rec : Record — cache row, then log event
Expand --> Spawn
Spawn --> Temp
Temp --> Cas
Cas --> Place
Place --> Rec
Rec --> [*]
Step by step:
- Expand. The command's
$in,$outand$depsbecome workspace-relative paths, such aslib/a.corout/lib/text. They read the same at every isolation tier, so a command is one text whichever tier runs it, and each tier makes those paths true where the action runs. - Spawn. The program starts directly, never through a shell, with only the variables the target declared. At tier 2, the sandbox, it starts in a directory of its own outside the workspace, holding copies of its declared inputs.
- Outputs written. Before the command starts, the folder each output goes in exists and nothing stands at the output's own path. The command makes what it produces there: a file or a directory.
- Hash into the cas. The worker stores what the action printed, then every regular file it left at each output path, then one manifest per output that lists those files.
- Place into
out/. Back on the scheduling thread, each output's path underout/is cleared and its files are put there from the cas. - Record. The cache row is written, and then the log event. Only after that are the targets that depend on this one released.
Cas first, row after, log always
The order of those last steps is the whole story:
| Write | When | Why there |
|---|---|---|
| cas | first | the content must exist before anything points at it |
| cache row | after the cas | a row is a promise that its content is held, so it is never written early |
| log event | always, last | every outcome is logged, failures and skips included, so the log tells the truth even about a broken build |
The code keeps that order in one file, crates/buildl-core/src/execute/record.rs: store places
the outputs and only then records the row, forget_contradicted removes a row a failure
contradicts, and append writes the log event for every outcome, whatever it is.
So when a build is stopped, at any moment, some finished work is remembered and the unfinished work is not. The next run plans again and carries on. A row never points at content the store does not hold, because the row is written second.
Two more things make that hold on disk:
- Every write is whole. Each blob and each state file is written to a temporary file and renamed into place. A reader finds the old file whole or the new file whole, never half of one.
- Nothing is synced to disk. A rename is enough when the process dies. It is not enough when
the machine dies mid-build, with writes still in memory. The remedy then is to remove
.buildl/andout/and build again. This is a choice, written up in Decision Records.
The same order runs the other way when things are removed. buildl gc forgets rows before it
removes any blob, so a gc that is stopped part way leaves extra blobs, never a row that names a
missing one. And a result fetched from a remote cache takes the same road as
one built here: its blobs are checked and stored in the cas, and only then is its row written.
Storing outputs by content does one more job. A rebuilt output with the same bytes has the same digest, so the keys of everything downstream stay the same, and those targets stay clean. That is early cutoff, and it comes free with the cas.
Failures are never cached
A cache row is written only after a success, so a failed action leaves no row, and the next run
simply tries it again. There is one more case. When a target already has a row under the very key
it just failed under, which happens to a test run again with --rerun and to a target declared
always, the failure forgets that row, and the forgetting is on disk before the failure's log
line is written. A failed rerun never leaves an old pass behind.
So there is no "cached failure" to get stuck on. This is a deliberate break from build systems that remember failures: with declared inputs, a retry costs one action, and a flaky failure is exactly the thing that should be run again rather than remembered.
The store
Everything under .buildl/ follows the rule above. Here is what it holds:
| File | What it holds |
|---|---|
cas/ab/cdef… | every blob by its SHA-256, in folders named by its first two characters |
cache.json, cache.journal | the cache rows: one per target, with its whole key, one digest per output and the digests of what it printed |
log.jsonl | one JSON line per outcome, append-only, with what was printed referred to by digest |
statcache.json | each input's size, modification time and digest, so an unchanged file is not read again |
graph.json | the graph the last build resolved |
A few details of the cas matter for safety:
- Blobs are read-only, mode
0444. A blob that was ever placed as an executable has a twin beside it,cdef….x, holding the same bytes with mode0555. It is the source a runnable output is copied from: the copy has the run bit, and the blob, which a plain output links to, does not. - A read checks its digest. Content that no longer has the digest it is stored under is removed and reported as not held, so a damaged blob is never put back as an output.
- An output is a manifest. It is described by an
OutputManifest: either one file, with its digest and whether it may be run, or a tree, a directory's files in path order. The manifest is itself a blob, and its digest is the output's digest. That is how the executable bit and every file of a directory reach a dependent's key. - Outputs are put back whole or not at all. Placing an output starts by clearing its path, so
nothing an earlier build left there survives. If a file cannot be placed, the path is cleared
again and the target fails, so
out/holds an output whole or not at all. out/holds copies of every file that may be run, programs and the shared libraries that carry the run bit, on every system. A program that finds its libraries next to itself (@loader_pathon macOS) must be found under its name inout/, and a hard link to the twin can be found under the twin's name in the cas instead, where those libraries are not. Any other file is a hard link into the cas where that protects the store, and a copy everywhere else. On a filesystem where a read-only file can still be written through, as root for example, every placement is a copy.
The action cache writes one line to cache.journal for each row, because rewriting the whole of
cache.json for every target would grow with the square of the build. The journal is folded into
cache.json once a build returns. A journal an interrupted run left behind is folded the next time
the cache is opened, with a cut-off last line left out. So cache.json holds the same bytes
whatever order the workers finished in.
Output capture
Each action's standard output and standard error are captured through pipes, separately. Two reader
threads per action pass what they read to the worker, which alone touches the process. The worker
also enforces the timeout: it watches a deadline on the monotonic clock and kills the process when
the deadline passes. Once the process is gone, anything it started that still holds a pipe gets one
more second (DRAIN in crates/buildl/src/exec/capture.rs), and the action ends with what arrived.
What was printed goes into the cas, and the log event refers to it by digest. That keeps large
output out of the JSON, and it means a cache hit can show the warnings from when the action really
ran, instead of losing them on every incremental build. It is also what
buildl log reads back.
On screen, each action's output is printed as one block under a header naming the target, when it
finishes, never mixed with another action's. A terminal gets a live status line; a pipe or CI gets
plain blocks in order. With --stream, one running action at a time is shown as it prints, and
what is stored is exactly what a quiet build stores. Everything a build says about itself goes to
standard error; standard output carries only what a command was asked for, such as the graph from
graph or the plan from plan.
Failure semantics
Every failure falls into one of three classes, told apart by structure (an exit status, a timeout, where a refusal came from), never by reading message text:
| Class | Means | Examples |
|---|---|---|
| Action failure | the build did its job by revealing a problem | a compile error, a failing test, a command killed by a signal, an output left missing or as something that cannot be kept |
| Infrastructure failure | the builder is sick | a missing tool, a sandbox error, a timeout |
| Policy refusal | the build wants more than it may have | a program outside the ceiling, a want a plugin does not allow, an approver's no |
A policy refusal always comes before anything runs: it is an error of the whole build, never the result of one action. Each class has its own exit code, so CI can tell "fix your code" from "fix your builder" without parsing text; Appendix D lists them, and Errors shows how they are built.
An action that exits zero has still failed when an output it declares is missing, or is something
buildl cannot keep. An output holds regular files only, because only those can be put back
exactly. Four things are refused:
| Refused | Where |
|---|---|
| a symbolic link | at the output's path, or anywhere below it |
| a device, a socket or a named pipe | at the output's path, or anywhere below it |
| an empty directory | the output itself, or a directory inside it |
| a name that is not valid Unicode | anywhere below the output's path |
Such an output is refused, not stored as something close to it, and no row is written. A tool that
must leave a tree like that can be given a stamp file to declare instead. A target whose output is
its standard output (stdout = true) turns the check around: it fails when anything at all stands
at its output path, because the command was meant to print the output, not write it.
A failure never cancels actions that are already running; their results land in the cas and are
kept. Targets downstream of a failure are skipped, and counted apart from failed ones, since they
were never tried: 1 failed, 2 skipped, 2 built. The failure report names the target, the build
file that declared it, the command as it ran, what it printed on standard error, and its class, and
the same is written to log.jsonl for tools to read.
Five Crates, Ports and Adapters
buildl is five Rust crates, split so that the logic of a build depends only on abstractions it
owns. Everything that touches the outside world, the airsl engine, the filesystem, child
processes, threads, the clock, plugs into that logic from the outside. Two of the five are
binaries: buildl-cli, the buildl command, and buildl-cargo, the cargo buildl command.
buildl/
Cargo.toml # workspace: resolver 3, shared lints (airsl's lint set)
crates/
buildl-core/ # domain data, ports (traits), pure logic of every phase: no I/O, no Lua
buildl-lua/ # DeclarationSource over airsl: engine per file, the buildl HostModule
buildl/ # every other adapter + LocalPorts + the command line: the composition root
buildl-cli/ # the `buildl` binary: `main` alone, which calls buildl::cli::run
buildl-cargo/ # the `cargo-buildl` binary, run as `cargo buildl`: buildl's commands from cargo
The workspace shares airsl's policy: unsafe_code = "forbid", unwrap_used and panic denied,
Clippy's pedantic and nursery groups at warn, and a comment in the workspace Cargo.toml giving
the reason for every dependency.
The five crates
Every dependency points at buildl-core, and buildl is the one crate that names concrete
adapters together. The two binaries are thin: each depends on buildl and on nothing else of
buildl's:
%% Crate dependency graph — arrows point at the dependency
graph TD
CLI["buildl-cli<br/>main"] --> LIB["buildl<br/>adapters + command line + composition root"]
CARGO["buildl-cargo<br/>cargo-buildl"] --> LIB
LIB --> LUA["buildl-lua<br/>DeclarationSource via airsl"]
LIB --> CORE["buildl-core<br/>domain data · ports · pure logic"]
LUA --> CORE
LUA --> AIRSL["airsl<br/>Engine, Policy, HostModule"]
Two rules are built into that picture:
- airsl is a dependency of
buildl-luaonly. No other crate knows Lua exists, andbuildl-corecannot name airsl at all, because airsl is not among its dependencies. The whole boundary with the runtime is one crate deep. That keeps the execution side testable without a Lua state, and keeps an airsl upgrade from spreading. - Phases talk through values, not calls. Load hands on
Vec<Declaration>, Resolve aTargetGraph, Plan aPlan, ExecuteVec<ActionOutcome>, as Declare, Then Execute showed. The pipeline inbuildl-coreowns the order, and no phase calls the next.
Dependency inversion
The logic of a build, loading, resolving, planning, scheduling and recording, depends only on abstractions it defines itself. The concrete implementations depend on those abstractions, and exactly one place picks which implementations run together. This is Robert C. Martin's Dependency Inversion Principle. The abstractions are ports and the implementations are adapters, in Alistair Cockburn's hexagonal architecture:
%% Dependency direction — arrows point at the dependency
graph TD
ROOT["buildl<br/>composition root: LocalPorts"] --> LOGIC["buildl-core<br/>pure logic of every phase"]
ROOT --> ADAPT["adapters in buildl and buildl-lua<br/>airsl engine · filesystem · processes · threads · clock"]
LOGIC --> PORTS["buildl-core<br/>ports — traits"]
ADAPT --> PORTS
ADAPT --> AIRSL["airsl"]
BINS["buildl-cli and buildl-cargo<br/>the two binaries"] --> ROOT
The structure exists for one result: every flow of the pipeline runs in buildl-core's tests
against fake ports, with no Lua state, no filesystem, no process and no thread.
Testing Layers shows how.
What buildl-core may depend on
Dependency inversion is aimed at I/O and at parts that change often. A stable library doing pure computation is not the implementation of a port, so the core may use one directly:
buildl-core may depend on | buildl-core must not depend on |
|---|---|
std, excluding its I/O, process, thread, environment, and clock APIs | airsl, mlua, toml, clap |
serde, serde_json | std::fs, std::process, std::thread, std::env, SystemTime |
thiserror | rayon, tempfile, walkdir, globset |
sha2 | any other buildl crate |
The table is the rule. crates/buildl-core/clippy.toml spells it out: 129 entries across
disallowed-methods, disallowed-types and disallowed-macros, split into nine families:
| Family | Entries | Note |
|---|---|---|
| the filesystem | 41 | counting the nine Path methods that reach it |
| the environment | 23 | including the compile-time reads and the two PATH-format helpers |
| threads | 20 | |
| processes | 14 | std::process::ExitCode is unbanned: rustc's generated test harness names it through libtest's re-export, which clippy 1.100 flags with a spanless error on every test target (see the decision record) |
| the platform filesystem extensions | 13 | |
| the standard streams | 10 | including the print macros |
| the clock | 3 | |
| the network | 3 | |
| floating-point numbers | 2 | not an I/O surface at all |
The nine counts add up to the 129, so the families cover the whole file. A float is banned
because a non-finite one is written to JSON as null, so a value could reach an action key that
differs from the value it was computed from (Determinism Rules,
rule 2). cargo make guard-core-purity checks that every entry still names something real, that
no source file switches the lints off, and that the file itself is not switched off.
The name buildl
Three different things are called buildl, and the crates keep them apart:
| Name | What it is | Lives in |
|---|---|---|
buildl binary | the command users run | buildl-cli ([[bin]] name = "buildl"), whose main calls buildl::cli::run |
buildl Lua global | the declaration framework build authors call | buildl-lua (the buildl HostModule) |
buildl Rust crate | the complete framework: every real adapter wired onto buildl-core | crates/buildl |
The fifth crate has a name of its own. buildl-cargo holds the cargo-buildl binary, which cargo
runs as cargo buildl. It runs every command through buildl::cli::execute, so a command given
to cargo buildl takes the buildl binary's flags and gives its output and exit codes.
The C4 views
The rest of the structure is drawn as the four levels of Simon Brown's C4 model: the system in its surroundings, then its running parts, then the components inside the process, then the code.
Level 1: system context
%% C4 level 1 — system context
graph TD
AUTHOR["[Person]<br/>Build author<br/>writes build.lua, runs buildl"]
CI["[Person]<br/>CI pipeline<br/>runs build and plan, reads the exit class"]
BUILDL["[Software system]<br/>buildl<br/>sandboxed, deterministic build system:<br/>Lua declares, Rust executes"]
WS["[External system]<br/>Workspace filesystem<br/>sources, out/"]
TOOLS["[External system]<br/>Toolchains<br/>go, cargo, bun, docker"]
REMOTE["[External system]<br/>Remote cache and executor — REAPI over gRPC<br/>results shared between machines, actions run there"]
GIT["[External system]<br/>Plugin repositories<br/>read by buildl plugins fetch"]
AUTHOR -->|"writes build files, invokes commands"| BUILDL
CI -->|"invokes build and plan"| BUILDL
BUILDL -->|"reads, writes"| WS
BUILDL -->|"spawns, no shell"| TOOLS
BUILDL -->|"looks results up, stores them and sends actions when asked"| REMOTE
BUILDL -->|"fetches a pinned revision, through the system git"| GIT
Level 2: containers
A C4 container is a separately running process or a place data is kept. The crates are not
containers: they compile into the two binaries, buildl and cargo-buildl, which run the same
pipeline, and appear at level 3.
%% C4 level 2 — containers
graph TD
subgraph SYS["buildl — system boundary"]
CLIP["[Container: Rust binary]<br/>buildl CLI process<br/>Load → Resolve → Plan → Execute → Record"]
CARGOP["[Container: Rust binary]<br/>cargo-buildl process<br/>the same pipeline, started as cargo buildl"]
DEFS["[Data]<br/>Build definitions<br/>buildl.toml, buildl.lock, build.lua, plugins"]
STATE["[Data store]<br/>.buildl/<br/>cas/, cache.json, cache.journal,<br/>log.jsonl, statcache.json,<br/>graph.json, lock, plugins/"]
OUT["[Data store]<br/>out/<br/>hard links and copies from the cas"]
end
CHILD["[Container]<br/>Child processes<br/>one toolchain invocation per action"]
CARGOP -->|"reads"| DEFS
CARGOP -->|"the same state as the CLI process"| STATE
CARGOP -->|"links named outputs"| OUT
CARGOP -->|"spawns argv with granted env"| CHILD
CLIP -->|"reads"| DEFS
CLIP -->|"cas first, row after, log always"| STATE
CLIP -->|"links named outputs"| OUT
CLIP -->|"spawns argv with granted env"| CHILD
Level 3: components
Inside the process, every adapter depends on buildl-core, and the one edge between adapter
crates is buildl → buildl-lua, which only the composition root may hold. buildl-cargo is the
second binary and calls buildl as buildl-cli does:
%% C4 level 3 — components inside the CLI process
graph TD
CLI["[Component: crate] buildl-cli<br/>main: reads the process,<br/>calls buildl::cli::run"]
CARGO["[Component: crate] buildl-cargo<br/>main: reads the process,<br/>calls buildl::cli::execute"]
LIB["[Component: crate] buildl — composition root<br/>command line: cli — clap argument surface,<br/>outcome classes and error variants to exit codes<br/>adapters: manifest, host, digest, tools,<br/>cas, cache, log, statcache, graph,<br/>exec, dispatch, clock, report, approver, remote, watch,<br/>ignore_rules<br/>no port: plugins — lock, check, fetch<br/>shared: state, search_path<br/>assembly: LocalPorts, Workspace facade"]
LUA["[Component: crate] buildl-lua<br/>implements DeclarationSource<br/>airsl Engine per build file<br/>buildl HostModule bound as a global<br/>buildl.use: one plugin instance per chain"]
subgraph CORE["[Component: crate] buildl-core — no I/O, no Lua, no threads"]
DATA["domain data<br/>Label, Digest, NodeId, Provenance<br/>Declaration, Origin, Discovered<br/>TargetGraph, Plan, Attribution<br/>KeyComponents, ActionKey<br/>RemoteAction, RemoteHit, RemoteUpload<br/>ChangedPath, ChangeBatch, Trigger<br/>WatchLayout, Built, Reference, Reaction<br/>Watched, Cycle<br/>ActionOutcome, OutcomeClass"]
PORTS["ports — traits<br/>DeclarationSource, Manifest, Host<br/>Digester, StatCache, ToolResolver<br/>ContentStore, ActionCache, EventLog<br/>RunHistory, Sweep, ExecStrategy, Dispatcher<br/>Clock, GraphRecord, Reporter<br/>Approver, RemoteCache, IgnoreRules<br/>Changes, Cycles, WatchReport"]
LOGIC["pure logic<br/>load, resolve, placement, plan, grants<br/>discovery, Schedule, record, verify<br/>react, watch, watched_inputs<br/>canonical JSON"]
end
AIRSL["[External crate] airsl<br/>Engine, Policy, HostModule"]
CLI -->|"calls"| LIB
CARGO -->|"calls"| LIB
LIB -->|"wires"| LUA
LIB -->|"implements"| PORTS
LIB -->|"wires into Pipeline"| LOGIC
LUA -->|"implements"| PORTS
LUA -->|"evaluates with"| AIRSL
LOGIC --> PORTS
LOGIC --> DATA
PORTS --> DATA
| Crate | Role | Depends on | Must not depend on |
|---|---|---|---|
buildl-core | domain data, ports, the pure logic of every phase | serde, serde_json, thiserror, sha2 | any buildl crate, airsl, any I/O API |
buildl-lua | the DeclarationSource adapter: evaluates one build file through airsl, and loads the plugins it uses | buildl-core, airsl, globset, walkdir, serde, serde_json, toml | buildl |
buildl | every other adapter; the plugins module; LocalPorts; the Workspace facade; the command line, in cli; re-exports buildl-core as buildl::buildl_core | buildl-core, buildl-lua, clap, toml, toml_edit, rayon, serde, thiserror, tempfile, tonic, tonic-prost, prost, prost-types, tokio, uuid, notify, ignore | nothing: it is the composition root |
buildl-cli | main alone: reads the process and calls buildl::cli::run | buildl | buildl-core and buildl-lua directly |
buildl-cargo | the cargo-buildl binary, run as cargo buildl: reads the process, calls buildl::cli::execute, and runs cargo buildl sync itself (reads cargo metadata, rewrites the generated section of build.lua) | buildl, clap, serde, serde_json; tempfile as a dev dependency only | buildl-core and buildl-lua directly: it reaches core types through buildl, as in buildl::buildl_core::TargetName |
crates/expected-edges.txt holds that list as the gate checks it. Each adapter dependency has a
reason: toml reads buildl.toml, and toml_edit points at the place in it where a [remote]
table is refused, since toml keeps no positions; in buildl-lua, toml reads the
env.unkeyed list of a plugin's extension.toml, a key airsl's manifest parser refuses; rayon hashes files, in the Digester adapter
and nowhere else; tempfile gives the write-then-rename every state file and blob goes through.
The remote cache's gRPC client is tonic, with tonic-prost, prost and prost-types for its
messages, tokio for the runtime the client needs, and uuid to name uploads. Only the remote
module names them. notify reports the operating system's file events to the watch module and
to no other. ignore matches the patterns of .buildlignore files, in the ignore_rules module and
nowhere else; buildl-lua does not depend on it, and reaches the rules through the core's port. In
buildl-cargo, serde and serde_json read the output of cargo metadata.
Inside buildl there is one module per adapter, plus plugins, which serves no port but is kept
apart as an adapter is, two shared modules and three that put everything together:
| Module | Holds | Implements |
|---|---|---|
manifest | buildl.toml, finding the workspace root, and the [plugins.<name>] tables | Manifest |
host | the operating system, the processor, environment values | Host |
digest | what stands at an input's path, and file hashing on rayon | Digester |
tools | a program's lookup and its fingerprint | ToolResolver |
cas | .buildl/cas, and the files placed under out/; listed and pruned through Sweep | ContentStore and Sweep |
cache | cache.json and cache.journal | ActionCache |
log | log.jsonl, appended to and read back | EventLog and RunHistory |
statcache | statcache.json | StatCache |
graph | graph.json | GraphRecord |
exec | tier 1, Bare; tier 2, InputSandbox; and Local, which picks between them from the manifest | ExecStrategy |
dispatch | worker threads for Load and Execute | Dispatcher |
clock | the system clock | Clock |
report | terminal output, and every rendering of a value into text | Reporter and WatchReport |
approver | the three approvers a manifest can name, LocalApprover, which picks one, and the approvals it remembers outside the workspace | Approver |
remote | the Remote Execution API client: its tokio runtime, the gRPC channel, blob transfer, Execute and WaitExecution, the retry rule; behind the test-server feature, an in-memory server for tests | RemoteCache |
watch | the workspace's file events through notify, gathered into batches by a 50 ms window | Changes |
ignore_rules | the .buildlignore files of one workspace, read from the root down, and the decision for a path | IgnoreRules |
plugins | buildl.lock, the digest of a plugin's files, the check that every plugin is there and unchanged, and fetching git plugins | none |
state | shared: where each state file is, the state lock, writing a file whole, clearing a path, the sandbox's scratch directory | none |
search_path | shared: the lookup of a program name | none |
local_ports | composition: the Ports bundle and its wiring | none |
workspace | composition: the Workspace facade, and the Cycles of buildl watch | none |
cli | composition: the buildl command line, its argument surface through clap, each command's flow, and the mapping of outcome classes and errors to exit codes | none |
The DeclarationSource adapter is buildl_lua::LuaSource. buildl, buildl-cli and
buildl-cargo build on Unix only; Linux and macOS are the supported platforms, the two the CI matrix runs.
Level 4: the code of buildl-core
Domain data
Every value is a checked newtype or a handoff that can be written out:
| Kind | Types |
|---|---|
| Names and identity | Directory, TargetName, Label, NodeId, Provenance |
| Content | Digest, the single SHA-256 type for files, outputs, keys and log blobs; Hasher, the same digest over bytes handed over in pieces |
| Outputs | OutputManifest, with StoredFile and FileMode, Tree, TreeEntry and TreePath; Found, FoundEntry and FoundKind, what a strategy reports at an output path |
| Time | Timestamp, nanoseconds since the Unix epoch, read only through the Clock port |
| Phase handoffs | Declaration, TargetGraph, Plan, ActionOutcome |
| Execution handoffs | OutputPath, ReadyAction with its ExpandedDescription, RawOutcome and Exit, OutcomeEvent, OnFailure, Summary |
| Incrementality | KeyComponents, ActionKey |
| Authority | Ceiling, WantedSet, Want, Workspace, Approval, DenialReason, ApproverMode, Attribution, Checkup |
| Plugins | PluginName, PluginVersion, PluginRef, PluginChain, Origin, PluginCap, PluginNetwork, PluginViolation, PluginSource, GitUrl, Rev, TagName, CommitId |
| Discovery | Discovered, Loaded, TargetRole::Discovery |
| Remote cache | RemoteSettings, RemoteAction, RemoteHit, RemoteUpload, Uploaded, Blob, RemotePolicy, RemoteUse, RemoteFailure, RemoteExecution, Executed, RemoteSwitch, RemoteCall, RemoteNotice, and the smaller values they are made of |
| Ignored paths | EntryKind, a path as its asker knows it: file, folder or unknown; Ignoring, the ignore file and the pattern that decided; IgnoredPath, the inputs file or subdir folder an error names |
| Watch mode | ChangedPath, ChangeBatch, Trigger, WatchLayout, Built, Reference, Reaction, Watched, Cycle |
| Execution settings | Execution, with Workers, Timeout and Isolation; none of them is part of a key |
| A run and what it shows | Scope, Purpose, Rerun, LiveOutput, Channel, LiveSink, Captured, Turn |
| Inputs | InputStat and InputKind: nothing, a regular file, or something else at an input's path |
| The log, read back | LogLine, LoggedRun |
| A verify and what it found | Sample, Check, OutputDifference, FileChange, EntryChange, Verification |
| Classification | OutcomeClass, InfraKind, OutputRefusal, TreeFault |
Ports
A port is a trait in crates/buildl-core/src/ports/. Every fallible method returns the crate's one
Result, whose error is the single buildl_core::Error enum described in
Errors. Two of them show the shape:
#![allow(unused)] fn main() { /// Evaluates one build file. The directory queue, `subdir` handling, and the /// sorted merge across files are Load logic in `buildl-core`, not the adapter's. pub trait DeclarationSource: Sync { fn evaluate(&self, file: &BuildFile, discovered: &Discovered) -> Result<Evaluated>; } /// The scheduler side is the single writer. A row is durable once `record` returns /// `Ok`; after `Err` the cache holds what it held before the call. pub trait ActionCache { fn row(&self, label: &Label) -> Option<&CacheRow>; fn labels(&self) -> Vec<Label>; fn record(&mut self, label: Label, row: CacheRow) -> Result<()>; fn forget(&mut self, label: &Label) -> Result<()>; } }
The full list is the port catalog below.
Pipeline and the Ports bundle
buildl uses static dispatch throughout. One trait of associated types carries every port, so
Pipeline takes a single type parameter instead of one per port. The trait lives in
crates/buildl-core/src/ports/bundle.rs, beside the traits it names:
#![allow(unused)] fn main() { pub trait Ports { type Source: DeclarationSource; type Manifest: Manifest; type Host: Host; type Digester: Digester; type StatCache: StatCache; type Tools: ToolResolver; type Cache: ActionCache; type Cas: ContentStore; type Log: EventLog + RunHistory; // plan, verify and build read discovery results from it type Strategy: ExecStrategy; type Dispatcher: Dispatcher; type Clock: Clock + Sync; // a worker reads the clock type Graph: GraphRecord; type Reporter: Reporter; type Approver: Approver; type Ignore: IgnoreRules; // Load asks it, from several threads type Remote: RemoteCache; // NoRemote when there is none } pub struct PortSet<P: Ports> { pub source: P::Source, pub manifest: P::Manifest, /* ... */ } pub struct Pipeline<P: Ports> { /* ports: PortSet<P> */ } // in `buildl`: generic over the reporter and the console a build is lent pub struct LocalPorts<R, C>(PhantomData<fn() -> (R, C)>); pub type LocalPipeline<R, C> = Pipeline<LocalPorts<R, C>>; }
%% C4 level 4 — the Ports bundle and its two implementations
classDiagram
class Pipeline~P~ {
check()
graph()
query()
plan()
build()
build_watched()
test()
verify()
}
class Ports {
<<trait>>
Source: DeclarationSource
Manifest: Manifest
Host: Host
Digester: Digester
StatCache: StatCache
Tools: ToolResolver
Cas: ContentStore
Cache: ActionCache
Log: EventLog + RunHistory
Strategy: ExecStrategy
Dispatcher: Dispatcher
Clock: Clock + Sync
Graph: GraphRecord
Reporter: Reporter
Approver: Approver
Ignore: IgnoreRules
Remote: RemoteCache
}
class LocalPorts {
crate buildl
real adapters
generic over R and C, the reporter and console of one build
}
class FakePorts {
crate buildl-core, tests only
in-memory fakes
}
Pipeline --> Ports : generic over
LocalPorts ..|> Ports
FakePorts ..|> Ports
Ports::Remote is called only by build and test. Every other command, a workspace with no
[remote] table and a run with the remote turned off hold a cache that is never asked: NoRemote
in the core's tests, Remote::Off in LocalPorts. Ports::Ignore has a default of the same kind,
NothingIgnored, which the core's tests bind and the watch loop passes to react. Ports::Log is
bound by both EventLog and RunHistory, because plan, verify, build and test read the
last result of each discovery target from the log they append to. The two stay separate traits,
since a writer and a reader never share a method. Ports::Ignore is asked by Load for each
inputs entry and each subdir, in both discovery passes. local_ports makes one BuildlIgnore
for each opening of the workspace and hands it both to Ports::Ignore and to LuaSource, whose
walk asks it about every entry and never enters an ignored folder. buildl watch opens the
workspace again on every cycle. Each file is read lazily and kept by that instance, so a changed
.buildlignore applies at the latest from the next open. Reopening keeps the rules of the last
workspace it opened and returns them through Cycles::rules.
Commands that need only a few ports are also free functions, beside the Pipeline methods. The
free functions need no state directory and take no lock: pipeline::check, pipeline::graph and pipeline::query
over a DeclarationSource, a Dispatcher, a RunHistory and a ContentStore; pipeline::doctor
with a Manifest as well; pipeline::log over just RunHistory and ContentStore; and
pipeline::gc, which adds an ActionCache and a Sweep.
Pure logic
| Logic | Input → output | Ports used |
|---|---|---|
| load | workspace root and a Discovered → Vec<Declaration>; an inputs entry or a subdir the rules ignore is Error::Ignored | DeclarationSource, IgnoreRules, Dispatcher |
| discovery | the build files, the log and the cas → declarations loaded twice, the second time with the discovery results | DeclarationSource, IgnoreRules, Dispatcher, RunHistory, ContentStore |
| resolve | Vec<Declaration> → TargetGraph | none |
| narrow | TargetGraph, a Scope and a Purpose → the graph of what a run asked for | none |
| reach | TargetGraph and a Query → the targets deps() or rdeps() reaches | none |
| plan | TargetGraph, setting overrides and a Rerun → Plan | Manifest, Host, Digester, StatCache, ToolResolver, ActionCache |
| grants | a plan's WantedSet and Attribution → go on, or Error::NotApproved; also what plugins do not allow, and which programs a dependency built | Approver |
| execute | the graph, the narrowed graph, its Plan and the run's choices → Vec<ActionOutcome> | Manifest, Dispatcher, ExecStrategy, ContentStore, ActionCache, EventLog, Clock, Reporter, RemoteCache |
| last_run | the log's lines and a Label → the newest run of that label that stored its output | none |
| verify | the graph, the narrowed graph, its Plan and a Sample → Verification | Manifest, ActionCache, ContentStore, ExecStrategy, Dispatcher, Clock |
| react | a ChangeBatch, a Reference and, when there are any, the ignore rules → a Reaction: build, check the build files, or nothing | IgnoreRules |
| watched_inputs | the graph and the narrowed graph → the files a build reads | none |
| watch | a WatchLayout → the error that ended it | Changes, Cycles (which hands back the rules of the last workspace it opened), WatchReport |
| canonical JSON | value → sorted-key bytes, and those bytes, and no others, → the value | none |
The port catalog
"Milestone" is the step of the roadmap the adapter arrived with: 1 is the core build, 2 the rest of
the everyday commands, 3 the sandbox, 4 approvers, 6 the remote cache and 7 watch mode. Plugins and
discovery targets (5) and remote execution (8) added no port of their own. IgnoreRules came with
.buildlignore, outside any milestone, so its row has a dash.
| Port | buildl-core uses it for | Adapter | Crate | Milestone |
|---|---|---|---|---|
DeclarationSource | Load: one build file per call, several calls at once, each with the discovery results | LuaSource: an airsl engine per file, with the plugins it uses loaded into the same evaluation | buildl-lua | 1 |
Manifest | the ceiling, the output and state directories, the execution settings and each plugin's cap | the buildl.toml reader | buildl | 1 |
Host | the platform in every key, and the values of the variables targets read | the running machine | buildl | 1 |
Digester | what stands at each input's path, and its content hash | the filesystem, with rayon, each file streamed in pieces | buildl | 1 |
StatCache | reusing a digest when size and modification time are unchanged | .buildl/statcache.json; keeps only files changed more than 2 s before the run began | buildl | 1 |
ToolResolver | the fingerprint of each program, in the key | a PATH lookup and a content hash | buildl | 1 |
ContentStore | the cas: storing a blob, asking for one, reading one back, clearing an output's path and placing a blob there | LocalCas: .buildl/cas/ab/…, read-only blobs, hard links or copies into out/ (copies only, for a file that may be run) | buildl | 1 |
ActionCache | reading, listing, recording and forgetting cache rows, each durable on return | .buildl/cache.json and .buildl/cache.journal | buildl | 1 |
EventLog | one event per outcome | .buildl/log.jsonl, appended to | buildl | 1 |
RunHistory | the log's lines, oldest first, each an event or a damaged line | .buildl/log.jsonl, read only | buildl | 2 |
Sweep | listing what the cas holds and removing a blob; kept out of Ports, so a build cannot remove what it stored | the same .buildl/cas | buildl | 2 |
ExecStrategy | running one action and reporting, and storing, what it left at each output path | Bare, tier 1 | buildl | 1 |
ExecStrategy | the same, in a directory of its own outside the workspace, with TZ, LC_ALL and SOURCE_DATE_EPOCH pinned | InputSandbox, tier 2, the default; Local picks Bare, InputSandbox or a refusal | buildl | 3 |
Dispatcher | evaluating build files and running actions in parallel, and carrying a running action's messages back | ThreadPool: scoped threads and mpsc, up to [execution] workers | buildl | 1 |
Approver | whether a build whose wants are inside the ceiling may run | LocalApprover: ManifestApprover, DenyApprover or InteractiveApprover | buildl | 4 |
RemoteCache | results shared between machines, and actions the server runs; every answer checked by the core, never trusted | Remote: a gRPC client over the Remote Execution API, its tokio runtime reached through block_on | buildl | 6 |
Clock | log timestamps and durations | the system clock | buildl | 1 |
GraphRecord | keeping the graph a build resolved | .buildl/graph.json, written whole | buildl | 1 |
Reporter | output blocks, the status line, the summary and notices about the remote | the terminal reporter, with a live and a plain mode | buildl | 1 |
IgnoreRules | Load: is an inputs entry or a subdir ignored; watch: is a changed path ignored; the walk behind buildl.sources asks it too, through the buildl-lua adapter | BuildlIgnore: the .buildlignore files, read from the root down through the ignore crate's pattern matcher | buildl | — |
Changes | waiting for files of the workspace to change | NotifyChanges: notify, relative paths, a 50 ms window | buildl | 7 |
Cycles | one watch cycle: the workspace opened again and built, or loaded; it also carries type Ignore and rules(), the rules of the last workspace opened | Reopening, in workspace/watching.rs | buildl | 7 |
WatchReport | what a watch says about itself | the terminal reporter's watch: lines | buildl | 7 |
One more trait sits beside them: BlobSource, which an upload to the remote reads blobs through,
because the remote adapter may not import the local content store.
The Clock port is how the wall clock is kept out of the core
(Determinism Rules, rule 4). The crate boundary alone does not
enforce it, since std::time is open to every crate, so crates/buildl-core/clippy.toml bans
Instant, SystemTime and SystemTimeError by name.
Dependency rules
buildl-coredepends on no buildl crate, no airsl, and no I/O API (see Whatbuildl-coremay depend on).- Adapters depend on
buildl-core.buildl-luanever depends onbuildl; insidebuildl, adapter modules never import each other. What several adapters need lives in two shared modules,stateandsearch_path, which implement no port and name no module of the crate; adapters meet only in the three composition modules,local_ports,workspaceandcli.plugins, which implements no port, is held to the same rule: it namesstateandsearch_path,local_portscalls itscheckandworkspaceitsfetch, and themanifestadapter, which reads which plugins a workspace names, shares with it values inbuildl-coreand no code. buildlis the single composition root: the only adapter crate that depends on another adapter crate (buildl-lua), and the only code that names more than one concrete adapter, throughLocalPorts. This is dependency inversion applied, not broken: the principle constrains the logic, and a composition root is where concrete choices are made.- The command line reaches core types through
buildl, where it lives. It is theclimodule ofbuildl, so it names core types throughbuildl's re-exports, and both binaries havebuildlas their one buildl dependency:buildl-cli, which holdsmainalone, andbuildl-cargo, which names a core type asbuildl::buildl_core::TargetName. Neither depends onbuildl-coreorbuildl-luadirectly. - The remote cache's gRPC client, its protobuf messages and its async runtime are the
remotemodule's, inbuildl.tonic,prostanduuidhavebuildlas the one crate that may depend on them, beside their own companion crates;tokiois not banned by name, andguard-crate-edgeskeeps every other member off it. Nothing outside the module names tokio, and the runtime is reached throughblock_on, sobuildl-core, theDispatcherand every other adapter stay synchronous (Decision Records).deny.tomlholds the crate edge; that no other module ofbuildlnames them is the module layout's doing, as it is forrayonindigest.
| Rule | Enforced by |
|---|---|
| the dependency half of 1, rules 4 and 5, and the cross-crate half of 2 | deny.toml's [bans] lists, which name the only direct parents a crate may have, plus cargo make guard-crate-edges, which compares every member's direct dependencies with crates/expected-edges.txt. The compiler alone stops a crate using what its [dependencies] leave out, but not a dependency being added or removed |
| the "no I/O API" half of 1 | crates/buildl-core/clippy.toml, the enumerated ban on the filesystem, process, thread, network, environment, standard-stream and clock APIs, checked by cargo make guard-core-purity |
no phase module of buildl-core names another | crates/expected-module-edges.txt, the committed list of buildl-core's module-to-module imports, compared by cargo make guard-module-edges. Import forms the list cannot read, such as a grouped crate::{…}, are refused outright |
adapter isolation inside buildl | cargo make guard-adapter-isolation, which reads every file under crates/buildl/src but lib.rs, test code included: an adapter module may name crate::state and crate::search_path and no other module, the two shared modules name none, and only local_ports, workspace and cli name any module they like |
Publishing
buildl-cli and buildl-cargo are published to crates.io, and crates.io takes a crate only when
its dependencies are published too, so all five crates are published, the one depended on first:
%% crates.io publish order
graph LR
P1["1: buildl-core"] --> P2["2: buildl-lua"] --> P3["3: buildl"] --> P4["4: buildl-cli"] --> P5["5: buildl-cargo"]
Only buildl-cli is shipped as a prebuilt binary, through cargo-dist. buildl-cargo sets
dist = false, so it comes through crates.io alone, with cargo install --locked buildl-cargo.
| Requirement | Form |
|---|---|
| internal dependencies | buildl-core = { version = "…", path = "crates/buildl-core" } in [workspace.dependencies]; packaging keeps the version and drops the path |
| version sync | each workspace dependency's version matches the crate's own version |
| metadata | description and readme per crate; license and repository from the workspace |
crate README.md | written for crates.io readers of that crate |
Four rules keep publishing possible, and every change to the workspace follows them:
- Every dependency between members is
{ workspace = true }, and no member depends, dev dependencies included, on a member later in the publish order:cargo packagefails on one, and a dev dependency given by path alone is silently dropped from the packaged manifest. - The workspace has the five members and no sixth (the generator of the Remote Execution API
types,
tools/reapi-codegen, sits outside it), andbuildlgains no[[bin]]or[[example]]for the sake of tests. Its one feature,test-server, builds the in-memory server the remote cache's tests talk to. It is off by default and turned on bybuildl-clionly as a dev dependency, so the shipped binary does not hold the server. - Fixtures and golden files live inside the package whose tests read them, reached through
CARGO_MANIFEST_DIRorinclude_str!; no test reads another package's directory. - No fixture path holds a component named
targetordebug.
Once published, the ports are a promise to anyone who writes an adapter:
| Concern | Rule |
|---|---|
| sealed or open | open: adapters live in other crates, and a sealed trait cannot be implemented outside its own crate |
| growing a port | new methods get default bodies; a required method breaks every implementor |
| growing data | #[non_exhaustive] on enums and structs expected to gain variants or fields |
| version line | 0.x until the port surface settles |
Errors
A build can go wrong in two different ways, and buildl keeps them apart.
- A target fails. Its action exits with an error, or leaves the wrong thing behind, or the machine cannot run it. That is an outcome: one target ended badly, and the build still knows what every other target did.
- The build cannot go on. A build file has a mistake, the build wants a program the ceiling does not allow, a state file is damaged. That is an error: nothing useful can be said about the targets, so no outcome is made for any of them.
Here are both, in a workspace that allows grep, sort and wc:
local b = buildl
b.target("names.txt", {
inputs = { "names.in" },
run = { "sort", "-o", "$out", "$in" },
})
b.target("bob.txt", {
inputs = { "names.in" },
run = { "grep", "bob", "$in" },
stdout = true,
})
b.target("count.txt", {
deps = { "bob.txt" },
run = { "wc", "-l", "$deps" },
stdout = true,
})
names.in has no bob in it, so grep exits 1:
$ buildl build --keep-going
FAILED //:bob.txt: action failure (exit status 1)
declared in build.lua
command: grep bob names.in
1 failed, 1 skipped, 1 built
$ echo $?
1
$ python3 -c 'import json; [print(e["label"], json.dumps(e["class"])) for e in map(json.loads, open(".buildl/log.jsonl"))]'
//:bob.txt {"ActionFailure": {"status": 1}}
//:count.txt {"Skipped": {"because": "//:bob.txt"}}
//:names.txt "Built"
Three outcomes, one per target, and the log holds each class as data. Now add a fourth target that
runs tr, which the ceiling leaves out, and ask for a target nobody declared:
$ buildl build
error: build.lua: //:shout.txt: program tr is outside the ceiling (proc.run allows: grep, sort, wc)
$ echo $?
4
$ buildl build nope
error: target //:nope was asked for but is not declared
$ echo $?
2
No target ran in either. The first is refused before anything starts, and the second before the build files are even planned.
Outcomes
Every target a build reaches gets one ActionOutcome, and its class field says how it ended. The
class is an OutcomeClass, from crates/buildl-core/src/types/outcome.rs:
#![allow(unused)] fn main() { #[non_exhaustive] pub enum OutcomeClass { Cached, // not run: the last build's result stands Built, // ran, exited 0, every output stored Fetched, // not run: the remote cache held the result Remote, // not run here: the remote server ran it ActionFailure { status: i32 }, // exited with another status Killed { signal: i32 }, // a signal ended it: no exit status OutputMissing { name: OutputName }, // exited 0, a declared output absent OutputRefused { name: OutputName, refusal: OutputRefusal }, OutputWritten { name: OutputName }, // exited 0, a stdout target wrote its own path InfraFailure { kind: InfraKind }, // the builder could not build it Skipped { because: Label }, // never begun: another target failed } }
| Family | Classes | What it means |
|---|---|---|
| success | Cached, Built, Fetched, Remote | the target's outputs are in place (OutcomeClass::succeeded is true for these four) |
| the code is at fault | ActionFailure, Killed, OutputMissing, OutputRefused, OutputWritten | the action ran and did not do its job |
| the builder is at fault | InfraFailure | buildl could not prepare the action's directory (Prepare), start it (Run), let it finish in time (TimedOut) or store what it made (Store) |
| never begun | Skipped | a target it needs failed; because names that target by label |
A few of these need a word.
Killedis its own class because a process a signal ended has no exit status, soActionFailure { status }would have nothing true to hold. A timeout is not read off the signal: the worker that stopped the action knows it did, and saysInfraFailure { kind: TimedOut }.OutputRefusedis an action that exited 0 and left, where an output should be, something that cannot be put back exactly by placing files.refusalsays what: aSymlink, somethingSpecialsuch as a socket, anEmptyDirectory, a name that isNotText, or, for a discovery target, whose output must be a file, a directory (NotAFile).nameis the first such output in declared order.OutputWrittenbelongs to a target withstdout = true. Its output is what the command printed, so a command that also wrote that path itself has done something no one asked for.Skippednames the failed target by itsLabel, never by the graph's internal node number, so the log reads the same whatever order the graph was built in.
Classes are decided where the facts are known: whether the process could be started, what status it exited with, whether the worker's timeout flag is set. Nothing downstream ever reads a message to work out what happened. No failure is cached: a failed target leaves no cache row, so it runs again next time.
Errors
Everything that is not an outcome is an Error. There is one error type for the whole of
buildl-core, in crates/buildl-core/src/error.rs, written with thiserror. One type, not one
per module, because a caller branches on a variant and its fields, never on the text of a message,
and every module returns the same Result without a conversion at its edge.
Error is #[non_exhaustive], so adding a variant breaks nobody downstream. Each variant carries
what a caller needs as data. A few of the ones you are most likely to meet:
| Variant | Raised when | Carries |
|---|---|---|
Refused | a want is outside the ceiling, at Plan or at the last program check before a build | the want, the lowest-labelled target wanting it with its build file, and the ceiling |
PluginRefused | a plugin's target wants something that plugin is not allowed, checked before the ceiling | the want, the target and its plugin, and what that plugin does allow |
NotApproved | the approver said no to the wanted set | the wants it did not approve, and the reason in words |
PinnedEnv | a target declares TZ, LC_ALL or SOURCE_DATE_EPOCH under a strategy that pins them | the variable, the value the sandbox sets, and the first target declaring it |
Nondeterministic | check evaluated the build files twice and got two different lists | the build file, and what each run declared at the first difference |
DiscoveryChanged | the load that read discovery results declared different discovery targets | the first such target and its build file |
UnknownTarget | a command named a target nobody declared | the label, and the nearest declared one as a suggestion |
NoRun | log was asked for a target with no logged run | the label, a suggestion, and the number of every damaged log line |
CorruptState | a state file does not hold what buildl writes there | the file, and the JSON error that says why |
DispatcherFault | the dispatcher answered success and left targets without an outcome | every such target, in label order |
LostBuildFiles | the dispatcher answered success and left build files unevaluated | every such directory, in directory order |
Ignored | an inputs entry, or a subdir, names a path a .buildlignore ignores; raised while loading, so it ends the command with exit code 5 | the build file and the declaration, the path and whether it was an input or a subdir, and the ignore file and pattern that decided |
IgnoreFile | a .buildlignore cannot be used: a pattern does not parse, its bytes are not UTF-8, or it cannot be read or is a symlink; exit code 5 | the file, the line when there is one, and why. When the walk of buildl.sources is the first to read the file, it reaches the command line as an Evaluation error with the same text |
PluginNotFetched, PluginChanged, PluginFetch | a plugin is not there to use, its files are not the ones buildl.lock pinned, or git could not fetch it | the plugin, and what is missing or different |
UploadUnsandboxed | uploading to the remote, or remote execution, was asked for while actions run bare | which of the two was asked for |
RemoteToken, RemoteSwitch, RemoteFlags | the remote token cannot be used, a BUILDL_REMOTE_* variable is not 1 or 0, or the remote flags contradict each other | the token's source (never the token), the variable and its value, or the conflict |
Policy refusals, Refused, PluginRefused and NotApproved, are errors and not outcomes on
purpose. They are raised while the build is planned, or by the approver right after, and always
before any action runs, so there is no target whose outcome could hold one.
Adapter, and the port that failed
One variant is different: Error::Adapter { port, diagnostic }. It carries an adapter's own
failure as text, for display only, and port is a PortName saying which port's adapter failed:
Manifest, ContentStore, ActionCache, RemoteCache, Approver, Changes and so on, one
for each port whose adapter can fail, plus PluginStore for the plugin store, which is not a port. Every variant above is kept out of Adapter because a caller branches on
its fields; Adapter is only ever shown.
Adapter and CorruptState show why the line matters. A storage adapter that cannot read
cache.json at all returns Error::Adapter. One that read it and found bytes the canonical reader
refuses returns CorruptState, naming the file and wrapping the JSON error (UnreadableJson or
NonCanonicalJson). The
first is the machine's trouble, the second a damaged file, and they end with different exit codes.
What a message looks like
Every error that can name a target carries its label and its provenance, the build file that
declared it. A plugin's target also carries its origin, the chain of plugins that declared it. The
Display of an error renders that the way airsl renders a refusal: what was wanted, what was
allowed or found, and where it was declared, as in the tr example above.
Exit codes
The command line, the cli module of buildl, turns all of this into one of eight exit codes, in crates/buildl/src/cli/exit.rs.
Four functions pick the code: Exit::of_class for one outcome, Exit::of_outcomes for a whole
build, Exit::of_verification for verify, and Exit::of_error for an error. Each one matches on
the variant, never on text.
| Code | Name | What lands there |
|---|---|---|
| 0 | Success | every outcome succeeded, or was skipped because of a failure that decides the code itself |
| 1 | ActionFailure | an action failed: ActionFailure, Killed, OutputMissing, OutputRefused, OutputWritten; a verify mismatch |
| 2 | Usage | the command line: an unknown target or override, a bad query, log with no run, a test run naming a target that is not a test, the remote switches and flags |
| 3 | Infrastructure | the builder or the machine: InfraFailure, a missing program, a missing blob, a failed plugin fetch, and Adapter for every port but Manifest |
| 4 | Refused | Refused, PluginRefused, NotApproved |
| 5 | Definition | a build file or buildl.toml is wrong, including Adapter for the Manifest port |
| 6 | CorruptState | CorruptState, the two JSON variants, PluginChanged |
| 7 | Internal | buildl itself is at fault: a dispatcher that lost work, and any class or variant this binary has no row for |
When a build has outcomes of several kinds, the most severe decides: a fault of buildl (7)
outranks one of the builder (3), which outranks a failed action (1). A sick builder means the run
says nothing reliable about the code. The numbers stay clear of 126, 127 and everything above 128,
which a shell gives meanings of its own, and the status an action exited with is never the
process's own: it is in the report of the failure.
Appendix D lists every code with every variant that leads to it.
Determinism Rules
One principle sits under everything on this page: every difference in behaviour between two
builds must be traceable to a difference in a declared input. The action key is the list of what
is declared. The sandbox makes sure nothing outside that list can matter. verify checks what is
left over.
The trouble with non-determinism is that it never fails loudly. It shows up as a cache that never
hits, or a file that differs on another machine for no reason anyone can see. So buildl treats
it as a bug, and has rules to keep it out at three levels: in its own Rust code, in the build
files, and in the actions.
The engineering rules
These are the house rules for buildl's own code. They can be checked in review, and some are
checked by the gate on every change. Code comments cite them by number, so the numbers do not
change.
1. No HashMap iteration reaches any output
Anything that is written to a file, shown to a person or hashed into a key iterates a BTreeMap
or a sorted Vec. A HashMap is fine as a lookup table; its order is never allowed to leak.
2. All JSON leaves through one canonical serializer
Object keys are sorted at every level, and floating-point numbers are refused. graph.json,
cache.json, log.jsonl and the bytes hashed into an ActionKey all go through it, so "the key
of X" and "the file of X" can never disagree.
The float ban is enforced twice, because neither half is complete alone. The serializer walks the
value after serde_json has turned it into a tree, so it catches every finite float a
dependency's Serialize might slip in. It cannot catch a non-finite one: serde_json has already
turned NaN and the infinities into null, which looks exactly like a real null. The real
guarantee is the ban on f32 and f64 in crates/buildl-core/clippy.toml, asserted by
cargo make guard-core-purity. The walk is the second line, not the first.
JSON comes back in through one place too. canonical::from_slice reads the value through its
type's own Deserialize, writes it again, and compares the bytes. So it accepts exactly what the
serializer writes, and nothing else: a missing or unknown field, keys out of order or written
twice, extra whitespace, or an escape the serializer would not use are all refused. The build log
is read the same way, a line at a time, and a line the reader refuses is skipped and counted as
damaged rather than failing the whole file.
3. Parallelism is never observable
Build files load in parallel, but the results are put back in order and merged sorted. Files are hashed in parallel, but each result goes into its own slot. The order in which actions finish shows up only in the log's timestamps, never in any output, cache file or key.
4. The wall clock is quarantined
The current time is read in exactly two places, the timestamps of log events and the durations
worked out from them, and only through the Clock port, whose one real adapter lives in buildl.
Two other times exist, and neither reaches an output as a reading of the clock. The exec adapter
reads the monotonic clock for an action's deadline, a value that reaches no key, file or log. The
stat cache's "began" is a file's modification time: the one the file system gave the state lock.
The crate boundary does not enforce this, since std::time is open to every crate.
crates/buildl-core/clippy.toml bans Instant, SystemTime and SystemTimeError, and
cargo make guard-core-purity runs that ban inside cargo make dod. It is lint configuration,
not a grep and not the compiler, that keeps the rule true.
5. Double-run checks are tests, not doctrine
buildl check evaluates the build files twice and compares the two sorted lists of declarations
by value (with a discovery target, the two loads that read its result). The test suite builds each
of two fixture workspaces twice, in two directories, once with four workers and once with one, and
asserts that out/, graph.json, cache.json and the cas are byte for byte the same
(two_clean_builds_in_two_directories_are_byte_identical, in crates/buildl/tests/e2e).
log.jsonl and statcache.json are left out of that comparison: the first holds clock readings
and finishing order, the second modification times.
6. This machine's folders never reach a key
The home folder, the workspace folder and the action's folder differ between users and
machines, so a key that held one would be another key on every machine, and a cache could not be
shared. Two things keep them out. A path that can only be relative is relative by its type: inputs
are workspace-relative paths and outputs are names, so they hold no folder. A variable that only
finds programs is marked unkeyed, and its key holds the name and never the value
(The Action Key).
What is left is text the build file wrote or a tool printed, and for that buildl looks. The host
reports the folders, and buildl-core searches for them in each word of a command, in the value of
each key variable, in the value of each setting a command names and in each discovery output,
through one type, MachineFolders. A match is a refusal with exit code 5 that names the folder, and
nothing more runs; a discovery's output is checked after the discovery has run. The match rule is
in one place, so a path that only starts the same as a folder, such as /home/al inside
/home/alice, is not a match. An unkeyed value is not searched: it is in no key.
Build files: deterministic by construction
A build file runs on airsl, and airsl's confined preset is already close. Two changes close the
rest.
What could vary is taken away. The declaration engine uses airsl's smallest language surface,
which has no os at all, so os.time and os.clock are gone. The host modules are json, path,
regex, hash and glob, and time, proc, env and stdio are left out. The smallest surface
still loads math whole, so buildl removes math.random and math.randomseed itself. It also
removes airsstack.path.absolute, which reads the working directory, and print, because standard
output belongs to the command line. Last, it replaces tostring and string.format: rendering a
table or a function shows its address, which changes between runs, so rendering one with no
__tostring is an error, and so is %p. The Toolbox shows what is left.
Order is made not to matter. Lua's pairs visits a table in no fixed order. Rather than ban
it, buildl makes the graph blind to the order declarations arrive in: targets are keyed by name
and numbered in label order when the graph is resolved. A pairs loop that declares targets gives
the same graph whatever order it runs in. The order inside one list is different. deps, inputs
and outputs reach the graph as written, and from there the action key, so a list whose order
changes between two evaluations is a real difference.
And because declaring is cheap, it can be checked. buildl check evaluates every build file twice
and compares the two sorted lists. A build file that declares something different the second time
fails with Error::Nondeterministic, which names the first place the two runs disagree and what
each run declared there. A pairs loop alone does not fail it, because both lists are sorted
before they are compared.
Actions: guarantee, mitigate, verify
buildl cannot make a compiler reproducible. What it can do is pin every input the compiler sees,
and then check what is left. Each property gets the strongest treatment buildl can give it:
| Property | Status |
|---|---|
| same declared inputs, same action run | guaranteed by the action key |
| an action sees only its declared inputs | enforced from tier 2, for the files of the workspace; a file named by an absolute path, or outside the workspace, is still the action's to read |
| time zone, locale and clock differ between machines | mitigated from tier 2: the sandbox pins three variables and the modification time of every file it copies in; at tier 1 these are the machine's |
| the network as a hidden input | removed at tier 3, which is not built yet |
| the same action gives the same bytes | up to the tool: checked by verify, not promised |
What the sandbox pins, for every strategy above bare (Isolation::pinned, in
crates/buildl-core/src/types/isolation.rs):
| What | Value | Why |
|---|---|---|
LC_ALL | C | sorting, messages and number formats do not follow the machine's locale |
SOURCE_DATE_EPOCH | 315532800, 1980-01-01T00:00:00Z | the time a tool stamps into what it writes; the earliest a ZIP file can hold, so a tool that packs a ZIP from it never fails |
TZ | UTC | local time is the same everywhere |
| modification times | the same 1980-01-01 (Isolation::BUILD_EPOCH) | every file and directory copied into the sandbox carries it, so a tool that records file times, such as a ZIP packer, writes the same times on every run and every system |
A target may not set a pinned variable itself: under any strategy above bare, declaring one in
env fails Plan with Error::PinnedEnv, exit code 5. The Sandbox shows all
of this from the outside, and verify is how what is
left is checked.
The explicitness ledger
The ledger is the full list of what can make two builds differ, and how each one is made explicit:
| Input | Made explicit by |
|---|---|
| source files | inputs, hashed by content through the stat cache (The Action Key) |
| what other targets made | deps: the digests of their outputs go into the key (Early Cutoff) |
| environment variables | only names the target declares, marked key or unkeyed; a key variable's value goes into the key, and an unkeyed variable's name does, with no value |
| this machine's folders | refused where they would enter a key: a command, a key variable, a setting, a discovery output (rule 6) |
| tools | a fingerprint of the program's file; a program a dependency built enters as that dependency's output |
| operating system and processor | a platform in every key, so a Mac and a Linux machine never share entries |
| the network | network = true is a declaration in the key, shown by plan and the approver; taking the network away from the rest is tier 3's job |
| where an output comes from | stdout = true is a field of the target and part of its key: turning it on or off rebuilds the target |
| time, locale, time zone | pinned by the sandbox, as above; a target may not declare them |
| the build file's own logic | reaches a key only through the fields it declares, not through a hash of the file; declaring is sandboxed, has no os, and is checked by running it twice |
Two things a workspace sets are left out of the ledger on purpose: the [execution] settings
(workers, timeout, strategy), and a rule's desc. Neither is part of the action key.
workers, timeout and desc change nothing an action produces from its inputs. The timeout
does reach the remote key: a remote server holds the timeout in its Action, and
Who should upload says what that means for sharing.
strategy changes none of the key's parts either, but under sandbox the action runs in another
directory with the pinned values, so a tool that records its directory or reads the clock, the
locale or the time zone can give other bytes than under bare.
What the ledger leaves out, and what that means, is on What buildl Can and Cannot Promise.
Decision Records
Most of buildl's shape comes from a few dozen decisions, each made once, for a reason, and
written down so nobody has to make it again. This page holds all of them. Each row gives the
question, the choice, and why. If you want to change one, the reason is what you have to argue
with.
They are grouped by subject. A decision that changed later says so in its row.
The language
| Decision | Choice | Because |
|---|---|---|
| What build files are written in | Lua, evaluated on airsl | Plain data such as YAML or TOML cannot express a loop or a condition, and a full scripting language can express things a build file should never do. Lua in a sandbox sits between them: real loops and functions, with a surface the host decides. airsl supplies exactly that: Lua 5.4 linked in, with no interpreter to install and integers kept apart from floats, so JSON stays byte-stable; a policy model of language surface, grants and resource limits; a HostModule seam, so buildl's functions install as their own module without forking airsl; sorted JSON and sorted directory walks; and engines cheap enough (about 128 µs to build one) to give every build file its own. xmake shows people want Lua for build files; buildl differs by making the sandbox, not convenience, the organising idea. |
Crates and structure
| Decision | Choice | Because |
|---|---|---|
| Where the core lives | A crate, buildl-core, not a core module | A crate-root mod core hides Rust's built-in core crate: use core::fmt::Debug; fails with error[E0432]: unresolved import core::fmt. A crate boundary also turns the dependency rules into compiler errors. |
| Crate cut | Five crates | Only airsl brings a C build and an upgrade risk of its own, so only the Lua adapter earns its own crate; the other adapters share buildl until there is a concrete reason to split. buildl-cargo, the cargo subcommand, is the fifth: a program of its own on top of the buildl library. cargo test -p buildl-core never compiles Lua. |
| Structure | Five dependency-inverted crates | Every flow can be tested against fake ports. Five Crates, Ports and Adapters has the whole picture. |
| Lua exposure | The buildl-lua crate only | An airsl or mlua upgrade touches one crate, and buildl-core compiles without Lua because airsl is not among its dependencies. |
| Composition root | buildl, not buildl-cli | Editors, other tools and watch mode get a wired Workspace without copying the command line's wiring. Watch mode is built this way: Workspace::watch keeps the root, the approvals directory and the search path, and opens a Workspace for each cycle. The end-to-end tests live beside the real adapters. |
| Where the command line lives | buildl, in its cli module; buildl-cli keeps main alone | A second binary, cargo-buildl, shares the command line, and one crate can reach another's public API only. buildl::cli exposes the parser, run and execute, so each binary is a few lines that read the process and call it. cli joins local_ports and workspace as a composition module, since it names the adapters together through the Workspace; the isolation gate lets it. clap moves to buildl with it. The binary's own tests stay in buildl-cli, so what the built binary does is still checked from outside. |
| Re-exporting the core | pub use buildl_core;, so the crate is reached as buildl::buildl_core | pub use buildl_core as core cannot work: in a crate root that also names core::fmt it is error[E0432], and a crate that glob-imports it and names core::fmt gets error[E0659]: core is ambiguous. A third name would invent vocabulary. The facade buildl::Workspace and the manifest value buildl::buildl_core::Workspace stay apart. |
| Adapter isolation | Checked by cargo make guard-adapter-isolation | Seventeen modules in one crate, sixteen adapters and plugins, is where a cross-import slips in. What they share lives in state and search_path, which implement no port. |
Adapter isolation inside buildl | A gate task, not review | An adapter module may name the two shared modules, state and search_path, and nothing else of the crate. A rule a reviewer has to remember is a rule that slips; the gate runs on every change. |
No ExitCode ban in buildl-core | Deleted the std::process::ExitCode entry; the other 14 process bans stay | rustc's generated test harness names ExitCode through libtest's re-export (pub use std::process::ExitCode; // used by rustc-generated test harness), and clippy 1.100 flags that against the ban with a spanless error on every test target — proven with a minimal crate carrying only the ban and one empty test. Nothing in buildl-core names ExitCode, and Command, Child, ExitStatus and the rest still enforce that running a process is the Exec port's. |
| The plugin lock and store | plugins, a module of buildl that serves no port | Plan never reads the lock or the store, so no trait stands between the core and them: local_ports runs the check once and hands the directories to the declaration source, and workspace runs the fetch. The module is isolated like an adapter. |
| Where the plugin lock and store live | The same plugins module, which names only state and search_path | Only Wiring::source and Workspace::fetch_plugins touch them, so a port would be a trait with one caller. The values it shares with manifest live in buildl-core, so the isolation gate covers it like any adapter. |
| Diagram notation | Mermaid graph with C4 element labels | It renders wherever the other Mermaid renders; Mermaid's own C4 syntax is marked experimental. |
Ports
| Decision | Choice | Because |
|---|---|---|
| Port dispatch | Generics, with one Ports bundle | Static dispatch, without a type parameter per port on Pipeline. |
| Port openness | Open traits, not sealed | Adapters are written in other crates, and a sealed trait cannot be implemented outside its own. Ports grow through methods with default bodies. |
| When ports are wired | Per call: every port for plan, build, test, verify and gc; a source of build files, the log and the cas for check, graph and query, plus the manifest for doctor; the log and the cas for log; none for clean | Pipeline needs every port, and a command that reads only build files and discovery results must not need, lock or be stopped by a state file: a corrupt cache.json does not stop check. The state lock is held for one call, so an editor that keeps a Workspace open does not hold the directory while idle. |
| Who owns the reporter | The caller: Workspace::build is lent &mut R for one build | Only build reports, and an embedder brings its own reporter. LocalPorts<R, C> is generic over it; the Console an interactive approver asks on is lent the same way, as C. |
| Scheduler | A pure Schedule, and a Dispatcher port | Keep-going and skipping can be tested without threads, and the scheduler is the only writer, so its counters need no atomics. |
| Load granularity | DeclarationSource evaluates one file | The queue of directories and the sorted merge decide determinism, so they stay in buildl-core where fakes can test them. |
| Source globbing | On the host side, in buildl-lua | b.sources() walks with globset and walkdir, so the declaration engine holds no grant and airsstack.glob.walk is refused there; sorting, symlinks and staying inside the workspace are decided in one place. The directories the walk skips and the ignore rules are required arguments of LuaSource::new(root, limits, skipped, ignore, plugins), filled by the composition root with the output and state directories and with the IgnoreRules port's adapter, so buildl-lua reads no manifest and no .buildlignore, and does not depend on the ignore crate. |
| Reaching discovery results | A second argument of DeclarationSource::evaluate, a Discovered that Load hands unchanged to every evaluation | An evaluation stays a function of its file and that one value, on whatever worker it runs. Nothing is published yet, so the signature changed in place and the compiler named every implementor. |
| What an approver is told | Approver::approve(wanted, attribution): the attribution explains, the wanted set decides | An approval is remembered by the wanted set alone, so an approver that ignores the attribution (ManifestApprover, DenyApprover) is correct, and one that shows it (InteractiveApprover) cannot change what a yes covers. |
The Ports::Log bound | EventLog + RunHistory | Pipeline::plan, Pipeline::verify and Pipeline::build read discovery results from the pipeline's own log rather than through a port of their own, and the log adapter implements both. |
| The remote cache's port | RemoteCache, blocking, with the checks in the core and BlobSource a dyn callback | Workers on plain threads call it at once, and a blocking port keeps the scheduler and the core synchronous whatever the adapter needs below. The core judges every answer against a fake. The adapter may not import the content store, so an upload names the blobs it needs through a callback the core hands across; with the dispatcher's progress closure, that is one of the two places a trait object is passed. |
Threads and concurrency
| Decision | Choice | Because |
|---|---|---|
| Async runtime | None: plain threads for the build and its scheduler. Changed later: a tokio runtime confined to the remote adapter, reached only through block_on | The work is starting processes and hashing files: about as many workers as cores, with no fan-out beyond that. An async runtime buys nothing and costs a dependency tree. The remote cache changed it, because tonic, the gRPC client, needs a runtime. The remote module creates and owns it, workers call it through block_on, and nothing else names tokio. deny.toml keeps tonic, prost and uuid inside buildl, and guard-crate-edges keeps every other member off tokio. Remote execution, which was expected to reopen the question, did not: it is more threads blocking on the one runtime, up to [remote] jobs at once. |
| Worker and scheduler channel | std mpsc | One set of producers, one consumer, no select needed. |
| Parallel hashing | rayon, confined to the Digester adapter | Chunks of CPU-bound work are exactly what it is for; keeping it in one adapter leaves the executor with one threading model. |
| How a running build reaches the reporter | Messages through the dispatcher: dispatch(work, step), where work is handed a way to tell and step takes each Turn | The scheduling thread waits inside dispatch, and the dispatcher's own channel is the only way in that needs no second consumer. A target counts as started when a worker says it began, not when it is handed out: forty ready tasks on eight workers would otherwise show forty running. |
| Live output | One action at a time; the others wait as blocks | --stream shows the first action to begin while none is shown. Outcomes that end meanwhile are logged at once and shown after it, so output never interleaves and parallelism is kept; the outcome is the same with or without the live view, so the stored bytes cannot differ. |
| A dispatcher that loses a task | An error of the build, Error::DispatcherFault; for Load, Error::LostBuildFiles | A build that answers Ok with fewer outcomes than targets reports success for work never done. Each fault names what was lost, as data, so each is its own variant. |
Hashing, files and storage
| Decision | Choice | Because |
|---|---|---|
| Graph library | Own arenas; petgraph declined | The graph is built once, never changes, needs three algorithms, and must serialize stably. |
| Hash | SHA-256 | Compatibility with the Remote Execution API outweighs blake3's speed, and the stat cache makes hashing rare on warm builds anyway. |
| Cache files | JSON written by the canonical serializer, read back by the canonical reader | Easy to diff and debug beats compact; airsl's sorted-key JSON is the precedent. The reader checks a key's digest against its parts and a row's outputs against its key, so a damaged file is Error::CorruptState, apart from a file that could not be read. |
| Floats in canonical JSON | Refused, and banned at compile time | Nothing in the model is a float, and a non-finite float serializes as null, which would make a key disagree with the value it came from. See rule 2. |
Timestamp representation | u64 nanoseconds since the Unix epoch; no date library | The clock feeds durations as well as timestamps, and Instant is banned in buildl-core, so a duration is the difference of two timestamps, which seconds could not express. Formatting belongs to whatever displays it. |
| What an output's digest is | The digest of its OutputManifest, for a file and a directory alike | A row, a log event and a dependent's key each hold one digest per output. One small manifest blob says whether it is a file, an executable file or a tree, so the executable bit is in the digest, and a file never shares a digest with a tree. |
| What a directory output may hold | Regular files only; anything else is refused, not approximated | A symbolic link, a special file, an empty directory and a name that is not Unicode cannot be put back exactly, so the action fails as OutputRefused. A stamp file is the way to handle such a tree. |
| The action cache on disk | A snapshot, cache.json, and a journal, cache.journal, folded once per build | A row must be on disk when record returns, and rewriting the whole file per row is quadratic: seconds for a thousand rows, where one appended line takes microseconds. Rows reach cache.json only sorted, so finishing order never shows. |
| Syncing to disk | None, for any file | A rename already covers the process dying, which is what crash safety promises. A sync would only help if the machine itself died, whose remedy is to remove .buildl/ and out/, at some thirty times the cost of the write. |
| Protecting the cas | Read-only blobs, an executable twin, and a link only where writing through it is refused | An action that opens a dependency's output for writing would otherwise write into the store. The adapter checks once per store that writing to a read-only file is refused, and copies everywhere when it is not. A tool that changes the mode first can still damage a blob. Changed later: a runnable output is no longer a link, see Placing a runnable output in out/ below. |
Placing a runnable output in out/ | Copies for runnable outputs: a file that may be run is copied from its twin on every system, never hard-linked | A hard link makes the program in out/ and the twin in the cas one file. On macOS the program was then sometimes started under the twin's name, and the c plugin's -Wl,-rpath,@loader_path looked for libgreet.dylib in the cas folder (dyld: Library not loaded: @rpath/libgreet.dylib), a failure that came and went with how the system resolved the name. A copy has one name. It costs a copy per runnable output, made with the system's file copy and staged in the store's staging folder before it is renamed into place, so it is whole or absent. A plain file keeps its link. |
| A second buildl in one workspace | Refused, by a lock on .buildl/lock held for one plan, build, test, verify, clean, gc or plugins fetch | Two builds at tier 1 write the same paths under out/. The lock is the operating system's, so it is freed when its holder dies, and StateLock::acquire lets it go on every failing path. check, graph, query, doctor and log take none. |
| Which stat-cache entries are kept | Those of files modified more than 2 s before the run began, keyed by path | An edit the stat cache cannot see leaves the modification time and size equal, so it falls inside the time's granule, and 2 s is the coarsest met. The price: a file edited in the two seconds before a run is hashed again next time. |
When graph.json is written | By every build, right after Resolve, always the whole graph | The graph on disk then matches the rows and blobs beside it, and is the same bytes for build and build <target>. plan, graph and query record nothing. |
Labels and declarations
| Decision | Choice | Because |
|---|---|---|
| Label syntax | Absolute only, with a separate resolver | A Label is //dir:name and nothing else, so nothing downstream asks whether one still needs resolving. Label::resolve is the one place the three forms a build file may write, //dir:name, :sibling and a bare name, become one. |
| Directory-only labels | Refused, not read as //dir:dir | One target with two spellings breaks the round trip from text to label and back, and admits two cache keys for the same target. |
| A rule's description | Expanded with the command; display text outside the key | It reaches a ReadyAction as its own type, ExpandedDescription, because an expanded list of paths has no length limit while a written Description is held to 1024 bytes. Nothing in Plan reads it, so editing only a desc leaves every target cached. |
| Whose code made a declaration | Origin on every declaration and node, shown and checked, never in a key | The same declaration has one key whoever wrote it, so moving a target from a build file into a plugin rebuilds nothing. A plugin's authority is checked at Plan instead, and every error naming a target prints the chain. |
Planning and running actions
| Decision | Choice | Because |
|---|---|---|
| The execution settings and the key | workers, timeout and strategy are not part of the key | workers is scheduling. timeout decides whether an action finishes, not what it makes, and a timed-out action is never cached. strategy decides what an action can reach beyond its inputs, not what they are; keying on it would rebuild everything on each move up the ladder. A tool that records its directory or reads the clock can still give other bytes under bare than sandbox. |
| The execution settings as types | Execution { workers: Workers, timeout: Timeout, strategy: Isolation } | Each grammar is checked once. The manifest's 0 never leaves Workers: a reader matches PerCore or Fixed, or asks Workers::on(cores). Timeout is whole milliseconds, never zero. Isolation is ordered like the ladder, so "tier 2 or above" is >= Isolation::Sandbox. |
| A program named through a build setting | Found at Plan, under the settings in force | A setting's value is known before anything runs, so the program gets the ceiling check, the lookup and a fingerprint like one written out. Plan also expands every command, so the last check before a build is one uniform check over every expanded command. |
| Who judges what an action left | collect reports what it Found; buildl-core decides | Input and output stay in the port, and every decision can be tested on plain values. Only a file's executable bit is kept. |
| A build of named targets | The graph is narrowed between Resolve and Plan | Plan asks for every input of every node it is given, so narrowing later would fail a build on a missing input of an unrelated target. Output places are still checked over the whole graph. Narrowing takes the run's Purpose: a test run that names a target that is not a test fails with Error::NotATest. |
| A command a signal ended | Its own class, Killed { signal }, an action failure | A process a signal ended has no exit status for ActionFailure to hold. A timeout is told by the worker's own flag, never by the signal. |
| Stopping an action | The direct child only; no process group at tier 1 | A child in its own group stops getting the terminal's Ctrl-C, and std can neither signal a group nor forward a signal to one. What an action started is not stopped with it. |
| Signals to buildl itself | No handler | std has no safe way to install one, and the workspace forbids unsafe. Actions stay in buildl's process group, so Ctrl-C ends both; storage survives a kill at any point, and an interrupted build prints no summary. |
| Finding a program | One search path, read once, used by the tool resolver and both strategies through exec/run.rs; no trait between them | The file run must be the file fingerprinted. A search path can be built from any list of directories, so tests need no seam. |
The sandbox
| Decision | Choice | Because |
|---|---|---|
| Putting inputs in the sandbox | Copies, mode kept; no symbolic link, no hard link | A symbolic link makes a file's real path the workspace's: a script linked in found the workspace's node_modules, and the same script copied in did not. A hard link shares the file, so a tool that writes its input overwrote the workspace's copy. A copy is near-instant where the file system can share the bytes (measured on APFS), and correctness does not depend on that. |
| Where the sandbox directory lives | Outside the workspace, under the temporary directory | From inside the workspace, tools that search upward find the workspace's go.mod, node_modules or Cargo workspace. The price is that the path is not under .buildl/, so the state lock removes it, and Scratch::claim uses an existing one only if it is a real directory, owned by the lock file's owner, mode 0700, and outside the workspace. |
| The sandbox directory's name | Stable per target: the first 32 hex digits of the SHA-256 of the workspace root's path, then of the label | The directory a compile runs in reaches its output: rustc -g in two directories made two different files. A random name would make a debug build differ on every run; a name from the label gives one target one path every time, and no two targets share one. |
| Where the pinned variables are written | In buildl-core: Isolation::pinned, and one check in Plan | The names and values are written once, beside the ladder, and the sandbox reads them from there. A target that declares one is refused at Plan as Error::PinnedEnv, a pure check. SOURCE_DATE_EPOCH is 1980-01-01 because a ZIP file cannot hold an earlier time. |
What verify does with out/, and what its sandbox does | verify puts out/ back from the cache first, and its sandbox leaves output paths alone | Re-runs go through the dispatcher on several workers, so a re-run that cleared its output paths could remove what a re-run of a dependent was copying. verify restores every clean target's outputs first, builds its sandbox with OutPaths::Untouched, and never places a re-run's outputs. build and test keep OutPaths::Cleared. |
Approvals and plugins
| Decision | Choice | Because |
|---|---|---|
| Where approvals are remembered | Outside the workspace: <data>/buildl/approved/<workspace id>.json, <data> being $XDG_DATA_HOME, else $HOME/.local/share | A repository can ship its own .buildl/, so an approval kept inside it would come with the code it approves. direnv keeps its approvals outside the project for the same reason. Only an absolute path counts, and a failure is never an approval. |
| Plugin caps against the ceiling | The plugin check runs before the ceiling check; a plugin's reach is its manifest, the workspace's cap and the ceiling, intersected | The manifest says what a plugin needs and the cap what the workspace lets it have. A want refused by either names the plugin, which the workspace-wide Error::Refused would not. No cap widens the ceiling. |
| What a plugin instance sees | A new environment per instance, with one-level copies of the library and module tables | A plugin that reached the build file's buildl could declare as the build file and slip past its cap, and one that wrote into a shared table could replace a function the build file calls later. Copies close both. |
| Checking a fetched plugin | Digest the stored files against buildl.lock on every command that makes a source; fetching never repins on its own | A changed file must not go unnoticed, and a check that trusted file times would miss an edit that keeps them. A difference, or a tag that moved, is PluginChanged, never a silent new pin. |
Discovery targets
| Decision | Choice | Because |
|---|---|---|
| Discovery results | Read back from the log and the cas for a second load; no result is not an error | The log and the cas already hold what a target made, so there is no new store, and a command that reads only build files stays lock-free. A damaged log or a missing blob turns check and graph into "nothing has run"; only build and test, which have just run the target, treat an unreadable result as the fault it is. |
The remote cache and remote execution
| Decision | Choice | Because |
|---|---|---|
| What a remote cache is asked | A Remote Execution API Action built by the core, with buildl's action key as its salt | The server can only be asked in the API's terms, and the action key is not an Action digest. The salt carries everything the key holds, so two targets with different keys never share an entry; the core builds the value and the adapter encodes it, so no protobuf reaches buildl-core. |
| Who judges a remote answer | buildl-core; the adapter only moves and encodes | A result written by another machine is trusted for nothing: the exit code, the declared paths, a discovery output's kind, and every blob's length and SHA-256 are checked in the core before a byte reaches the content store. |
| A remote failure | Lenient by default: warn once, run locally, and turn the remote off for the rest of the command; --remote-strict fails the build | A cache that is down must not stop a build that can run without it, and a flapping one must not be asked again for every target. Strict is for CI, where a silent fall-back to a full local build is what you want to find out about. |
| Uploading from a bare action | Refused | At tier 1 an action can read files it did not declare, so its result depends on more than its key, and a shared cache would hand it to every machine. The refusal comes before the approver is asked. |
| The protocol code | Vendored .proto files, committed generated code, and a generator outside the workspace | Generating at build time would add a license outside the allowed set and a banned dependency, and put the generator's tools into every build. CI regenerates and diffs, so the committed code cannot drift. |
| Where the test server lives | A test-server feature of buildl, off by default | The adapter's tests, the end-to-end tests and the binary's tests all need the same in-memory server, and another crate can reach only a library's public API. The shipped binary does not enable it; buildl-cli takes it as a dev-dependency only. |
Watch mode
| Decision | Choice | Because |
|---|---|---|
| File events | notify 8.2.1, in buildl alone; its CC0-1.0 license by a one-crate exception; no debouncer crate | It speaks FSEvents and inotify, and its minimum Rust version is under ours. deny.toml allows CC0-1.0 for notify only, so the general list holds only what the graph needs. A 50 ms settling window is small enough to write in the adapter. |
| What starts a build in watch | A check over paths, never event kinds: a path that is not a declared input or a config file loads the build files, and a build follows only if the graph changed | On macOS the event kinds are merged and unreliable, so whether a file is new cannot be read from an event. A new file reaches a build only through a load, so the load is the test: it builds when b.sources() now matches a file, and ignores a README, an editor's swap file or a comment. Read events are the exception: inotify reports every open, so they are dropped, and only a file closed after a write is kept. |
| Taking the state lock in watch | Per cycle, inside the build only; the workspace is opened again for every cycle | An open Workspace reads buildl.toml once, so a watch that kept one would never see an edit to the ceiling. Opening again makes each cycle exactly the buildl build you would have typed, and lets the lock go between cycles, so plan, log, graph and doctor work while watch waits. |
Tests
| Decision | Choice | Because |
|---|---|---|
| Tools in tests | System tools by argv; no compiled helper, no published kit of fakes | Cargo gives a test the path of a built binary only in the package that owns it, so a helper would cost the published buildl crate a binary or a feature, or the workspace a fifth member. |
| Tools in adapter and end-to-end tests | System tools run by argv; sh -c in tests only | The same reason, from the adapters' side: sh, cp, sort, true, false and sleep are on every machine that builds buildl, and buildl itself never starts a shell. |
Testing Layers shows where each kind of test lives.
Testing Layers
The phases of buildl talk to each other through plain values, and to the outside world through
ports. That makes the narrow places between them the natural place to test. Every flow is tested
first in buildl-core, against fake ports, with no Lua, no file system, no processes and no
threads. Then it is tested again against the real adapters, in the crate that owns them.
%% Testing layers — the widest coverage at the bottom
graph BT
CORE["buildl-core<br/>every flow against fake ports<br/>no Lua, no filesystem, no processes, no threads"]
ADP["buildl adapters<br/>each module alone: a temp directory, system tools run by argv"]
LUA["buildl-lua<br/>real airsl: build.lua fixtures to exact declarations"]
E2E["buildl/tests/e2e<br/>real adapters through the Workspace facade:<br/>a fixture workspace built twice, byte-identical"]
CLIT["buildl::cli and buildl-cli<br/>argument parsing and exit mapping in process,<br/>then the built binary"]
CORE --> ADP --> LUA --> E2E --> CLIT
The widest coverage is at the bottom, where tests are fastest and need nothing.
| Layer | Lives in | May touch | Must not |
|---|---|---|---|
| Core flows | crates/buildl-core/tests/flows, with the fakes in common.rs | buildl-core's public API and the fakes | Lua, the file system, a process, a thread |
| Lua | crates/buildl-lua/tests/flows, with fixtures in crates/buildl-lua/tests/fixtures, and unit tests beside the code | real airsl; fixture build files, or files written into a temp workspace, turned into exact StagedFiles | anything of buildl |
| Adapter unit | crates/buildl/src/<module>/, beside the code | its own module, state, search_path, buildl-core, one temp directory; exec starts system tools | another adapter module; the process's current directory; setting an environment variable |
| End to end | crates/buildl/tests/e2e, with fixtures in crates/buildl/tests/fixtures | buildl's public API; a temp copy of a fixture | a private item; a path outside the package |
| CLI unit | crates/buildl/src/cli, beside the code | argument parsing, the exit mapping, terminal detection, a command's flow over byte buffers and a temp workspace | a process; a terminal |
| CLI binary | crates/buildl-cli/tests/cli | the built binary, with a chosen working directory and environment, its output piped | buildl internals; a terminal |
buildl-core forbids threads even in its tests: crates/buildl-core/clippy.toml bans
std::thread::spawn and its kin for the whole crate, test code included. A test that needs real
workers belongs to buildl.
The tools the tests run
Tests that run actions run system tools, sh, cp, sort, true, false, sleep and their
like, by argv. sh -c appears in tests only, never in buildl. There is no compiled helper
program and no shared kit of fakes; Decision Records says why.
The one thing the layers share is a server. The remote cache adapter's tests, buildl's
end-to-end tests and buildl-cli's binary tests all talk to the in-memory Remote Execution API
server that buildl's test-server feature builds, on loopback. No test reaches the internet,
and the shipped binary does not hold the server.
The fakes
The fakes live in buildl-core's integration tests, crates/buildl-core/tests/flows/common.rs, not
under #[cfg(test)]. They implement the public traits through the public API alone, so whatever a
fake can do, an adapter in another crate can do too, and the compiler checks that on every test
build.
| Port | Fake | What the test no longer needs |
|---|---|---|
DeclarationSource | FakeSource: a fixed build file, missing file or failed evaluation per directory; other files once the root is evaluated again or handed a discovery result | airsl, Lua |
Manifest | FakeManifest: one fixed workspace and ceiling | a buildl.toml |
Host | FakeHost: a fixed platform and fixed variables, some of which it can be told to fail on | the real environment |
Digester | FakeDigester: files held as bytes with their metadata, counting every call | a file system |
StatCache | FakeStatCache: in memory, counting commits | a file system |
ToolResolver | FakeTools: fixed fingerprints, recording every lookup | a PATH |
ContentStore and Sweep | FakeCas: blobs and placed paths in memory, each with its mode; digests it can be told to forget, paths it can be told to fail on, reads it can be told to lose | a file system |
ActionCache | FakeCache: rows in memory, labels it can be told to fail on, and the labels it forgot | a file system |
EventLog and RunHistory | FakeLog, and FakeHistory for history alone: what was appended, and whether to fail | a file system |
ExecStrategy | FakeStrategy: scripted per label, how the action exits, what it prints, and what is left at each output: a file, an executable, a directory, a symbolic link, something special, or nothing | starting processes |
Dispatcher | FakeDispatcher: runs tasks inline on the test thread, oldest or newest first; it can be told to lose a task, or run one and drop its result | threads; results are deterministic |
Clock | FakeClock: a counter, one tick per read | the wall clock |
GraphRecord | FakeGraphRecord: the graphs recorded, and whether to fail | a file system |
Reporter | FakeReporter: every call kept, in order | a terminal |
Approver | FakeApprover: one answer, given every time, and every set it was asked about with its attribution | a terminal, a data directory |
RemoteCache | FakeRemote: results in memory, every call kept in order; it can be told to fail any call, serve tampered bytes, or answer that an input changed | a network, a server |
The watch loop's own ports, Changes, Cycles and WatchReport, have unit-test fakes beside the
loop, in crates/buildl-core/src/watch/run.rs, and a scripted Changes in buildl's end-to-end
watch tests.
What runs where
A sample of what each layer proves. The core flows check the decisions; the end-to-end tests check the same promises against real files and processes.
In buildl-core, against fakes | Proves |
|---|---|
//:a fails under --keep-going | the summary is 1 failed, 2 skipped, 2 built |
| the cas write succeeds, the cache write fails | there is no row for the target: crash safety |
| a rebuilt output is byte-identical | downstream targets stay clean: early cutoff |
| one input changed | the reason the target is dirty is the difference between its old and new KeyComponents |
the [execution] settings all change after a build | every target stays clean: none is part of a key |
| a wanted program outside the ceiling | Error::Refused before any strategy runs |
| a plugin's target wants what its plugin may not have | Error::PluginRefused, naming the plugin, before the ceiling is asked |
| the dispatcher loses a task | Error::DispatcherFault, naming every target left without an outcome |
| a build with a discovery target | the discovery target runs first, then what it declared; a second build is all cached |
| a target the fake remote holds | it ends Fetched, no strategy is called, and its row is written after its content |
| a remote call fails | lenient: one warning and the target runs; strict: the build fails |
In crates/buildl/tests/e2e, against real adapters | Proves |
|---|---|
| a fixture built in two directories, with four workers and with one | out/, cache.json, graph.json and the cas are byte-identical |
| a second build | every target cached; cache.json and graph.json unchanged |
out/ removed | every output put back without running, the executable bit kept |
| the states an interrupted build leaves | the next build finishes, trusts no blob without a row, and clears what was half done |
a corrupt cache.json | Error::CorruptState naming the file; check, graph and query still work |
| a target that reads a file it did not declare | it fails under sandbox and builds under bare |
the same chain under bare and under sandbox | out/ is byte-identical across the two |
verify over a target that writes its process id | that target is reported as mismatched, naming its output |
| a second checkout against the server a first build uploaded to | every target fetched, no action run, outputs byte-identical |
A real server, once per CI run
The in-memory server answers as the protocol says, but it is still buildl's own. One CI job,
remote-execution, runs crates/buildl-cli/tests/real_remote.rs against NativeLink v1.4.0, built
from ci/nativelink.Dockerfile. The file's tests run only when BUILDL_TEST_REAPI_URL names a
server, which the job sets, and skip otherwise. A workspace built with --remote-execute ends with
every target remote, and a second build in a fresh checkout ends with every target fetched and
byte-identical outputs.
buildl builds buildl
The last layer is buildl building and testing this repository, with a released buildl. The
repository root is a buildl workspace: build.lua, buildl.toml, buildl.lock, .buildlignore
and .buildl-version. cargo make dod stays the gate; this layer shows that the release can run
it.
build.lua is written by hand, not by cargo buildl init or cargo buildl sync, and makes four
calls on the rust plugin, pinned at plugin-rust-v0.2.1:
| Target | Call | cargo runs |
|---|---|---|
buildl | rust.binary("buildl", …) on rust.package("buildl-cli") | cargo build --locked --bin buildl --profile dev --target-dir target -p buildl-cli |
cargo-buildl | rust.binary("cargo-buildl", …) on rust.package("buildl-cargo") | the same, for cargo-buildl and -p buildl-cargo |
tests | rust.test("tests", …) | cargo test --locked --profile dev --target-dir target --workspace --all-targets --all-features |
doctests | rust.test("doctests", …) | cargo test --locked --profile dev --target-dir target --workspace --all-features --doc |
tests and doctests carry the arguments of cargo make test and cargo make test-doc, so a pass
means what the gate's two test steps mean. buildl.toml holds what cargo buildl init writes,
plus [execution] timeout = "30m", a margin over the default ten minutes: a cold buildl test
took 238 seconds on an aarch64 macOS machine, and a CI runner has fewer cores.
What is an input
The rust plugin takes every file under the workspace as an input of every target. The root
.buildlignore keeps only what cargo reads:
/*
!/Cargo.toml
!/Cargo.lock
!/rust-toolchain.toml
!/crates/
.DS_*
*.rs.bk
mutants.out*/
The first line leaves out everything at the root; the next four bring back the workspace manifest,
the lock file, the toolchain file and the crates. buildl reads no .gitignore, so the last three
leave out three kinds of stray file the repository's .gitignore also lists: .DS_*, *.rs.bk
and mutants.out*/. Each cargo target then has 529 inputs, and an edit to book/, examples/,
skills/ or any other root folder rebuilds no cargo target. A new file at the root stays out; a new file cargo reads outside crates/ needs
a !/<path> line. Any other file left under crates/ is an input, and makes every target dirty on
that machine.
The pin
.buildl-version holds one line, the version without a v: 0.3.0. buildl never reads it; people
and CI install that release with it:
$ curl -LsSf https://airsstack.github.io/buildl/install.sh | BUILDL_VERSION="$(cat .buildl-version)" sh
$ export PATH="$HOME/.local/bin:$PATH"
$ buildl plugins fetch
$ buildl build
$ buildl test
The installer refuses a malformed or unreleased version, but an empty pin, or latest, installs the
newest release. So CI checks that buildl --version prints exactly buildl <pin> before any
buildl command runs.
The toolchain probe
rust-toolchain.toml tracks stable, so a rustup update changes the compiler without changing an
input. Each call passes version_probe = true, which declares a <name>.version target running
rustc -vV and puts its output in the key, so a new compiler rebuilds. The cost shows in plan:
right after a full build it reads 4 to run, 2 conditional, 0 clean, and a build that changes
nothing ends 4 built, 2 cached, the four being the probes.
The probe runs in the sandbox, without rust-toolchain.toml, so it reports rustup's default
toolchain. On a machine whose default is not stable, an update to stable changes what cargo
uses without changing what the probe reports, and a stale result can stay cached. The remedy there
is to delete .buildl/, then run buildl plugins fetch.
The CI job
The self-build job, on Linux and macOS, installs the pinned release, builds and tests twice, and
keeps .buildl/ in GitHub's Actions cache:
flowchart TD
install["install the pinned buildl, check its version"] --> restore["restore .buildl/"]
restore --> fetch["buildl plugins fetch"]
fetch --> first["buildl build, buildl test"]
first --> second["second pass: 4 built, 2 cached, then tests: 2 passed (2 cached)"]
second --> gc["buildl gc"]
gc -- "miss, job passed" --> save["save .buildl/ under the key"]
gc -- "exact hit" --> done["save nothing"]
| key | buildl-<os>-<pin>-<sha256 of rustc -vV>-<hash of the inputs> |
| restore key | buildl-<os>-<pin>-: the newest cache for the same OS and release |
| inputs hashed | Cargo.toml, Cargo.lock, rust-toolchain.toml, crates/**, build.lua, buildl.toml, buildl.lock, .buildlignore, .buildl-version |
The key only decides what is restored; buildl decides what is clean from its own action keys, so a
restored older store is rebuilt where its inputs changed. The second pass must end with the two
lines in the diagram, which buildl prints on stderr. buildl gc then drops what the current
results no longer need, so the saved store does not grow. The cache is saved only on a miss, and
only when the job passed.
After each release
The pin can name only a published release, so it moves after the release is out, in its own
change: .buildl-version names the new version, and the build files change in the same change if
the release needs it. The new pin is a cache miss, and the restore key never brings back a store
another release wrote.
Where buildl Sits
Build systems are an old subject with a good theory behind them. This page places buildl in
that theory: what kind of build system it is, which ideas it takes from others, and what it adds
that the theory has no word for.
The map used here is Build Systems à la Carte, by Andrey Mokhov, Neil Mitchell and Simon Peyton Jones (ICFP 2018). Its central idea is that every build system is two parts:
- a scheduler, which decides the order work is done in, and
- a rebuilder, which decides whether a piece of work needs doing at all.
The grid
Each part comes in a few kinds. A scheduler can be topological: work out the whole graph first, then walk it from the leaves up. Or it can be suspending: start a task, and pause it when it turns out to need something not built yet. A rebuilder can use a dirty bit, as Make does by comparing file times, or traces: a record of what each task read and made, the strongest form being constructive traces, which keep the outputs themselves, stored by the hash of what made them.
%% buildl placed in the scheduler x rebuilder grid
quadrantChart
title Scheduler strategy vs rebuilder strategy
x-axis Dirty bit --> Constructive traces
y-axis Topological --> Suspending
quadrant-1 Dynamic and cached
quadrant-2 Dynamic graphs
quadrant-3 Classic static
quadrant-4 Static and cached
Make: [0.15, 0.15]
Ninja: [0.45, 0.2]
Bazel: [0.8, 0.55]
Buck2: [0.85, 0.9]
Nix: [0.9, 0.85]
buildl: [0.8, 0.15]
buildl is a topological scheduler with constructive traces. The graph is fully known once the
build files are read and resolved, it is walked from the bottom up, and every action's outputs are
kept in a content-addressed store, the cas, under its action key. That is
Bazel's rebuilder with the simpler scheduler of Make and Ninja. The pairing is deliberate: the
declaration phase produces a complete static graph, so a scheduler that can suspend and restart
tasks would buy nothing.
The theory also predicts the one thing such a design cannot do. A purely topological scheduler
cannot handle a dependency found while an action runs, such as the header a C compiler happens to
read. What buildl Can and Cannot Promise says how buildl handles
that.
What the grid cannot show is buildl's real signature: authority comes from the graph, not from
the host. None of the tools on the grid has that axis.
The scheduler and the rebuilder, made literal
The theory draws a build system as a pipeline: a request, a scheduler, a rebuilder, and then run or
skip. buildl's five phases are that pipeline, with each boundary between phases turned into a
value you can print.
%% buildl's five phases mapped to the a la carte anatomy
flowchart TD
subgraph THEORY["Theory — a la carte anatomy"]
REQ["Request"] --> SCH["Scheduler<br/>walk graph in dep order"]
SCH --> REB{"Rebuilder<br/>inputs unchanged?"}
REB -->|yes| SKIP["Skip — reuse output"]
REB -->|no| RUN["Execute stale work"]
end
subgraph BUILDL["Practice — buildl phases"]
L["Load<br/>airsl evaluates build.lua"] --> R["Resolve<br/>assemble the DAG"]
R --> P["Plan<br/>action keys vs cache"]
P --> X["Execute<br/>parallel workers"]
X --> REC["Record<br/>cas, cache row, log"]
end
SCH -.->|"is"| R
REB -.->|"is"| P
RUN -.->|"is"| X
Resolve builds what the scheduler walks. Plan is the rebuilder: it compares action keys with the
cache. Execute runs only what Plan found dirty. What buildl adds is that every arrow between
phases is a value, Vec<Declaration>, then TargetGraph, then Plan, then Vec<ActionOutcome>.
That is why buildl graph and buildl plan come for free: each command is the pipeline stopped at
one of those values. Declare, Then Execute walks through them.
A build system first
buildl is a build system first. The question it exists to answer is "does this need to run at
all?", and the action key, the cas and the dirty check are how it answers. Using it as a task
runner, for chores, for graphs of aliases, or in place of cargo make, is a special case the model
gives for free. It is not what the design was shaped around: nothing was designed for it, and
nothing needs removing to allow it later.
Here is what that special case looks like. A build system contains a task runner, reachable
through an escape hatch, and buildl's hatch is always = true:
b.target("push", {
deps = { "api_image" },
run = { "docker", "push", "registry.example.com/api" },
network = true, -- declared, shown by plan and the approver
})
b.target("deploy", { deps = { "push" }, run = { "kubectl", "apply", "-f", "k8s/" },
always = true }) -- a verb: never cached, never skipped
%% Nouns and verbs in one graph — the containment made concrete
graph LR
subgraph NOUNS["Nouns — cached by action key"]
SRC["go sources"] --> BIN["server binary"]
BIN --> IMG["api_image<br/>iidfile digest"]
end
subgraph VERBS["Verbs — effects on the world"]
PUSH["push<br/>network true"] --> DEP["deploy<br/>always true"]
end
IMG --> PUSH
The interesting node is push. It is a cached side effect, and that is right here: an unchanged
image digest means the registry already has these bytes, so skipping the push is what you want.
deploy is the true verb, and carries always = true. A simple test sorts every node: ask the tool
to do the same thing twice. The nouns do nothing the second time, push does nothing while the
digest matches, and deploy runs every time.
This is also why the summary line has the words it has. 1 failed, 2 skipped, 2 built, 9 cached, from
Declare, Then Execute, names states a pure task runner has no use for: cached and
skipped are the rebuilder's words.
The capability gradient
Tools that run tasks sit along a line, each step adding something: named tasks, then ordering, then
caching you have to trust, then hermeticity that is enforced. buildl adds one more step at the
end.
%% The gradient with buildl placed at the far end
flowchart LR
N["Named tasks<br/>npm scripts"] --> O["Ordering<br/>just, Taskfile"]
O --> C["Trust-based caching<br/>Turborepo, Nx"]
C --> H["Enforced hermeticity<br/>Bazel, Buck2, Nix"]
H --> A["Declared authority<br/>buildl"]
C -.->|"one-way door:<br/>hermeticity needs<br/>execution control"| H
H -.->|"second door:<br/>evaluation itself<br/>is sandboxed"| A
Turborepo's cache is only as correct as your declarations. Bazel enforces the declarations by
sandboxing actions as they run. buildl adds a step the line did not have: the build files
themselves run inside the sandbox, and the build's whole authority is worked out from the graph
and checked against a ceiling before anything runs. Each step to the right costs effort to adopt.
buildl's bet is that starting from declared authority, inherited from airsl, makes the last step
cheaper than adding it to a tool that began without it.
The summary card
%% Coverage summary
mindmap
root((buildl vs<br/>fundamentals))
Covered
Static DAG from declarations
Topological scheduler
Constructive traces — cas
Early cutoff
Input sandbox — tiers 1 and 2
Determinism — verify, double-run
Tools as inputs — fingerprints
Settings fold into the key
Phony escape hatch — always true
Dynamic inputs — discovery targets
Per-file C and C++ — the C plugin over discovery targets
Remote cache, then remote execution
Parallel loading of build files
Deferred by decision
Configurations — one target one platform
Demand-driven loading
OS sandbox and containers — tiers 3 and 4
Everything the theory calls load-bearing exists in buildl as a concrete mechanism. The one
correctness question the grid predicted, dependencies found while an action runs, is answered by
discovery targets, which also carry per-file C and C++ through
the c plugin. And each deferred item has a named way in, which is what
makes leaving it out a choice that can be undone.
What buildl Can and Cannot Promise
A build tool is only as useful as your knowledge of where its promises stop. Here they are.
What it does promise
- A build file can be read safely before you trust it. Evaluating build files grants them nothing: no files, no processes, no environment, no clock.
- You can see everything a build may do before it does it. The programs, variables, network
use and folders a build wants are worked out from the graph, held to the ceiling in
buildl.toml, and shown to the approver before any action runs. - The same declared inputs run the same action. That is what the action key is, and
plancan always say what will rebuild and why. - A machine's own folders stay out of the key. A variable that only finds programs is marked
unkeyed, and its key holds the name alone. A command, akeyvariable, a setting or a discovery output that holds this machine's home, workspace or action's folder is refused, so users and CI can share a cache (The Action Key). - A crash never leaves a cache row pointing at nothing. Content goes into the cas first, the cache row after, and failures are never cached.
- Nothing on the ledger is hidden. Every input that can change an action's result is in the
explicitness ledger, and a difference
between two builds that is not traceable to it is a bug in
buildl, not in your build.
Per-file C and C++ goes through the plugin
buildl compiles C and C++ one file at a time, with one target per object, through the c
plugin. The C and C++ Plugin shows how. The reason it needs discovery targets
is the depfile gap: a compiler reads headers nobody declared, Ninja and Make learn about them from
a depfile the compiler writes, and buildl reads no depfiles.
Discovery Targets draws the missing edge, and what
each strategy does with it: under bare an edited header is silently ignored, and under sandbox
the first compile fails because the header is not there.
The plugin closes the gap with a discovery target per source. It is
an ordinary action, keyed, cached, sandboxed and approved, that runs the compiler with -MM and
whose output the next pass over the build files reads. Each object is then declared with the source
and the headers it read as inputs. The executor still reads no depfile, and none of this
changes what the sandbox or the ledger promise.
Its limits:
- One build file per project. A header outside the build file's folder cannot be declared as an
input, so a source may include only headers inside the build file's folder and listed in
headers, or ones another target generates and the call names inheader_deps. Anything else is an error naming the header. - Linux and macOS, with
gccandclang. Windows and MSVC are out, and so is cross-compiling. The programs the plugin may run are a fixed list, and a versioned name such asgcc-13is not on it. - A compiler update behind a launcher goes unseen. A target's key records the program file, and
on macOS
/usr/bin/ccis one launcher file that stays the same when the compiler behind it changes. Unless a call setsversion_probe = true, a new compiler does not rebuild the objects. With it, a probe runs--versionand every object depends on its output.planalways lists those compiles as conditional, even right after a full build, because it never runs the probe; a build still takes them from the cache when the probe prints the same.
What is really left of the gap is narrower than "depfiles": finding an input in the middle of one action, which a discovery target does not cover, because its output feeds the next declaration pass and not the action running now. If that case is ever needed, it will extend what a discovery target can do, rather than add a side channel to the executor. Ninja's depfile format would then be one way to feed it, not the design.
Rust goes through the plugin too
buildl builds a Rust crate through the rust plugin, which runs plain cargo. There is no depfile
gap here, since cargo tracks the sources it reads, and so there is no discovery per file: a call
declares one target for the crate, with every file below the build file's folder as an input.
The Rust Plugin shows how. Its limits:
- Dependencies compile again whenever an input changes. Each build runs in a fresh sandbox, so
cargo has no
target/from the last one. Plaincargokeeps its owntarget/and is faster for an edit loop on one crate. - Crates live in cargo's cache, outside buildl's store. Cargo finds them under
HOME(~/.cargo), which isunkeyed, so a crate a machine already holds is not part of the key. - Programs cargo starts are unseen. The ceiling sees the
shthat started cargo, not therustc, the linker or the build scripts cargo runs beneath it. - The dev profile does not verify. Its debug info holds the absolute path of the folder the
crate was built in, and
buildl verifyruns the action in a folder of its own, so it reports adevbinary as differing. The examples build withprofile = "release", which holds no path. - A toolchain update goes unseen, with
rustupor without. Each target runssh, so its key records neithercargonorrustc. Unless a call setsversion_probe = true, a new toolchain does not rebuild the target; with it,planlists the target as conditional even after a full build.
Linux and macOS only, and no cross-compiling.
What each isolation tier does not guarantee
The Sandbox shows the tiers in use. Here is what each one leaves open.
Tier 1, bare, confines nothing. It does promise five things: the command is started from an
argument list, never through a shell; the program run is the file the plan fingerprinted; the
environment holds exactly the declared variables that have a value; standard input is empty; and
the action's own process is stopped at the timeout. Beyond that, an action can:
- read any file you can, declared or not, so a hidden input is silent instead of an error;
- reach the network, whatever
networksays; - write anywhere you can, another target's output included;
- leave the processes it started running, at a timeout or when it exits;
- leave a partial output at its path if it fails or is stopped. No cache row names such a file, and the next build clears the path before running the action again;
- damage the store, if it changes the mode of a dependency's read-only output and writes to it.
The machine's clock, time zone and locale are the action's own.
Tier 2, sandbox, stops one thing: reading a workspace file the action did not declare. An
action that names a workspace file by its absolute path, or climbs out of its directory with ..,
still reaches the workspace. It reads /usr, your home folder and tool caches as at tier 1. It
reaches the network, and the processes it starts outlive it. When it does read an undeclared file,
it fails with the tool's own message, "file not found" or "cannot find module", and buildl does
not name the file. And because the strategy is not part of the action key, a target built under
bare is a cache hit under sandbox: switching does not re-check it. buildl verify is how a
cached target is checked.
Tiers 3 and 4, os-sandbox and container, are not built. They are the tiers meant to seal
the network and system files, and to pin the toolchain in an image. This version refuses them
rather than run your actions with less isolation than you asked for.
The limits of the ledger
The ledger is finite and named, and some things are honestly outside it:
- What the machine is. The kernel version, the C library, the file system's behaviour, and the
exact processor as it affects generated code are not in any key. Two machines with the same
operating system and processor family share cache entries even when these differ. Containers,
tier 4, and
verifyare what exist to contain them, and onlyverifyis built. - A folder the check cannot see.
buildlsearches for this machine's folders in the places a text enters a key. It does not search anunkeyedvalue, which is in no key, and it does not name the programs a command starts by itself, such as the linker a compiler runs. A tool that writes a folder into its own output is under Where the workspace is, below. - Whether a tool is reproducible.
buildlpins the inputs, the time zone, the locale and the build time, and an action's folder has the same path on every run of one workspace, as long as the temporary directory stays the same. A tool that still gives different bytes from the same inputs is the tool's property.verifyfinds it and names it; nothing fixes it. - Where the workspace is. The action's folder has a different path in another workspace, a git
worktree included, and on a machine whose workspace path or temporary directory differs. That is
by design: no two workspaces share a folder or wait on one. A tool that writes the folder into its
output, as rustc does for a file included from
OUT_DIRor a compiler does for the build directory in debug information, gives other bytes there. That difference is explained; it is not a bug inbuildl. The result is never wrong: a cache only reuses less (see Who should upload). - The settings left out on purpose.
workers,timeout,strategyand a rule'sdescare in no local key. Thetimeoutis in the remote key, not the local one: a remote server names an action by its timeout as well, so a copy with anothertimeoutinbuildl.tomlfetches nothing the first uploaded (Who should upload). Onlystrategycan change an action's bytes: undersandboxthe action runs in another directory with pinned values, so a tool that records its directory or reads the clock can give other bytes than underbare. A compile with debug information is one such tool.
Outside those, a difference between two builds that the ledger cannot explain is not your build's
fault. It is a bug in buildl.
Appendix
The chapters teach buildl one idea at a time. The appendices are for looking things up. A to D
are read from the code and the binary of this version, not from the design documents, so where the
two ever disagree, the appendix says what buildl actually does.
| Appendix | What it holds |
|---|---|
| A. Command-Line Reference | every command, its arguments and flags, and the environment variables buildl reads |
B. buildl.toml Reference | every table and key buildl.toml accepts, with its type, default and meaning |
| C. Build File API | every function of the buildl table a build file calls, and what it accepts and returns |
| D. Exit Codes | the eight exit codes, 0 to 7, and what ends in each |
| E. References | the papers, specifications and tools the design draws on |
A. Command-Line Reference
Everything here is what buildl --help and each command's --help print in this version. Run
buildl from the workspace root, the folder holding buildl.toml, or from any folder below it.
$ buildl --help
A sandboxed, deterministic build system
Usage: buildl [OPTIONS] <COMMAND>
| Command | What it does |
|---|---|
check | Evaluate every build file twice and run nothing |
graph | Print the target graph |
query | Ask what a target needs, or what needs it |
plan | Say what a build would run, and why |
build | Build targets and what they need |
watch | Build targets, then build again when a file they read changes |
test | Run test targets and what they need |
verify | Re-run cached actions and name those whose outputs differ |
doctor | Print the workspace's ceiling, approver, run settings and what its build wants |
log | Show what a target printed when it last ran |
clean | Remove the output directory |
gc | Drop rows of targets no longer declared and remove what nothing needs |
plugins | Work with the plugins buildl.toml names |
buildl help prints the same list, and buildl help <COMMAND> the help of one command.
Options every command takes
These three are accepted before the command and after it, by every command and subcommand.
| Flag | What it does |
|---|---|
--color <WHEN> | When to colour what is printed: auto (the default) colours when standard error is a terminal and NO_COLOR is unset, always always does, never never does |
-h, --help | Print help; -h prints a shorter summary |
-V, --version | Print the version, such as buildl 0.3.1 |
Naming targets
Every command that takes a target accepts it in three forms:
| Form | Means |
|---|---|
//dir:name | the target name declared in the build file of dir |
:name | the target name declared in the build file of the folder you are in |
name | the same as :name |
buildl check
buildl check [OPTIONS]
Evaluates every build file twice and runs nothing. Two evaluations that declare different targets
mean a build file is not deterministic, and check says so. No flags of its own.
buildl graph
buildl graph [OPTIONS]
Prints the target graph.
| Flag | What it does |
|---|---|
--json | Print the graph as canonical JSON, the bytes of .buildl/graph.json (the default) |
--dot | Print the graph in Graphviz DOT |
buildl query
buildl query [OPTIONS] <EXPR>
| Argument | Means |
|---|---|
<EXPR> | deps(TARGET) for what TARGET needs, or rdeps(TARGET) for what needs it |
| Flag | What it does |
|---|---|
--json | Print the answer as canonical JSON |
buildl plan
buildl plan [OPTIONS] [TARGET]...
Says what a build would run, and why, without running it. With no target, it plans every target but tests.
| Flag | What it does |
|---|---|
--set <NAME=VALUE> | Give a build setting a value for this run; may be repeated |
--json | Print the plan as canonical JSON |
buildl build
buildl build [OPTIONS] [TARGET]...
Builds targets and what they need. With no target, it builds every target but tests.
| Flag | What it does |
|---|---|
--set <NAME=VALUE> | Give a build setting a value for this run; may be repeated |
-k, --keep-going | After a failure, still build everything that does not depend on it |
--stream | Show one running action's output as it is printed |
--remote-upload | Upload what this run produced to the remote cache |
--remote-strict | Fail the run when a call to the remote cache fails, instead of warning and building locally |
--no-remote | Do not use the remote cache in this run, and run nothing on the remote, whatever the manifest and variables say |
--remote-execute | Run the actions the remote cache has no result for on the remote, whatever the manifest and variables say |
--no-remote-execute | Run every action here, and keep using the remote cache, whatever the manifest and variables say |
--remote-jobs <N> | How many actions may be with the remote at once, from 1 to 1024, for this run |
The six remote flags are refused, with exit code 2, when they contradict each other or the workspace:
| Refused | Why |
|---|---|
--no-remote with --remote-upload, --remote-strict, --remote-execute or --remote-jobs | the run uses no remote |
--remote-execute with --no-remote-execute | they say opposite things |
--remote-upload, --remote-strict, --remote-execute, --no-remote-execute or --remote-jobs in a workspace with no [remote] table | there is no remote to use |
--remote-jobs in a run where remote execution is off | there is nothing to count |
--remote-upload or --remote-execute under strategy = "bare" | a result from an unconfined action is not shared |
buildl watch
buildl watch [OPTIONS] [TARGET]...
Builds the targets, then builds them again whenever a file the build reads changes, or the build
files declare a different graph. It takes exactly the flags of build:
| Flag | What it does |
|---|---|
--set <NAME=VALUE> | Give a build setting a value for this run; may be repeated |
-k, --keep-going | After a failure, still build everything that does not depend on it |
--stream | Show one running action's output as it is printed |
--remote-upload | Upload what this run produced to the remote cache |
--remote-strict | Fail the run when a call to the remote cache fails, instead of warning and building locally |
--no-remote | Do not use the remote cache in this run, and run nothing on the remote, whatever the manifest and variables say |
--remote-execute | Run the actions the remote cache has no result for on the remote, whatever the manifest and variables say |
--no-remote-execute | Run every action here, and keep using the remote cache, whatever the manifest and variables say |
--remote-jobs <N> | How many actions may be with the remote at once, from 1 to 1024, for this run |
Changes under the output directory, under .buildl and under .git are ignored, and so are
changes to paths a .buildlignore
ignores. watch runs until Ctrl-C, a usage error (exit code 2) or a failure of the file watcher
(exit code 3).
buildl test
buildl test [OPTIONS] [TARGET]...
Runs test targets and what they need. With no target, it runs every test.
| Flag | What it does |
|---|---|
--set <NAME=VALUE> | Give a build setting a value for this run; may be repeated |
--stop | Start nothing new after the first failure |
--stream | Show one running action's output as it is printed |
--rerun | Run the selected tests even when nothing they depend on changed |
--verbose | Show what every test printed, not only what a failing one did |
--remote-upload | Upload what this run produced to the remote cache |
--remote-strict | Fail the run when a call to the remote cache fails, instead of warning and building locally |
--no-remote | Do not use the remote cache in this run, and run nothing on the remote, whatever the manifest and variables say |
--remote-execute | Run the actions the remote cache has no result for on the remote, whatever the manifest and variables say |
--no-remote-execute | Run every action here, and keep using the remote cache, whatever the manifest and variables say |
--remote-jobs <N> | How many actions may be with the remote at once, from 1 to 1024, for this run |
The remote flags are refused in the same cases as for build.
buildl verify
buildl verify [OPTIONS] [TARGET]...
Runs cached actions again in the input sandbox and names those whose outputs differ from the cache.
It records nothing. With no target, it takes every target but tests. Under strategy = "bare" it is
refused.
| Flag | What it does |
|---|---|
--set <NAME=VALUE> | Give a build setting a value for this run; may be repeated |
--sample <N> | Re-run only the N cached actions whose keys sort lowest: the same ones while their keys stay the same |
buildl doctor
buildl doctor [OPTIONS]
Prints the workspace's ceiling, its approver, its run settings, its remote settings and everything its build wants. It refuses nothing and connects to nothing. No flags of its own.
buildl log
buildl log [OPTIONS] <TARGET>
Shows what a target printed when it last ran.
| Argument | Means |
|---|---|
<TARGET> | The target, as //dir:name, :name or name |
| Flag | What it does |
|---|---|
--stdout | Print only what the run wrote to standard output |
--stderr | Print only what the run wrote to standard error, on standard output |
buildl clean
buildl clean [OPTIONS]
Removes the output directory, out unless buildl.toml names another. The cache in .buildl is
kept. No flags of its own.
buildl gc
buildl gc [OPTIONS]
Drops the cache rows of targets no longer declared, and removes from the store what nothing needs. No flags of its own.
buildl plugins
buildl plugins [OPTIONS] <COMMAND>
Works with the plugins buildl.toml names. It has one subcommand.
buildl plugins fetch
buildl plugins fetch [OPTIONS]
Pins every git plugin in buildl.lock and stores its files, so a build needs no network. No flags
of its own.
Environment variables
buildl reads these from the environment it is started in. None of them reaches an action: an
action gets only the variables its target declares.
| Variable | Read by | What it does |
|---|---|---|
NO_COLOR | every command | when set and not empty, --color auto does not colour |
TERM | every command | when unset, empty or dumb, output is plain lines: no live status line and no colour under --color auto |
BUILDL_REMOTE_UPLOAD | build, watch, test | 1 is the same as --remote-upload; 0 or unset is off |
BUILDL_REMOTE_STRICT | build, watch, test | 1 is the same as --remote-strict; 0 or unset is off |
BUILDL_REMOTE_EXECUTE | build, watch, test | 1 turns remote execution on and 0 turns it off, over what [remote] execute says; the flags win over it |
XDG_DATA_HOME | the interactive approver | the folder approvals are kept in, as buildl/approved/<name>.json below it, when it is an absolute path |
HOME | the interactive approver | when XDG_DATA_HOME is not usable, approvals are kept below $HOME/.local/share instead |
PATH | every command that reads the workspace | the folders searched for a program named by its bare name, such as cc, and for git when fetching plugins |
For the three BUILDL_REMOTE_ variables, any value other than 1 or 0 is refused.
B. buildl.toml Reference
buildl.toml sits at the workspace root and marks it. Every table and every key in it is optional,
and an empty file is valid: every setting takes its default, and the ceiling is empty, which allows
nothing. A key this version does not know is an error wherever it stands, and so is a value of the
wrong type or one its key refuses. Each is reported on one line with the place it was written:
error: manifest: buildl.toml:2:4: unknown field `wirte`, expected `read` or `write`
The Line column below names the line of crates/buildl/src/manifest/schema.rs that declares
the key, so you can check this page against the code.
| Table | What it sets | Line |
|---|---|---|
[workspace] | the workspace's name, its build file name and its output directory | 66 |
[ceiling] | the most any build may be granted | 69 |
[declaration] | the limits one build file is evaluated under | 72 |
[execution] | how actions are run | 75 |
[approver] | who approves what a build wants | 78 |
[plugins.<name>] | where each plugin comes from, and what it may have | 81 |
[remote] | the remote cache, and remote execution | 85 |
[workspace]
| Key | Type | Default | Meaning | Line |
|---|---|---|---|---|
name | string | none | a name for people; must not be empty | 93 |
entry | string | "build.lua" | the file name of the build file in every directory | 95 |
out | string | "out" | the directory every output is placed under; not the workspace root, and not .buildl, a directory holding it or one inside it | 97 |
config | integer | none | the version of this file's format; when written, it must be 1 | 99 |
buildl keeps its own files, the cache, the store and the log, in .buildl. No key changes that.
[ceiling]
The ceiling has three parts, written as sub-tables [ceiling.proc], [ceiling.env] and
[ceiling.fs], or as dotted keys such as proc.run = [...] under [ceiling]. A list left out is
empty, and an empty list allows nothing. The output directory and .buildl are not added for you:
a workspace that builds writes them into fs.write itself.
| Key | Type | Default | Meaning | Line |
|---|---|---|---|---|
proc | table | empty | the programs, below | 108 |
env | table | empty | the environment variables, below | 111 |
fs | table | empty | the directories, below | 114 |
proc.run | list of strings | [] | the programs a command may run, by bare name such as "cc" | 123 |
env.read | list of strings | [] | the environment variables a target may read | 132 |
env.unkeyed | list of strings | [] | the variables a target may mark "unkeyed": given to the command, but only the name enters the action key and nothing is sent to a remote server. Every name must also be in env.read, or the file is refused | 135 |
fs.read | list of strings | [] | the directories inputs may come from; "." is the workspace root | 144 |
fs.write | list of strings | [] | the directories a build may write under; "." is the workspace root | 147 |
proc and env are also the names of the same lists in a plugin's table, below. A variable may
be marked "unkeyed" only when every level lists it: the ceiling's env.unkeyed and, for a
plugin's target, the plugin's table and its manifest too. The
Build File API says what the two marks do.
[declaration]
Limits on evaluating one build file. A build file that goes over one stops with an error.
| Key | Type | Default | Meaning | Line |
|---|---|---|---|---|
memory | string | "16MB" | the memory one build file may use: a whole number followed by B, KB, MB or GB, each 1024 times the one before; not zero | 155 |
instructions | integer | 10000000 | how many Lua instructions one build file may run; at least 1 | 157 |
walk_entries | integer | 100000 | how many directory entries one build file's source listings may visit; at least 1. A folder a .buildlignore ignores is not entered and an ignored path is not counted | 159 |
[execution]
| Key | Type | Default | Meaning | Line |
|---|---|---|---|---|
workers | integer | 0 | how many actions run at once; 0 is one per core of the machine | 167 |
timeout | string | "10m" | how long one action may run before it is stopped: a whole number followed by ms, s, m or h; not zero | 169 |
strategy | string | "sandbox" | how strongly actions are kept apart, one of the four below | 171 |
strategy | What this version does with it |
|---|---|
"bare" | runs each action as a plain process in the workspace, with only the variables its target declared |
"sandbox" | runs each action in a fresh directory outside the workspace, holding only its declared inputs, with TZ, LC_ALL and SOURCE_DATE_EPOCH pinned |
"os-sandbox" | accepted, but build, test and verify refuse it |
"container" | accepted, but build, test and verify refuse it |
[approver]
| Key | Type | Default | Meaning | Line |
|---|---|---|---|---|
default | string | "manifest" | who answers whether a build may have what it wants: "manifest", "interactive" or "deny" | 179 |
default | Means |
|---|---|
"manifest" | the ceiling is all the approval there is |
"interactive" | you are asked on the terminal about anything new, and a yes is remembered outside the workspace |
"deny" | no build runs |
[plugins.<name>]
One table per plugin, under the name build files load it by with buildl.use. A plugin comes from
exactly one of path, git and github. What the plugin may have starts empty: a list or flag
left out allows nothing.
| Key | Type | Default | Meaning | Line |
|---|---|---|---|---|
path | string | none | a directory of the workspace holding the plugin; not the output directory or .buildl, nor one holding or inside them; takes no rev | 226 |
git | string | none | the URL of a git repository holding the plugin; needs rev | 228 |
github | string | none | a GitHub repository written owner/repo, the same as git = "https://github.com/owner/repo"; needs rev | 230 |
rev | string | none | the tag or full commit the repository is pinned to | 232 |
dir | string | the repository root | the folder of the repository that holds the plugin, relative to its root, with no .., no leading / and no empty part; only that folder is stored and digested; takes git or github, not path | 234 |
proc | table | empty | holds run, the programs the plugin's targets may run | 237 |
env | table | empty | holds read and unkeyed, the environment variables the plugin's targets may read, and may mark "unkeyed" | 240 |
network | boolean | false | whether the plugin's targets may reach the network | 242 |
proc.run | list of strings | [] | as in [ceiling] | 123 |
env.read | list of strings | [] | as in [ceiling] | 132 |
env.unkeyed | list of strings | [] | as in [ceiling]; every name must also be in this table's env.read | 135 |
[remote]
The remote cache this workspace shares results with, which may also run actions. With no
[remote] table, buildl uses no remote. When the table is there, url is required.
| Key | Type | Default | Meaning | Line |
|---|---|---|---|---|
url | string | required | the cache's address: grpc:// or grpcs://, a host, and an optional :port | 187 |
instance | string | none | the instance name the cache's storage is addressed under | 189 |
ca | string | none | a certificate authority file to trust: an absolute path, or one inside the workspace | 191 |
token | table | none | where the token sent with every request comes from, below; only over grpcs:// | 193 |
header | string | "authorization" | the request header the token is sent in | 195 |
timeout | string | "30s" | how long one request may take, written as in [execution] | 197 |
execute | boolean | false | whether the cache also runs the actions it has no result for | 199 |
jobs | integer | 128 | how many actions may be with the remote at once, from 1 to 1024 | 201 |
queue_timeout | string | "1h" | how long a remote execution may wait in the cache's queue, written as in [execution] | 203 |
retries | integer | 5 | how many times a failed call is tried again after the first, from 0 to 10 | 205 |
properties | table of strings | none | the platform properties asked of the remote executor, such as pool = "large"; OSFamily and ISA are set by buildl and cannot be written | 208 |
token names exactly one of its two keys:
| Key | Type | Meaning | Line |
|---|---|---|---|
token.env | string | the environment variable holding the token | 216 |
token.file | string | the file holding the token: an absolute path, or one inside the workspace | 218 |
Every table at once
This buildl.toml writes every table, and every key but the four that fetch a plugin from git.
Beside it are a build.lua declaring one target and an empty folder plugins/local. It passes
buildl check:
[workspace]
name = "everything"
entry = "build.lua"
out = "out"
config = 1
[ceiling]
proc.run = ["sh"]
env.read = ["CC"]
env.unkeyed = ["CC"]
fs.read = ["."]
fs.write = ["out", ".buildl"]
[declaration]
memory = "16MB"
instructions = 10000000
walk_entries = 100000
[execution]
workers = 0
timeout = "10m"
strategy = "sandbox"
[approver]
default = "manifest"
[plugins.local]
path = "plugins/local"
proc.run = ["sh"]
env.read = ["CC"]
env.unkeyed = ["CC"]
network = false
[remote]
url = "grpcs://cache.example.com:443"
instance = "main"
ca = "certs/ca.pem"
token.env = "BUILDL_TOKEN"
header = "authorization"
timeout = "30s"
execute = false
jobs = 128
queue_timeout = "1h"
retries = 5
properties = { pool = "large" }
$ buildl check
ok: 1 declaration in 1 build file
A plugin from git is written with git or github, and rev, and with dir when the plugin is
one folder of the repository:
[plugins.fromgit]
git = "https://example.com/plugins/fromgit.git"
rev = "v1.0.0"
[plugins.fromgithub]
github = "example/fromgithub"
rev = "v1.0.0"
dir = "plugins/fromgithub"
Every command that reads the workspace, check included, refuses such a plugin until
buildl plugins fetch has pinned it in buildl.lock:
$ buildl check
error: plugin fromgit is not fetched: buildl.lock does not pin https://example.com/plugins/fromgit.git at v1.0.0; run `buildl plugins fetch`
Plugins from Git shows the whole round.
C. Build File API
A build file reaches buildl through one table, bound to two names: the global buildl, and
airsstack.buildl beside the other airsstack modules (json, path, regex, hash and
glob). The book's examples start with local b = buildl. The table holds twelve functions:
| Function | Returns | Declares |
|---|---|---|
target(name, options) | nothing | a target that builds files |
test(name, options) | nothing | a test target |
discover(name, options) | nothing | a discovery target |
rule(name, options) | nothing | a command several targets share |
alias(name, target) | nothing | a second name for a target |
option(name, options) | nothing | a build setting |
subdir(path) | nothing | another directory with a build file |
sources(pattern) | a list of file names | |
folder() | a string | |
discovered(label) | a string, or nil | |
decode_all(text) | a list of values | |
use(name) | the plugin's module |
The names come from crates/buildl-lua/src/module.rs, where the table is filled. This build file
asks the table for its own keys and shows them in an error, since a build file cannot print:
local names = {}
for k in pairs(buildl) do names[#names + 1] = k end
table.sort(names)
error("buildl holds: " .. table.concat(names, " "), 0)
$ buildl check
error: build.lua: runtime error: lua error in build.lua: runtime error: buildl holds: alias decode_all discover discovered folder option rule sources subdir target test use
stack traceback:
[C]: in ?
[C]: in function 'error'
build.lua:4: in main chunk
How arguments are read
The rules every function shares:
- An options table accepts only the keys listed for its function. Any other key is an error, so a misspelt key never passes silently.
- A list option takes strings, and may hold lists of strings one level deep, which are spliced in
place:
{ "go.mod", b.sources("*.go") }is one flat list. - A name, a path and a label are plain strings.
- A function that refuses its arguments fails the build file with the line that called it. A
pcallaround the call does not undo that: the build file has still failed. - File names in
inputsand patterns insourcesare relative to the folder of the build file.
Labels
deps, rule, an alias's target and discovered name a target in one of three ways:
| Form | Means |
|---|---|
"//dir:name" | the target name declared in the build file of dir; "//:name" is the root's |
":name" | the target name in this build file's folder |
"name" | the same as ":name" |
Placeholders in commands
A command never holds a real path. Inside each string of run, these words are replaced just
before the action runs:
| Placeholder | Becomes |
|---|---|
$in | the target's inputs, in the order written |
$out | the target's outputs, in the order written |
$deps | every output of every dependency |
$opt:name | the value of the build setting name |
A string that is exactly $in, $out or $deps becomes one argument per path, and none when the
list is empty. Inside a longer string, such as "$out/app" or "--src=$in", the paths are joined
by single spaces. $input is not a placeholder: the word after $ must be exactly in, out or
deps. The paths are relative to the workspace root.
target(name, options)
Declares a target that builds files. Returns nothing.
| Option | Type | Default | Meaning |
|---|---|---|---|
run | list of strings | the command: program first, then its arguments | |
rule | label | a rule whose run is the command instead; exactly one of run and rule | |
inputs | list of strings | {} | the files the command reads; a file a .buildlignore ignores is refused (exit code 5), a plugin's inputs included |
deps | list of labels | {} | the targets whose outputs the command reads |
outputs | list of strings | { name } | the files the command writes |
env | table from name to "key" or "unkeyed" | {} | the environment variables the command is given, read from yours, each with its mark, below |
network | boolean | false | true says the command reaches the network; plan and the approver show it |
stdout | boolean | false | true makes what the command prints the output; needs exactly one output |
always | boolean | false | true runs the command on every build instead of caching it |
b.target("hello.txt", { run = { "sh", "-c", "echo hello > $out" } })
The marks of env
env names each variable and marks it. The mark says whether the variable's value is part of what
makes the action's key:
| Mark | Given to the command | In the action key | Sent to a remote server |
|---|---|---|---|
"key" | its value | name and value | name and value |
"unkeyed" | its value | name only | no |
b.target("app", {
run = { "cargo", "build" },
env = { RUSTFLAGS = "key", HOME = "unkeyed", PATH = "unkeyed" },
})
- Every variable is marked: there is no default mark.
env = {}, or noenv, declares none. - A list such as
env = { "HOME" }, and a table that mixes the two, such asenv = { "HOME", PATH = "unkeyed" }, are refused. - A mark that is not the string
"key"or"unkeyed"is refused. TZ,LC_ALLandSOURCE_DATE_EPOCHare refused with either mark: the sandbox sets them.- An
"unkeyed"variable that is not set on the machine is not given to the command, and the key is the same as when it is set. - A
"key"variable whose value holds one of this machine's folders is refused, and so is a command that does. Exit Codes lists the messages. "unkeyed"needs the name inenv.unkeyedinbuildl.toml, besideenv.read([ceiling]).
test(name, options)
Declares a test, run by buildl test and passed when its command exits 0. Returns nothing. It
takes the options of target except stdout, and outputs defaults to none: a test is a record of
its exit status and what it printed.
| Option | Type | Default |
|---|---|---|
run | list of strings | |
rule | label | |
inputs | list of strings | {} |
deps | list of labels | {} |
outputs | list of strings | {} |
env | table from name to mark | {} |
network | boolean | false |
always | boolean | false |
b.test("hello_test", { run = { "grep", "-q", "hello", "$deps" }, deps = { ":hello.txt" } })
discover(name, options)
Declares a discovery target: an action whose one output, <name>.json, a later pass of the build
files reads with discovered. Returns nothing. It takes the options of
target except outputs and always, since its output is fixed and it is always cached.
| Option | Type | Default |
|---|---|---|
run | list of strings | |
rule | label | |
inputs | list of strings | {} |
deps | list of labels | {} |
env | table from name to mark | {} |
network | boolean | false |
stdout | boolean | false |
b.discover("pkgs", { run = { "go", "list", "-json=ImportPath", "./..." }, stdout = true })
rule(name, options)
Declares a command that targets name with rule instead of writing their own run. Its
placeholders take the values of the target that uses it. Returns nothing.
| Option | Type | Default | Meaning |
|---|---|---|---|
run | list of strings | required | the command |
desc | string | none | the line shown for each action that uses the rule; placeholders are replaced in it too |
b.rule("join", { run = { "cat", "$in" }, desc = "joining $in" })
alias(name, target)
Declares name as a second name for target, a label. Returns nothing.
b.alias("default", ":hello.txt")
option(name, options)
Declares a build setting, which a command reads as $opt:name and a run changes with
--set name=value. Returns nothing.
| Option | Type | Default | Meaning |
|---|---|---|---|
default | string | required | the value when no --set gives another |
b.option("greeting", { default = "hello" })
subdir(path)
Adds the build file of the folder path, relative to this one, to the workspace. It is read too,
and its targets are named by its folder from the workspace root, such as //lib:name. A path that
leaves the workspace is refused, and so is a folder a
.buildlignore ignores (exit code 5).
Returns nothing.
b.subdir("lib")
sources(pattern)
Returns the files below this build file's folder whose path matches pattern, as a list of
strings relative to the folder, sorted. * matches within one folder name and stops at /;
**/ matches any number of folders, none included. Only regular files are listed, links are not
followed, and the output directory and .buildl are never searched. A path a
.buildlignore ignores is not
listed, and an ignored folder is not entered. Every other entry visited counts against
[declaration] walk_entries; an ignored one does not. A .buildlignore the walk meets that cannot
be used stops the build file with exit code 5.
local go_files = b.sources("**/*.go")
folder()
Returns the folder of the build file that is being read, as a string relative to the workspace root:
"" in the root build file, "lib" in lib/build.lua, "lib/net" in lib/net/build.lua. It takes
no arguments. Inside a plugin it is the folder of the build file that called the plugin, not the
plugin's own.
local dir = b.folder()
discovered(label)
Returns the output of the discovery target label as a string, or nil when it has not run yet.
build and test run discovery targets first, then read the build files again, so in that second
pass the string is there.
local listed = b.discovered(":pkgs")
decode_all(text)
Returns a list of the JSON values in text, one after another, as airsstack.json.decode would
give each. Values are separated by white space, which may be left out beside an object, an array
or a string. Empty text gives an empty list. Unlike the other functions, its errors are plain Lua
errors that pcall can catch.
for _, pkg in ipairs(b.decode_all(listed or "")) do --[[ one target per package ]] end
use(name)
Loads the plugin buildl.toml names under [plugins.<name>] and returns what its entry file
returns, usually a table of functions. A second use of the same name in the same build file
returns the same value without loading the plugin again.
local zip = b.use("zip")
What is taken away
A build file runs with no way to reach the world or to differ from one run to the next. Three
standard Lua functions are removed, set to nil:
| Removed | Why |
|---|---|
print | a build file declares, it does not talk; an error is the way to show something |
math.random | a random number would declare something different on every run |
math.randomseed | goes with math.random |
tostring and string.format are also changed: for a table or function without its own
__tostring they raise an error instead of giving text with a memory address in it, which would
differ on every run.
D. Exit Codes
buildl ends with one of eight codes, so a script, a CI job or an editor can tell whose fault a
failure is without reading the message. They are defined in crates/buildl/src/cli/exit.rs.
| Code | Name | Whose fault | Running again may help? |
|---|---|---|---|
| 0 | Success | nobody's: the command did what it was asked | |
| 1 | ActionFailure | the code being built | no, fix the code |
| 2 | Usage | the command line | no, fix the command |
| 3 | Infrastructure | the builder or the machine | yes |
| 4 | Refused | the build wants more than the workspace allows, or than was approved | no, widen the ceiling or approve |
| 5 | Definition | a build file or buildl.toml | no, fix the file |
| 6 | CorruptState | a file buildl keeps its state in | no, the state was changed by something else |
| 7 | Internal | buildl itself: a bug | no, report it |
The codes stay clear of 126, 127 and everything above 128, which a shell uses for its own
meanings. The code a failed action exited with is never buildl's own: it is in the report of the
failure, as exit status 1 below.
When one build has targets that end in different ways, the most serious code wins: 7 over 3, and 3 over 1. A builder that failed means the run says nothing reliable about the code.
0, Success
Every target asked for was built, served from the cache, fetched from the remote cache or run
there. A target skipped because another failed does not change the code: that failure decides it.
A verify that checked nothing also ends with 0.
$ buildl build hello.txt
1 built
$ echo $?
0
1, ActionFailure
An action ran and failed. Any of these ends with 1:
- it exited with a status other than 0;
- a signal ended it, which is how a timeout ends it;
- it exited 0, but left nothing, or something that cannot be kept, where a declared output should be;
- its output is what it prints (
stdout = true), and it also wrote that output's file itself; verifyran it again and its outputs differ from the cache.
b.target("broken.txt", { run = { "sh", "-c", "echo no file for you; exit 1" } })
$ buildl build broken.txt
--- //:broken.txt
no file for you
FAILED //:broken.txt: action failure (exit status 1)
declared in build.lua
command: sh -c "echo no file for you; exit 1"
1 failed
$ echo $?
1
2, Usage
The command line is wrong:
- an unknown flag or argument, or a missing one;
- a target no build file declares, or a
querythat is notdeps(...)orrdeps(...); --setfor a setting nothing declares;testgiven a target that is not a test;logasked for a target that has never run;- remote flags that contradict each other or the workspace, upload or remote execution asked for
under
strategy = "bare", aBUILDL_REMOTE_variable that is neither1nor0, or a remote token that is named but cannot be read.
$ buildl build --fast
error: unexpected argument '--fast' found
tip: to pass '--fast' as a value, use '-- --fast'
Usage: buildl build [OPTIONS] [TARGET]...
For more information, try '--help'.
$ echo $?
2
3, Infrastructure
The builder or the machine failed, and nothing is known about the code. Running again may help:
- a program a command names is not found;
- the builder could not run an action at all;
- another
buildlholds the workspace, or a file of.buildlcannot be read or written; - a call to the remote cache failed under
--remote-strict; - fetching a plugin from git failed;
- the file watcher of
watchfailed; - what a target printed when it last ran, or an output
verifyneeds, is gone from the store.
With a [remote] table whose url points at a port nothing listens on, here
grpc://127.0.0.1:1, and --remote-strict, the first lookup fails after its five retries:
$ buildl build --remote-strict
error: remote cache: lookup: grpc://127.0.0.1:1: ActionCache.GetActionResult: cannot connect: transport error: tcp connect error: tcp connect error: Connection refused (os error 61) (after 6 calls)
$ echo $?
3
The os error number is the operating system's: 61 on macOS, 111 on Linux. Without
--remote-strict, the same run warns and builds locally:
$ buildl build
warning: remote cache lookup failed: grpc://127.0.0.1:1: ActionCache.GetActionResult: cannot connect: transport error: tcp connect error: tcp connect error: Connection refused (os error 61) (after 6 calls); the build goes on without it
1 built
$ echo $?
0
4, Refused
The build wants something it may not have:
- a program, variable or directory outside the ceiling in
buildl.toml, or a variable marked"unkeyed"thatenv.unkeyeddoes not list; - a plugin's target wants something its plugin does not allow;
- the approver said no, or is
deny.
The ceiling here allows only sh, and the target runs python3:
b.target("version.txt", { run = { "python3", "--version" }, stdout = true })
$ buildl build version.txt
error: build.lua: //:version.txt: program python3 is outside the ceiling (proc.run allows: sh)
$ echo $?
4
A variable marked "unkeyed" is held to env.unkeyed at every level, as a variable marked "key"
is held to env.read. Here the ceiling lists HOME in env.read but not in env.unkeyed, and the
target marks it "unkeyed":
b.target("app", { inputs = { "a.txt" }, env = { HOME = "unkeyed" }, run = { "cp", "$in", "$out" } })
$ buildl plan
error: build.lua: //:app: unkeyed variable HOME is outside the ceiling (env.unkeyed allows: nothing)
$ echo $?
4
When the plugin's table in buildl.toml is what leaves HOME out of env.unkeyed, the message
names the plugin and its version:
$ buildl plan
error: build.lua: //:bye (plugin gobin@0.1.0): unkeyed variable HOME is outside plugin gobin@0.1.0 (env.unkeyed allows: nothing)
$ echo $?
4
5, Definition
A build file or buildl.toml is wrong, and editing it is the fix:
- a build file has a syntax error, raises an error, or goes over a
[declaration]limit; - a folder named by
subdirhas no build file; - a declaration is refused: an unknown option, both or neither of
runandrule, a name declared twice, a label or setting that names nothing, a dependency cycle, an input file that does not exist, two targets writing the same output, a command with no program; - an
inputsentry or asubdirnames a path a.buildlignoreignores, or a.buildlignorecannot be used, below; - two evaluations of the build files declared different things;
- a target declares
TZ,LC_ALLorSOURCE_DATE_EPOCH, which the sandbox sets itself; - a target's
envis wrong, or a target or a discovery output holds one of this machine's folders, below; - a git plugin has not been fetched;
buildl.tomlis missing, does not parse, lists a name inenv.unkeyedthatenv.readdoes not, or asks for what this version cannot do, such asstrategy = "container".
This build.lua is missing the }) that closes the options and the call:
local b = buildl
b.target("hello.txt", { run = { "sh", "-c", "echo hello > $out" }
$ buildl build
error: build.lua: syntax error: lua error in build.lua: syntax error: build.lua:3: '}' expected (to close '{' at line 2) near <eof>
$ echo $?
5
.buildlignore
These cases are also exit 5, and buildl check reports them, since the build files are read to
find them. Leaving paths out
says what the files do.
| Case | Message |
|---|---|
an inputs entry is ignored | error: <build file>: inputs: <path> is ignored by <file> (<pattern>) |
a subdir names an ignored folder | error: <build file>: subdir: <folder> is ignored by <file> (<pattern>) |
| a pattern does not parse | error: <file>:<line>: error parsing glob '<pattern>': <why> |
| the file is not UTF-8 | error: <file>:<line>: not UTF-8, the line being the first with bytes that are not |
| the file cannot be used | error: <file>: <why>, with no line |
When a plugin made the declaration, <build file> is followed by (plugin <chain>), as in
error: build.lua (plugin pl@0.1.0): inputs: notes/todo.txt is ignored by .buildlignore (notes/).
An inputs entry under notes/, which the root .buildlignore ignores with notes/:
b.target("bundle", { inputs = { "notes/todo.txt" }, run = { "cat", "$in" }, stdout = true })
$ buildl check
error: build.lua: inputs: notes/todo.txt is ignored by .buildlignore (notes/)
$ echo $?
5
A subdir of examples, which the root .buildlignore ignores with examples/:
b.subdir("examples")
$ buildl check
error: build.lua: subdir: examples is ignored by .buildlignore (examples/)
$ echo $?
5
A pattern that does not parse, here [z-a] on line 1 of lib/.buildlignore. The message is the
glob error with the file and line in front:
$ buildl check
error: lib/.buildlignore:1: error parsing glob '[z-a]': invalid range; 'z' > 'a'
$ echo $?
5
When the file is first read by buildl.sources, the build file that called it fails with the same
text inside a runtime error. The exit code is the same:
$ buildl check
error: lib/build.lua: runtime error: line 4: buildl.sources: lib/.buildlignore:1: error parsing glob '[z-a]': invalid range; 'z' > 'a'
$ echo $?
5
A lib/.buildlignore whose second line holds a byte that is not UTF-8:
$ buildl check
error: lib/.buildlignore:2: not UTF-8
$ echo $?
5
A lib/.buildlignore that is a symbolic link is not followed:
$ buildl check
error: lib/.buildlignore: a symlink, not a file
$ echo $?
5
One that cannot be read gives the operating system's own text:
$ buildl check
error: lib/.buildlignore: Permission denied (os error 13)
$ echo $?
5
env and this machine's folders
These cases are also exit 5. Each message starts with the file that is wrong: a build file with the
target, or buildl.toml. Where a message shows the home folder, it is /home/alice, the HOME of
the run it was captured from.
| Case | Message |
|---|---|
env written as a list, or a list mixed with marks | error: build.lua: //:app: env must mark each variable "key" or "unkeyed", such as env = { HOME = "unkeyed" } |
a mark that is not "key" or "unkeyed" | error: build.lua: //:app: env HOME is marked "pass"; mark it "key" or "unkeyed" |
| a variable name that is not valid | error: build.lua: declaration #0: invalid env: invalid environment variable name: "A-B" — may hold only ASCII letters, digits and '_' |
TZ, LC_ALL or SOURCE_DATE_EPOCH, with either mark | error: build.lua: //:app: env TZ is set to UTC by the sandbox and cannot be declared |
env.unkeyed lists a name its table's env.read does not | error: buildl.toml: ceiling env.unkeyed lists HOME, which env.read does not |
| a word of a command holds this machine's folder | error: build.lua: //:note: the command holds this machine's path /home/alice; it would give the target another key on every machine |
a "key" variable's value holds one | error: build.lua: //:app: the variable RUSTFLAGS holds this machine's path /home/alice; mark it "unkeyed" if it only finds files |
| a setting a command names holds one | error: build.lua: //:app: the setting prefix holds this machine's path /home/alice; it would give the target another key on every machine |
| a discovery target's output holds one | error: build.lua: //:cargo.metadata: its output holds this machine's path /home/alice |
A name in env.unkeyed that env.read does not list is refused in the same way in a
[plugins.<name>] table and in a plugin's extension.toml, and the message names that table or
file.
The folders checked are the home folder, the workspace folder and the action's folder. Inputs and outputs are workspace-relative, so they are not checked, and neither is
the value of an "unkeyed" variable, which is in no key. Each check runs at its own moment:
| What holds the folder | When it is refused |
|---|---|
| a word of a command | by every command that reads the build files, before anything runs |
a "key" variable's value, or a setting's value | when the action's key is gathered |
| a discovery target's output | when the second pass reads it |
The discovery's own run finishes, as the 1 built line shows, and its output stays in the cache, so
the refusal comes again on every run until the discovery's command changes. tail -n 2 leaves out
anything the discovery printed, and /home/alice stands for your own home folder. The command
exits with code 5:
$ buildl build 2>&1 | tail -n 2
1 built
error: build.lua: //:cargo.metadata: its output holds this machine's path /home/alice
6, CorruptState
A file in .buildl does not hold what buildl writes there: it is not JSON, it does not describe
what it should, or its bytes are not the exact bytes buildl writes for that value. The same code
is given when a fetched plugin's files in the store are no longer the ones buildl.lock pinned.
buildl never makes such a file itself, so something else changed it.
7, Internal
buildl reached a state it has no answer for: an error that should never happen, or an error or
outcome this binary has no row for in its table of codes. This is a bug in buildl, never the user's fault.
E. References
The works the design and architecture of buildl draw on, each listed once.
The Lua runtime
- airsstack. airsl — Embeddable Lua runtime with a host standard library (source, its architecture, sandbox and extension documents, and its workspace lint and dependency policy). GitHub, 2026. https://github.com/airsstack/airsl
- airsstack. airsl crate. crates.io, 2026. https://crates.io/crates/airsl
- khvzak et al. mlua — high-level Lua bindings for Rust. crates.io. https://crates.io/crates/mlua
Build systems
- Andrey Mokhov, Neil Mitchell, Simon Peyton Jones. Build Systems à la Carte. Microsoft Research / ICFP, 2018. https://www.microsoft.com/en-us/research/uploads/prod/2018/03/build-systems.pdf
- Build System Fundamentals. A study document, not published, drawing on Mokhov, Mitchell, Peyton Jones et al.
- Task Runner Fundamentals. A study document, not published.
- Evan Martin et al. The Ninja build system — manual (depfiles, restat). ninja-build.org. https://ninja-build.org/manual.html
- xmake-io. Xmake — a cross-platform build utility based on Lua. xmake.io. https://xmake.io/
- Google / Bazel authors. Hermeticity. bazel.build. https://bazel.build/basics/hermeticity
- Google / Bazel authors. Sandboxing. bazel.build. https://bazel.build/docs/sandboxing
- Reproducible Builds project. SOURCE_DATE_EPOCH specification. reproducible-builds.org. https://reproducible-builds.org/specs/source-date-epoch/
Remote cache and execution
- Bazel authors. remote-apis — An API for caching and execution of actions on a remote system (the Digest and ActionCache model). GitHub. https://github.com/bazelbuild/remote-apis
- Bazel authors. remote-apis —
build/bazel/remote/execution/v2/remote_execution.protoandplatform.md, at commitc2c07e3d718d3d490a4958344d9c3e47de0bfaf3. GitHub. https://github.com/bazelbuild/remote-apis/tree/c2c07e3d718d3d490a4958344d9c3e47de0bfaf3 - Google. googleapis —
google/bytestream/bytestream.protoand the other protos the REAPI imports, at commitdff1cd0c7ff8c26ff4c9f7a87cbe175fb5124d4e. GitHub. https://github.com/googleapis/googleapis/tree/dff1cd0c7ff8c26ff4c9f7a87cbe175fb5124d4e - BuildBuddy. Bazel's Remote Caching and Remote Execution Explained. buildbuddy.io. https://www.buildbuddy.io/blog/bazels-remote-caching-and-remote-execution-explained/
- Buchgr et al. bazel-remote — a remote cache for REAPI clients. GitHub. https://github.com/buchgr/bazel-remote
Rust libraries
- petgraph developers. petgraph — graph data structures and algorithms (toposort). docs.rs. https://docs.rs/petgraph/
- rayon developers. rayon — data parallelism with work stealing. crates.io. https://crates.io/crates/rayon
- notify-rs authors. notify — cross-platform filesystem notification library for Rust (8.2.1: FSEvents on macOS, inotify on Linux). crates.io, 2026. https://crates.io/crates/notify
Approvals
- direnv authors. direnv —
internal/cmd/rc.go, the allow list under$XDG_DATA_HOME/direnv/allow. GitHub. https://github.com/direnv/direnv/blob/master/internal/cmd/rc.go
Software architecture
- Simon Brown. The C4 model for visualising software architecture. c4model.com. https://c4model.com/
- arc42. Building block view. https://docs.arc42.org/section-5/
- Robert C. Martin. The Dependency Inversion Principle. C++ Report, 1996.
- Alistair Cockburn. Hexagonal architecture (ports and adapters). https://alistair.cockburn.us/hexagonal-architecture/
- Rust library team. Rust API Guidelines — Future proofing (C-SEALED). https://rust-lang.github.io/api-guidelines/future-proofing.html
- Microsoft. Pragmatic Rust Guidelines. https://microsoft.github.io/rust-guidelines/
- The Cargo team. The Cargo Book — Publishing on crates.io. https://doc.rust-lang.org/cargo/reference/publishing.html
Agent skills
- Agent Skills authors. Agent Skills specification (the
SKILL.mdformat thebuildlandbuildl-migrateskills follow). agentskills.io. https://agentskills.io/specification
Cargo
- The Cargo team. The Cargo Book — External tools: Custom subcommands (
cargo-<name>onPATHruns ascargo <name>). https://doc.rust-lang.org/cargo/reference/external-tools.html#custom-subcommands