Why buildrules

Why the rules are built the way they are, how they work, and what they give up. Where a thing is planned and not built, the text says "planned". How to use it is the manual.

Note. This page describes the repository at its current main. The longer text, with section numbers, is docs/why.md in the repository.

Summary #

buildrules is a set of Buck2 rules and a command line, written in Zig, that builds Rust, Node.js, Zig, C/C++ and Mojo projects from the files their native tools already use (Cargo.toml, Cargo.lock, package.json, package-lock.json, mopm.toml), with every compiler and runtime pinned by hash, and with a separate cacheable action for each dependency.

Four ideas carry the design:

  1. The native lockfile stays the source of truth. buildrules never keeps a second dependency list, and cargo build, cargo test and npm test keep working on the same files.
  2. Toolchains are pinned downloads, not host installs. No action reads a host compiler, a host PATH or a host node.
  3. The unit of caching is one dependency. A registry crate is one action, an npm package is one download, a Mojo package is one action. A change recompiles what it touched and nothing else.
  4. Build metadata is generated ahead of time and checked. A command (buildrules sync) bakes the lockfiles into a generated table, and a second command (buildrules check) refuses a table that has gone stale.

Status: version 0, linux x86_64 only for the rules. The public repository's releases hold a source archive and the command line for three platforms (see Releases).

Planned. Not built: Arm and macOS (and Windows) hosts for the rules, and Python rules. A Homebrew formula and an apt repository are made by every release and published only after setup (RELEASING.md). See what is not done.

The problem #

Native tools are good at one language #

cargo, npm and zig build are what the people who write each language expect to use. They resolve versions, write a lockfile, build and test. A repository of several languages meets the limit: each tool has its own idea of caching and of where a build happens, and none knows about the others. The glue is shell scripts and CI configuration, which nothing checks.

Monorepo build systems take the description over #

Systems such as Buck2 and Bazel express the whole graph, across languages, as targets in build files. That buys one scheduler, one cache and remote execution. The usual price is that the build system's description becomes the source of truth: dependencies are copied from a lockfile, and the native tool no longer knows about the build, so its own commands stop working or work on a copy that can drift. buildrules is an attempt to keep the benefits and avoid that price. (This paragraph is background about build systems in general, not a claim about this repository's code.)

Host toolchains make builds differ between machines #

A build that calls whichever rustc, cc or node is on the PATH produces different output on different machines, and a cache keyed on the inputs cannot tell. The cache is unsound (a hit can return the output of a different compiler) or useless between machines (the key has to include the machine). The fix is to make the compiler an input: download it by hash, give every action a path to it, and give the action nothing else.

Caches that miss #

buildrules answers the first with one action per dependency and the second by building every pinned tool with the working directory remapped out of its output, and then building each test repository twice in two directories to prove it (see determinism).

Remote execution needs complete inputs #

Remote execution runs an action on another machine that has only what the action declares. A build that works locally because the host happens to have a library fails there, or works there by accident. Remote execution is therefore a strong test of hermeticity, and buildrules uses it that way: its default execution platform is remote, and a local fallback exists only as an explicit opt-in.

The approach #

buildrules is a thin layer. It does not replace Cargo's resolver, npm's resolver or mopm's. Each of them still decides what the dependency graph is. buildrules reads the decision and turns it into Buck2 actions. Buck2 supplies the scheduler, the content-addressed cache and the Remote Execution API client.

LanguageWho decides the graphWhat buildrules readsWhat it adds
RustCargoCargo.lock, and the unit graph Cargo prints (--unit-graph)one action per unit; pinned rustc, std, cargo, clippy
Node.jsnpmpackage-lock.json (lockfile version 3)one download per locked tarball; pinned Node.js
Mojomopmmopm's unit graph (mopm plan --unit-graph)one action per unit (mopm unit build); pinned mopm
Zigyou, by handbuild files you writepinned Zig, tests welded to executables
C/C++you, by handthe prelude's cxx_library and cxx_binarya toolchain on the pinned Zig (zig cc)

What a user sees #

shell
buildrules init . --git <origin> --commit <40 hex>   # once per repository
buildrules cargo new crates/hello                    # or: cargo adopt
buildrules sync                                      # after Cargo.toml, Cargo.lock or rust-toolchain.toml change
buck2 build //crates/hello:test //crates/hello:debug
buildrules check                                     # offline, read-only: the pull-request gate

A member's BUCK file is two lines and the command line writes it. Node and Mojo have the same shape (buildrules npm sync, buildrules mojo sync, one macro call per package).

crates/hello/BUCK
load("//:buildrules.bzl", "cargo_package")

cargo_package(path = ".")

Layers #

your repository
  .buckconfig                    cells, execution platforms, pinned buildrules commit
  toolchains/BUCK                one call per toolchain family
  platforms/BUCK                 the execution platforms
  buildrules.lock.bzl            generated table (Rust)         <- buildrules sync
  buildrules.bzl                 generated binding of table to macros
  third_party/buildrules/BUCK    registry crates as units
buildrules (a Buck2 cell, pinned to one commit)
  rules/                         the rules: rust, node, zig, cxx, mojo, mopm, coverage, core, pins
  cli/                           the `buildrules` program (Zig); contains the generator
  platforms/                     target platforms, one per instruction-set level
Buck2 (pinned release; the bundled prelude is part of the binary)

buildrules is used as a Buck2 cell pinned by a full commit hash (a git external cell, or a vendored copy). Every machine that builds the repository gets the same rules. The pin is a commit, not a branch or a tag: buildrules init refuses anything that is not 40 lower-case hex digits.

The Mojo rules avoid transitive sets. Buck2 treats a .bzl file's types as distinct per loading cell (an open upstream limitation, facebook/buck2#683), so a transitive set's type is per cell. The providers of the Mojo rules are lists and dicts, which cross cells, so a rules cell can sit next to a consumer cell.

The sync and check model #

Starlark cannot read TOML. While Buck2 loads a package, a macro cannot open Cargo.toml, and shelling out at load time would put an unpinned tool into every query. So the reading happens ahead of time, in buildrules sync, and its result is written down as data: buildrules.lock.bzl (pure Starlark literals: the compiler version, the sha256 of Cargo.lock and of every Cargo.toml, the policy, and one row per unit), buildrules.bzl (the binding to the macros) and third_party/buildrules/BUCK (the registry crates). All three are committed. A second sync on unchanged inputs writes the same bytes, and a generated file says "Do not edit" in its first line.

Staleness has three layers, from cheap to thorough:

No compile action takes a Cargo.toml as an input, so editing the policy in [package.metadata.buildrules] re-runs the check and nothing else. The cost is real: a developer must remember to run sync after changing a manifest. The design makes forgetting loud (the pull-request check fails; the build fails) instead of silent.

Rust: one action per unit #

cargo build --unit-graph is unstable, so sync sets RUSTC_BOOTSTRAP=1 for that one invocation, and nothing is compiled. It prints the graph Cargo itself would execute: every crate, with its features, profile, edition and dependencies. sync runs it per member and per verb (build, test, release), merges the graphs, and writes one table row per distinct unit. buildrules does not re-implement Cargo's resolver or feature unification.

Each unit becomes one cargo_unit target, named by a content id, <crate>-<version>_<hash>. The hash covers the unit's body: sources, features, flags, profile fields that rustc sees, and the ids of its dependencies. Two builds that share a unit share its target and so its action key. Nothing in the key names the workspace member being edited. That is the per-crate cache.

ModeAction
buildcompile an rlib, a proc-macro, or a binary
testcompile with --test and run the binary; the output is a .passed marker
run-custom-buildrun a build script and capture what Cargo would
lintrun clippy-driver with the member's [lints]; a lint under -D warnings fails the action

Compilation runs the pinned rustc through rustc_launch, a small Zig program. It rebuilds the environment from nothing (an empty PATH; private HOME, TMPDIR and Zig caches), remaps the working directory to ., and acts as the linker: it runs zig cc from the pinned Zig with -Wl,--strip-debug, because Zig's C runtime start-up objects otherwise record the directory they were built in.

Build scripts run under bs_runner, which reproduces what Cargo gives a script: OUT_DIR, CARGO_CFG_*, DEP_<LINKS>_<KEY> from direct dependencies with links, and CC, CXX and AR pointing at the pinned Zig. A variable the script reads and the runner does not define is unset. The runner honors rustc-cfg, rustc-link-lib, rustc-link-search, rustc-flags, rustc-env, warning, error and metadata, and refuses rustc-link-arg* and any other rustc- key, so nothing is dropped silently. A registry crate whose build script cannot be reproduced can be replaced by an override in third_party/buildrules/overrides.json that points at a buildrules target; the AWS-LC target under third_party/aws-lc is built for that use. No override file ships in the repository, and the generator's unit tests exercise the override keys.

Tests are build actions that write a .passed marker, so a cached buck2 build of :test means the tests passed on identical inputs. Doctests are not run. Lints use the same pinned toolchain, and clippy is a component of each Rust version's pin.

The macros refuse, with the fix in the message: a compiler that is not pinned; a table whose recorded toolchain hashes differ from the pins; lto, a custom codegen backend, rpath, incremental and split-debuginfo profile fields; alternate-registry dependencies, and git dependencies not pinned by commit or not on github.com (refused by sync); a root [package]. A set of hand-written rules (rust_library, rust_binary, rust_test) covers crates described without Cargo; rust_library can weld its tests with gate_tests.

Node.js: one download per locked tarball #

package-lock.json (lockfile version 3) is the single source of what is installed, and package.json is the single source of what is run. buildrules npm sync reads both and writes buildrules.lock.bzl: the pinned Node.js version, the sha256 of both files, the scripts and the "buildrules" policy, and one row per locked tarball.

A row holds the registry URL, the lockfile's sha512 integrity, and a sha256 and size. Buck2 keys downloads by sha256 and npm records sha512, so sync downloads each tarball once, checks that its sha512 equals the lockfile's, and records the sha256. A tarball whose bytes changed under the same version fails the build.

:node_modules is one cached action per locked tarball plus one assembly action that copies each package to the path the lockfile gives it and links .bin. No install script runs. Packages whose os, cpu or libc exclude linux x64 glibc are not declared. A lockfile change re-runs the assembly and not the downloads.

A script step (:typecheck, :lint, :test, :build) runs the package's package.json script with the pinned Node.js in a copy of the package, with a scratch HOME, UTC, and a PATH of Node and the declared step_tools. Scripts are read without a shell: &&, quotes, backslashes and leading NAME=value are understood; pipes, redirection, ;, ||, $, globs, npm and npx are refused with the fix. The refusal is raised when the step is built, not by sync.

Mojo: mopm decides, buildrules caches #

mopm is a package manager for Mojo. It owns what "build Mojo" means: it resolves dependencies into mopm.lock and can print a unit graph (mopm plan --unit-graph) naming every compile unit, its inputs and its outputs. buildrules does not write a second Mojo driver. It runs mopm's answer as cached Buck2 actions, as it runs rustc on Cargo's answer.

mopm-toolchain.toml names the mopm and Mojo versions. It is required, as rust-toolchain.toml is.

Note. A mopm row of rules/mopm/pins.bzl marked release_pending is a stand-in built from a development tree, and its hash is not that of the published mopm release at the same URL; the Mojo beta leg is skipped while a row is marked. A row without that mark is the published release, and the leg runs. The file shows which it is, and a test fails if the file, beta/mojo/STEPS and RELEASING.md disagree.

Zig, C and C++ #

Zig is the toolchain for everything native. The zig_exe, zig_test and zig_module rules compile Zig code with a pinned Zig (0.12.0 by default, 0.15.2 available). A zig_exe can name unit_tests = [...] so the executable is not built unless its unit tests pass: the weld.

C and C++ use the prelude's cxx_library and cxx_binary with a toolchain that cxx_toolchains() declares. The compiler, assembler and archiver are zig cc, zig c++ and zig ar of the pinned Zig. The target is x86_64-linux-gnu.2.34, so a produced binary uses no glibc symbol newer than 2.34. The toolchain compiles with -g0 and links with -Wl,--strip-debug. nm, objcopy, strip and every Python helper tool of the prelude are refusals that name the tool and exit 2, never a search of the worker's PATH.

Gates run as Buck2 validations, in every build whose graph holds the library:

GateWhat it refuses
hermetic_checka binary with a .debug_* section or the path of its link directory in its bytes
glibc_floor_checkan ELF needing a glibc symbol version newer than a stated floor
prefixed_archive_checka vendored library whose defined symbols do not all carry a prefix
c_checka built executable whose exit status or stdout is not as declared

A vendored C library can be built with every global symbol renamed under a prefix. The worked example is AWS-LC 1.39.0 (libcrypto only), which a Rust override can use in place of a crate's own AWS-LC build script. The renaming header is generated from the library's own symbol table, and the prefixed archive is read back and refused unless every defined symbol carries the prefix. docs/cxx_defects.md lists six known defects that each go red.

Pins and version tables #

Every tool an action runs is a download with a URL, a sha256 and a size. A wrong hash fails the download.

ToolWhere the pin livesPinned today
Rust (rustc, rust-std, cargo, clippy; llvm-tools for the ISA audit)rules/rust/pins.bzl1.95.0 (default), 1.85.0 (oldest)
Zigrules/pins/pins.bzl0.12.0 (default), 0.15.2
busybox (the shell and file utilities)rules/pins/pins.bzl1.35.0, static
Node.jsrules/node/pins.bzl24.21.0, linux x64
mopmrules/mopm/pins.bzl0.0.48 (a stand-in only if the row is marked release_pending)
Mojonot pinned by buildrules: named by mopm's graphthe one version mopm pins
libgcc, libstdcxx (conda-forge)rules/pins/pins.bzl15.3.0

A repository selects a Rust version in rust-toolchain.toml, which must name an exact release. stable, 1.95, a beta channel or a dated nightly is refused, because a floating channel is a different compiler tomorrow. This one file also selects the compiler for plain cargo, through rustup, so Cargo and Buck2 agree.

A repository that needs a version buildrules does not pin writes its hashes into buildrules-pins.toml; a version buildrules already pins is refused there, so the reviewed hashes win. A toolchain is an input of every compile, test and lint action of its units, so two Rust versions never share an action key. An upgrade is a visible diff of a pin and a regenerated table.

The pins are fetched from their upstream hosts. buildrules.url_map replaces a URL's leading part and nothing else, to route a download through a mirror; the hash is still checked. docs/pins.md lists the mirrors that were verified byte-identical and says which pins have none.

Instruction-set platforms #

A target platform can pick an instruction-set level. rules/isa.bzl holds one table, ISA_LEVELS: x86-64-v1 to v4 and armv8.0-a to armv8.4-a, each with the flags of rustc, zig cc and Mojo. native is never passed: a farm matches "at least, within the family", so host-tuned code would be cached under a lower level's key.

Planned. Only the x86-64 half is exercised. The Arm rows are data: there is no Arm worker and no execution platform that carries an Arm level, and an Arm test finds no platform and is refused.

Where actions run #

[buildrules_re] mode is remote (the default) or local. In remote mode every action runs on the REAPI farm named in the gitignored .buckconfig.local; if the worker property set is missing, the platform fails to load and says so, with no silent fallback. In local mode every action runs on the machine running Buck2, with the same pinned toolchains, command lines and inputs; it is refused when a farm is also configured, so a machine that has a farm cannot slip into running locally.

Local mode is hermetic in what it runs, not where: the machine still supplies Buck2, its kernel and its CPU. Action cache keys do not depend on the mode. The public CI uses local mode on GitHub's hosted Ubuntu runners. No endpoint, account or worker property appears in any rule, generated file or committed configuration.

Tests are part of the build #

A test is an action, and the library it covers cannot exist without it: a Rust library with gate_tests, a Zig executable with unit_tests, a Cargo member's :test marker. A cached rebuild therefore means the tests passed on identical inputs. The consequence for review: a green cached build is evidence about the inputs it was keyed on, and a gate is proven only by a red build on a known defect. The repository follows that rule: ci/negative holds known defects that must stay red.

What the repository runs on #

The public repository is built by its own rules. //ci:all is every target of the tree except those ci/all.bzl lists with a reason each. A completeness query fails and names any target of the tree that is in the closure of neither //ci:all nor //ci:mojo and is not excluded, so a new target cannot go unbuilt.

//ci:matrix builds the examples on the default and the oldest Rust, on both pinned Zigs, and at ISA levels v1 and v3. This site is built and tested by the Node rules, and its tests read the sources the pages describe and fail when a page names a command, rule or version that does not exist.

Determinism, and its proof #

A hermetic build should produce the same bytes everywhere. buildrules claims a narrower thing and tests it.

This is the beta stage of the release. The test repositories are hello-world projects per language, made as a user makes one: beta/<lang>/ holds the files the user writes and a STEPS file lists the commands the user types.

The proof found a real defect. C and C++ outputs depended on the directory they were linked in, because Zig assembles the C runtime's start-up objects at link time with debug info that names the working directory, whatever -g0 said. The toolchain now links with -Wl,--strip-debug, and hermetic_check fails a binary that has a .debug_* section or contains its link directory. The check was red on the farm without the flag and green with it.

Limit. What this establishes: those two path dependencies are gone, and each environment's two builds agree across two paths. It does not establish that a binary built on a GitHub runner and one built on the farm are the same bytes, because no run compares a runner leg with a farm leg. It does not cover Arm or macOS.

Releases #

A release is automatic: every push to main that changes more than documentation or CI and is green in every stage is tagged and published with no human action. The pipeline is .github/workflows/release.yml, described in RELEASING.md. Its stages run in order, each only if the previous succeeded.

StageWhat
gatethe whole tree (//ci:all) and the completeness check, in local mode on a runner
plandecides whether this commit is released and the version; creates nothing; the one place a repository variable can freeze every release
build-clibuilds the command line for the three release targets from the tested commit with the planned version stamped in, and packages the three tarballs and, from the two Linux binaries, the two Debian packages
betahello-world repositories per language, consuming the candidate commit as a user would and run with the linux x86_64 command line that build-cli built, each built twice in two directories
gammathe maintainers' own repositories built on the farm with the candidate; fails the release if no farm is configured
archivea deterministic source archive of the tested commit, the three tarballs (the one the beta ran is checked to hold the very file it ran), the two Debian packages (each checked to hold the program of the tarball of its architecture), and SHA256SUMS over the six files
attesta keyless signature and a GitHub build provenance attestation of each of the seven files
verifyread-only: the sums match; the checkout is the tested commit; the attestations and signatures verify, pinned to this workflow, commit and refs/heads/main; rebuilding the archive, the three binaries and the two Debian packages gives the same bytes; the shipped program prints the release version; the file list equals the commit's tree; the public-repository scrub passes
tagthe annotated tag, made only after everything is built, signed and verified
publishthe GitHub release, from the verified files: fourteen in all
bumpafter publish: opens a pull request, with auto-merge, in a downstream repository named by a repository variable, moving its buildrules submodule to the released commit; nothing waits for it, and a failed bump un-releases nothing

A version is v<MAJOR>.<MINOR>.<PATCH>. MAJOR.MINOR is the VERSION file; PATCH is the highest existing tag plus one. A release holds buildrules-<version>.tar.gz, the command line as buildrules-cli-<version>-<target>.tar.gz for linux-x86_64, linux-aarch64 and macos-arm64, buildrules_<version>_<arch>.deb for the two Linux ones, SHA256SUMS over those six files, a keyless signature and a build provenance attestation of each of those seven files, and notes. The three tarballs and the two Debian packages are built twice, on two runners, and must be the same bytes. A consumer relies on the published file and its sha256. The user beta runs the linux x86_64 program only; the other two are built from the same source behind the same tests and checked for their file header and their version, and are not yet run on their own platform.

The install script (site/static/install.sh, served by the site once it is published) installs the command line for your platform after checking its sha256, and --verify adds a cosign check of its signature (how to). A test runs it against fake releases and injects a defect for each of its checks. The release binaries can also be unpacked by hand, and the command line can be built from the source archive on your farm or machine.

Planned. A Homebrew formula and an apt repository are made by every release and published only after setup (RELEASING.md): until then none exists.

Trade-offs #

Limits today #

What is not done #

Planned. macOS, Windows and Arm hosts, and execution platforms for the Arm instruction-set levels. beta.yml runs the command line of each natively on an Arm Linux and a macOS runner, up to the build (its version, init, Buck2 loading the candidate); a build there waits for toolchains that run on those hosts.
Planned. The publication of the Homebrew formula and the apt repository (after setup, RELEASING.md).
Planned. Python rules. No design is committed.
Planned. Publishing this site at buildrules.dev. The site is built and tested; its hosting stack is a step the repository owner runs.

Why it may still be the right trade #

For a team that already runs a remote cache and wants Rust, Node, native code and Mojo in one graph without giving up cargo and npm, the cost is a sync step and a stricter toolchain policy. For a single-language project that builds well with its native tool, buildrules adds a layer that does not pay for itself. That judgment is the reader's; this page makes no claim about build times, and none is measured here.