Skip to content

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.

  1. Every repository builds with Bazel, at a version pinned in .bazelversion. bazel build //... and bazel test //... work the same way in every repo.
  2. 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’s nix_tools (see below), not rules_nixpkgs. Upgrading a tool is then a one-line commit, and Bazel rebuilds exactly what depends on it.
  3. 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.
  4. Everyone reads the shared cache; only SVRBC’s developers and its CI write to it. CI means pipelines in svrbc/forks and tags (and staging branches) of the projects; a developer is anyone with the Developer role or more in the svrbc group on GitLab (see below), and svrbc-mr builds, tests and uploads from their workstation before it pushes. A change is built once, and nobody builds it again: not its pipeline, not master (which runs no pipeline), not a reviewer, not another developer.
  5. Secrets live in GitLab CI/CD variables, never in a repository. The cache itself needs none.
  6. 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.
  7. 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.
  8. 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 an sh_test that lays out what it reads, as doreancon.org’s //:unit_tests does for vitest. A Rust crate’s tests are rust_tests (Building the function).
  9. 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).

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:

  1. One nix-instantiate evaluation writes every tool’s recipe (a .drv file) to the Nix store and records its path. Nothing is downloaded but nixpkgs itself.
  2. 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.
  3. The .drv path 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.
MODULE.bazel
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 expression
use_repo(nix_tools, "nix_tools")
BUILD.bazel
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 calling ffprobe) sets PATH=<pinned tool>/bin and nothing else, so a missing tool fails instead of quietly using the machine’s.
  • Fetch tools before changing HOME. realise.sh finds Nix in the ordinary places; a step that swaps in a throwaway HOME does 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).

Terminal window
bazel build //... # build every cacheable output
bazel test //... # run every test Bazel knows about
bazel run //:assets # put generated files where the app reads them, and run
# the steps that can't be cached

bazel 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:

  1. 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);
  2. 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’s PATH.

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.

Two rules, decided 2026-11-24, which svrbc-audit checks, each a failure from the start rather than a warning:

  1. Tests must exist (tests-exist). A project with code fails if bazel 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).
  2. 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.

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-coverage

It 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.

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-v8 at vitest’s own version, give vitest.config.ts a coverage with provider: 'v8', reporter: ['lcovonly', 'text-summary'] and an include of the code a unit test can load (src/**/*.{ts,mts,js,mjs}, router/**/*.js), and run it as vitest run --coverage.enabled --coverage.reportsDirectory="$TEST_UNDECLARED_OUTPUTS_DIR/coverage" (the template’s vitest.sh). The include makes a file no test loads count as uncovered rather than disappear. Astro components aren’t in it: astro check and //:site_test check them. A script a test runs in node:vm (the CloudFront router) counts once it is given its file URL as filename (test/router.test.ts).
  • Rust (an API): a rust_coverage_test (@svrbc_rust//:defs.bzl) of its rust_tests, which builds them again with -Cinstrument-coverage for the repository’s own crates, runs them, and writes their line coverage of src/ as api.lcov with the llvm-profdata and llvm-cov of 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’s api/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.

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 their cas/ hashes.
Looking up an action in the cache An action's command, inputs and tools are hashed into an ac/ key. The ac/ entry lists the action's outputs by their cas/ hashes, and each cas/ entry holds the bytes. If there is no ac/ entry, Bazel runs the action itself. An action command + environment + every input’s hash + every tool’s hash ac/d6fa21f4… “exit 0; psalm-82.svg is cas/9a3eb477…” a claim: only trusted writers cas/9a3eb477… the SVG’s bytes checks itself: name = hash hash fetch no entry: run it, then store miss

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.

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:

Who reads and who writes the shared cache Every machine reads through bazel-cache.svrbc.org, a read-only CloudFront distribution in front of the private S3 bucket svrbc-bazel-cache. Protected CI pipelines write with bazel-cache-sync using GitLab OIDC, and developers’ workstations write with bazel-cache-sync using their GitLab token. Any machine workstations, MR pipelines Protected CI master and tags, svrbc group Developer’s workstation a Developer in the svrbc group bazel-cache.svrbc.org CloudFront GET only; ac/ and cas/ keys anything else is a 404 S3 bucket svrbc-bazel-cache private, us-west-2 ac/ expires at 60 days cas/ at 67 days reads bazel-cache-sync, GitLab OIDC bazel-cache-sync, GitLab token
  • Reading. Every repository’s .bazelrc points Bazel at the cache over plain HTTPS, and tells it never to upload:

    Terminal window
    common --remote_cache=https://bazel-cache.svrbc.org
    common --remote_upload_local_results=false
    common --disk_cache=~/.cache/bazel-disk

    CloudFront serves the private bucket read-only. A CloudFront function passes only ac/<sha256> and cas/<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: every cas/ blob before any ac/ 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 and cas/ 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 a 403 (an error). Listing itself is still blocked by the path filter.

How it was built, as AWS CLI commands, is in infra/bazel-cache/.

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:

Terminal window
bazel-cache-sync # with glab's token, or GITLAB_TOKEN

Why 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_BRANCH

It 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.

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).

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.yml is 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 to master: 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 from master keeps that pipeline until it takes releases.
  • CI’s check reads 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.

//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 from debian:bookworm-slim and 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 /bin as 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, so SSL_CERT_FILE doesn’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.

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.

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.

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.

//: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 (as nuxt prepare does), 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.

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_modules and 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.json and package.json sit one directory above that copy, and Vite’s TypeScript loader finds the parent tsconfig.json and fails with “Tsconfig not found”. Remove the sandbox’s links to the config files once they are copied.
  • Run nuxt prepare first, since it’s the postinstall that the dependency step skipped; it writes the .nuxt/tsconfig files 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.

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.

  • 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’s Path(__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.

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) and CONTENT_SRCS (content/, public/); SITE_SRCS is both, for //:site alone. 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 //:site it 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-blast after adding or changing a target: svrbc-blast <file> lists the steps and tests an edit to that file reruns, and svrbc-blast --sample does it for one file of each kind in the repository. Each should be a list you would expect. svrbc-audit’s bazel-narrow-inputs flags the two common shapes, a test given content/ or public/ and a glob(["**"]).

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.

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 and npm run dev still 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) needs Access-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/.

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.

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 GET and PUT. 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-remote on 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.

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/fonts and scans /usr/share/fonts, so text could set differently per machine with nothing in the cache key to show it. Pin a fonts.conf that lists only Nix fonts and a prebuilt cache, and pass it as FONTCONFIG_FILE (doreancon.org’s nix/fonts.nix). That makes the step hermetic and also removes most of the per-action cost: a fresh HOME no 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 -a races when actions run in parallel: most X servers die on a shared display number. Start Xvfb -displayfd directly instead.
  • GTK starts gvfs daemons that leave a FUSE mount in $HOME. Set GIO_USE_VFS=local.
  • Bazel falls back to processwrapper-sandbox on Ubuntu workstations (AppArmor restricts unprivileged user namespaces) and in unprivileged containers. It works, but it can’t hide absolute paths outside the sandbox.
  • 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.