Cotton code
789 lines · 35.4 KB · ShellRaw
#!/usr/bin/env bash## Verify the Rust workspace from a WHOLE-repo `git archive HEAD` extraction.## WHY NOT THE WORKTREE. Several agents share one worktree during a step, so the# disk carries other lanes' in-flight edits and lies about what HEAD builds: a# green `cargo test` in the worktree has told us three times that a tree which# could not even compile was fine, because a file the build needed existed only# on somebody's disk and was never committed. `git archive HEAD` is the only# reading of "what will CI see" that a shared worktree cannot corrupt.## WHY THE WHOLE REPO. Never a `crates` pathspec subset: tests read files# outside `crates/` by path (`rust-crate-local-reads.test.ts` names each), so a# subset extraction fails with an error that names neither side.## WHY THE EXTRACTION IS INSTALLED. Tests that run scripts of the repo need its# `node_modules`; `--frozen-lockfile --offline` serves the whole tree from the# pnpm store: the extraction carries the same `pnpm-lock.yaml` the worktree was# installed from, so the store already holds every package.## THE BARE FORM IS `all`, AND IT USED TO BE `check`. A command called# "verify" whose default is `cargo check` tells you the workspace COMPILES and# nothing else — no clippy, no test ran — and at least three agents read a green# bare run as "the Rust tests pass" and said so in a PR body. A default that is# quietly the cheapest third of what its name promises is not a fast path, it is# a wrong answer. So the bare verb now runs all three phases in order, and every# SINGLE-phase verb prints, on its way out, which phases it did not run.##   pnpm rust:verify            all three: check, then clippy, then the tests#   pnpm rust:verify all        the same, written out#   pnpm rust:verify extract    refresh the extraction from HEAD#   pnpm rust:verify check      cargo check --workspace --all-targets#   pnpm rust:verify clippy     cargo clippy --all-targets -- -D warnings#   pnpm rust:verify test [...] one `cargo test --no-fail-fast` PER CRATE, then#                               a per-crate table and the line "N crates ran,#                               M did not"; extra arguments passed through, and#                               `-p <crate>` narrows the set#                               (`scripts/rust-verify-tests.sh` carries the why)#   pnpm rust:verify cold       a TIMED cargo test --workspace into an EMPTY#                               target dir — what the CI runner pays. ONE cargo#                               run, so it still stops at the first red target:#                               it answers a wall-clock question, not "is the#                               workspace green". Use `test` for that.#   pnpm rust:verify sweep      reclaim stale extractions now; with paths,#                               reclaim exactly those##   --keep                      on check/clippy/test/cold, LEAVE the target#                               directory and the extraction warm on the way#                               out for an immediate retry (default: a run#                               removes everything it made but its log — see#                               "A RUN CLEANS UP AFTER ITSELF" below).#   --clean                     the default, spelled out; with --keep too,#                               --clean wins. Accepted so old muscle memory#                               keeps working.## Every run writes a log of its own under `<scratch>/logs`, named for the verb,# a UTC stamp and the pid, and prints the path before it does anything else.## `all`, `check`, `clippy`, `test` and `cold` re-extract on their own whenever the# extraction is missing or was taken from a different commit, so a stale# extraction cannot report a green that belongs to an older HEAD.## WHY IT KEEPS THE TARGET WARM — AND WHAT BOUNDS IT INSTEAD.## One extraction's target directory is ~27 GB. Until 2026-09-09 every run left# one behind for ever: five of them held 102 GB of this Mac's disk, the machine# sat at 87% full and two agents died on ENOSPC. The answer then was that a# GREEN run deleted its own target, and it over-corrected — a verify is run# before every PR, several times a day, and each one paid a ~20-minute cold# rebuild of the same workspace to save disk on a Mac with 339 GB free. Deleting# a cache that will certainly be wanted within the hour is not thrift.## So the default is the other way round now, and the disk is bounded by rules# stated in the units a person can check rather than by a delete after every# pass:##   AGE     — a sibling extraction nothing has touched for `RUST_VERIFY_STALE_HOURS`#             (6) is reclaimed by every run, exactly as before;#   BUDGET  — and then, LAST, the only rule in gigabytes: measure what survived#             and evict oldest-first until the set fits `RUST_VERIFY_BUDGET_GB`#             (30). The age rule is a proxy for size and cannot say "30 GB";#             this one can, and one warm extraction fits inside it.## BOTH NUMBERS WERE TOO LOOSE, AND THE MEASUREMENT SAYS SO. An extraction is not# the ~27 GB the paragraph above was written against: on one Mac, 2026-09-22, the# scratch root held 81 GB in THREE extractions — 27 GB each — every one of them# inside a 24-hour window and the set inside a 60 GB budget only because the# budget was bigger than the disk could afford. A verify is minutes of work and# the next one is usually on a different branch, so a 24-hour window keeps two# extractions nobody will touch again. Six hours keeps today's branch warm; 30 GB# is one extraction plus slack, which is what a warm cache is actually for.## AND BOTH SWEEPS RUN BEFORE THE EXTRACTION, never only after it: every verb# that can extract calls `sweep_stale` and `sweep_budget` first, so the 27 GB a# new extraction is about to need is reclaimed before it is asked for rather# than after the disk has already carried both. Guard:# `scripts/__tests__/rust-verify-sweep.test.ts`.## A RUN CLEANS UP AFTER ITSELF (since 2026-09-27). Green, red, or killed, a# run removes on the way out what it made: `target`, `target-cold`, the# extraction and its stamp — only the run log stays. From 2026-09-15 to this# date the default was the other way round (keep the target warm; `--clean`# opted out), on the argument that a cold rebuild was twenty minutes and the# next run was usually the same one. The owner measured what that cost instead:# about 29 GB left behind by EVERY run — one scratch per worktree, and nothing# reclaims the last worktree's scratch but a later run from a DIFFERENT one,# which on a Mac with five worktrees never comes soon enough. And the argument# no longer holds: every Mac carries one shared sccache at# `~/.cache/cottondb/rust/sccache` (15 GB), and this script wraps rustc with it,# so a rebuild into an empty target is a copy out of that cache for every crate# whose content did not change — `cargo check` included (measured: 116 of 154# compiles served on the second cold check). What a run pays again is the# proc-macros, the build scripts and the linking, not the workspace.## `--keep` is the opt-in for a warm retry, and it is a flag the caller typed,# so it holds on a RED run too; the sweeps below still reclaim what it left# after `RUST_VERIFY_STALE_HOURS`. `--clean` remains accepted (it is the# default, and it wins over `--keep`), because until 2026-09-16 the red branch# ignored it and that cost an agent three consecutive exit-101 verifies ended# by a `cargo clean -p cotton-server` typed by hand: a flag the caller typed is# never second-guessed by the failure it was typed in response to.## The cleanup runs from the EXIT trap as well as after the verb, so a run that# is interrupted (INT, TERM) or that dies inside cargo still leaves only its# log. Guard: `scripts/__tests__/rust-verify-cleanup.test.ts`.## The sweep only ever removes directories this script itself created: `reclaim`# refuses any path that does not resolve inside the scratch root, symlinks# included, and never takes one whose lock has a live holder.## SCCACHE, WHEN THE PINNED BINARY IS ALREADY HERE. `scripts/ci/setup-sccache.sh`# installs one copy per machine under `~/.cache/cottondb/rust/bin` and every CI# lane wraps rustc with it; an extraction is the lane that benefits most,# because it builds from a tree that has never existed before and every crate# is nominally cold. This script FETCHES NOTHING — a verification that reached# for the network would be a different kind of thing — it just uses the copy the# CI bootstrap left, and pairs it with `CARGO_INCREMENTAL=0`, which is not a# preference: rustc's incremental mode writes state sccache cannot key, so# sccache declines to cache an incremental compile and a run with both set pays# for both and gets neither.## The extraction and the target dir live outside the repo. ON A MAC THERE IS# ONE OF EACH PER MACHINE, whichever worktree asks (11 Oct 2026, the build-store# lane): sccache keys every `CARGO_*` variable, `CARGO_MANIFEST_DIR` among them,# so an extraction at a per-worktree path made every one of Cotton's own crates# a miss the first time a new worktree verified — 111 of 462 compiles, the# heavy ones (measured on the signing Mac: 83 s against 39 s at one fixed path, where# a second worktree at the same commit compiled zero crates). A Mac runs one# verify at a time anyway (the machine lock above), so sharing costs no# concurrency. A run still removes its extraction on the way out (so the next# re-extracts and every crate is served from sccache: `check` measured 119 s# cold, then 71 s from a second worktree); under `--keep` a second worktree at# the same commit reuses the extraction and target as they stand. Elsewhere# (Linux, no machine lock)# the scratch is keyed by the worktree path, so concurrent verifies never share# a target dir. Runs into one scratch hold one exclusive lock across# extraction, cargo and cleanup; the second waits before touching the# extraction, polling every 10 seconds. `--print-scratch` prints the scratch# directory and exits (the guard's hook).## Environment: `CARGO_BUILD_JOBS` (default 3 — the build Mac is 16 GB and a# full-width cargo build swaps it), `RUST_VERIFY_DIR` to move the scratch root,# `RUST_VERIFY_STALE_HOURS` (default 6) for the sweep's window,# `RUST_VERIFY_BUDGET_GB` (default 30; 0 turns the budget off),# `RUST_VERIFY_SCCACHE` (a path to use, or `off`).set -euo pipefailexport PATH="$HOME/.cargo/bin:$PATH"export CARGO_BUILD_JOBS="${CARGO_BUILD_JOBS:-3}"REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"REPO="$(git -C "$REPO" rev-parse --show-toplevel)"# THE MACHINE'S BUILD MUTEX FIRST, on a Mac. This verify is a full-width cargo# build and test run, and until 28 Sep 2026 it took none of the locks CI's own# cargo steps queue behind (`scripts/ci/with-machine-lock.sh`). PR #1026's# Swift suite died with a signal — 5199 of 5200 passed — while a hand-run# `rust:verify` had the same Mac's memory (todo bb40fae2, defect 2), and two# `swift` jobs on the signing Mac died mid-compile on 27 Sep beside a session's cargo# runs. A verify and a CI build on one 16 GB Mac is a machine swapping; queued,# each gets the machine whole. On Linux the wrapper runs the command as it is.# The wrapper walks its own parent chain, so a caller already holding the lock# runs straight through; the variable is what stops THIS re-exec recursing.# Guard: `scripts/__tests__/rust-verify-test-table.test.ts`.# ON LINUX TOO, since the same day: there the wrapper takes no lock, but it is# where a builder's run is ranked below the check jobs — nice 19 and four test# threads, not sixteen at nice 0 (the CI host read load 49 on 16 cores from# builders' verifies). A check job passes straight through it.if [ -z "${COTTON_VERIFY_UNDER_LOCK:-}" ] && [ "${1:-}" != --print-scratch ]; then  export COTTON_VERIFY_UNDER_LOCK=1  exec env BUILD_LOCK_LABEL="${BUILD_LOCK_LABEL:-local-rust-verify}" \    bash "$(dirname "${BASH_SOURCE[0]}")/ci/with-machine-lock.sh" bash "${BASH_SOURCE[0]}" "$@"fi# `--keep` and `--clean` may appear anywhere; everything else is the verb and# cargo's own arguments. Cleaning up is the default; `--keep` opts out; `--clean`# wins when both are typed.CLEAN=0KEEP=0args=()for arg in "$@"; do  case "$arg" in    --clean) CLEAN=1 ;;    --keep) KEEP=1 ;;    *) args+=("$arg") ;;  esacdoneset -- ${args[@]+"${args[@]}"}# The scratch's name — see "ON A MAC THERE IS ONE OF EACH PER MACHINE" above.# Elsewhere one per worktree: the basename reads in an `ls`, the hash keeps# two worktrees that share a basename apart.if [ "$(uname -s)" = Darwin ]; then  key="this-mac"else  key="$(basename "$REPO")-$(printf '%s' "$REPO" | shasum | cut -c1-8)"fiROOT="${RUST_VERIFY_DIR:-${TMPDIR:-/tmp}/cotton-rust-verify}"# shellcheck source=/dev/null. "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib/owned-root.sh"refuse_wide_root "the scratch root (RUST_VERIFY_DIR)" "$ROOT"ROOT="${ROOT%/}"SCRATCH="$ROOT/$key"if [ "${1:-}" = --print-scratch ]; then printf '%s\n' "$SCRATCH"; exit 0; fiBASE="$SCRATCH/base"STAMP="$SCRATCH/extracted-from"STALE_HOURS="${RUST_VERIFY_STALE_HOURS:-6}"# The only rule stated in gigabytes. 0 turns it off. 30 holds ONE warm# extraction — measured at 27 GB, not the 21 GB this was first sized against.BUDGET_GB="${RUST_VERIFY_BUDGET_GB:-30}"export CARGO_TARGET_DIR="$SCRATCH/target"# THE RUN LOG, NAMESPACED PER RUN — AND PRINTED FIRST.## Three agents share this Mac and each of them wanted a file to read the last# verify out of. A fixed path is the obvious answer and it is the wrong one:# two runs at once write the same file and the one you read afterwards is# neither of them. So the script writes its OWN log, under this worktree's# scratch (already one directory per worktree), named for the verb, a UTC stamp# and the pid — three things no two concurrent runs share — and prints the path# before anything else happens, including the lock wait that is usually what# somebody is trying to look into.## stdout and stderr are tee'd SEPARATELY so a caller still sees two streams;# the log holds both, in order.LOG_DIR="$SCRATCH/logs"log_verb="$(printf '%s' "${1:-all}" | tr -c 'A-Za-z0-9._-' '-')"LOG_FILE="${RUST_VERIFY_LOG:-$LOG_DIR/${log_verb}-$(date -u '+%Y%m%dT%H%M%SZ')-$$.log}"mkdir -p "$(dirname "$LOG_FILE")": >"$LOG_FILE"# Keep the newest 20. One run leaves one file; nothing else ever removes them# until the whole scratch is reclaimed, which can be days.ls -t "$LOG_DIR" 2>/dev/null | tail -n +21 | while IFS= read -r old_log; do  rm -f "$LOG_DIR/$old_log"doneexec > >(tee -a "$LOG_FILE")exec 2> >(tee -a "$LOG_FILE" >&2)echo "rust-verify: log → $LOG_FILE"# THE COMPILE CACHE, IF THE MACHINE ALREADY HAS THE PINNED ONE.## `scripts/ci/setup-sccache.sh` is the one place the version and its sha256# live, and it installs the binary into `~/.cache/cottondb/rust/bin`. This# script never fetches — a verification lane that downloaded a compiler wrapper# would be a supply-chain surface nobody asked for — so it uses that copy, or a# pinned one already on PATH, and otherwise says nothing and builds as before.## `CARGO_INCREMENTAL=0` travels with it or not at all: rustc's incremental mode# and a compilation cache are mutually exclusive.setup_sccache() {  local candidate="${RUST_VERIFY_SCCACHE:-}"  [ "$candidate" = off ] && return 0  if [ -z "$candidate" ]; then    if [ -x "$HOME/.cache/cottondb/rust/bin/sccache" ]; then      candidate="$HOME/.cache/cottondb/rust/bin/sccache"    else      candidate="$(command -v sccache 2>/dev/null || true)"    fi  fi  [ -n "$candidate" ] && [ -x "$candidate" ] || return 0  # NOT `$candidate` ITSELF. sccache hashes every `CARGO_*` environment variable  # but four, and this script exports `CARGO_TARGET_DIR` (per worktree off a Mac)  # — so the cache could never serve the one case worth serving, a new task's  # first verify. The shim drops that one variable before exec'ing the binary;  # `scripts/ci/sccache-shim.sh` carries the measurement and the two properties  # it has to keep, and the CI bootstrap uses the same file.  RUSTC_WRAPPER="$(bash "$REPO/scripts/ci/sccache-shim.sh" "$candidate" "$SCRATCH/sccache-shim")"  export RUSTC_WRAPPER  export CARGO_INCREMENTAL=0  export SCCACHE_DIR="${SCCACHE_DIR:-$HOME/.cache/cottondb/rust/sccache}"  export SCCACHE_CACHE_SIZE="${SCCACHE_CACHE_SIZE:-15G}"  # THE DIRECTORY, BEFORE THE FIRST CLIENT STARTS A SERVER AGAINST IT. A server  # that starts against a missing path never creates one and never writes:  # `scripts/reclaim-sccache.sh` has the failure this closes.  mkdir -p "$SCCACHE_DIR" 2>/dev/null || true  echo "rust-verify: wrapping rustc with $candidate through $RUSTC_WRAPPER (cache $SCCACHE_DIR, incremental off)"}# Like with-build-lock.sh: atomic mkdir, a live holder is never evicted, and a# dead holder is reclaimed. Use the pid as the record's NAME so two reclaimers# cannot unlink a new holder's record after observing the same dead holder.LOCK_DIR="$SCRATCH/.lock"LOCK_HELD=0release_lock() {  if [ "$LOCK_HELD" = 1 ]; then    rm -f "$LOCK_DIR/$$"    rmdir "$LOCK_DIR" 2>/dev/null || true  fi}# Armed by run_verb before the verb starts, disarmed by the cleanup itself, so# an interrupted or crashed run cleans up from here and a finished one does not# clean up twice. The lock is released AFTER the cleanup: what is being removed# is still this run's, and a sweep from another worktree must keep its hands off# until it is gone.CLEANUP_ARMED=0# Armed right AFTER the lock is ours and BEFORE the extraction, by every# building verb: a run that dies or is interrupted while it extracts (the# `git archive | tar`, the dependency install) removes the half-made extraction# too, not only one that dies inside cargo. Never before the lock: a run killed# while it WAITS must not remove the holder's scratch. The `extract` verb does# not arm it — keeping the extraction is what that verb is for.arm_cleanup() {  CLEANUP_ARMED=1}on_exit() {  if [ "$CLEANUP_ARMED" = 1 ]; then    clean_own_scratch || true  fi  release_lock}trap on_exit EXITtrap 'exit 130' INTtrap 'exit 143' TERM# True when any pid-named record in the lock directory names a live process.# An empty lock directory, or one whose every record is a dead pid, is a# crash's residue and protects nothing.lock_has_live_holder() {  local lock="$1" record pid  for record in "$lock"/*; do    [ -f "$record" ] || continue    pid="${record##*/}"    [[ "$pid" =~ ^[1-9][0-9]*$ ]] || continue    kill -0 "$pid" 2>/dev/null && return 0  done  return 1}acquire_lock() {  local record holder since announced=0  mkdir -p "$SCRATCH"  until mkdir "$LOCK_DIR" 2>/dev/null; do    holder="" since="unknown (holder starting)"    for record in "$LOCK_DIR"/*; do      [ -f "$record" ] || continue      holder="${record##*/}"      [[ "$holder" =~ ^[1-9][0-9]*$ ]] || continue      since="$(cat "$record" 2>/dev/null || true)"      if ! kill -0 "$holder" 2>/dev/null; then        echo "rust-verify: holder pid $holder is dead — reclaiming lock" >&2        if rm "$record" 2>/dev/null; then          rmdir "$LOCK_DIR" 2>/dev/null || true        fi      fi    done    [ -d "$LOCK_DIR" ] || continue    # A crash between mkdir and writing the pid leaves an empty directory.    # rmdir removes only an empty lock, never a newly published holder.    if [ -z "$holder" ] && [ -n "$(find "$LOCK_DIR" -maxdepth 0 -mmin +5 -print 2>/dev/null)" ]; then      rmdir "$LOCK_DIR" 2>/dev/null || true      continue    fi    if [ "$announced" = 0 ]; then      echo "rust-verify: waiting for pid ${holder:-unknown}, holding $LOCK_DIR since $since" >&2      announced=1    fi    sleep 10  done  LOCK_HELD=1  date -u '+%Y-%m-%dT%H:%M:%SZ' > "$LOCK_DIR/$$"}# The one gate between the sweep and the disk: a path is ours only if it# RESOLVES inside the scratch root. Resolving is the point — a sibling that is# a symlink to somebody's checkout is not ours, and `cargo clean --target-dir`# would happily follow it.owns_path() {  local p="$1" real root_real  [ -n "$ROOT" ] || return 1  root_real="$(cd "$ROOT" 2>/dev/null && pwd -P)" || return 1  if [ -d "$p" ]; then    real="$(cd "$p" 2>/dev/null && pwd -P)" || return 1  else    real="$p"  fi  case "$real" in    "$root_real"/?*) return 0 ;;    *) return 1 ;;  esac}# Remove one extraction directory this script created. Cargo does the deleting# wherever there is a manifest to run it from — it verifies the target's# CACHEDIR.TAG first, which a bare `rm -rf` would not.reclaim() {  local dir="$1" manifest  if ! owns_path "$dir"; then    echo "rust-verify: refusing to remove '$dir' — not inside $ROOT" >&2    return 1  fi  [ -d "$dir" ] || return 0  # A lock whose holder is still alive protects the extraction. A lock whose  # holder died (a killed run, a rebooted box) must NOT: that extraction is the  # 21 GB the sweep exists to reclaim, and nothing else would ever remove it.  if [ -d "$dir/.lock" ] && lock_has_live_holder "$dir/.lock"; then    echo "rust-verify: refusing to remove '$dir' — verify lock exists" >&2    return 1  fi  manifest="$dir/base/crates/Cargo.toml"  if [ -d "$dir/target" ] && [ -f "$manifest" ]; then    cargo clean --manifest-path "$manifest" --target-dir "$dir/target" >/dev/null 2>&1 || true  fi  rm -rf "$dir"}# Fresh if anything this script stamps has been touched inside the window. A# directory's own mtime does not move while cargo builds into it, but# `target/`'s does, so all four are asked.recently_used() {  local dir="$1" mins="$2" p  for p in "$dir" "$dir/target" "$dir/target-cold" "$dir/extracted-from"; do    [ -e "$p" ] || continue    if [ -n "$(find "$p" -maxdepth 0 -mmin "-$mins" -print -quit 2>/dev/null)" ]; then      return 0    fi  done  return 1}sweep_stale() {  [ -d "$ROOT" ] || return 0  local dir mins=$(( STALE_HOURS * 60 ))  for dir in "$ROOT"/*; do    [ -d "$dir" ] || continue    if [ "$dir" = "$SCRATCH" ]; then continue; fi    if recently_used "$dir" "$mins"; then continue; fi    if reclaim "$dir"; then      echo "rust-verify: swept $dir — nothing touched it for over ${STALE_HOURS}h"    fi  done}# THE BUDGET, AND IT RUNS LAST. The age rule above is a proxy for size and# cannot say "30 GB": a machine that verifies three branches inside a day keeps# three 27 GB extractions, every one of them inside its window and every one of# them correct by that rule — 81 GB, measured on one Mac on 2026-09-22. So what survived is MEASURED, and the oldest are# evicted until the set fits. This run's own scratch is never a candidate — it# is the thing the budget exists to let us keep.## `du -sk` because a gigabyte is not a size a test fixture can reach on a CI# disk; `RUST_VERIFY_BUDGET_KB` is the same number in the unit the arithmetic# happens in, and it wins when both are set, which is what makes the rule# testable at all.## HOW OLD A SIBLING IS, AS A NUMBER. `stat` reads an mtime with a different flag# AND a different format on each platform this runs on, and GNU's `%m` is the# MOUNT POINT rather than a time — so `stat -c '%m'` succeeds, answers `/`,# every directory sorts equal, and the eviction takes whichever the glob# happened to name first. (That cost `scripts/ci/sweep-cargo-targets.sh` run# 2404; the reasoning is written out there.) Decide by reading a NUMBER, and# fall back to "unknown, therefore newest" rather than guess an order.newest_mtime() {  local dir="$1" newest=""  if [ -z "${STAT_MTIME+set}" ]; then    if [ -n "$(stat -c '%Y' "$dir" 2>/dev/null | tr -dc '0-9')" ] &&       [ -z "$(stat -c '%Y' "$dir" 2>/dev/null | tr -d '0-9\n')" ]; then      STAT_MTIME=(stat -c '%Y')    elif [ -n "$(stat -f '%m' "$dir" 2>/dev/null | tr -dc '0-9')" ] &&         [ -z "$(stat -f '%m' "$dir" 2>/dev/null | tr -d '0-9\n')" ]; then      STAT_MTIME=(stat -f '%m')    else      STAT_MTIME=()    fi  fi  [ "${#STAT_MTIME[@]}" -gt 0 ] || { printf '%s\n' 9999999999; return 0; }  newest="$(find "$dir" -maxdepth 2 -exec "${STAT_MTIME[@]}" {} + 2>/dev/null | sort -n | tail -1 || true)"  case "$newest" in    ''|*[!0-9]*) printf '%s\n' 9999999999 ;;    *) printf '%s\n' "$newest" ;;  esac}sweep_budget() {  local budget_kb="${RUST_VERIFY_BUDGET_KB:-}"  [ -n "$budget_kb" ] || budget_kb=$(( BUDGET_GB * 1024 * 1024 ))  [ "$budget_kb" -gt 0 ] || return 0  [ -d "$ROOT" ] || return 0  local dir size total=0 listing=""  for dir in "$ROOT"/*; do    [ -d "$dir" ] || continue    [ "$dir" = "$SCRATCH" ] && continue    # `|| true`: a sibling can be removed by another lane between the glob and    # the measurement, and `set -e` must not turn that race into a failure.    size="$(du -sk "$dir" 2>/dev/null | awk '{ print $1 }' || true)"    case "$size" in ''|*[!0-9]*) continue ;; esac    total=$(( total + size ))    listing="$listing$(newest_mtime "$dir") $size $dir"$'\n'  done  # This run's own extraction counts against the budget but is never evicted:  # the honest reading of "what is on this disk" includes it.  size="$(du -sk "$SCRATCH" 2>/dev/null | awk '{ print $1 }' || true)"  case "$size" in ''|*[!0-9]*) size=0 ;; esac  total=$(( total + size ))  [ "$total" -gt "$budget_kb" ] || return 0  echo "rust-verify: extractions hold $(( total / 1024 / 1024 )) GB against a $(( budget_kb / 1024 / 1024 )) GB budget — evicting oldest first"  local line  while IFS= read -r line; do    [ -n "$line" ] || continue    [ "$total" -le "$budget_kb" ] && break    dir="${line#* * }"    size="${line#* }"; size="${size%% *}"    if reclaim "$dir"; then      total=$(( total - size ))      echo "rust-verify: swept $dir — the extractions were over the $(( budget_kb / 1024 / 1024 )) GB budget"    fi  done <<<"$(printf '%s' "$listing" | sort -n)"}# ~27 GB per extraction, and it is KEPT unless the caller asked otherwise: the# next verify is usually within the hour, and the age and budget sweeps above# are what bound the disk now.## WHAT THE CLEANUP REMOVES, AND WHY IT IS CHECKED. Every target directory this# scratch owns — `target` and `cold`'s `target-cold` — and then the extraction# (`base`) and its stamp; the run log stays, and the scratch directory itself,# holding only `logs`. `cargo clean` is run against each target first, `rm -rf`# behind it as the thing that actually guarantees the removal (`cargo clean`# declines a directory carrying no `CACHEDIR.TAG`), and each removal is checked# and reported with its size, because the old `--clean` once claimed to have# cleaned a directory that was still there. Nothing is removed that does not# resolve inside the scratch root.## `--keep` leaves all of it warm and says what the next run will do about it.clean_own_scratch() {  CLEANUP_ARMED=0  if [ "$KEEP" = 1 ] && [ "$CLEAN" != 1 ]; then    local warm_kb    warm_kb="$(du -sk "$SCRATCH" 2>/dev/null | awk '{ print $1 }' || true)"    case "$warm_kb" in ''|*[!0-9]*) warm_kb=0 ;; esac    echo "rust-verify: --keep — leaving $CARGO_TARGET_DIR and the extraction warm ($(( warm_kb / 1024 )) MB under $SCRATCH); the next run here without --keep removes them, and a run from any worktree sweeps them after ${STALE_HOURS}h"    return 0  fi  local dir kb removed=0 total=0  for dir in "$SCRATCH/target" "$SCRATCH/target-cold"; do    [ -d "$dir" ] || continue    if ! owns_path "$dir"; then      echo "rust-verify: refusing to clean '$dir' — not inside $ROOT" >&2      return 1    fi    kb="$(du -sk "$dir" 2>/dev/null | awk '{ print $1 }' || true)"    case "$kb" in ''|*[!0-9]*) kb=0 ;; esac    if [ -f "$BASE/crates/Cargo.toml" ]; then      cargo clean --manifest-path "$BASE/crates/Cargo.toml" \        --target-dir "$dir" >/dev/null 2>&1 || true    fi    rm -rf "$dir"    if [ -d "$dir" ]; then      echo "rust-verify: could NOT remove $dir" >&2      return 1    fi    echo "rust-verify: removed $dir ($(( kb / 1024 )) MB)"    total=$(( total + kb ))    removed=$(( removed + 1 ))  done  if [ -d "$BASE" ]; then    if ! owns_path "$BASE"; then      echo "rust-verify: refusing to clean '$BASE' — not inside $ROOT" >&2      return 1    fi    kb="$(du -sk "$BASE" 2>/dev/null | awk '{ print $1 }' || true)"    case "$kb" in ''|*[!0-9]*) kb=0 ;; esac    rm -rf "$BASE" "$STAMP"    if [ -d "$BASE" ]; then      echo "rust-verify: could NOT remove the extraction $BASE" >&2      return 1    fi    echo "rust-verify: removed the extraction $BASE ($(( kb / 1024 )) MB)"    total=$(( total + kb ))    removed=$(( removed + 1 ))  fi  if [ "$removed" -eq 0 ]; then    echo "rust-verify: cleaned up — nothing under $SCRATCH to remove"  else    echo "rust-verify: cleaned up — $removed director$([ "$removed" = 1 ] && echo y || echo ies) removed, $(( total / 1024 )) MB back; only the log stays under $SCRATCH (--keep holds a target warm for a retry)"  fi}# Run a cargo verb in the extraction, and clean up after it whatever it# answered. A RED run says on stderr that the target is gone and how to hold one# warm next time; `--keep` holds it now, and `--clean` wins over `--keep`.run_verb() {  local status=0  CLEANUP_ARMED=1  ( cd "$BASE/crates" && "$@" ) || status=$?  if [ "$status" -ne 0 ]; then    if [ "$KEEP" = 1 ] && [ "$CLEAN" != 1 ]; then      echo "rust-verify: exit $status — --keep holds $CARGO_TARGET_DIR warm for the retry" >&2    else      echo "rust-verify: exit $status — removing the target and the extraction as every run does;" \           "pass --keep to hold them warm for an immediate retry (sccache makes the rebuild cheap either way)" >&2    fi  fi  clean_own_scratch  return "$status"}# What a SINGLE-phase run did not do, said on the way out rather than left to# be inferred from the verb. One line, and it names the command that does.say_what_did_not_run() {  local ran="$1" missing="$2"  echo "rust-verify: that was \`$ran\` ONLY — $missing did NOT run. \`pnpm rust:verify\` (or \`all\`) runs all three."}# The whole verification, in the order that fails cheapest first. Runs INSIDE# the extraction (run_verb has already cd'd there) and stops at the first red:# clippy over a tree that does not compile, and tests over a tree clippy# rejects, are both answers nobody is waiting for.verify_all() {  # A GIT FOR THE SERVER'S GIT-BACKED TESTS, on a Linux box — the same export  # the `rust` lane makes, for the same reason (`scripts/ci/setup-test-git.sh`).  # On a Mac the ladder answers and the script exports nothing.  if [ -z "${COTTON_GIT:-}" ]; then    local git_env    git_env="$(mktemp)"    GITHUB_ENV="$git_env" bash "$REPO/scripts/ci/setup-test-git.sh" || return $?    # shellcheck disable=SC1090    set -a; . "$git_env"; set +a    rm -f "$git_env"  fi  echo "rust-verify: [1/3] cargo check --workspace --all-targets"  cargo check --workspace --all-targets "$@" || return $?  echo "rust-verify: [2/3] cargo clippy --all-targets -- -D warnings"  cargo clippy --all-targets "$@" -- -D warnings || return $?  echo "rust-verify: [3/3] the tests — one cargo test PER CRATE, then the table"  bash "$REPO/scripts/rust-verify-tests.sh" "$@" || return $?  echo "rust-verify: all three phases passed — check, clippy, and the per-crate tests."}extract() {  local head  head="$(git -C "$REPO" rev-parse HEAD)"  rm -rf "$BASE"  mkdir -p "$BASE"  git -C "$REPO" archive HEAD | tar -x -C "$BASE"  install_deps  printf '%s\n' "$head" >"$STAMP"  echo "rust-verify: extracted HEAD ($(git -C "$REPO" rev-parse --short HEAD)) into $BASE"}# The extraction's own `node_modules`, from the pnpm store. Offline first: every# package the lockfile names is already in the store, since the worktree was# installed from the same file, and an offline install cannot be slowed or# broken by the network. A registry fetch is the fallback and says so.install_deps() {  if ! command -v pnpm >/dev/null 2>&1; then    echo "rust-verify: pnpm is not on PATH — tests that run the repo's scripts will fail" >&2    return 0  fi  echo "rust-verify: installing the extraction's dependencies (offline, from the pnpm store)"  if ! (cd "$BASE" && pnpm install --frozen-lockfile --offline >/dev/null); then    echo "rust-verify: the offline install failed — retrying with --prefer-offline (the store is missing something the lockfile names)" >&2    (cd "$BASE" && pnpm install --frozen-lockfile --prefer-offline >/dev/null) || {      echo "rust-verify: install failed; tests that run the repo's scripts will fail" >&2      return 0    }  fi}# Re-extract unless the extraction on disk was taken from the commit we are on.ensure_extracted() {  local head stamped=""  head="$(git -C "$REPO" rev-parse HEAD)"  [ -f "$STAMP" ] && stamped="$(cat "$STAMP")"  if [ ! -d "$BASE/crates" ] || [ "$stamped" != "$head" ]; then    extract  fi}# `all`, not `check` — see "THE BARE FORM IS `all`" at the top.cmd="${1:-all}"[ $# -gt 0 ] && shiftcase "$cmd" in  all)    acquire_lock    arm_cleanup    sweep_stale    sweep_budget    ensure_extracted    setup_sccache    echo "rust-verify: all — check, clippy and the per-crate tests, stopping at the first red."    run_verb verify_all "$@"    ;;  sweep)    if [ $# -eq 0 ]; then      sweep_stale      sweep_budget    else      # Named paths: the same guard, no age test — the caller said which.      failed=0      for dir in "$@"; do        if reclaim "$dir"; then          echo "rust-verify: reclaimed $dir"        else          failed=1        fi      done      exit "$failed"    fi    ;;  extract)    acquire_lock    sweep_stale    sweep_budget    extract    ;;  check)    acquire_lock    arm_cleanup    sweep_stale    sweep_budget    ensure_extracted    setup_sccache    run_verb cargo check --workspace --all-targets "$@"    say_what_did_not_run check "clippy and the tests"    ;;  clippy)    acquire_lock    arm_cleanup    sweep_stale    sweep_budget    ensure_extracted    setup_sccache    run_verb cargo clippy --all-targets "$@" -- -D warnings    say_what_did_not_run clippy "the compile check and the tests"    ;;  test)    acquire_lock    arm_cleanup    sweep_stale    sweep_budget    ensure_extracted    setup_sccache    # Not a bare `cargo test`: that stops at the first failing target and prints    # a subset's counts as though they were the workspace's. The phase script    # runs each crate separately and names every crate that did not run.    run_verb bash "$REPO/scripts/rust-verify-tests.sh" "$@"    say_what_did_not_run test "clippy"    ;;  cold)    acquire_lock    arm_cleanup    # A separate target dir, emptied: the point of this one is the WALL CLOCK a    # cold CI runner pays, and a warm cache would answer a different question.    sweep_stale    sweep_budget    ensure_extracted    export CARGO_TARGET_DIR="$SCRATCH/target-cold"    rm -rf "$CARGO_TARGET_DIR"    # NO SCCACHE HERE, DELIBERATELY: `cold` answers "what does the CI runner    # pay for a build from nothing", and a warm compile cache answers a    # different question just as surely as a warm target directory would.    export RUSTC_WRAPPER=""    run_verb /usr/bin/time -p cargo test --workspace "$@"    ;;  *)    echo "usage: pnpm rust:verify <all|extract|check|clippy|test|cold|sweep> [--clean] [cargo args...]" >&2    echo "       all     check, then clippy, then the per-crate tests — the DEFAULT when no verb is given" >&2    echo "       --keep  leave the target directory and the extraction warm on the way out" >&2    echo "               for a retry (default: a run removes everything it made but its log)" >&2    echo "       --clean the default, spelled out; wins over --keep" >&2    echo "       sweep   reclaim extractions unused for ${STALE_HOURS}h, then evict oldest-first" >&2    echo "               until they fit ${BUDGET_GB} GB; with paths, reclaim exactly those" >&2    exit 2    ;;esac