Builds and CI
These are SVRBC’s best practices for building a project: every repository
follows them, and svrbc-audit checks the ones that can
be checked. Where a project departs from one, its AGENTS.md says so and why.
The rules
Section titled “The rules”- Every repository builds with Bazel, at a version pinned in
.bazelversion.bazel build //...andbazel test //...work the same way in every repo. - Tools are pinned by the repository, never assumed from the machine, and
fetched only when a step runs. Programs a build runs come from one
pinned nixpkgs commit through
svrbc_bazel’snix_tools(see below), notrules_nixpkgs. Upgrading a tool is then a one-line commit, and Bazel rebuilds exactly what depends on it. - CI uses one shared base image. It contains Nix, Bazelisk, the AWS CLI
and
bazel-cache-sync, and nothing project-specific. No repository maintains its own CI image. It is itself a Bazel step (below), built from the same Nix pins. - Everyone reads the shared cache; only SVRBC’s developers and its CI
write to it. CI means pipelines in
svrbc/forksand tags (and staging branches) of the projects; a developer is anyone with the Developer role or more in thesvrbcgroup on GitLab (see below), andsvrbc-mrbuilds, tests and uploads from their workstation before it pushes. A change is built once, and nobody builds it again: not its pipeline, notmaster(which runs no pipeline), not a reviewer, not another developer. - Secrets live in GitLab CI/CD variables, never in a repository. The cache itself needs none.
- The same commands build every repository, here and in CI (see below). An npm script or a Makefile target may be a convenience alias, but docs and CI use the Bazel commands.
- Cache every step that can be cached, including the expensive ones at the end: building the site itself, and anything rendered from it (such as doreancon.org’s bulletin PDFs). A step outside Bazel runs on every build, on every machine, forever.
- Tests are Bazel tests. Every test a repository has runs under
bazel test //..., so its result is cached like any step’s: a commit tested once, anywhere, is never tested again. A test runner called directly (npm test,cargo test) is a convenience for iterating, never what CI runs. Wrap the suite in ansh_testthat lays out what it reads, as doreancon.org’s//:unit_testsdoes for vitest. A Rust crate’s tests arerust_tests (Building the function). - Tests exist, and cover at least 80% of the lines. A repository with
code has tests that
bazel test //...runs, and each release reports their line coverage, which must be 80% or more (see below).
Tools are fetched only when a step runs
Section titled “Tools are fetched only when a step runs”A build whose every step comes from the cache should download no tools at
all. The usual way to bring Nix packages into Bazel, rules_nixpkgs, can’t do
that: it makes each tool an external repository and runs nix-build when the
repository is fetched, and Bazel fetches every repository a target refers to
before it knows which steps are cache hits, so a fully cached build still
downloads MuseScore, Qt and the rest for steps that never run.
So SVRBC repositories use the nix_tools extension from this handbook’s
bazel/
module instead:
- One
nix-instantiateevaluation writes every tool’s recipe (a.drvfile) to the Nix store and records its path. Nothing is downloaded but nixpkgs itself. - A step that uses a tool fetches it as it runs:
nix_tool("musescore")expands to$(realise.sh <drv>), the tool’s store path. A cache hit never runs, so it never fetches. - The
.drvpath is a hash of the tool’s exact recipe: the same on every machine, and written into the step’s command, so it is part of the cache key. A new pin is a new key.
bazel_dep(name = "svrbc_bazel", version = "0.0.0")git_override( module_name = "svrbc_bazel", remote = "https://gitlab.com/svrbc/developers.svrbc.org.git", commit = "<a commit of developers.svrbc.org>", strip_prefix = "bazel",)
nix_tools = use_extension("@svrbc_bazel//nix:extensions.bzl", "nix_tools")nix_tools.nixpkgs(commit = "<nixpkgs commit>", sha256 = "<nix-prefetch-url --unpack hash>")nix_tools.tool(name = "musescore", attr = "musescore")nix_tools.tool(name = "fonts", file = "//nix:fonts.nix") # your own expressionuse_repo(nix_tools, "nix_tools")load("@nix_tools//:tools.bzl", "NIX_TOOLS", "nix_tool")
genrule( name = "engraving", srcs = ["hymn.musicxml"], outs = ["hymn.svg"], tools = NIX_TOOLS, cmd = nix_tool("musescore") + "/bin/mscore -o $@ $<",)The same goes for a Rust toolchain, which rules_rust needs while Bazel
analyses the build: svrbc_rust, a module beside svrbc_bazel, gives it
wrappers that fetch the pinned toolchain only when a step runs
(Building the function).
Three rules keep it honest:
- Never name a tool by a host path or a bare command name. A step that
needs a program on
PATH(a script callingffprobe) setsPATH=<pinned tool>/binand nothing else, so a missing tool fails instead of quietly using the machine’s. - Fetch tools before changing
HOME.realise.shfinds Nix in the ordinary places; a step that swaps in a throwawayHOMEdoes so after. - Test a cached build in a fresh container. The proof that nothing is fetched needlessly is an empty Nix store that stays empty: a fully cached build leaves no tools in the store, and editing one hymn fetches MuseScore, and only it. It is also where a leaked host tool shows up.
In CI, steps have to be able to write to /nix to fetch: the base image sets
that up (/etc/bazel.bazelrc, with Nix on the plain PATH Bazel gives a
step).
The standard commands
Section titled “The standard commands”bazel build //... # build every cacheable outputbazel test //... # run every test Bazel knows aboutbazel run //:assets # put generated files where the app reads them, and run # the steps that can't be cachedbazel build //... is the build. Every step that turns committed inputs
into outputs is a Bazel action, so it’s cached and shared: engraving a hymn,
probing a track’s length, rendering a PDF page to an image, and (the goal,
rule 7) building the site and rendering from it.
bazel test //... runs every check the build’s outputs have to pass.
A site’s include //:site_test (it is a PWA, with its special pages) and
//:budget_test, which holds every page of //:site’s tarball to the
site’s load-time budget and writes each
page’s numbers to budget.json among the test’s outputs. Both come with
the template; the budget’s table is the site’s
own.
bazel run //:assets exists because most apps read generated files from
the source tree (Nuxt serves public/), while Bazel keeps outputs under
bazel-bin/. In a repository with generated files, //:assets is a
sh_binary that:
- copies what Bazel built into the tree, overwriting in place (CI’s checkout belongs to the runner, so files there can be written but not chmod-ed);
- then runs the steps that can’t be Bazel actions, such as rendering pages
from a running dev server or anything that needs the npm dependencies, with
tools Bazel pins (passed as
$(rootpath …)arguments) rather than ones from the machine’sPATH.
Keep the second part small, and shrinking: anything that reads only committed
files and writes files belongs in the first, and the second exists only until
a step has been brought into Bazel. doreancon.org’s
BUILD.bazel
and scripts/bazel/assets.sh
are the worked example.
Tools outside Bazel come from a shell.nix at the repository root, pinned
to the same nixpkgs commit as MODULE.bazel: typically Node for npm ci and
a dev server. The tests are not among them (rule 8); a job
that needs nix-shell is running something outside Bazel. Use mkShellNoCC unless something really compiles, so
CI doesn’t download a C compiler. Run commands as nix-shell --run '…', or
open a shell with nix-shell.
Each repository’s AGENTS.md names any extra command a person needs (such as
npm ci first) and nothing else.
Test coverage
Section titled “Test coverage”Two rules, decided 2026-11-24, which svrbc-audit
checks, each a failure from the start rather than a warning:
- Tests must exist (
tests-exist). A project with code fails ifbazel test //...would run no test of it, and so does one with code that isn’t built with Bazel yet: builds and tests go through Bazel (rules 1 and 8). - Coverage is reported, and at least 80% of lines (
test-coverage). The audit reads the line coverage GitLab records for the project’s newest release pipeline, and fails a project below 80% or reporting none.
Why. Nothing reaches master without bazel test //... passing, and
the verified marker lets that one pass stand for every
machine after it. That is only worth as much as the tests: a project with
none passes every time, and one whose tests run a fifth of its code says
nothing about the rest. Coverage is how a reviewer, or the audit, can see
which it is without reading every test. It is a floor, not a target: 80%
leaves room for what only runs in production (a Lambda entry point, the
real AWS client behind an in-memory one) without leaving a module untested.
Lines, because every tool SVRBC uses reports them the same way (LCOV), so
a Rust API’s and a site’s TypeScript add up to one figure.
What counts as code: a source file in a programming language (Rust,
TypeScript, JavaScript, Astro, Vue, Svelte, Python, Go, …), outside build
steps (scripts/bazel/, .bzl), configuration (*.config.*), tests
(test/, tests/, *.test.*, test_*.py), infra/, nix/, and generated
or vendored paths (node_modules/, dist/, bindings/, …). Shell isn’t
counted: it is the glue Bazel steps run, which the tests of what they build
check. A repository whose files are all documentation, configuration or
build steps has no code, and neither check applies to it. One with code
but no Bazel build (no MODULE.bazel, or no BUILD file) fails both: no
test bazel test //... could run, and no release of it reports coverage
from .svrbc-coverage. A test is a
*_test(…) or test_suite(…) in a BUILD file that isn’t tagged manual,
or a macro of the repository’s own that calls one.
How coverage is measured
Section titled “How coverage is measured”A test writes LCOV among its outputs. Bazel gives every test a directory
for files it leaves behind, $TEST_UNDECLARED_OUTPUTS_DIR, and keeps them
with the test’s result: in the shared cache, and in
bazel-testlogs/<target>/test.outputs/ (a directory, in Bazel 9, not a
zip). A test writes lcov.info, or any *.lcov, there. So a test that is
a cache hit still has its coverage: it is part of the result that was
cached, from the run that measured it.
The release’s coverage job reads it. ci/bazel.yml has the job,
.svrbc-coverage:
coverage: extends: .svrbc-coverageIt runs bazel test //... --build_tests_only --remote_download_minimal,
with --remote_download_regex set to download the LCOV files and nothing
else, merges them (a line counts as run when any test ran it) and prints
svrbc-coverage: 81.70% of lines (1559 of 1908, 21 files, 2 reports)which its coverage: pattern hands GitLab, rounded down (79.996% is not
80%). It runs in each release’s pipeline, where every test is already in the
cache, so it costs a fully cached bazel test //... and fetches a few
kilobytes. It never fails the release (allow_failure): the
audit holds the project to the floor, and a missing figure is a failure
there. The handbook’s own
//:coverage_report_test
tests the job’s merging, its pattern and its download filter, and
examples/hello runs it in this repository’s pipeline.
Why the release’s pipeline. It is the one pipeline every release is
sure to have (the review bot starts it), it belongs to the project rather
than its fork, and it is the commit that was deployed. A push to master
starts no pipeline, and a merge request’s commit that svrbc-mr verified
often has none in the fork either (Verified commits),
so neither could be relied on. A project with no release yet is read from
its newest passing pipeline, then its fork’s.
Measuring it in a test
Section titled “Measuring it in a test”The site template and
templates/public-accounts
do it already; a new site starts with its coverage job and with tests
that cover all of the template’s code. For a
project that started before:
- vitest (a site’s
//:unit_tests): add@vitest/coverage-v8at vitest’s own version, givevitest.config.tsacoveragewithprovider: 'v8',reporter: ['lcovonly', 'text-summary']and anincludeof the code a unit test can load (src/**/*.{ts,mts,js,mjs},router/**/*.js), and run it asvitest run --coverage.enabled --coverage.reportsDirectory="$TEST_UNDECLARED_OUTPUTS_DIR/coverage"(the template’svitest.sh). Theincludemakes a file no test loads count as uncovered rather than disappear. Astro components aren’t in it:astro checkand//:site_testcheck them. A script a test runs innode:vm(the CloudFront router) counts once it is given its file URL asfilename(test/router.test.ts). - Rust (an API): a
rust_coverage_test(@svrbc_rust//:defs.bzl) of itsrust_tests, which builds them again with-Cinstrument-coveragefor the repository’s own crates, runs them, and writes their line coverage ofsrc/asapi.lcovwith thellvm-profdataandllvm-covof the LLVM rustc is built with (rustc.llvm, from the same nixpkgs pin, a tool of its own so that the Lambda build doesn’t depend on it:rust.toolchain(coverage = …)) (the template’sapi/BUILD.bazel,nix/rust-coverage.nix). - Anything else that writes LCOV works the same way: coverage.py’s
coverage lcov, for one, though no SVRBC project has tried it yet.
To see a figure before a release: bazel test //..., then look in
bazel-testlogs/<target>/test.outputs/, or run vitest with
npm test -- --coverage.
Why not bazel coverage. Bazel has a coverage command of its own, and
it doesn’t fit. It builds in a configuration of its own, so every action
(the site’s build included) is built and cached a second time; its combined
report needs Bazel’s Java LCOV merger, a JDK download for every job; and
SVRBC’s tests are sh_tests around vitest, which Bazel’s instrumentation
doesn’t reach, and a Rust API’s coverage builds only its own crates
instrumented (rust_coverage_test), so each writes its own LCOV anyway.
Nor is coverage a build step: a build step can’t read a test’s result, so it
would run the suite a second time. And the check job can’t report it: in a
release it stops at the verified marker without running a test.
How the cache decides what to rebuild
Section titled “How the cache decides what to rebuild”Bazel models a build as actions. An action is one command with declared
inputs and outputs, such as “engrave psalm-82 with MuseScore into an SVG.”
The cache has two halves:
cas/(content-addressable store): files, each stored under the SHA-256 of its own bytes. A blob can’t be stored under the wrong name, and identical files are stored once.ac/(action cache): results, each stored under the hash of the action itself: its command line, its environment, the hash of every input file and of every tool. A result says which outputs the action produced, by theircas/hashes.
If an action’s ac/ entry exists, Bazel downloads its outputs instead of
running it. Timestamps play no part, so a fresh clone on another machine gets
the same hits.
Bazel also stops early. If an action re-runs but produces byte-identical output, the hashes downstream don’t change, so nothing downstream re-runs.
Caching is only correct if every input is declared. Bazel runs actions in a sandbox that hides undeclared files, so a missing input fails the build instead of producing a wrong cache hit.
Why only SVRBC’s developers write: a cas/ blob checks itself, but an
ac/ entry is a claim (“this action produced that file”) that nobody can check
without re-running the action. A bad writer could point a legitimate action at
a poisoned file, and every reader would use it. So the writers are the people
SVRBC has made developers, who may push to its forks anyway, and its CI.
The shared cache
Section titled “The shared cache”One cache serves every SVRBC project. Keys hash the exact command, tools and inputs, so projects can’t collide, and identical work is stored once. There is no cache server:
-
Reading. Every repository’s
.bazelrcpoints Bazel at the cache over plain HTTPS, and tells it never to upload:Terminal window common --remote_cache=https://bazel-cache.svrbc.orgcommon --remote_upload_local_results=falsecommon --disk_cache=~/.cache/bazel-diskCloudFront serves the private bucket read-only. A CloudFront function passes only
ac/<sha256>andcas/<sha256>paths, so the bucket can’t be listed, and compression is off because Bazel checks every blob against its hash. Reads are public. That’s fine for public repositories, whose outputs anyone could build from the source; finding a private repository’s outputs would take its source too. -
Writing. Bazel can’t write to S3 (it can’t sign requests), and doesn’t need to. A writer builds into its disk cache as usual, then runs
bazel-cache-sync, which uploads the new entries: everycas/blob before anyac/entry, so a result never appears before its outputs. CI uploads with short-lived AWS credentials from its OIDC token; a developer’s workstation, through presigned URLs that its GitLab token buys (below). -
Retention. S3 lifecycle rules expire
ac/entries after 60 days andcas/blobs after 67, so a result rarely outlives its outputs. When one does, Bazel notices the missing blob, re-runs that one action and carries on. -
Misses are quiet. CloudFront may read the bucket’s key list, so a missing key is a
404(a miss), not a403(an error). Listing itself is still blocked by the path filter.
How it was built, as AWS CLI commands, is in
infra/bazel-cache/.
Trusted workstations
Section titled “Trusted workstations”Every SVRBC developer’s workstation is trusted: one whose owner has the
Developer role or more in the svrbc group on GitLab, with full-disk
encryption. It writes with the GitLab token its owner already has, and no
AWS account. There’s no shared secret to hand out: write access is the
person’s GitLab membership, and revoking it is removing them from the group.
The token goes to svrbc-bazel-cache-upload, a Lambda function in
infra/bazel-cache
(tools/bazel-cache-upload/handler.py).
It asks GitLab whether the token’s user is a Developer or more in the group,
checks which of the entries the bucket lacks, and answers with a presigned
upload URL for each, good for 15 minutes. It remembers a token’s answer for
five minutes, so removing someone takes effect within that. Its log says who
asked to upload how many entries, never the token.
It uploads when it opens a merge request: svrbc-mr builds and tests
the commit (bazel test //...) and runs bazel-cache-sync before it pushes,
so the merge request’s pipeline finds every step done (see
Getting started for the one-time
setup). By hand, it is:
bazel-cache-sync # with glab's token, or GITLAB_TOKENWhy GitLab, not AWS (decided 2026-10-29). A trusted workstation could
be an administrator’s, signed in to AWS through the
access portal. But a developer can already write the
cache through a fork’s pipeline, so an AWS account wouldn’t limit who writes
it; it would only mean a ship stops whenever the sign-in expires, and that
nobody who isn’t an administrator can ship without waiting for a pipeline. The
function hands out presigned URLs rather than AWS credentials, so it needs no
sts:AssumeRole, which the workload boundary
doesn’t give, and may only size up entries and sign uploads of them. An AWS
sign-in is still what lets svrbc-mr plan infrastructure on the
workstation; without one, the fork’s pipeline plans it.
Upload only what you built from committed code, as svrbc-mr does: it
refuses a working tree with changes in it, and uploads only what that build
ran. It builds in an output base of its own with an empty disk cache, so the
disk cache it uploads holds this commit’s new results and nothing else. Your
everyday disk cache holds whatever you have built from uncommitted work too,
and bazel-cache-sync by hand uploads all of it. An upload is trusted by every other
machine, but no more than a fork’s pipeline is, which uploads a branch before
anyone has reviewed it; review decides what merges, not what is cached. An
entry says only that these inputs gave these outputs, and a commit nobody
merges is simply never asked for again.
Every repository includes the shared template rather than writing its own cache and runner setup:
include: - project: svrbc/developers.svrbc.org file: ci/bazel.yml
check: extends: .svrbc-bazel script: # Builds every target under //..., not only the tests, and runs the tests. - bazel test //... --remote_download_minimal --test_output=errors rules: - if: $CI_COMMIT_BRANCHIt runs on every branch: in the fork, where a merge request is built, and on
master after the merge. In the fork, the template adds the review bot’s
gate, review-bot, a manual job the bot starts once its statuses are in
the pipeline (The review bot). That is the whole job, in doreancon.org too, with
its generated assets and npm tests: everything it checks is a Bazel step
(rule 8), so once svrbc-mr has uploaded a commit, the
job finds it all cached and only confirms it.
doreancon.org’s release job builds nothing: it fetches the deployable site, which check
already built and cached, and deploys it (Releases,
below).
.svrbc-bazel runs the job in the shared base image. Its after_script
asks GitLab for an OIDC token, exchanges it for short-lived AWS credentials,
and runs bazel-cache-sync. The svrbc-bazel-cache-writer role decides who
may: any branch of a project in svrbc/forks, and master, main and tags
of svrbc projects. A fork outside SVRBC carries its own project path in
that token, so it can’t. A failed upload is reported but never fails the
job: the cache only ever saves time.
Do developers need to build locally? Their machines read the shared
cache, so they build just the steps their change touches, and svrbc-mr
does that before it pushes. For something too heavy to build locally,
svrbc-mr --no-build pushes without it, and the fork’s pipeline builds
it once for everyone. Building twice (locally and in CI) is never needed for
consistency: a cached step is as good as a rebuild. What a workstation
builds stays on it until it is uploaded, which svrbc-mr does.
Will CI reuse what I built locally? Only once it is in the shared cache.
A build lands in the workstation’s own disk cache, which no pipeline can see,
so until it is uploaded (which svrbc-mr does),
the fork’s pipeline builds it all again. Uploaded, it
doesn’t: cache keys come out the same on every machine, so
every step CI would run on the same inputs is a hit. Two things can still
cost time. A pipeline still waits for a runner; and whatever a job does
outside Bazel runs every time, which is why the tests are Bazel tests
(rule 8). A merge request pushed with svrbc-mr --no-build is
built by the fork’s pipeline.
A step that isn’t reproducible makes this worse. Keys are computed from inputs, so two machines that each build a step get the same key but may get different bytes, and then everything downstream differs too. MuseScore is one: it writes a hymn SVG’s lyric extender lines in no fixed order, so a hymn engraved on a workstation differs from CI’s, invisibly, and the bulletin PDFs printed from it get new hashes. Make a step’s output stable (sort what the tool leaves unsorted) rather than relying on whoever built it first.
Runners
Section titled “Runners”Every job can run on the group’s own runners, GitLab Runners SVRBC
keeps running, registered to the svrbc group and taking untagged jobs.
A job that only GitLab’s hosted runners can run is a bug: their free
compute minutes run out (ci_quota_exceeded), and then the job can’t run
at all. So a build that needs privileges a group runner doesn’t give (such
as rootless BuildKit) has no place in CI: both images, the CI one and the
review bot’s, are Bazel steps (Nix and nix2container), built on a group
runner or a workstation and only uploaded by CI. Hosted runners may still
pick up a job when they have minutes, but nothing may depend on them.
SVRBC keeps at least two of its own runners online, on different
machines, each taking several jobs at once (its concurrent setting
above 1). With one runner taking one job at a time, every pipeline waits
behind every other, and CI stops whenever that
one machine is down.
svrbc-audit warns when fewer than two of the group’s
runners are online (a runner’s concurrency is in its own configuration,
which GitLab’s API doesn’t show), and about a CI file that pins a job to
GitLab’s hosted runners (saas-linux-… tags).
Verified commits
Section titled “Verified commits”A fully cached bazel test //... still takes time, because
Bazel can only find a step’s cache key by loading the whole build: starting,
evaluating nixpkgs for the tool pins, analysing every target. None of that is
needed to learn that a commit has already passed. So once bazel test //...
has passed for a commit and its results are uploaded, the writer records
that, as one more entry in the shared cache:
ac/sha256("svrbc-verified:<commit sha>") {"verified": "bazel test //...", "commit": …, "by": …, "at": …}It is written last, after the upload, as an action result is written after
its outputs, and it stands for everything: every target under //... built
and every test passed for exactly that commit, whose tree pins every input
(Bazel’s version, the nixpkgs commit, svrbc_bazel’s commit). Reading it is
one HTTPS request to https://bazel-cache.svrbc.org/ac/<key>, with no
Bazel, Nix or checkout. Bazel never asks for that key, since no step’s key is
that hash. Only the cache’s writers (SVRBC’s developers, through
svrbc-mr, and its CI) can write it, so it is exactly as
trustworthy as the cache. A test that passed once stays passed for that
commit, flaky or not. Like any ac/ entry it expires after 60 days, and the
commit is then simply built again.
Who reads it:
- The review bot treats a verified commit with no pipeline as tested, and
starts a pipeline only for one that isn’t verified
(The review bot). A pipeline that ran for the
commit counts either way: the marker vouches for
bazel test //...and nothing else. So a push to a fork starts no pipeline (the rule below), unless it changes something the marker doesn’t cover: a project whose CI also plans infrastructure or builds an image starts one for a push that changes those paths, and only those (this handbook’s.gitlab-ci.ymlis the example). A project that starts a pipeline on every push makes the bot wait for it, verified or not, for nothing. In a project that releases from tags, nor does a push tomaster: a merge is only of a commit that passed, fast-forward, so there is nothing left to build, and a release is its tag’s pipeline (Releases). A project that still deploys frommasterkeeps that pipeline until it takes releases. - CI’s
checkreads it first and stops at once when it’s there, so a release’s pipeline, for the same commit the merge request built, takes seconds. When the job runs the tests itself and they pass, it writes the marker in turn.
workflow: rules: # A push to a fork starts no pipeline: the review bot starts one when the # commit isn't verified. Nor does a push to master, which the bot makes # with a commit that passed; it starts each release's pipeline itself. # (Only in a project that releases from tags, through ci/release.yml.) - if: $CI_PROJECT_NAMESPACE == "svrbc/forks" && $CI_PIPELINE_SOURCE == "push" when: never - if: $CI_PROJECT_NAMESPACE == "svrbc" && $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $CI_PIPELINE_SOURCE == "push" when: never - if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/ - if: $CI_COMMIT_BRANCH
check: extends: .svrbc-bazel script: - | key=$(printf 'svrbc-verified:%s' "$CI_COMMIT_SHA" | sha256sum | cut -d' ' -f1) if curl -fsSI -o /dev/null "https://bazel-cache.svrbc.org/ac/$key"; then echo "verified: $CI_COMMIT_SHA already built and tested"; exit 0 fi - bazel test //... --remote_download_minimal --test_output=errors - touch .svrbc-tested after_script: - !reference [.svrbc-bazel, after_script] - | # Only after the upload above, and only where CI may write the cache. [ -f .svrbc-tested ] && [ "$CI_JOB_STATUS" = success ] || exit 0 key=$(printf 'svrbc-verified:%s' "$CI_COMMIT_SHA" | sha256sum | cut -d' ' -f1) printf '%s' "$SVRBC_AWS_ID_TOKEN" > "$CI_BUILDS_DIR/.aws-token" printf '{"verified":"bazel test //...","commit":"%s","by":"%s"}' "$CI_COMMIT_SHA" "$CI_JOB_URL" | AWS_ROLE_ARN="$SVRBC_BAZEL_CACHE_ROLE" AWS_WEB_IDENTITY_TOKEN_FILE="$CI_BUILDS_DIR/.aws-token" \ AWS_ROLE_SESSION_NAME="gitlab-$CI_PROJECT_ID-$CI_JOB_ID" AWS_REGION=us-west-2 \ aws s3 cp - "s3://svrbc-bazel-cache/ac/$key" --only-show-errors || echo "verified: not recorded" rm -f "$CI_BUILDS_DIR/.aws-token"The shared template (ci/bazel.yml) should carry this, so a project only
extends it; it lives in each project for now. (A change to ci/ alone
doesn’t rebuild the base image: it runs the example in the published
:latest. Only a change to images/ci/ or bazel-cache-sync rebuilds
it.) The template’s own after_script exits early where CI may
not write the cache, which skips the marker too.
The base image marks every directory safe for git. It runs jobs as its
own builder user, and the runner checks the repository out as another, so
git would refuse the checkout (“detected dubious ownership in repository”)
in any job that runs it (git rev-parse, git fetch, git checkout). The
check guards a shared machine against a repository another user planted; a
job’s container holds only its own checkout, so the image’s
/etc/gitconfig trusts every directory (safe.directory = *), and the example job
runs git rev-parse to prove it. No job needs a
git config --global --add safe.directory "$CI_PROJECT_DIR" of its own.
The CI image is a Bazel step
Section titled “The CI image is a Bazel step”//images/ci:image builds the shared CI image: Nix and
nix2container build it from
images/ci/image.nix, from the same pinned nixpkgs as every tool, with no
Dockerfile, no container runtime and no privileges. So it is built and
tested like everything else: svrbc-mr builds it and runs
//images/ci:image_test (the user, the PATH, the tools, git’s trust,
Nix’s settings, compressed layers) before a push, the shared cache keeps
it, and the base-image job only uploads it (bazel run //images/ci:push), on the group’s runner. The archive is reproducible:
an unchanged image is the same bytes.
- Debian underneath, pinned by digest. An image of only Nix store paths
can’t run Bazel: Bazel’s own binary, and toolchains it fetches prebuilt
(its remote JDK), expect an ordinary Linux loader at
/lib64/ld-linux-x86-64.so.2. So the image starts fromdebian:bookworm-slimand adds everything else from Nix, in/usr/local/bin, first on the job’s PATH and on the plain PATH Bazel gives an action. (Debian keeps/binas a link to/usr/bin, so not there.) - Nix works inside, single-user, as
builder, who owns/nix; its database lists every store path the image holds. - The CA bundle is where tools look by default, at Debian’s path and in
nix.conf: a Bazel action starts with an empty environment, soSSL_CERT_FILEdoesn’t reach it, and without the bundle Nix silently builds from source instead of downloading. - Layers are compressed (gzip), so a job has less to download.
To try a change by hand: bazel build //images/ci:image, then load it into
Docker with skopeo (skopeo copy oci-archive:<image.tar> docker-daemon:<name>).
GitLab.com’s shared runners start every job from a clean state, so each job downloads its toolchain from the Nix binary cache. If that proves slow, the fix is to add the common tools to the image (from the same pins) or a Nix binary cache near the runners.
Making builds fast: practices for every project
Section titled “Making builds fast: practices for every project”Each of these applies to any SVRBC project. They are as much part of the build practices as the rules at the top of this page.
Build everything once, before release
Section titled “Build everything once, before release”The pipeline that builds a merge request (in its fork) builds everything,
the deployable site included, with bazel build //.... The merge is
fast-forward, so the release’s pipeline, for that same commit, finds it all
cached. Nothing heavy is ever built twice.
Don’t download what a job won’t read
Section titled “Don’t download what a job won’t read”bazel build downloads every top-level output by default, cache hit or not.
A job that only needs to know everything is built passes
--remote_download_minimal: cached steps are confirmed, not fetched. Then
fetch only what the job actually uses (bazel run //:assets fetches the
assets it installs; a deploy job builds just the target it ships).
Without it, a cached check downloads outputs it never reads, such as
node_modules and the site’s builds.
Make the release only deploy
Section titled “Make the release only deploy”A release tag exists only for a commit the review bot merged, which passed before it merged (Releases), so the release job neither rebuilds nor retests. It builds (that is, fetches) the one deployable target and deploys it.
npm dependencies are a build step
Section titled “npm dependencies are a build step”//:node_modules runs npm ci from package.json and package-lock.json and
packs the result as a tarball, so every step that needs the dependencies
depends on the lock file, not on whatever is installed on the machine:
- skip only the root package’s own postinstall (
npm ci --ignore-scripts) when it needs the whole app (asnuxt preparedoes), then run the native modules’ install scripts that matter (npm rebuild better-sqlite3); - pack it with
tar --sort=name --mtime=@0 --owner=0 --group=0 --numeric-owner, so an unchanged lock gives identical bytes and nothing downstream rebuilds.
Building a Nuxt (Vite) site inside Bazel
Section titled “Building a Nuxt (Vite) site inside Bazel”doreancon.org’s
scripts/bazel/nuxt-build.sh
is the worked example. Three traps:
- Vite follows symlinks, and in a Bazel sandbox every source is a symlink
into the checkout. Built in place, the site would read the checkout’s own
node_modulesand generated files. Copy the declared inputs, dereferenced (cp -RL), into a directory of the action’s own, and build there. - Tools look upward for configuration. The sandbox’s own links to
tsconfig.jsonandpackage.jsonsit one directory above that copy, and Vite’s TypeScript loader finds the parenttsconfig.jsonand fails with “Tsconfig not found”. Remove the sandbox’s links to the config files once they are copied. - Run
nuxt preparefirst, since it’s the postinstall that the dependency step skipped; it writes the.nuxt/tsconfigfiles the build needs.
Work inside the action’s directory, never /tmp: a site plus its
node_modules is a couple of gigabytes, and /tmp is often memory.
Deploying from the cache
Section titled “Deploying from the cache”The release job deploys the site CI already built: a Bazel step builds it with
the host’s Nitro preset (aws-lambda), and the deploy uploads only what
changed. Hosting has the setup and its traps.
Inputs and outputs
Section titled “Inputs and outputs”- Keep generated, Git-ignored paths out of globs. A glob over
public/**picks up whatever a developer last generated there. Exclude those paths and give the build Bazel’s own outputs instead. - A script built into Bazel keeps working outside it. Give it overrides
for where it writes (doreancon.org’s
HYMNAL_OUT,QR_OUT,BULLETIN_OUT), and find the repository from its own path without following symlinks (node --preserve-symlinks-main; Python’sPath(__file__).absolute(), not.resolve()). - A script that edits files in place gets a copy of what it edits, made into its own outputs first.
- Outputs Bazel can’t list ahead of time (one QR code per project in a JSON file) go into a tarball.
A target lists only what it reads
Section titled “A target lists only what it reads”An edit reruns every step and test that lists the file, whether or not it reads it. The sandbox catches the opposite mistake, an input a step reads but wasn’t given (above), by failing the build; an input given but never read fails nothing. It only makes the step rerun on every edit to it, on every machine, and nobody notices until incremental builds are slow. So it is the one a person has to watch for, and it creeps in the same way everywhere: one list of sources, made for the site’s build, handed to every step after it.
- Name the sources by kind, and give each step the kinds it reads.
The template has
CODE_SRCS(src/, the config) andCONTENT_SRCS(content/,public/);SITE_SRCSis both, for//:sitealone. A list that grows a new kind (api/bindings/, a data directory) gets a name of its own. - A unit test reads the code it tests, not the site’s content: editing a page’s Markdown should never rerun vitest. A test that does read content (a schema check of every Markdown file) lists that directory and says so in its comment.
- A test of the built site depends on
//:site, the output, and not on the site’s sources as well. - No
glob(["**"])of a whole package. It hands a step every file added to that directory from then on: doreancon.org’s scripts are all inputs to its unit tests, which import a few of them. - An expensive step gets a target of its own, with its own inputs:
icons, PDFs, engraving, data generated for the site. Inside
//:siteit reruns on every page edit; as its own target it reruns only when what it reads changes, and the site takes its output. - Check with
svrbc-blastafter adding or changing a target:svrbc-blast <file>lists the steps and tests an edit to that file reruns, andsvrbc-blast --sampledoes it for one file of each kind in the repository. Each should be a list you would expect.svrbc-audit’sbazel-narrow-inputsflags the two common shapes, a test givencontent/orpublic/and aglob(["**"]).
One step can’t be split this way: an Astro or Nuxt build reads its whole
site, so //:site reruns on any edit to it. What can be kept narrow is
everything around it, which is where the savings are.
Large files go to an assets domain
Section titled “Large files go to an assets domain”A site’s large files (bulletin PDFs, audio, video) don’t belong in its
deploy: every release fetches them from the cache and uploads them to the
host again, and the host’s bandwidth pays for every download. They go to the
site’s assets domain instead, assets.<domain> (see
Domains):
- Content-addressed keys. A Bazel step hashes each file and maps the path
the site links to onto
<sha256>/<name>in the site’s bucket. A key names exact bytes, so it’s immutable (cached for a year) and a changed file is a new key, never an overwrite. - The site keeps its paths and redirects them (Nuxt
routeRules, 302), so no link changes andnpm run devstill serves the files locally. - Upload before deploy, only what’s new. The release job lists the bucket, uploads the keys it lacks with a role that trusts only that project’s release tags, and only then deploys the site that points at them. It fetches those files from the build cache only when one is new.
- CORS. Anything the site
fetches from there (doreancon.org’s countdown music) needsAccess-Control-Allow-Origin: CloudFront’s managed SimpleCORS policy.
doreancon.org’s large files are there. See infra/doreancon-org-assets/.
symbolics.dev’s scans (the PDF of each printing its texts follow) are there
too, with one difference: its data, which its API answers, names each scan
by its assets.symbolics.dev URL, since an API’s answer is read far from the
site and has no path of the site’s to redirect. The files aren’t in its
repository at all: the release fetches each new one from the library that
holds it and checks its hash, and one no release can fetch is uploaded once
from a workstation. See infra/symbolics-dev-assets/.
seminary.svrbc.org’s scans (each the whole of an archive.org file, which a
reading’s page opens at the reading) are there the same way, fetched by its
release from archive.org and checked against their hashes. See
infra/seminary-svrbc-org-assets/.
recipes.svrbc.org’s photos are there too, with a private area: its API writes
each uploaded photo’s cleaned original to pending/, which CloudFront never
serves and which expires after 30 days, and the release publishes a reviewed
one’s resized variants to published/<sha256>/<width>.webp. See
infra/recipes-svrbc-org-photos/.
Prove a new build equal before switching
Section titled “Prove a new build equal before switching”Before a Bazel step replaces an old build path, compare their outputs: bytes where the tool is deterministic (MIDI, manifests, JPEG renders), text and page counts and then pixels where it isn’t (PDFs), and structure where hashes legitimately differ (a site’s routes and file list). That catches real problems, such as a host font leaking into a render or a route the old host served and the new build lacks, before they reach production.
Render both in the same browser on the same machine. Against files built
elsewhere (CI’s pinned fonts, another Chrome), every page differs a little,
and a real difference (icons printing as solid squares) hides in the noise.
For a site, site-compare
does this page by page: screenshots at each width and color scheme, and the
text.
Why this setup
Section titled “Why this setup”The goal: never redo a build step whose inputs haven’t changed, whether on a workstation, in CI, or on another machine, while keeping local edit-and-rebuild fast.
- Why not Nix on its own? Nix caches whole derivations and decides whether to rebuild by inputs. It has no early stop on unchanged output (that needs content-addressed derivations, which are experimental), and every build pays for evaluation and copying the source into the store. That’s fine for CI and slow for an edit-and-see loop. We still use Nix, for what it does best: pinned, reproducible tools.
- Why not a Docker image per project? Images drift from the build’s idea of its inputs. Upgrade Chromium in an image, forget to tell the build, and the cache serves stale artifacts. They also add a pipeline stage and tag juggling to every repo.
- Why no cache server? Bazel’s remote cache speaks gRPC, or HTTP
GETandPUT. S3 needs signed requests, so Bazel can’t write to it. But it can read from it, and writes don’t have to go through Bazel: a writer uploads its disk cache afterwards. That removes the server (bazel-remoteon EC2, with its patching, TLS and password file) and leaves a bucket, a CDN and an upload script. The cost: new results appear when a job finishes, not as each action completes. - Why not hand-rolled input hashes? A file of stamps (a
build-stamps.json) can skip unchanged steps. But it only hashes the inputs someone remembered to list (not tool versions), and it can’t share results between machines.
Pilot results
Section titled “Pilot results”doreancon.org’s hymn engraving was the pilot for this setup. What it showed:
- A single local edit is not faster. It’s a little slower than running the engraver directly (Bazel’s sandbox and start-up), which is acceptable. The gains are elsewhere: no work is repeated across machines, nothing re-runs when an output comes out unchanged, and the tool versions are part of every cache key.
- Nix’s fontconfig reads the host’s fonts. On a non-NixOS machine it falls
back to
/etc/fontsand scans/usr/share/fonts, so text could set differently per machine with nothing in the cache key to show it. Pin afonts.confthat lists only Nix fonts and a prebuilt cache, and pass it asFONTCONFIG_FILE(doreancon.org’snix/fonts.nix). That makes the step hermetic and also removes most of the per-action cost: a freshHOMEno longer rescans fonts. - Bazel can reproduce production exactly. The hymnal built through Bazel matched the old pipeline’s, file for file, and passed the same tests (Prove a new build equal).
- Scripts that edit files in place (annotate, the manifest step) work as Bazel actions by copying what they edit into their own outputs first.
- Python’s
Path(__file__).resolve()escapes the sandbox, as Node’s symlink resolution does: it follows the symlink into the source tree. Use.absolute(). - Once everything cacheable is cached, a release costs what isn’t: fetching tools for steps that never run, a build outside Bazel, starting the job. Hence tools fetched only when a step runs (above), the site’s build as a Bazel action, and a release that only deploys.
- MuseScore’s output isn’t byte-stable, so nothing downstream of a fresh engraving can be skipped. The skip happens before MuseScore, at the per-hymn manifest cut.
xvfb-run -araces when actions run in parallel: most X servers die on a shared display number. StartXvfb -displayfddirectly instead.- GTK starts gvfs daemons that leave a FUSE mount in
$HOME. SetGIO_USE_VFS=local. - Bazel falls back to
processwrapper-sandboxon Ubuntu workstations (AppArmor restricts unprivileged user namespaces) and in unprivileged containers. It works, but it can’t hide absolute paths outside the sandbox.
Open questions
Section titled “Open questions”- Per-job toolchain download on GitLab.com.
- Does GitLab record
.svrbc-coverage’s figure for a real release? Its report, pattern and download filter are tested (//:coverage_report_test), and the job runs on a fresh output base, every test a cache hit, but no project has released with it yet.