Cotton code
885 lines · 39.3 KB · ShellRaw
#!/usr/bin/env bash# Reclaim the per-branch cargo target directories this runner has no use for.##   scripts/ci/sweep-cargo-targets.sh [--dry-run] [--days N] [--max N]#                                     [--budget-gb N] [--everything] [--dev-below-gb N]#                                     [--root DIR] [--keep NAME]...#                                     [--no-remote] [--no-legacy] [--no-dev-target]## THE ONE RULE ABOVE EVERY RULE: A TARGET A JOB HOLDS IS NEVER TAKEN. Every# lane holds `<name>.lock` beside its directory for the whole of its cargo work# (`scripts/ci/with-cargo-lock.sh` — `flock` on Linux, `<name>.lock.d/pid` on a# Mac), and this script asks that lock, non-blocking, before any rule below may# remove the directory. The grace window stays as the fallback for a directory# nothing locks, but it is a PROXY for "a job is in here" and it is wrong for# exactly the phase that reads without writing: run 613 (28 Sep 2026) lost a# 17 GB target, and the test binary inside it, to a remover that judged the# directory idle while the job holding its lock was running its tests.# `--everything` is the deep tier's spelling of "every regenerable one": every# target that is not `--keep`, not inside the grace window and not held.## WHY. Since 2026-09-09 every head branch gets its OWN cargo target directory# under the runner's HOME (`scripts/ci/cargo-target-dir.sh` — the reason is on# that script and in the procedure “Work with the forge — tokens, the pnpm forge surface, workflows and runs”). That ends four classes of# cross-PR corruption and buys one problem in exchange: a merged branch's# directory is never touched again, and one of them is 70–85 GB. So every `rust`# and `swift` job sweeps before it builds.## THREE RULES, AND WHY THE AGE ONE ALONE WAS NOT ENOUGH. Six hours after the# per-branch directories landed, the CI host was 100% full: seven branch targets# of 70–85 GB (460 GB), five of them for branches whose PR had already merged,# and run 2400 died on `No space left on device`. A seven-day window cannot keep# up with a repo that opens several branches a day at 80 GB each. So:##   DEAD      — the branch is gone from every remote. The live remote named#               by `.cottondb/host.json` is asked first (cotton → cotton,#               forgejo → origin), then all others. A branch on any remote#               stays live. If any listing fails, the rule is OFF: a network#               failure cannot prove a branch dead. The grace window below#               still protects a fresh fork build.#   CAP       — at most the `--max` (default 3) most recently written targets#               survive besides the `--keep` ones. This is the rule that bounds#               the disk: three branches at 80 GB is a number the host can hold,#               and any fourth branch is by definition the one nobody is pushing#               to. LRU, by the newest mtime two levels down — the same reading#               of "used" as the age rule below. A directory written within the#               grace window is spared here too, and that is not a nicety: the#               Linux runner's capacity is 8, so EIGHT `rust` jobs on eight#               branches can be building at once and only one of them is this#               run's `--keep`. Reclaiming a target another live job is linking#               into is the corruption this whole page exists to prevent, so the#               cap yields to the disk guard rather than take that risk.#   AGE       — nothing has touched it within `--days` (default 7). Kept as a#               floor: it reclaims a directory the other two rules would leave#               (a branch still open on the remote, inside the cap, abandoned).#   BUDGET    — and then, LAST, the only rule stated in gigabytes: measure what#               survived and evict oldest-first until the set fits `--budget-gb`#               (default 0, off). The three rules above are proxies for size and#               none of them can say "20 GB"; on the CI host they left 76 GB#               behind while every one of them was working as designed. Written#               out where it runs, near the bottom of this file.## WHAT COUNTS AS USED. The directory's own mtime is not enough — cargo writes# deep inside it and a top-level mtime can sit still through a whole build — so# anything modified within two levels counts: the directory, its children# (`debug/`, `release/`, `.rustc_info.json`) and its grandchildren (`debug/deps`,# `debug/.fingerprint`), which is where a build's writes land. Two levels is# also cheap: an 80 GB tree is hundreds of thousands of files and this looks at# a few hundred.## WHAT IT WILL NOT DO. Remove anything that does not RESOLVE inside the targets# root. Resolving is the point: a directory in there that is a symlink to# somebody's checkout is not ours, and `rm -rf` would follow it. The root itself# is refused, and so is a path that merely shares the root's prefix# (`…/targets-elsewhere`).## AND THE ONE FROM BEFORE ALL OF THIS. Until #408 every run of every PR built# into ONE shared directory, `~/.cache/cottondb/rust/target` — the sibling of# `targets/`, not one of its children. It is 162 GB on the CI host and it is# STILL WRITTEN TO: a branch cut before 157b79c4 carries the old workflow at its# head (the three dependabot PRs, at least), so its runs still build there. No# rule above can see it, because it is not under the root. So the sweep reclaims# it too, under the OLD lock (`~/.cache/cottondb/rust/.lock`, which those runs# still take through `with-cargo-lock.sh`), taken NON-BLOCKING: if a run holds# it the sweep says so and leaves it for next time. It is only a cache; the# branches that still use it pay one cold build. `--no-legacy` turns it off.## AND THE OTHER SIBLING — THE ONE A PERSON BUILDS INTO. `pnpm worktree:new`# writes a `.cargo/config.toml` naming ONE target directory per machine,# `~/.cache/cottondb/cargo-target` (Cotton note "The Rust core — the file format, and how a change to it lands", "One cargo# target directory per MACHINE"), so six worktrees share one set of compiled# dependencies. On the build Mac that directory is written by the interactive# sessions the machine also hosts, it is 7-8 GB, no CI lane ever builds into it,# and — like the legacy target — it is a SIBLING of the root, so no rule above# can see it.## THE RULE, STATED IN THE UNIT THE GATE USES. It is reclaimed when the# filesystem holding it has less than `--dev-below-gb` free — the SAME floor# `require-free-disk.sh` is about to refuse the build on, read from the same# `COTTON_CI_MIN_FREE_GB` so the two cannot drift. Above the floor it stays# warm; below it, a rebuildable cache loses to a build that would otherwise not# start at all. A reader predicts this rule with `df -g`, which is the reason it# is a floor rather than an age: "will my warm dev target survive tonight's# release build?" has an answer somebody can check from the keyboard, and it is# the same number the red bar names. It is never taken while something wrote it# inside the grace window — a person's `cargo build` may be in it, and the disk# guard refusing loudly beats corrupting a live build. `--no-dev-target` turns# the rule off.## WHY THIS MATTERS ON THE SIGNING MAC. Steady state there is ~55 GB free against a# 60 GB floor, an iOS archive run costs ~12 GB and the sweep above hands back# ~4 GB, so every SECOND consecutive release run was refused at the gate: runs# 3157 (refused) → 3158 (shipped 1.0.0 (149)) → 3165 (refused, 54 GB free).## A `<name>.lock` file lives beside each target directory (the cargo step lock).# It goes with its directory, and an ORPHANED one — a lock whose target# directory is already gone — is reclaimed too.## Env: COTTON_CARGO_TARGETS_ROOT, COTTON_CARGO_TARGETS_STALE_DAYS (default 7),# COTTON_CARGO_TARGETS_MAX (default 3; 0 turns the cap off),# COTTON_CARGO_TARGETS_BUDGET_GB (default 0, off) and its exact sibling# COTTON_CARGO_TARGETS_BUDGET_KB (unset; wins when both are given),# COTTON_CARGO_LEGACY_TARGET / COTTON_CARGO_LEGACY_LOCK (default: the siblings# `<root>/../target` and `<root>/../.lock`), COTTON_CARGO_LEGACY_LOCK_TOOL# (auto | flock | mkdir — `auto` picks flock where there is one, the macOS# mkdir shape where there is not; naming one is for tests and for a hand run),# COTTON_CARGO_DEV_TARGET (default: COTTON_CARGO_TARGET_DIR, else the sibling# `<root>/../../cargo-target` — the path the worktree setup writes),# COTTON_CARGO_DEV_TARGET_MIN_FREE_GB (default: COTTON_CI_MIN_FREE_GB, else 60).set -euo pipefail# The Mac's device policy owns pressure reclamation: dependencies first,# never a live lane target. Preserve the operator's dry-run contract.if [ "$(uname -s)" = Darwin ]; then  policy_mode=--check  for arg in "$@"; do [ "$arg" != --dry-run ] || policy_mode=--dry-run; done  exec bash "$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/mac-build-policy.sh" --path "$HOME" "$policy_mode"fiHERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"NAME_FOR="$HERE/cargo-target-dir.sh"ROOT="${COTTON_CARGO_TARGETS_ROOT:-$HOME/.cache/cottondb/rust/targets}"DAYS="${COTTON_CARGO_TARGETS_STALE_DAYS:-7}"MAX="${COTTON_CARGO_TARGETS_MAX:-3}"# 0 = off, and off is the default: one branch's target directory on a build Mac# is 70-85 GB, so a number sized for the Linux box would empty that cache on# every build. The Linux lanes name their own.BUDGET_GB="${COTTON_CARGO_TARGETS_BUDGET_GB:-0}"# THE SAME RULE IN THE UNIT THE SCRIPT MEASURES IN. `du -sk` answers in KiB and# everything below is KiB arithmetic; `--budget-gb` is the human spelling of# this number. It is named because a gigabyte is not a size a test fixture can# reach on a CI disk, and a budget test that cannot make its fixture exceed the# budget is a test that proves the eviction loop compiles. When both are set the# KiB one wins, because it is the more precise statement of the same thing.BUDGET_KB="${COTTON_CARGO_TARGETS_BUDGET_KB:-}"# A directory written this recently is never called dead, whatever the remote# says: a fork's head ref may not be on these remotes, nor is a branch# deleted while its last run is still building.GRACE_MINS="${COTTON_CARGO_TARGETS_GRACE_MINS:-60}"# THE FLOOR THE DEV TARGET IS SPENT AT, and it is the disk guard's own number:# `require-free-disk.sh` reads COTTON_CI_MIN_FREE_GB (60) and refuses the build# below it, so reading the same variable here is what makes "reclaimed exactly# when the gate would otherwise refuse" true rather than approximately true.DEV_MIN_FREE_GB="${COTTON_CARGO_DEV_TARGET_MIN_FREE_GB:-${COTTON_CI_MIN_FREE_GB:-60}}"DRY_RUN=0REMOTE=1LEGACY=1DEV=1EVERYTHING=0KEEP=()while [ $# -gt 0 ]; do  case "$1" in    --dry-run) DRY_RUN=1; shift ;;    --days) DAYS="${2-}"; shift 2 ;;    --max) MAX="${2-}"; shift 2 ;;    --budget-gb) BUDGET_GB="${2-}"; shift 2 ;;    # A budget of nothing: the budget loop, which already honours --keep, the    # grace window and the held lock, evicts every other target. The deep tier    # of `scripts/disk-guard.sh` asks for this instead of running an `rm -rf`    # loop of its own, so the one set of rules applies wherever a target goes.    --everything) EVERYTHING=1; BUDGET_KB=0; shift ;;    --dev-below-gb) DEV_MIN_FREE_GB="${2-}"; shift 2 ;;    --root) ROOT="${2-}"; shift 2 ;;    --keep) KEEP+=("${2-}"); shift 2 ;;    --no-remote) REMOTE=0; shift ;;    --no-legacy) LEGACY=0; shift ;;    --no-dev-target) DEV=0; shift ;;    *)      echo "usage: sweep-cargo-targets.sh [--dry-run] [--days N] [--max N] [--budget-gb N] [--everything] [--dev-below-gb N] [--root DIR] [--keep NAME]... [--no-remote] [--no-legacy] [--no-dev-target]" >&2      exit 2      ;;  esacdoneROOT="${ROOT%/}"# shellcheck source=/dev/null. "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/../lib/owned-root.sh"refuse_wide_root "the cargo targets root (--root / COTTON_CARGO_TARGETS_ROOT)" "$ROOT"for pair in "--days:$DAYS" "--max:$MAX" "--budget-gb:$BUDGET_GB" "--dev-below-gb:$DEV_MIN_FREE_GB" ${BUDGET_KB:+"COTTON_CARGO_TARGETS_BUDGET_KB:$BUDGET_KB"}; do  case "${pair#*:}" in    ''|*[!0-9]*)      echo "sweep-cargo-targets: ${pair%%:*} wants a whole number, got '${pair#*:}'" >&2      exit 2      ;;  esacdonelog() { echo "[sweep-cargo-targets] $*"; }# Modified within the window, anywhere in the top two levels. Declared here# rather than beside the per-branch rules because the two sibling reclaims below# — the legacy target and the dev target — run BEFORE the root is even looked# at, and both ask the same question of a directory: has anything written it# recently enough that a build might be inside it.used_within_mins() {  local dir="$1" mins="$2"  [ -n "$(find "$dir" -maxdepth 2 -mmin "-$mins" -print -quit 2>/dev/null)" ]}LEGACY_TARGET="${COTTON_CARGO_LEGACY_TARGET:-$(dirname "$ROOT")/target}"LEGACY_LOCK="${COTTON_CARGO_LEGACY_LOCK:-$(dirname "$ROOT")/.lock}"LEGACY_LOCK_TOOL="${COTTON_CARGO_LEGACY_LOCK_TOOL:-auto}"# The dev target's default is DERIVED FROM THE ROOT, the way the legacy one is,# so a `--root` pointed at a fixture never reaches a real cache: the root is# `<cache>/rust/targets`, and the worktree setup writes# `<cache>/cargo-target`. `COTTON_CARGO_TARGET_DIR` is read first because that# is the variable a person overrides the dev target with when creating a# worktree — one name, both ends.DEV_TARGET="${COTTON_CARGO_DEV_TARGET:-${COTTON_CARGO_TARGET_DIR:-$(dirname "$(dirname "$ROOT")")/cargo-target}}"# Both are removed WHOLE, and a variable can point either anywhere.refuse_wide_root "the legacy shared target (COTTON_CARGO_LEGACY_TARGET)" "$LEGACY_TARGET"refuse_wide_root "the dev cargo target (COTTON_CARGO_DEV_TARGET / COTTON_CARGO_TARGET_DIR)" "$DEV_TARGET"# THE PRE-#408 SHARED TARGET. Not under the root, so no rule below can see it;# 162 GB on the CI host and still written to by branches whose head carries the# old workflow. Taken under the OLD lock, non-blocking: those runs hold it# through `with-cargo-lock.sh`, and a cache is never worth racing a live build# for. Returns 0 whether it removed anything or not — a held lock is a normal# outcome, not a failure.reclaim_legacy() {  local tool="$LEGACY_LOCK_TOOL"  [ "$LEGACY" = 1 ] || return 0  [ -e "$LEGACY_TARGET" ] || return 0  evidence_kept "$LEGACY_TARGET" && return 0  if [ -L "$LEGACY_TARGET" ]; then    echo "[sweep-cargo-targets] refusing to remove '$LEGACY_TARGET' — it is a symlink, and what it points at is not ours" >&2    return 1  fi  if [ ! -d "$LEGACY_TARGET" ]; then    echo "[sweep-cargo-targets] refusing to remove '$LEGACY_TARGET' — it is not a directory" >&2    return 1  fi  # The name is part of the contract: this reclaims the OLD cargo target and  # nothing else, whatever an override was pointed at.  if [ "$(basename "$LEGACY_TARGET")" != "target" ]; then    echo "[sweep-cargo-targets] refusing to remove '$LEGACY_TARGET' — the legacy target is named 'target'" >&2    return 1  fi  if [ "$tool" = auto ]; then    if command -v flock >/dev/null 2>&1; then tool="flock"; else tool="mkdir"; fi  fi  mkdir -p "$(dirname "$LEGACY_LOCK")"  if [ "$tool" = flock ]; then    # NON-BLOCKING. fd 9 is closed either way; the kernel drops the lock with it.    exec 9>"$LEGACY_LOCK" || {      echo "[sweep-cargo-targets] cannot open $LEGACY_LOCK for locking — leaving the legacy target alone" >&2      return 1    }    if ! flock -n 9; then      exec 9>&-      log "the legacy shared target $LEGACY_TARGET is in use — a run holds $LEGACY_LOCK; leaving it for next time"      return 0    fi    if [ "$DRY_RUN" = 1 ]; then      log "would remove the legacy shared target $LEGACY_TARGET — the pre-#408 directory, and its lock is free"    else      rm -rf "$LEGACY_TARGET"      log "removed the legacy shared target $LEGACY_TARGET — the pre-#408 directory nothing should build into any more"    fi    exec 9>&-    return 0  fi  # macOS: no flock(1). The same mkdir shape `with-cargo-lock.sh` uses there,  # and non-blocking by construction — one attempt, no poll, no reclaim of a  # dead holder's lock. Waiting is not worth it for a cache.  local lock_dir="$LEGACY_LOCK.d"  if ! mkdir "$lock_dir" 2>/dev/null; then    log "the legacy shared target $LEGACY_TARGET is in use — a run holds $lock_dir; leaving it for next time"    return 0  fi  echo "$$" > "$lock_dir/pid"  if [ "$DRY_RUN" = 1 ]; then    log "would remove the legacy shared target $LEGACY_TARGET — the pre-#408 directory, and its lock is free"  else    rm -rf "$LEGACY_TARGET"    log "removed the legacy shared target $LEGACY_TARGET — the pre-#408 directory nothing should build into any more"  fi  rm -rf "$lock_dir"  return 0}sibling_status=0reclaim_legacy || sibling_status=1# THE DEV CARGO TARGET — THE OTHER SIBLING, the one a PERSON builds into.## The worktree setup points every worktree's `build.target-dir` at ONE# directory per machine, `~/.cache/cottondb/cargo-target`. On the build Mac,# which is also the machine interactive sessions run on, that is 7-8 GB nothing# in CI ever reads — and it is a sibling of the targets root, so the dead-branch,# cap, age and budget rules are all blind to it, exactly as they were to the# pre-#408 target above.## ONE RULE, IN GIGABYTES: reclaim it when the filesystem holding it is below# `--dev-below-gb`, which defaults to the very floor `require-free-disk.sh` is# about to refuse the build on. Above the floor the cache stays warm and costs# a person nothing; below it, the choice is not "warm cache or cold cache", it# is "a build, or a red bar at the gate". A reader answers "will tonight's# release take my dev target?" with `df -g`.## WHAT IT WILL NOT DO, and each of these is the legacy reclaim's rule too:# follow a symlink standing where the directory should be, remove something that# is not a directory, or remove a path whose basename is not `cargo-target`# (the name is part of the contract, whatever an override was pointed at). And# it never takes a directory written inside the grace window: a person's# `cargo build` may be in it, and a disk guard that refuses loudly is a far# better outcome than a target directory pulled out from under a live compile.reclaim_dev_target() {  local free  [ "$DEV" = 1 ] || return 0  [ -e "$DEV_TARGET" ] || return 0  evidence_kept "$DEV_TARGET" && return 0  if [ -L "$DEV_TARGET" ]; then    echo "[sweep-cargo-targets] refusing to remove '$DEV_TARGET' — it is a symlink, and what it points at is not ours" >&2    return 1  fi  if [ ! -d "$DEV_TARGET" ]; then    echo "[sweep-cargo-targets] refusing to remove '$DEV_TARGET' — it is not a directory" >&2    return 1  fi  if [ "$(basename "$DEV_TARGET")" != "cargo-target" ]; then    echo "[sweep-cargo-targets] refusing to remove '$DEV_TARGET' — the dev target is named 'cargo-target'" >&2    return 1  fi  # `df -Pk` is POSIX output on both the Linux runner and the build Mac — the  # same read `require-free-disk.sh` makes, so the two agree about the number  # this rule is stated in. An answer that is not a number is a REFUSAL, never a  # pass: a rule that deletes 8 GB must not fire because `df` was unreadable.  local avail_kb  avail_kb="$(df -Pk "$DEV_TARGET" 2>/dev/null | awk 'NR == 2 { print $4 }' || true)"  case "$avail_kb" in    ''|*[!0-9]*)      echo "[sweep-cargo-targets] could not read the free space on the filesystem holding '$DEV_TARGET' — leaving the dev cargo target alone" >&2      return 1      ;;  esac  free=$(( avail_kb / 1024 / 1024 ))  if [ "$free" -ge "$DEV_MIN_FREE_GB" ]; then    log "the dev cargo target $DEV_TARGET stays warm — ${free} GB free, at or above the ${DEV_MIN_FREE_GB} GB floor this build is about to be gated on"    return 0  fi  if used_within_mins "$DEV_TARGET" "$GRACE_MINS"; then    log "the dev cargo target $DEV_TARGET was written in the last ${GRACE_MINS} minutes — a build may be inside it; leaving it, and the disk guard will refuse rather than risk it"    return 0  fi  if [ "$DRY_RUN" = 1 ]; then    log "would remove the dev cargo target $DEV_TARGET — only ${free} GB free against the ${DEV_MIN_FREE_GB} GB floor, and no CI lane builds into it"    return 0  fi  rm -rf "$DEV_TARGET"  log "removed the dev cargo target $DEV_TARGET — only ${free} GB free against the ${DEV_MIN_FREE_GB} GB floor; it is rebuildable and no CI lane builds into it"  return 0}dev_status=0reclaim_dev_target || dev_status=1[ "$dev_status" = 0 ] || sibling_status=1if [ ! -d "$ROOT" ]; then  log "nothing to sweep under $ROOT — it does not exist yet"  exit "$sibling_status"fiROOT_REAL="$(cd "$ROOT" && pwd -P)"# `stat` reads an mtime with a DIFFERENT FLAG AND A DIFFERENT FORMAT on each# platform, and this runs on both (Linux runner, build Mac). GNU is# `stat -c '%Y'`; BSD is `stat -f '%m'`. The trap that cost run 2404: GNU's# `%m` is the MOUNT POINT, not a time — so `stat -c '%m'` succeeds, answers# `/`, and every directory sorts equal, which turns the LRU cap into "whatever# order the glob produced" and reclaims the NEWEST target. Decide once, by# reading a number rather than by trusting an exit status, and refuse to run at# all if neither flavour answers one: ordering by a value this script does not# understand is exactly how it would delete the wrong directory.if [ -n "$(stat -c '%Y' "$ROOT" 2>/dev/null | tr -dc '0-9')" ] &&   [ -z "$(stat -c '%Y' "$ROOT" 2>/dev/null | tr -d '0-9\n')" ]; then  STAT_MTIME=(stat -c '%Y')elif [ -n "$(stat -f '%m' "$ROOT" 2>/dev/null | tr -dc '0-9')" ] &&     [ -z "$(stat -f '%m' "$ROOT" 2>/dev/null | tr -d '0-9\n')" ]; then  STAT_MTIME=(stat -f '%m')else  echo "[sweep-cargo-targets] neither 'stat -c %Y' nor 'stat -f %m' reads an mtime here." >&2  echo "[sweep-cargo-targets] refusing to sweep: the cap orders directories by mtime, and an" >&2  echo "[sweep-cargo-targets] order this script cannot read is an order that deletes the wrong one." >&2  exit 1fi# Ours only if it resolves inside the root, and is not the root.owns_path() {  local p="$1" real parent  if [ -d "$p" ] && [ ! -L "$p" ]; then    real="$(cd "$p" 2>/dev/null && pwd -P)" || return 1  else    # A symlink, or a plain file (a `.lock`): resolve the PARENT and keep the    # basename, so a symlink is judged by where it lives, never by where it    # points — and then the caller refuses to follow it.    parent="$(cd "$(dirname "$p")" 2>/dev/null && pwd -P)" || return 1    real="$parent/$(basename "$p")"  fi  case "$real" in    "$ROOT_REAL"/?*) return 0 ;;    *) return 1 ;;  esac}# The newest mtime in the top two levels — the same reading of "used" as above,# as a number, so the cap can order the survivors.newest_mtime() {  local dir="$1" newest  # `|| true` for the same reason as the `du` in the budget loop: $dir can be  # removed by a sibling job while this runs, `find` exits non-zero, and  # `pipefail` + `set -e` would kill the script with the stderr already  # suppressed. The empty answer falls into the case below, which is the  # behaviour that was always intended.  newest="$(find "$dir" -maxdepth 2 -exec "${STAT_MTIME[@]}" {} + 2>/dev/null | sort -n | tail -1 || true)"  case "$newest" in    # Only an unreadable directory reaches this, and the cap must not silently    # call it "oldest": say so, and let the caller keep it.    ''|*[!0-9]*)      echo "[sweep-cargo-targets] could not read an mtime under '$dir' — treating it as in use" >&2      echo 9999999999      ;;    *) echo "$newest" ;;  esac}keeping() {  local name="$1" k  for k in ${KEEP[@]+"${KEEP[@]}"}; do    [ "$name" = "$k" ] && return 0  done  return 1}# Is a job inside this target right now? The lane's `with-cargo-lock.sh` holds# `<dir>.lock` for its whole cargo step — `flock` where there is one, and on a# Mac the directory `<dir>.lock.d` with the holder's pid inside. Both are asked# NON-BLOCKING and never taken: this only reads whether somebody else has it.# An ownerless Mac lock (killed between the mkdir and the pid write) counts as# held — `with-cargo-lock.sh` ages that one out on its own clock, and a cache is# never worth racing it for. A dead holder's lock is not a hold: the kernel# dropped a flock with its process, and a pid nothing answers to is a job that# is gone.held_by_a_job() {  local dir="$1" lock="$1.lock" holder  if [ -f "$lock" ] && command -v flock >/dev/null 2>&1; then    if ! flock -n "$lock" true 2>/dev/null; then return 0; fi  fi  if [ -d "$lock.d" ]; then    holder="$(cat "$lock.d/pid" 2>/dev/null || true)"    case "$holder" in      ''|*[!0-9]*) return 0 ;;      *) if kill -0 "$holder" 2>/dev/null; then return 0; fi ;;    esac  fi  return 1}# The same question as `held_by_a_job`, minus its caution about an ownerless# Mac lock: is a process that is alive holding `<dir>.lock` right now?lock_has_live_holder() {  local lock="$1.lock" holder  if [ -f "$lock" ] && command -v flock >/dev/null 2>&1; then    if ! flock -n "$lock" true 2>/dev/null; then return 0; fi  fi  if [ -d "$lock.d" ]; then    holder="$(cat "$lock.d/pid" 2>/dev/null || true)"    case "$holder" in      ''|*[!0-9]*) ;;      *) if kill -0 "$holder" 2>/dev/null; then return 0; fi ;;    esac  fi  return 1}# Take `<dir>.lock` the way `with-cargo-lock.sh` on THIS machine would —# `flock` where there is one, else `mkdir <dir>.lock.d` with this pid inside —# and NEVER wait for it. Fails when anybody else has it. fd 8, because the# legacy reclaim above uses 9 and this script runs under the Macs' bash 3.2,# which has no `{fd}` allocation.take_target_lock() {  local lock="$1.lock"  if command -v flock >/dev/null 2>&1; then    exec 8>>"$lock" || return 1    if ! flock -n 8; then      exec 8>&-      return 1    fi    return 0  fi  if ! mkdir "$lock.d" 2>/dev/null; then    # A dead holder's lock is reclaimed, once, exactly as `with-cargo-lock.sh`    # reclaims it; an ownerless one or a live one is somebody else's.    local holder    holder="$(cat "$lock.d/pid" 2>/dev/null || true)"    case "$holder" in ''|*[!0-9]*) return 1 ;; esac    kill -0 "$holder" 2>/dev/null && return 1    rm -rf "$lock.d"    mkdir "$lock.d" 2>/dev/null || return 1  fi  echo "$$" > "$lock.d/pid"  return 0}drop_target_lock() {  local lock="$1.lock"  if command -v flock >/dev/null 2>&1; then    exec 8>&-  else    rm -rf "$lock.d"  fi}reclaim() {  local path="$1" why="$2"  [ "$(basename "$path")" != shared ] || return 1  evidence_kept "$path" && return 1  if ! owns_path "$path"; then    echo "[sweep-cargo-targets] refusing to remove '$path' — it does not resolve inside $ROOT_REAL" >&2    return 1  fi  if [ -L "$path" ]; then    echo "[sweep-cargo-targets] refusing to remove '$path' — it is a symlink, and what it points at is not ours" >&2    return 1  fi  if [ "$DRY_RUN" = 1 ]; then    log "would remove $path — $why"    return 0  fi  case "$path" in    # A lock itself (the orphan pass below) is removed as it stands.    *.lock|*.lock.d) ;;    *)      # A TARGET IS REMOVED UNDER ITS OWN LOCK. `held_by_a_job` above asked      # the lock and was told "free" — but a job can take it between that      # answer and the `rm -rf`, start building, and lose its target anyway.      # So the lock is TAKEN, non-blocking, for the length of the removal: a      # job that asks for it now waits in `with-cargo-lock.sh` until the      # directory is gone, and then builds into a fresh one.      if ! take_target_lock "$path"; then        log "keeping $(basename "$path") — a job took $(basename "$path").lock as this sweep reached it"        return 0      fi      rm -rf "$path"      drop_target_lock "$path"      log "removed $path — $why"      return 0      ;;  esac  rm -rf "$path"  log "removed $path — $why"}# The live branches, as the DIRECTORY NAMES they would own, so the comparison is# against exactly what `cargo-target-dir.sh` writes rather than against a raw# ref. Empty output is treated conservatively as a failure: a live repo has `main`,# so an empty answer cannot prove a branch dead.LIVE=""HAVE_LIVE=0if [ "$REMOTE" = 1 ]; then  if [ ! -r "$NAME_FOR" ]; then    log "cannot read $NAME_FOR — the dead-branch rule is off for this run"  else    # Ask the live host first, then prove absence on every other remote. A    # stale mirror cannot declare a live branch dead; a failed remote cannot    # prove absence either. A host.json naming a host this tooling has no    # backend for resolves no live remote.    source "$HERE/../lib/host-remote.sh"    repo_root="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"    host="$(host_config_host "$repo_root")"    case "$host" in      forgejo|'') live_remote=origin ;;      *) live_remote="" ;;    esac    remotes="$(git remote 2>/dev/null || true)"    ordered=""    if [ -n "$live_remote" ] && printf '%s\n' "$remotes" | grep -qxF "$live_remote"; then      ordered="$live_remote"      log "live remote is $live_remote — host ${host:-forgejo}"    else      log "no live remote resolved — a branch is dead only if it is on no remote"    fi    while IFS= read -r remote; do      [ -n "$remote" ] || continue      printf '%s\n' "$ordered" | grep -qxF "$remote" && continue      ordered="${ordered}${ordered:+}$remote"    done <<REMOTES$remotesREMOTES    complete=1    [ -n "$ordered" ] || complete=0    while IFS= read -r remote; do      [ -n "$remote" ] || continue      if refs="$(GIT_TERMINAL_PROMPT=0 git ls-remote --heads "$remote" 2>/dev/null)" && [ -n "$refs" ]; then        while IFS= read -r line; do          branch="${line#*refs/heads/}"          [ -n "$branch" ] || continue          [ "$branch" = "$line" ] && continue          LIVE="$LIVE$(basename "$(bash "$NAME_FOR" --per-ref "$branch" "$ROOT")")"        done <<REFS$refsREFS        log "$remote has $(printf '%s\n' "$refs" | grep -c 'refs/heads/' || true) branches"      else        complete=0        log "could not list $remote's branches — the dead-branch rule is off for this run"      fi    done <<ORDERED$orderedORDERED    if [ "$complete" = 1 ]; then      HAVE_LIVE=1      log "listed every remote — a target with no branch on any remote is dead"    else      log "could not prove absence on every remote — the dead-branch rule is off for this run"    fi  fifiis_live() {  local name="$1" l  while IFS= read -r l; do    [ "$name" = "$l" ] && return 0  done <<LIVE_LIST$LIVELIVE_LIST  return 1}status="$sibling_status"swept=0survivors=""for dir in "$ROOT"/*; do  [ -e "$dir" ] || continue  [ -d "$dir" ] || continue  name="$(basename "$dir")"  # `with-cargo-lock.sh` on a machine with no `flock(1)` (the build Mac) holds  # its lock as a DIRECTORY, `<name>.lock.d`. That is a lock, not a target.  case "$name" in *.lock.d) continue ;; esac  if keeping "$name"; then    log "keeping $name — this run is building into it"    continue  fi  if [ -L "$dir" ]; then    echo "[sweep-cargo-targets] refusing to remove '$dir' — it is a symlink, and what it points at is not ours" >&2    status=1    continue  fi  if evidence_kept "$dir"; then continue; fi  # BEFORE ANY RULE. A held target is not a candidate for the dead-branch, age,  # cap or budget rule — it is not even a survivor the cap orders — because  # whatever its mtime says, a job is in it.  if held_by_a_job "$dir"; then    log "keeping $name — a job holds $name.lock; its cargo step is running, whatever the mtime says"    continue  fi  if [ "$HAVE_LIVE" = 1 ] && ! is_live "$name" && ! used_within_mins "$dir" "$GRACE_MINS"; then    if reclaim "$dir" "its branch is gone from every remote"; then      swept=$(( swept + 1 ))    else      status=1    fi    continue  fi  if ! used_within_mins "$dir" $(( DAYS * 24 * 60 )); then    if reclaim "$dir" "nothing touched it for over ${DAYS} days"; then      swept=$(( swept + 1 ))    else      status=1    fi    continue  fi  survivors="$survivors$(newest_mtime "$dir") $dir"done# THE CAP. Whatever survived the two rules above, ordered newest first; anything# past `--max` goes. This is the rule that bounds the disk rather than hoping# branches are abandoned politely.if [ "$MAX" != 0 ] && [ -n "$survivors" ]; then  while IFS= read -r line; do    [ -n "$line" ] || continue    dir="${line#* }"    # Never a directory a build may be writing right now — see the CAP note at    # the top. The disk guard is what answers a host that fills anyway.    if used_within_mins "$dir" "$GRACE_MINS"; then      log "keeping $(basename "$dir") — written in the last ${GRACE_MINS} minutes, a job may be building in it"      continue    fi    if reclaim "$dir" "beyond the ${MAX} most recently built branch targets"; then      swept=$(( swept + 1 ))    else      status=1    fi  done <<CAPPED$(printf '%s' "$survivors" | sort -rn | tail -n +$(( MAX + 1 )))CAPPEDfi# THE BUDGET — THE ONLY RULE STATED IN THE UNIT THE DISK IS MEASURED IN.## The three rules above are proxies for size: a branch count, an age, a remote# listing. None of them knows how big a target directory actually is, so the set# they leave behind is whatever those proxies happened to allow — and on the CI# host that was 76 GB under `~/.cache/cottondb` while every rule was working as# designed. A cap of three says "three branches"; it cannot say "20 GB".## So: measure the survivors, newest first, and evict from the OLD end until the# set fits. It runs LAST, after the dead-branch, cap and age rules, because it# is the backstop rather than the policy — if those rules already did the job# this loop removes nothing and says so.## WHAT IT WILL NOT EVICT, in the order the checks are made:#   * a `--keep` — this run is building into it. Its bytes still COUNT toward#     the total (a budget that ignored the largest directory on the disk would#     be arithmetic about the wrong thing), so a single directory larger than#     the whole budget leaves the loop with nothing left to evict and a line in#     the log saying exactly that.#   * anything written inside the grace window — the Linux runner's capacity is#     8, so eight jobs can be building at once and only one of them is this#     run's `--keep`. Reclaiming a directory a live job is linking into is the#     corruption this whole page exists to prevent.## OFF BY DEFAULT (0), and that is deliberate: this script runs on the build Macs# too, where ONE branch's target directory is 70-85 GB because it carries two# iOS slices beside the host ones. A number sized for the Linux box would empty# the Mac's cache on every build. The Linux lanes name their own budget# (`--budget-gb`, or COTTON_CARGO_TARGETS_BUDGET_GB); everywhere else the rule# is simply not in play.## `du -sk` per surviving directory, not per file: a handful of directories, one# stat-walk each, and the numbers are in the units the disk guard already# prints. `-k` because `du -h` is unsortable and `du -b` is GNU-only — the build# Macs run BSD `du`, which has neither.if [ -n "$BUDGET_KB" ] || [ "$BUDGET_GB" != 0 ]; then  if [ "$EVERYTHING" = 1 ]; then    budget_kb=0    budget_said="nothing (--everything)"  elif [ -n "$BUDGET_KB" ]; then    budget_kb="$BUDGET_KB"    budget_said="$(( budget_kb / 1024 )) MB"  else    budget_kb=$(( BUDGET_GB * 1024 * 1024 ))    budget_said="${BUDGET_GB} GB"  fi  sized=""  total_kb=0  for dir in "$ROOT"/*; do    [ -d "$dir" ] || continue    case "$(basename "$dir")" in *.lock.d) continue ;; esac    # `|| true` IS LOAD-BEARING, and so is the line it lets us print.    #    # Three other rust jobs sweep this same root, and one of them can remove    # $dir between the `[ -d ]` above and this `du`. `du` then exits non-zero,    # `pipefail` carries that out of the pipeline, `set -e` kills the script —    # and `2>/dev/null` has already eaten the only explanation. That is not a    # theory: lane G's rust job died exactly here at 36s, on adc199f5, with no    # message at all.    #    # A directory that went away is not a failure. It is zero bytes this sweep    # is no longer responsible for. Count it as zero and SAY which one, so the    # next silent death cannot be silent.    kb="$(du -sk "$dir" 2>/dev/null | awk 'NR==1{print $1}' || true)"    case "$kb" in      ''|*[!0-9]*)        log "could not measure $dir — it went away mid-sweep; counting it as 0"        kb=0        ;;    esac    total_kb=$(( total_kb + kb ))    sized="$sized$(newest_mtime "$dir") $kb $dir"  done  if [ "$total_kb" -le "$budget_kb" ]; then    log "the target directories hold $(( total_kb / 1024 )) MB, inside the ${budget_said} budget — nothing evicted for size"  else    log "the target directories hold $(( total_kb / 1024 )) MB against a ${budget_said} budget — evicting oldest-first until they fit"    # Oldest first: sort by mtime ascending, and stop the moment the total fits.    while IFS= read -r line; do      [ -n "$line" ] || continue      [ "$total_kb" -le "$budget_kb" ] && break      rest="${line#* }"      kb="${rest%% *}"      dir="${rest#* }"      name="$(basename "$dir")"      if keeping "$name"; then        log "keeping $name despite the budget — this run is building into it"        continue      fi      if held_by_a_job "$dir"; then        log "keeping $name despite the budget — a job holds $name.lock; its cargo step is running"        continue      fi      if used_within_mins "$dir" "$GRACE_MINS"; then        log "keeping $name despite the budget — written in the last ${GRACE_MINS} minutes, a job may be building in it"        continue      fi      if reclaim "$dir" "the target directories are over the ${budget_said} budget"; then        swept=$(( swept + 1 ))        total_kb=$(( total_kb - kb ))      else        status=1      fi    done <<SIZED$(printf '%s' "$sized" | sort -n)SIZED    if [ "$total_kb" -gt "$budget_kb" ]; then      log "still $(( total_kb / 1024 )) MB after the budget sweep — what is left is being built into right now, or is this run's own --keep"    fi  fifi# A lock whose target directory is gone — reclaimed just now, by an earlier# run, or by a hand. Both shapes: the `flock` file and the Mac's lock directory.for lock in "$ROOT"/*.lock "$ROOT"/*.lock.d; do  [ -e "$lock" ] || continue  owner="${lock%.lock}"  owner="${owner%.lock.d}"  [ -d "$owner" ] && continue  # NOT A LOCK A JOB HOLDS. A job on a new branch takes `<name>.lock` BEFORE  # cargo creates `<name>/`, so "the directory is gone" is also what a job that  # has only just started looks like; removing its lock would let a second job  # in beside it and leave its target with nothing that says a job is inside.  # An ownerless Mac lock made inside the grace window is spared too: that is a  # job between its `mkdir` and its pid write.  # (A LIVE holder here, not `held_by_a_job`'s ownerless-counts-as-held: an  # ownerless Mac lock with no target is exactly the leftover this pass is for,  # and the grace window below is what keeps one a job has only just made.)  if lock_has_live_holder "$owner"; then    log "keeping $(basename "$lock") — its target is gone but a job holds the lock"    continue  fi  case "$lock" in    *.lock.d)      if [ -z "$(cat "$lock/pid" 2>/dev/null || true)" ] && used_within_mins "$lock" "$GRACE_MINS"; then        log "keeping $(basename "$lock") — made in the last ${GRACE_MINS} minutes and not yet owned; a job may be writing its pid"        continue      fi      ;;  esac  reclaim "$lock" "its target directory is gone" || status=1doneif [ "$swept" = 0 ]; then  log "nothing to reclaim under $ROOT_REAL — no dead branch, nothing past the cap of ${MAX}, nothing older than ${DAYS} days"fiexit "$status"