Cotton code
350 lines · 19.1 KB · ShellRaw
#!/usr/bin/env bash# SCCACHE — COMPILE ONCE PER CRATE, NOT ONCE PER BRANCH.##   bash scripts/ci/setup-sccache.sh## Writes `RUSTC_WRAPPER`, `SCCACHE_DIR`, `SCCACHE_CACHE_SIZE` and# `SCCACHE_IDLE_TIMEOUT` to `$GITHUB_ENV` and puts the pinned binary on# `$GITHUB_PATH`, so every cargo step after it in the same job is wrapped.# `RUSTC_WRAPPER` names a generated SHIM rather than the binary — the block at# the bottom of this file says why, and it is the difference between a 0% Rust# hit rate and a useful one. Run# by `verify-main.yml`'s `rust`, `swift` and `ios` jobs and by `rust-deep.yml`'s# `deep` job — ONE copy, because the pin and its sha256 drifting between four# copies is a supply-chain check that quietly stops being one.## LINUX AND THE CHECK MACS, from the same file. The Mac lanes have the identical# problem and it costs them more per run than it costs Linux: the per-branch# target directory means a new branch cross-compiles `cotton-ffi` and its# dependency graph from nothing every time — measured on run 3421's `swift` job,# 4m51s of release cargo for the mac slice, and on run 3425's `ios` job, 2m01s +# 1m10s for the device and simulator slices. The asset is chosen from `uname`# below; everything after that — the cache directory, the cap, the server, the# four variables — is the same on both.## The per-branch target directory (#406) ended four classes of corruption and# bought them with a cold build on every new branch: ~25 minutes of the same# crates.io dependencies compiled again because the artifacts next door are not# addressable by anything but their path. sccache is the missing half — a LOCAL# disk cache keyed by the hash of the compiler, its arguments and the# preprocessed input, so a crate another branch already compiled is COPIED# rather than compiled. It sits BESIDE the per-branch target directory, the# lock, the sweep and the disk guard; it replaces none of them, and nothing# about which tree an artifact came from becomes ambiguous, because a cache hit# is decided by content and never by mtime.## It needs no server. The runbook's earlier refusal ("sccache or a shared# read-only artifact cache: there is no server to run one on") was about# sccache's DIST mode; `SCCACHE_DIR` is a directory under the lane's HOME, which# is the same durable store everything else here already uses.## BOUNDED BY SCCACHE ITSELF (`SCCACHE_CACHE_SIZE`), which is why the sweep is# taught nothing about this directory: it is LRU-evicting and never grows past# its cap, unlike a target directory, which only ever grows. The free-disk guard# names it anyway, because a human reading that message wants to know every# large thing under that root.## AND IT DOES CACHE C, WITHOUT `CC` BEING SET. `cc-rs` prefixes the C compiler# with `$RUSTC_WRAPPER` itself when that variable's FILE STEM is one of# `sccache`/`cachepot`/`buildcache`/`kache` (`rustc_wrapper_fallback`,# src/lib.rs), which is why the lane's C/C++ and assembler hit rates read 100%# while only `RUSTC_WRAPPER` is set — SQLite's amalgamation is covered. It is# also a constraint on the NAME of whatever goes in that variable: see the shim# at the bottom of this file. What stays outside all of it is MuPDF's vendored# tree, built by `make` from a build script, and the `cc` invocations that pass# several source files at once, which sccache declines to key.## PINNED AND VERIFIED. The Linux CI host carries /usr/local/bin/sccache# (installed by hand — the runbook has the recipe and the sha); this script uses# that copy when its version matches the pin, and otherwise fetches the same# release into the lane's HOME and checks the published sha256 before unpacking# it. A hash that does not match is a hard failure, never a fallback. The check# Macs carry no hand-installed copy and are not meant to: the fetch branch is# the normal path there, it runs once per machine, and a Homebrew sccache of# some other version on a developer's Mac is stepped over rather than used,# because `$GITHUB_PATH` PREPENDS the lane's own copy.## CARGO_INCREMENTAL=0 IS WHAT MAKES ANY OF THIS POSSIBLE: rustc's incremental# mode and a compilation cache are mutually exclusive — an incremental compile# writes state sccache cannot key, so sccache refuses to cache one. The guard in# `cargo-cache.test.ts` reads them as a pair: no job that runs this script may# leave `CARGO_INCREMENTAL` unset.## THE SERVER IS STARTED HERE, OUTSIDE THE CARGO LOCK — this script is not run# under `with-cargo-lock.sh` and the cargo steps that follow it are. (On the Mac# lanes it is outside `with-build-lock.sh` too: a download and a daemon are not# a build, and queueing for a 16 GB machine to fetch 10 MB would stall the# signing lanes' neighbours for nothing.)## sccache's first client daemonises the server, and a daemon inherits every open# file descriptor of the process that started it. The cargo lock lives on fd 9# of `with-cargo-lock.sh`'s shell, and `flock` is held while ANY process holds# that descriptor — so a server started inside a locked cargo step holds that# branch's cargo lock for ever, and the job's next cargo step waits on its own# compile cache. Measured: run 2413, cancelled after `ls -l /proc/<pid>/fd`# showed the server holding `…/targets/ci-sccache.lock`. `with-cargo-lock.sh`# now closes fd 9 for its command, which closes the class; starting the server# here is the second, independent belt and costs nothing.## `SCCACHE_IDLE_TIMEOUT=0` keeps the server alive between jobs: its counters are# what `--show-stats` reads at the end of a job, and a server that had exited# would report a run's work as zeros.set -euo pipefail# A hand run outside CI has neither file; `set -u` would die on the redirect# rather than on anything this script is about.GITHUB_ENV="${GITHUB_ENV:-/dev/null}"GITHUB_PATH="${GITHUB_PATH:-/dev/null}"# ── THE WEDGE DECISION ──────────────────────────────────────────────────────## A SERVER THAT ANSWERS IS NOT A SERVER THAT WORKS. Measured on one Mac on 23 Sep# (PR #915, run 100, the `swift` job): `cargo build --profile release -p# cotton-ffi` had three `sccache … rustc` children pinned at 0% CPU for# SEVENTY-SEVEN minutes while `sccache --show-stats` answered normally — 64,907# requests, 51,118 executed, ~13k that were neither a hit nor a compile. The# "is it listening" probe at the bottom of this file would have said yes, the# job would have inherited the wedge, held the machine-wide build lock and# blocked the household. `sccache --stop-server` unwedged it instantly: a new# server started and rustc went straight to 100% CPU.## So before a job adopts an existing server, ask the only question that# distinguishes a busy server from a wedged one: is there a compile that is OLD# and doing NOTHING? Age alone is not it — a release LTO unit legitimately runs# for many minutes — and 0% CPU alone is not it either, since a process sampled# between slices reads as idle. BOTH, for ten minutes, is a compile that has# stopped.## Reads `ps -axo etime[s]=,pcpu=,command=` on stdin and prints the age of the# oldest idle `sccache … rustc`, in whole minutes, or nothing. Both spellings of# the age column are accepted: `etimes` (seconds) is GNU-only, `etime`# ([[dd-]hh:]mm:ss) is on every platform, and the caller feeds whichever its# `ps` produced — which is also why the test can drive this with a fixture.## FAIL-OPEN, ALWAYS: no `ps`, an unreadable line, or a stop that does not work# leaves the server exactly as it was. This is a watchdog on a cache, and a# cache is never worth failing a job over.## Guard: `scripts/__tests__/sccache-watchdog.test.ts`.SCCACHE_WEDGE_MIN="${SCCACHE_WEDGE_MIN:-10}"SCCACHE_WEDGE_CPU="${SCCACHE_WEDGE_CPU:-1.0}"wedged_minutes_from() {  awk -v min="$SCCACHE_WEDGE_MIN" -v cpu="$SCCACHE_WEDGE_CPU" '    $0 !~ /sccache/ || $0 !~ /rustc/ { next }    {      if ($1 ~ /^[0-9]+$/) {        secs = $1 + 0      } else {        n = split($1, f, /[:-]/)        if (n == 2)      secs = f[1] * 60 + f[2]        else if (n == 3) secs = f[1] * 3600 + f[2] * 60 + f[3]        else if (n == 4) secs = f[1] * 86400 + f[2] * 3600 + f[3] * 60 + f[4]        else next      }      if (secs >= min * 60 && ($2 + 0) <= cpu && secs > oldest) oldest = secs    }    END { if (oldest > 0) printf "%d\n", oldest / 60 }  '}# Testing/debug hook: read `ps` output on stdin and print the verdict. No# processes, no server — the test feeds it the exact shapes both platforms print.if [ "${1:-}" = "--wedged-from-ps" ]; then  wedged_minutes_from  exit 0fiversion=0.17.0# ONE RELEASE, ONE ASSET PER LANE. Every sha256 here is the one published beside# the asset as `<asset>.tar.gz.sha256`, and each was checked against a fresh# download before it was written down. The platform is read rather than passed,# so a job that calls this script gets the right binary by running on the right# machine and nothing has to remember to say which.case "$(uname -s)/$(uname -m)" in  Linux/x86_64)    # musl, never gnu: a statically linked binary cannot repeat the    # `libtinfo.so.5` failure `setup-libclang.sh` spends a chapter on.    asset="sccache-v$version-x86_64-unknown-linux-musl"    sha=67c4a96dd237c1f518f6b36083f270f9976d516f1e57fce891755ea782e50006    ;;  Darwin/arm64)    # THE CHECK MACS. Apple silicon only — every machine carrying    # `cotton-checks-mac` is M-series, and the x86_64 asset would run rustc's    # wrapper under Rosetta on every crate for nothing. The binary Mozilla ships    # is ad-hoc (linker-)signed, which is what arm64 macOS requires to exec it,    # and a `curl` download carries no quarantine attribute.    asset="sccache-v$version-aarch64-apple-darwin"    sha=0c560bfba31aef5bdfb4fb3d2677f6e61d71c5c00952f2a83344f47aa31f00f1    ;;  *)    echo "::error::scripts/ci/setup-sccache.sh has no pinned sccache $version asset for $(uname -s)/$(uname -m). Add the asset and its published sha256 here before wiring a lane onto that machine — an unpinned download is not a fallback." >&2    exit 1    ;;esacroot="$HOME/.cache/cottondb/rust"bin="$root/bin"usable() {  command -v "$1" >/dev/null 2>&1 || return 1  [ "$("$1" --version 2>/dev/null | head -1)" = "sccache $version" ]}# AND `$bin` GOES ON *THIS* SHELL'S PATH TOO, NOT ONLY ON `$GITHUB_PATH`.# `$GITHUB_PATH` is applied to the NEXT step; the server start at the bottom of# this file runs in THIS one. On the Linux CI host that was invisible, because# /usr/local/bin/sccache is the hand-installed pinned copy and the first branch# always won. The check Macs carry no such copy, so they take the fetch branch —# and a bare `sccache --start-server` there dies `command not found` (exit 127)# under `set -e`, failing the job on the step that was supposed to make it# faster. Measured by running this script under a throwaway HOME on a Mac.real=""if usable sccache; then  echo "sccache: $(command -v sccache) is already the pinned $version"  real="$(command -v sccache)"elif usable "$bin/sccache"; then  echo "sccache: the lane's own copy at $bin/sccache is the pinned $version"  echo "$bin" >> "$GITHUB_PATH"  export PATH="$bin:$PATH"  real="$bin/sccache"else  echo "sccache: no pinned $version on this host — fetching it into $bin"  mkdir -p "$bin"  tmp="$(mktemp -d)"  trap 'rm -rf "$tmp"' EXIT  curl -fsSL --proto '=https' --tlsv1.2 -o "$tmp/sccache.tar.gz" \    "https://github.com/mozilla/sccache/releases/download/v$version/$asset.tar.gz"  # macOS ships no `sha256sum`. `shasum -a 256 -c -` reads exactly the same  # "<sha>  <path>" line and exits non-zero on a mismatch, so the hard failure  # is the same one on both lanes — there is no path past a bad hash.  if command -v sha256sum >/dev/null 2>&1; then    echo "$sha  $tmp/sccache.tar.gz" | sha256sum -c -  else    echo "$sha  $tmp/sccache.tar.gz" | shasum -a 256 -c -  fi  tar xzf "$tmp/sccache.tar.gz" -C "$tmp"  install -m 0755 "$tmp/$asset/sccache" "$bin/sccache"  echo "$bin" >> "$GITHUB_PATH"  export PATH="$bin:$PATH"  "$bin/sccache" --version  real="$bin/sccache"fi# ── THE SHIM, AND WHY THE WRAPPER IS NOT `sccache` ITSELF ───────────────────## MEASURED, run 181's `rust` job: `Cache hits rate (Rust) 0.00 %` over 1,419# Rust compilations. Not low — ZERO, cumulatively, since the server started. The# cache was written to (0 write errors, 41 GB on disk) and never once read,# because this lane's `CARGO_TARGET_DIR` is per head branch and sccache hashes# every `CARGO_*` variable but four. The whole argument, the measurement that# proves it and the two properties the shim must keep are in# `scripts/ci/sccache-shim.sh`, which `rust-verify.sh` shares — one copy,# because a second would be the one that stops being right.shim_path="$(bash "$(dirname "$0")/sccache-shim.sh" "$real" "$root/shim")"echo "sccache: wrapping rustc through $shim_path (it drops CARGO_TARGET_DIR, which sccache would otherwise hash)"# THE CAP, PER MACHINE. 15 GB on a Mac (40 until 14 Oct 2026: at 40 GiB the# cache sat at its cap on the serving Mac while every build there was refused at# the disk floor), whose disk the iOS lanes and a person's sessions also live on. 100 GB on the Linux host since 2026-09-27:# with the build slots (`scripts/ci/build-slot.sh`) the per-branch target# directories are gone and sccache is the one place a compiled crate survives# a slot's target being wiped, so it is worth the disk the directories used to# take — and it is still LRU-bounded, which they never were. A `du` at the end# of every job prints what it actually holds.if [ "$(uname -s)" = Darwin ]; then  cache_size=15Gelse  cache_size=100Gfi{  echo "RUSTC_WRAPPER=$shim_path"  echo "SCCACHE_DIR=$root/sccache"  echo "SCCACHE_CACHE_SIZE=$cache_size"  echo "SCCACHE_IDLE_TIMEOUT=0"} >> "$GITHUB_ENV"# START THE SERVER HERE, OUTSIDE THE CARGO LOCK — this step is not# under `with-cargo-lock.sh` and the cargo steps below are.## sccache's first client daemonises the server, and a daemon inherits# every open file descriptor of the process that started it. The cargo# lock lives on fd 9 of `with-cargo-lock.sh`'s shell, and `flock` is# held while ANY process holds that descriptor — so a server started# inside a locked cargo step holds this branch's cargo lock for ever,# and the job's next cargo step waits on its own compile cache.# Measured: run 2413 on this PR, cancelled after `ls -l /proc/<pid>/fd`# showed the server holding `…/targets/ci-sccache.lock`.# `with-cargo-lock.sh` now closes fd 9 for its command, which closes# the class; starting the server here is the second, independent belt# and costs nothing.## ASK BEFORE STARTING. With `SCCACHE_IDLE_TIMEOUT=0` the server outlives# the job that started it, so on every run after the first it is already# listening and a bare `--start-server` prints# `error: Server startup failed: Address in use` — harmless, `|| true`# swallows it, and it reads in a green log like something broke.# `--show-stats` succeeds only against a live server, so it IS the probe.export SCCACHE_DIR="$root/sccache" SCCACHE_CACHE_SIZE="$cache_size" SCCACHE_IDLE_TIMEOUT=0# Linux has both runner and developer accounts. The default TCP server can# belong to the developer and cannot read the runner's mode-0640 artifacts# (run 2143: all workspace tests passed, then dependency hashing got EACCES).# Select our own socket BEFORE probing or starting a daemon and keep it in# every later step. Never chmod build artifacts or stop another user's cache.if [ "$(uname -s)" = Linux ]; then  export SCCACHE_SERVER_UDS="$root/sccache.sock"  echo "SCCACHE_SERVER_UDS=$SCCACHE_SERVER_UDS" >> "$GITHUB_ENV"fi# THE DIRECTORY FIRST, ALWAYS. sccache's server opens its cache directory once,# at start, and never creates or recreates one: started against a path that does# not exist it accepts every compile and fails every WRITE, silently, for its# whole life — and `SCCACHE_IDLE_TIMEOUT=0` above means that life is "until the# machine reboots". One Mac reached 29,679 cache write errors and a 4.32% Rust# hit rate this way, after disk-guard deleted the directory under a live server# (`scripts/reclaim-sccache.sh` is the other half of that fix). One `mkdir -p`# makes a missing directory unreachable from this side too.mkdir -p "$SCCACHE_DIR"# ── THE WATCHDOG ────────────────────────────────────────────────────────────# (the decision itself is `wedged_minutes_from` at the top of this file, so the# test can feed it `ps` output and read the verdict without a wedged server.)if [ "${SCCACHE_NO_WATCHDOG:-}" = 1 ]; then  echo "sccache: watchdog off (SCCACHE_NO_WATCHDOG=1)"else  stuck_min="$( { ps -axo etimes=,pcpu=,command= 2>/dev/null || true; } | wedged_minutes_from || true)"  if [ -z "$stuck_min" ]; then    stuck_min="$( { ps -axo etime=,pcpu=,command= 2>/dev/null || true; } | wedged_minutes_from || true)"  fi  if [ -n "$stuck_min" ]; then    echo "sccache: a \`sccache … rustc\` compile has been ${stuck_min}m old at ~0% CPU — that is a wedged server, not a slow one."    echo "sccache: stopping it before this job starts (one Mac, 23 Sep: 77m of this held the build lock while --show-stats answered normally)."    sccache --stop-server >/dev/null 2>&1 || echo "sccache: --stop-server did not succeed; continuing with the server as it is"  fifi# THE CAP IS READ ONCE, AT SERVER START. A server an earlier job started with a# different SCCACHE_CACHE_SIZE keeps that one for its whole life — and with# `SCCACHE_IDLE_TIMEOUT=0` its life is "until the machine reboots" — so the cap# this file names would be a fiction until then. `--show-stats` prints the size# the live server runs with ("Max cache size   15 GiB"); when it is not this# one, the server is stopped and started again. Its counters restart from zero,# and the log says so, so a `--show-stats` reader is not surprised.# shellcheck source=../lib/sccache-alone.sh. "$(cd "$(dirname "${BASH_SOURCE[0]}")/../lib" && pwd)/sccache-alone.sh"# Probed before `--show-stats` reads the cap: with no server listening that# command would start one in THIS step's process group.running_cap=""sccache_heal_tmp sccacheif sccache_listening; then  running_cap="$(sccache --show-stats 2>/dev/null | sed -n 's/^Max cache size *//p' | head -1 | tr -d ' ')"fiif [ -n "$running_cap" ] && [ "$running_cap" != "${cache_size%G}GiB" ]; then  echo "sccache: the running server is capped at $running_cap, this lane wants ${cache_size%G} GiB — restarting it (its stats start over)"  sccache --stop-server >/dev/null 2>&1 || echo "sccache: --stop-server did not succeed; continuing with the server as it is"fiif sccache_listening; then  echo "sccache: the server from an earlier job is still listening"else  # In a session of its own (`scripts/lib/sccache-alone.sh`): born in this  # step's process group, it died with whatever stopped that group next.  sccache_alone sccache --start-server  echo "sccache: started the server in a session of its own"fiecho "sccache: cache at $root/sccache, capped at $cache_size, wrapping rustc for the rest of this job"