diff --git a/.gitea/workflows/ci.yaml b/.gitea/workflows/ci.yaml index 07b523e..2e40e8e 100644 --- a/.gitea/workflows/ci.yaml +++ b/.gitea/workflows/ci.yaml @@ -4,6 +4,11 @@ on: push: branches: [master] +# Only the newest commit is worth building and caching +concurrency: + group: ci + cancel-in-progress: true + jobs: check: name: Check, build and cache nixfiles @@ -47,31 +52,6 @@ jobs: env: HARMONIA_SSH_KEY: ${{ secrets.HARMONIA_SSH_KEY }} CI_IFD_REQUIRED: ${{ steps.ifd.outputs.required }} - run: | - set -o pipefail - nix_options=(--option allow-import-from-derivation "$CI_IFD_REQUIRED") - - echo "::group::Collect cache garbage" - ci/push-to-cache.sh --gc - echo "::endgroup::" - - nix eval "${nix_options[@]}" --json --apply "builtins.attrNames" .#ci.x86_64-linux | jq -cr '.[]' | while read job; do - echo "::group::Build $job" - nix build "${nix_options[@]}" --no-link .#ci.x86_64-linux."$job" - echo "::endgroup::" - - echo "::group::Cache $job" - ci/push-to-cache.sh "$(nix eval "${nix_options[@]}" --raw .#ci.x86_64-linux."$job")" - echo "::endgroup::" - done - - if [[ "$CI_IFD_REQUIRED" == true ]]; then - echo "::group::Check flake" - # The target closures are available for the evaluation-time reference graphs. - nix flake check "${nix_options[@]}" - echo "::endgroup::" - fi - - echo "Building and caching CI derivation" - nix build "${nix_options[@]}" --no-link .#ciDrv.x86_64-linux - UPDATE_PROFILE=1 ci/push-to-cache.sh "$(nix eval "${nix_options[@]}" --raw .#ciDrv.x86_64-linux)" + run: >- + nix shell .#nixpkgs.unstable.x86_64-linux.python3 .#nixpkgs.unstable.x86_64-linux.nix-eval-jobs + --command python3 ci/build-and-cache.py diff --git a/ci/build-and-cache.py b/ci/build-and-cache.py new file mode 100755 index 0000000..0acd3e9 --- /dev/null +++ b/ci/build-and-cache.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +"""Evaluate, build and cache every attribute of `.#ci.`. + +Then point the cache's `nixfiles` profile at a link farm of the results. +CI_IFD_REQUIRED=true allows import from derivation and runs the flake check +after the builds, when the evaluation-time reference graphs are available. +Expects `nix-eval-jobs` on PATH. +""" + +import json +import os +import re +import subprocess +import sys +from contextlib import contextmanager +from pathlib import Path +from tempfile import TemporaryDirectory + + +SYSTEM = "x86_64-linux" +PUSH = "ci/push-to-cache.sh" + +# Every evaluation worker first pays for a shared evaluation of the flake (a +# few GiB), so keep workers alive for several jobs. workers * memory is the +# evaluation budget; it must leave room on the runner for Gitea and for builds +# started by import from derivation. +EVAL_WORKERS = os.environ.get("CI_EVAL_WORKERS", "4") +EVAL_WORKER_MEMORY = os.environ.get("CI_EVAL_WORKER_MEMORY", "6144") + +ANSI_ESCAPE = re.compile(r"\x1b\[[0-9;]*m") + + +@contextmanager +def group(title: str): + print(f"::group::{title}") + try: + yield + finally: + print("::endgroup::") + + +def annotate_error(title: str, message: str): + # Workflow commands are single lines, so escape multi-line messages + message = ANSI_ESCAPE.sub("", message) + for char, escape in (("%", "%25"), ("\r", "%0D"), ("\n", "%0A")): + message = message.replace(char, escape) + + print(f"::error title={title}::{message}") + + +def succeeds(*command: str) -> bool: + return subprocess.run(command).returncode == 0 + + +def evaluate(nix_options: list[str], work: Path) -> tuple[bool, list[dict]]: + """Evaluate every CI job, returning whether all of them evaluated.""" + result = subprocess.run( + [ + "nix-eval-jobs", *nix_options, + "--workers", EVAL_WORKERS, "--max-memory-size", EVAL_WORKER_MEMORY, + "--gc-roots-dir", str(work / "gc-roots"), + "--flake", f".#ci.{SYSTEM}", + ], + stdout=subprocess.PIPE, + text=True, + ) + jobs = [json.loads(line) for line in result.stdout.splitlines() if line] + + ok = result.returncode == 0 + for job in jobs: + if "error" in job: + annotate_error(f"Evaluation of {job['attrPath'][0]} failed", job["error"]) + ok = False + + return ok, [job for job in jobs if "error" not in job] + + +def build(jobs: list[dict]) -> tuple[bool, dict[str, str]]: + """Build the jobs' outputs, returning whether all built and the built ones by job.""" + ok = succeeds( + "nix", "build", "--keep-going", "--no-link", + *(f"{job['drvPath']}^out" for job in jobs), + ) + + built = {} + for job in jobs: + name = job["attrPath"][0] + path = job["outputs"]["out"] + if succeeds("nix-store", "--check-validity", path): + built[name] = path + else: + annotate_error(f"Build of {name} failed", "See the build log above.") + ok = False + + return ok, built + + +def link_farm(outputs: dict[str, str], work: Path) -> str: + """Build a link farm of the outputs from their paths, without evaluating them again.""" + outputs_file = work / "outputs.json" + outputs_file.write_text(json.dumps(outputs)) + + drv = subprocess.check_output( + [ + "nix", "eval", "--impure", "--raw", f".#nixpkgs.unstable.{SYSTEM}", + "--apply", + f"""pkgs: (pkgs.linkFarm "ci" (builtins.mapAttrs (_: builtins.storePath) + (builtins.fromJSON (builtins.readFile {json.dumps(str(outputs_file))})))).drvPath""", + ], + text=True, + ) + + return subprocess.check_output( + ["nix", "build", "--no-link", "--print-out-paths", f"{drv}^out"], + text=True, + ).strip() + + +def main(): + allow_ifd = os.environ.get("CI_IFD_REQUIRED", "false") == "true" + nix_options = ["--option", "allow-import-from-derivation", str(allow_ifd).lower()] + + with group("Collect cache garbage"): + subprocess.run([PUSH, "--gc"], check=True) + + with TemporaryDirectory() as work: + work = Path(work) + + with group("Evaluate"): + ok, jobs = evaluate(nix_options, work) + + built = {} + if jobs: + with group("Build"): + built_all, built = build(jobs) + ok = ok and built_all + + # Cache whatever built, even when the run fails + if built: + with group("Cache"): + subprocess.run([PUSH, *built.values()], check=True) + + if not ok: + sys.exit(1) + + if allow_ifd: + with group("Check flake"): + subprocess.run(["nix", "flake", "check", *nix_options], check=True) + + with group("Update cache profile"): + farm = link_farm(built, work) + subprocess.run([PUSH, farm], env=os.environ | {"UPDATE_PROFILE": "1"}, check=True) + + +if __name__ == "__main__": + # Keep this script's output in order with its commands' + sys.stdout.reconfigure(line_buffering=True) + main() diff --git a/ci/push-to-cache.sh b/ci/push-to-cache.sh index 45e9bdd..21dee7e 100755 --- a/ci/push-to-cache.sh +++ b/ci/push-to-cache.sh @@ -31,12 +31,15 @@ if [ "${1-}" = "--gc" ]; then exit fi -path="$1" +if [ -n "${UPDATE_PROFILE-}" ] && [ $# -ne 1 ]; then + echo "UPDATE_PROFILE needs exactly one path" >&2 + exit 1 +fi -echo "Pushing $path to cache..." -nix copy --no-check-sigs --to "$STORE_URI" "$path" +echo "Pushing $# path(s) to cache..." +nix copy --no-check-sigs --to "$STORE_URI" "$@" -if [ -n "$UPDATE_PROFILE" ]; then +if [ -n "${UPDATE_PROFILE-}" ]; then echo "Updating profile..." - remote_cmd nix-env -p "$REMOTE_STORE"/nix/var/nix/profiles/nixfiles --set "$path" + remote_cmd nix-env -p "$REMOTE_STORE"/nix/var/nix/profiles/nixfiles --set "$1" fi diff --git a/docs/architecture.md b/docs/architecture.md index 44dc2e2..3eb1903 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -51,8 +51,7 @@ Per platform (`eachDefaultSystem`), the flake produces: - `devShells.default` — the `numtide/devshell` from [`devshell/`](../devshell) (see [deployment.md](deployment.md)). - `ci.` — one attr per buildable thing (`system-`, `home-` with `@` mangled - to `-at-`, `package-`, plus `shell`), consumed by CI; `ciDrv` is a `linkFarm` of all of - them. + to `-at-`, `package-`, plus `shell`), consumed by CI. ## Systems: `systemOpts` and `mkSystem` diff --git a/docs/deployment.md b/docs/deployment.md index e4e209c..ea3cc24 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -302,26 +302,40 @@ GitHub/Gitea Actions workflows live in [`.gitea/workflows/`](../.gitea/workflows On pushes to `master`, this installs Determinate Nix on the runner (via `DeterminateSystems/determinate-nix-action`, configured with the same performance settings and -Harmonia substituter as the boxes). CI normally runs `nix flake check --no-build` first and -keeps import from derivation disabled. It builds every attribute of `.#ci.x86_64-linux`: -systems as `system-`, homes as `home-` (with `@` changed to `-at-`), packages as -`package-`, and the development `shell`. Each result is pushed to the -Harmonia cache with [`ci/push-to-cache.sh`](../ci/push-to-cache.sh). Before the first push, the -workflow deletes cache-profile generations older than its retention period, then collects -unreachable paths so a full cache cannot prevent collection from being reached. Paths pushed by -`slop build` survive collection through their own GC roots (see -[`slop-broker.md`](slop-broker.md#binary-cache)). +Harmonia substituter as the boxes). A newer push cancels a run still in progress. CI normally +runs `nix flake check --no-build` first and keeps import from derivation disabled. It then runs +[`ci/build-and-cache.py`](../ci/build-and-cache.py), which builds every attribute of +`.#ci.x86_64-linux`: systems as `system-`, homes as `home-` (with `@` changed to +`-at-`), packages as `package-`, and the development `shell`. + +The script works in stages: + +- **Collect garbage.** It deletes cache-profile generations older than their retention period, + then collects unreachable paths so a full cache cannot prevent collection from being reached. + Paths pushed by `slop build` survive collection through their own GC roots (see + [`slop-broker.md`](slop-broker.md#binary-cache)). +- **Evaluate.** [`nix-eval-jobs`](https://github.com/nix-community/nix-eval-jobs) evaluates the + attributes in a pool of workers. Each worker reuses one evaluation of the flake for several + jobs, and the worker count and per-worker memory bound (`CI_EVAL_WORKERS`, + `CI_EVAL_WORKER_MEMORY`) cap the evaluation's memory on the runner. +- **Build.** One `nix build --keep-going` builds every evaluated derivation, so a failing job + doesn't stop the others. +- **Cache.** Every output that built is pushed to the Harmonia cache with + [`ci/push-to-cache.sh`](../ci/push-to-cache.sh). Any evaluation or build failure fails the run + at this point. +- **Update the profile.** A `linkFarm` of all the outputs, built from their known store paths + rather than a second evaluation, is pushed with `UPDATE_PROFILE=1`. That updates the + `nixfiles` profile on the cache box. When `.#ciIfdReasons.x86_64-linux` lists an active exception, CI logs a warning with the reason -and allows import from derivation for the target builds. It runs a build-capable flake -check afterward. CI checks [the shared runtime replacement list](../lib/runtime-dependency-replacements.nix) +and allows import from derivation for the evaluation. The evaluation workers then wait on those +builds in parallel. CI runs a build-capable flake check after caching and before updating the +profile. CI checks [the shared runtime replacement list](../lib/runtime-dependency-replacements.nix) against the nixpkgs channels used by its systems and standalone homes. A matching entry requires reading generated store reference graphs during evaluation. -It then builds `.#ciDrv.x86_64-linux`, a `linkFarm` of all CI attributes, and pushes it with -`UPDATE_PROFILE=1`. That updates the `nixfiles` profile on the cache box. The SSH store uses -`/var/lib/harmonia`, `HARMONIA_SSH_KEY`, and pinned `ci/known_hosts`; clients use -`https://nix-cache.nul.ie` through `lib.my.c.nix.cache`. +The SSH store uses `/var/lib/harmonia`, `HARMONIA_SSH_KEY`, and pinned `ci/known_hosts`; clients +use `https://nix-cache.nul.ie` through `lib.my.c.nix.cache`. ### `installer.yaml` diff --git a/flake.nix b/flake.nix index 18f7ede..3144321 100644 --- a/flake.nix +++ b/flake.nix @@ -303,7 +303,6 @@ homes' // systems' // packages' // { inherit shell; }; - ciDrv = pkgs.linkFarm "ci" ci; ciIfdReasons = let