#!/usr/bin/env bash# ONE BUILD SLOT PER CARGO JOB — a fixed path, a bounded target directory, one holder.## scripts/ci/build-slot.sh run [--label NAME] -- <command...># scripts/ci/build-slot.sh list## WHAT A SLOT IS. `<root>/<k>` for k in 1..N: a lease file, a hardlinked COPY of# the job's checkout at `<root>/<k>/src`, and a cargo target directory at# `<root>/<k>/target` that every job leasing slot k builds into, one after# another. Linux trains take the next free slot before pull checks, oldest# train first; a waiting train reserves free capacity until admitted.# `run` leases the first eligible free slot (waiting, bounded, if all N are# taken), copies the checkout it was started in, exports CARGO_TARGET_DIR and# runs the command INSIDE the copy, and releases the slot when the command ends —# however it ends.## WHY NOT A TARGET DIRECTORY PER BRANCH ANY MORE (the shape from #406 to# 2026-09-27). It ended four classes of cross-PR corruption and it bought them# with disk nobody bounded by rule: 17 GB per branch on the Linux host, 70-85 GB# on a Mac, one per head ref, swept by four rules and a budget (`sweep-cargo-# targets.sh`) that the host still filled past twice. And it left sccache half# blind: sccache hashes the compile's WORKING DIRECTORY, and cargo runs rustc# from each package's own root — a throwaway `work/<random>/hostexecutor/...`# path on every run — so the ~500 crates.io dependencies hit and not one of# Cotton's own crates ever could (`sccache-shim.sh`, "WHAT IT DOES NOT FIX").## A SLOT ANSWERS BOTH. The disk is N target directories, each wiped when it# passes its budget (sccache re-links what it held), and N is a number a person# reads off the box: three on a 16-core host. The path is FIXED per slot, so a# workspace crate compiled in slot 2 today hits in slot 2 tomorrow if its# source and its dependencies' contents are the same — which is the case the# per-branch shape could never serve.## AND IT KEEPS THE PROPERTY THE PER-BRANCH DIRECTORY EXISTED FOR. The corruption# (PR #404, runs 1908/1911) needed ANOTHER job writing the same target directory# BETWEEN this job's steps: cargo fingerprints path dependencies relative to the# workspace root and judges freshness by mtime, so a neighbour's cotton-core# landed at our paths under a fingerprint that still matched. A lease is held for# the WHOLE of a job's cargo work — every phase, in one `run` — so no second job# writes the slot while this one is in it.## SEQUENTIAL REUSE MUST NOT TRUST CHECKOUT MTIMES. A job checked out at t0# can wait while a different branch builds at t1, then mistake that branch's# newer artifacts for its own. Changed bytes therefore get the next whole# second after lease. For the SAME immutable CI commit, a completed lease's# source stamp can be reused only when all copied bytes, modes and symlinks# match and the previous command left every source unchanged. The cache record# is removed before the command, so an interrupted or source-mutating lease# cannot leave it valid. The real Cargo regression proves both a warm hit and# correct execution after a backdated edit (19 Oct 2026, fifteen-minute jobs).## HOW THE LEASE IS HELD. `flock` on Linux: the kernel drops it when the holder# dies, SIGKILL included, so a cancelled job can never wedge a slot. macOS has no# `flock(1)`, so there it is the mkdir + live-pid shape `with-cargo-lock.sh` and# `with-build-lock.sh` use: a dead holder's slot is reclaimed by the next comer.# The lease descriptor is CLOSED for the command (`9>&-`): a daemon the command# starts — sccache's server — must not inherit it, or the slot is held for ever# (run 2413 did exactly this to the per-branch cargo lock).## THE COPY. `cp -al` — hard links, so a 1 GB checkout with node_modules costs# seconds and no disk; `cp -a` when the slot and the checkout are on different# filesystems. Cargo and Gradle only read sources and write new files, so a# shared inode is never rewritten under the original; and the original is the# runner's throwaway checkout, deleted when the job ends, so what remains is the# slot's copy — which is removed at release, because a stale copy is disk with# no reader. The target directory stays; it is the point.## WHAT THE COMMAND SEES.# cwd the copy's root (the same relative layout as the checkout)# CARGO_TARGET_DIR <root>/<k>/target — with `CACHEDIR.TAG`, so `cargo clean` accepts it# COTTON_CARGO_LOCK_HELD the lease file — `cargo-test-with-one-retry.sh` refuses to# `cargo clean` without it, and here it is held for the whole run# COTTON_BUILD_SLOT <root>/<k># CARGO_BUILD_JOBS, NEXTEST_TEST_THREADS, RUST_TEST_THREADS# when other slots are busy, each capped at this# slot's SHARE of the host (below); alone, as asked# COTTON_BUILD_SLOT_THREADS the share itself, for a tool the three names do# not reach (`android-check.sh` passes it to Gradle);# unset when the slot runs alone## THE SHARE — WHY A SLOT CAPS THE THREADS, AND WHY HERE. Measured 28 Sep 2026# 11:50Z on the Linux host: load 31 on 16 threads, 863% of it the runner's own# check jobs. Every cargo job sized ITSELF — `rust-job-sizing.sh` reads the load# once, at its start, so a job that starts on a quiet host takes 12 build jobs# and 16 test threads and keeps them when three more arrive; `android` asked# for 6; nothing added them up. The one place that knows how many cargo jobs# are running is this script: it holds their leases. So at lease time it# counts the slots BUSY (its own included) and:## busy = 1 (alone) no cap — the job keeps what it asked for, which on the# Linux host is `rust-job-sizing.sh`'s measured range# (8-16 test threads, 3-12 build jobs)# busy = B > 1 share = cores / (B + 1)# 16 / (2 + 1) = 5, 16 / (3 + 1) = 4 on the Linux host## and CARGO_BUILD_JOBS / NEXTEST_TEST_THREADS / RUST_TEST_THREADS are each the# SMALLER of the share and whatever the job already asked for — so the Mac's# memory sizing (2-4 jobs on a 16 GB Mac) is never RAISED, only a CPU-blind# number is lowered. The `+ 1` is the share of everything that runs outside a# slot: the `checks` job's vitest workers, the other runner lane, the forge,# Bugsink, the relay and the agent sessions on the box. Three busy slots at# four threads each and one share for the rest is sixteen.## WHY NOT A FIXED cores / (N + 1). It was, and review refused it (29 Sep# 2026): 4 threads for a job running ALONE is half the bottom of the measured# 8-16 range, so the lone job — the common case outside the busy hours — took# about twice as long for nothing. Counting the busy slots keeps the busy# hours' sum at about the cores and gives a lone job the idle machine.## THE ONE CASE THIS READS WRONG. The count is taken once, at lease time, and# nextest cannot give threads back mid-run: a job that started alone keeps its# full width when two more arrive, and those two are cut by the count they see# (three busy: 4 each). That is at most one job's worth of oversubscription,# for as long as the lone job runs. A workflow cannot forget the cap: it is# exported where the slot is taken, and a job that takes no slot builds# nothing in Rust.## Env knobs (each for a test and for a hand run; a lane sets none of them):# COTTON_BUILD_SLOTS_ROOT default $HOME/.cache/cottondb/rust/slots# COTTON_BUILD_SLOTS N (default 3 on Linux, 1 on macOS)# COTTON_BUILD_SLOT_BUDGET_GB a slot's target is wiped at lease when it exceeds this (default 40)# COTTON_BUILD_SLOT_SWEEP_BELOW_GB under this much free disk, a lease empties every OTHER slot's# target no job holds (default 80; 0 turns it off)# COTTON_CI_MIN_FREE_GB and if the disk is still under this floor after that, it empties its own# slot's target too — the floor `require-free-disk.sh` refuses a build under (default 60)# COTTON_BUILD_SLOT_WAIT_S max seconds to wait for a free slot (default 2700, or 5400 for merge_group; exit 75 after)# COTTON_BUILD_SLOT_POLL_S seconds between attempts (default 5)# COTTON_BUILD_SLOT_STALE_S macOS only: reclaim an OWNERLESS lease after this (default 300)# COTTON_BUILD_SLOT_OS override `uname -s`# COTTON_BUILD_SLOT_CORES override the core count the share is cut from## Guard: `scripts/__tests__/build-slot.test.ts`.set -uo pipefailusage() { echo "usage: build-slot.sh run [--label NAME] -- <command...> | list" >&2exit2}os="${COTTON_BUILD_SLOT_OS:-$(uname -s)}"ROOT="${COTTON_BUILD_SLOTS_ROOT:-$HOME/.cache/cottondb/rust/slots}"if [ -n "${COTTON_BUILD_SLOTS:-}" ]; then N="$COTTON_BUILD_SLOTS"elif [ "$os" = Darwin ]; then N=1else N=3fiBUDGET_GB="${COTTON_BUILD_SLOT_BUDGET_GB:-40}"EVENT="${GITHUB_EVENT_NAME:-${FORGEJO_EVENT_NAME:-${EVENT:-unknown}}}"DEFAULT_WAIT_S=2700[ "$EVENT" = merge_group ] && DEFAULT_WAIT_S=5400WAIT_S="${COTTON_BUILD_SLOT_WAIT_S:-$DEFAULT_WAIT_S}"POLL_S="${COTTON_BUILD_SLOT_POLL_S:-5}"STALE_S="${COTTON_BUILD_SLOT_STALE_S:-300}"SWEEP_BELOW_GB="${COTTON_BUILD_SLOT_SWEEP_BELOW_GB:-80}"FLOOR_GB="${COTTON_CI_MIN_FREE_GB:-60}"if [ "$(uname -s)" = Darwin ] && [ "${1:-}" = run ]; then bash "$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/mac-build-policy.sh" --path "$ROOT" --check || exit $? FLOOR_GB="$(bash "$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/mac-build-policy.sh" --path "$ROOT" --floor-gb)" || exit $?fifor pair in"COTTON_BUILD_SLOTS:$N""COTTON_BUILD_SLOT_BUDGET_GB:$BUDGET_GB""COTTON_BUILD_SLOT_WAIT_S:$WAIT_S""COTTON_BUILD_SLOT_POLL_S:$POLL_S""COTTON_BUILD_SLOT_SWEEP_BELOW_GB:$SWEEP_BELOW_GB""COTTON_CI_MIN_FREE_GB:$FLOOR_GB"; docase"${pair#*:}"in''|*[!0-9]*) echo "build-slot: ${pair%%:*} wants a whole number, got '${pair#*:}'" >&2; exit2 ;;esacdone[ "$N" -ge 1 ] || { echo "build-slot: COTTON_BUILD_SLOTS must be at least 1" >&2; exit2; }log() { echo "[build-slot] $(date +%H:%M:%S) $*" >&2; }verb="${1-}"shift || usageif [ "$verb" = list ]; then [ $# -eq 0 ] || usageif [ ! -d "$ROOT" ]; then echo "no slots under $ROOT yet"exit0fi k=1while [ "$k" -le "$N" ]; do dir="$ROOT/$k" state=freeif [ -d "$dir" ]; thenif command -v flock >/dev/null 2>&1 && [ -f "$dir/.lease" ]; then flock -n "$dir/.lease" true 2>/dev/null || state=leasedelif [ -d "$dir/.lease.d" ]; then state="leased by pid $(cat "$dir/.lease.d/pid" 2>/dev/null || echo '?')"fi size="$(du -sk "$dir/target" 2>/dev/null | cut -f1 || true)" size="$(( ${size:-0} / 1024 )) MB"else size="empty"fi echo "slot $k: $state — target $size" k=$(( k + 1 ))doneexit0fi[ "$verb" = run ] || usageLABEL=""while [ $# -gt 0 ]; docase"$1"in --label) LABEL="${2-}"; shift2 ;; --) shift; break ;; *) usage ;;esacdone[ $# -ge 1 ] || { echo "build-slot: no command after --" >&2; usage; }LABEL="${LABEL:-$(whoami)-$$}"SRC_ORIGIN="$(pwd -P)"mkdir -p "$ROOT" || { log "cannot create $ROOT"; exit1; }ROOT_REAL="$(cd "$ROOT" && pwd -P)"case"$ROOT_REAL/"in"$SRC_ORIGIN"/*) log "refusing: the slots root $ROOT_REAL is inside the checkout $SRC_ORIGIN, and the copy would contain itself"exit2 ;;esac# ── THE LEASE ────────────────────────────────────────────────────────────────SLOT=""deadline=$(( $(date +%s) + WAIT_S ))announced=0if [ "$os" != Darwin ] && command -v flock >/dev/null 2>&1; then# Admission and registration share a short mutex: no pull can observe an# empty queue while a train registers, or race its next free slot. Sequence# numbers order even trains arriving within the same second. A waiter holds# fd 7; SIGKILL drops it, so the next admission prunes cancelled waiters. mkdir -p "$ROOT/.waiters" || exit1 exec 8>"$ROOT/.admission" || exit1 flock 8 || exit1 sequence="$(cat "$ROOT/.waiter-sequence" 2>/dev/null || echo 0)" sequence=$(( sequence + 1 )) echo "$sequence" > "$ROOT/.waiter-sequence" WAITER="$ROOT/.waiters/$(printf '%012d' "$sequence").waiter" exec 7>"$WAITER" || exit1 flock 7 || exit1 printf '%s\n%s\n%s\n'"$EVENT""$LABEL""$(date +%s)" >&7trap'rm -f "$WAITER"' EXITtrap'exit 130' INTtrap'exit 143' TERM flock -u 8 next_report=0while :; do flock 8 || exit1 first_train=""for waiter in"$ROOT/.waiters/"*.waiter; do [ -f "$waiter" ] || continueif [ "$waiter" != "$WAITER" ] && flock -n "$waiter" true; then rm -f "$waiter" continuefiif [ "$(head -1 "$waiter")" = merge_group ] && [ -z "$first_train" ]; then first_train="$waiter"fidone# A train gets the NEXT free slot, even if its poll is slower than a# pull's. This also reserves the last free slot while a train waits.if [ -z "$first_train" ] || [ "$first_train" = "$WAITER" ]; then k=1while [ "$k" -le "$N" ]; do mkdir -p "$ROOT/$k" exec 9>"$ROOT/$k/.lease" || exit1if flock -n 9; then SLOT="$ROOT/$k" printf '%s\n%s\n%s\n'"$LABEL""$EVENT""$(date +%s)" > "$SLOT/.holder" rm -f "$WAITER" breakfi exec 9>&- k=$(( k + 1 ))donefi flock -u 8 [ -n "$SLOT" ] && break now=$(date +%s)if [ "$now" -ge "$deadline" ]; then log "TIMEOUT after ${WAIT_S}s — no eligible slot under $ROOT ($N slots; event $EVENT)"exit75fiif [ "$announced" -eq 0 ]; thenif [ -n "$first_train" ] && [ "$first_train" != "$WAITER" ]; then log "'$LABEL' ($EVENT) is waiting for the oldest train to take its reserved slot (up to ${WAIT_S}s)"else log "all $N slots are leased — '$LABEL' is waiting for one (up to ${WAIT_S}s; event $EVENT)"fi announced=1fiif [ "$EVENT" = merge_group ] && [ "$now" -ge "$next_report" ]; then holders="" k=1while [ "$k" -le "$N" ]; do dir="$ROOT/$k"if [ -f "$dir/.lease" ] && ! flock -n "$dir/.lease" true; then job=unknown; event=unknown; since="$now"if [ -f "$dir/.holder" ]; then { IFS= read -r job; IFS= read -r event; IFS= read -r since; } < "$dir/.holder"ficase"$since"in''|*[!0-9]*) since="$now" ;; esac holders="$holders${holders:+; }slot $k is held by '$job' ($event) for $(( now - since ))s"else holders="$holders${holders:+; }slot $k is free and reserved for the oldest waiting train"fi k=$(( k + 1 ))done log "'$LABEL' ($EVENT) has waited $(( now - (deadline - WAIT_S) ))s: $holders." next_report=$(( now + 300 ))fi sleep "$POLL_S"7>&- 8>&-done exec 7>&- 8>&- log "leased $SLOT of $N for '$LABEL' (flock)"else# macOS: `mkdir` is the atomic acquire; the pid inside says whether a lease a# killed job left behind is still owned by anything.while :; do k=1while [ "$k" -le "$N" ]; do mkdir -p "$ROOT/$k" lease_dir="$ROOT/$k/.lease.d"if mkdir "$lease_dir"2>/dev/null; then echo "$$" > "$lease_dir/pid" SLOT="$ROOT/$k" breakfi holder=""if [ -f "$lease_dir/pid" ]; then holder="$(cat "$lease_dir/pid" 2>/dev/null || true)"; fiif [ -n "$holder" ] && ! kill -0"$holder"2>/dev/null; then log "holder pid $holder of $lease_dir is dead — reclaiming" rm -rf "$lease_dir" continuefiif [ -z "$holder" ]; then created="$(stat -f %m "$lease_dir" 2>/dev/null || stat -c %Y "$lease_dir" 2>/dev/null || date +%s)"if [ $(( $(date +%s) - created )) -ge "$STALE_S" ]; then log "ownerless lease at $lease_dir is older than ${STALE_S}s — reclaiming" rm -rf "$lease_dir" continuefifi k=$(( k + 1 ))done [ -n "$SLOT" ] && breakif [ "$(date +%s)" -ge "$deadline" ]; then log "TIMEOUT after ${WAIT_S}s — all $N slots under $ROOT are leased"exit75fiif [ "$announced" -eq 0 ]; then log "all $N slots are leased — '$LABEL' is waiting for one (up to ${WAIT_S}s)" announced=1fi sleep "$POLL_S"donetrap'rm -rf "$SLOT/.lease.d"' EXIT INT TERM log "leased $SLOT of $N for '$LABEL' (mkdir)"fi# ── A LOW DISK EMPTIES THE SLOTS NOBODY HOLDS ────────────────────────────────# The budget below bounds ONE slot, and only when that slot is leased again, so# an idle slot keeps its tens of GB for as long as nobody happens to pick it.# On 28 Sep 2026 three slots held 27, 39 and 54 GB while the CI host fell to# 57 GB free, under the 60 GB `require-free-disk.sh` refuses a Rust build at,# and every pull's rust jobs went red on disk. So a lease on a low disk empties# the target of every OTHER slot it can take the lease of without waiting (a# slot a job holds is never touched: `flock -n` fails and it is kept), and if# the disk is still under the build floor after that, its own — this job is# about to rebuild into it anyway, and sccache re-links what it held. Other# slots are swept under flock on Linux; our leased target is swept on both OSes.free_gb() { df -Pk "$ROOT"2>/dev/null | awk 'NR == 2 && $4 ~ /^[0-9]+$/ { print int($4 / 1048576) }'; }free="$(free_gb)"if [ "$os" != Darwin ] && command -v flock >/dev/null 2>&1 && [ "$SWEEP_BELOW_GB" -gt 0 ] \ && [ -n "$free" ] && [ "$free" -lt "$SWEEP_BELOW_GB" ]; then log "${free} GB free on the disk holding $ROOT, under ${SWEEP_BELOW_GB} GB — emptying the targets of slots no job holds" k=1while [ "$k" -le "$N" ]; do other="$ROOT/$k"if [ "$other" != "$SLOT" ] && [ -d "$other/target" ]; thenif ( exec 8>"$other/.lease" && flock -n 8 && rm -rf "$other/target" ); then log " slot $k: idle — target emptied"else log " slot $k: held by a job — kept"fifi k=$(( k + 1 ))done free="$(free_gb)" log "${free:-?} GB free after the idle-slot sweep"fi# This slot is leased on BOTH platforms. macOS uses mkdir rather than flock,# but clearing our own target before invoking the command is just as safe.# Do this before cargo-phases reaches require-free-disk, including on a Mac.if [ "$os" != Darwin ] && [ "$(uname -s)" != Darwin ] && [ "$SWEEP_BELOW_GB" -gt 0 ] && [ -n "$free" ] && [ "$free" -lt "$FLOOR_GB" ] && [ -d "$SLOT/target" ]; then log "still ${free} GB free, under the ${FLOOR_GB} GB build floor — emptying this slot's own target as well" rm -rf "$SLOT/target" free="$(free_gb)" log "${free:-?} GB free after the sweep"fi# ── THE TARGET DIRECTORY, BOUNDED ────────────────────────────────────────────TARGET="$SLOT/target"if [ "$os" != Darwin ] && [ "$(uname -s)" != Darwin ] && [ -d "$TARGET" ]; then kb="$(du -sk "$TARGET" 2>/dev/null | cut -f1 || true)"case"$kb"in''|*[!0-9]*) kb=0 ;; esacif [ "$(( kb / 1024 / 1024 ))" -ge "$BUDGET_GB" ]; then log "$TARGET holds $(( kb / 1024 )) MB, past the ${BUDGET_GB} GB budget — wiping it; sccache re-links what it held" rm -rf "$TARGET"else log "$TARGET holds $(( kb / 1024 )) MB (budget ${BUDGET_GB} GB)"fifimkdir -p "$TARGET"if [ ! -f "$TARGET/CACHEDIR.TAG" ]; then cat > "$TARGET/CACHEDIR.TAG" <<'TAG'Signature: 8a477f597d28d172789f06886806bc55# This file is a cache directory tag created by CottonDB's CI lane.# For information about cache directory tags see https://bford.info/cachedir/# It is written by scripts/ci/build-slot.sh so that `cargo clean --target-dir`# will accept this directory, and so that backup tools skip it.TAGfi# ── THE COPY ─────────────────────────────────────────────────────────────────SRC="$SLOT/src"rm -rf "$SRC"if ! cp -al "$SRC_ORIGIN""$SRC"2>/dev/null; then rm -rf "$SRC" log "hard links refused between $SRC_ORIGIN and $SLOT (different filesystems?) — copying" cp -a "$SRC_ORIGIN""$SRC" || { log "could not copy the checkout into $SRC"; exit1; }else# pnpm shares dependency inodes across CI checkouts, including nested# workspace node_modules. Isolate every real dependency directory before# stamping, while retaining the full immutable-source fingerprint.while IFS= read -r -d '' dependency_copy; do dependency_relative="${dependency_copy#"$SRC/"}" rm -rf "$dependency_copy" cp -a "$SRC_ORIGIN/$dependency_relative""$dependency_copy" || { log "could not isolate this slot's dependency inodes" rm -rf "$SRC"exit1 }done < <(find "$SRC" -type d -name node_modules -prune -print0)fi# ONE MTIME FOR EVERY FILE — THE LEASE TIME — see "SEQUENTIAL REUSE" above. Hard# links share an inode, so this also stamps the runner's throwaway checkout;# that tree is deleted when the job ends and nothing reads its times. `touch -h`# so a symlink is stamped rather than followed.## THE STAMP IS THE NEXT WHOLE SECOND, IN UTC, AND THE COMMAND WAITS FOR IT.# `touch -t` takes whole seconds, while cargo compares mtimes to the nanosecond.# If the stamp were the CURRENT second truncated, a previous holder's artifact# written at 12:00:05.7 would outrank sources stamped 12:00:05.0 by a job that# leased at 12:00:05.9, and cargo would call them fresh. The next whole second# is strictly later than anything written before now. The one-second sleep# makes sure this job's own outputs are not older than its sources. UTC on both# sides, because a local wall-clock time is ambiguous in the hour that DST# repeats, and `touch` may pick the earlier instant.lease_epoch=$(( $(date -u +%s) + 1 ))# Six concurrent jobs otherwise rebuild the same checkout for every partition.# Reuse a completed lease's stamp only for the same CI sha AND identical bytes.# The record is removed before running; interruption or source mutation makes# the next lease cold. Changed/backdated bytes still get the next whole second.stamp_helper="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/build-slot-source-stamp.py"stamp_state="$SLOT/.source-stamp.json"stamp_choice="$(python3 "$stamp_helper" prepare "$SRC" "$stamp_state" "$lease_epoch")" || exit $?read -r lease_epoch reused_stamp <<< "$stamp_choice"LEASE_STAMP="$(date -u -d "@$lease_epoch" +%Y%m%d%H%M.%S 2>/dev/null || date -u -r "$lease_epoch" +%Y%m%d%H%M.%S)"find "$SRC" -exec env TZ=UTC0 touch -h -c -m -t "$LEASE_STAMP" {} + 2>/dev/null || { log "could not re-stamp every file under $SRC — refusing to build on a copy whose times cargo could misread" rm -rf "$SRC"exit1}if [ "$reused_stamp" = 1 ]; then log "checkout copied to $SRC; unchanged checkout bytes on the same CI commit retain source stamp $LEASE_STAMP"else sleep 1 log "checkout copied to $SRC (the fixed path sccache keys this slot's crates on); every file stamped $LEASE_STAMP, later than anything the slot's target holds"fi# ── THE SHARE ────────────────────────────────────────────────────────────────# Busy = the slots whose lease is held right now, this one included.slot_busy() {local dir="$ROOT/$1" holder [ "$dir" = "$SLOT" ] && return0if [ "$os" != Darwin ] && command -v flock >/dev/null 2>&1; then [ -f "$dir/.lease" ] || return1 ( exec 8<"$dir/.lease" && flock -n 8 ) 2>/dev/null && return1return0fi [ -d "$dir/.lease.d" ] || return1 holder="$(cat "$dir/.lease.d/pid" 2>/dev/null || true)"# An ownerless lease is someone between mkdir and writing their pid. [ -z "$holder" ] && return0 kill -0"$holder"2>/dev/null}BUSY=0k=1while [ "$k" -le "$N" ]; doif slot_busy "$k"; then BUSY=$(( BUSY + 1 )); fi k=$(( k + 1 ))doneasked="jobs=${CARGO_BUILD_JOBS:-unset} nextest=${NEXTEST_TEST_THREADS:-unset} test=${RUST_TEST_THREADS:-unset}"if [ "$BUSY" -le 1 ]; thenunset COTTON_BUILD_SLOT_THREADS log "share: alone ($BUSY of $N slots busy) — running as asked, $asked"else cores="${COTTON_BUILD_SLOT_CORES:-}"case"$cores"in''|*[!0-9]*) cores="$( { nproc 2>/dev/null || sysctl -n hw.logicalcpu 2>/dev/null; } | head -1)" ;;esaccase"$cores"in''|*[!0-9]*|0) cores=4; log "cannot read the core count — cutting the share from 4" ;;esac SHARE=$(( cores / (BUSY + 1) )) [ "$SHARE" -ge 1 ] || SHARE=1# The smaller of the share and what the job already asked for; an unset or# non-numeric ask is the share. capped() {case"${1-}"in''|*[!0-9]*|0) echo "$SHARE" ;; *) if [ "$1" -lt "$SHARE" ]; then echo "$1"; else echo "$SHARE"; fi ;;esac }export CARGO_BUILD_JOBS="$(capped "${CARGO_BUILD_JOBS-}")"export NEXTEST_TEST_THREADS="$(capped "${NEXTEST_TEST_THREADS-}")"export RUST_TEST_THREADS="$(capped "${RUST_TEST_THREADS-}")"export COTTON_BUILD_SLOT_THREADS="$SHARE" log "share: $cores cores / ($BUSY of $N slots busy + 1) = $SHARE — asked $asked; running with jobs=$CARGO_BUILD_JOBS nextest=$NEXTEST_TEST_THREADS test=$RUST_TEST_THREADS"fi# ── THE COMMAND ──────────────────────────────────────────────────────────────export CARGO_TARGET_DIR="$TARGET"export COTTON_CARGO_LOCK_HELD="$SLOT/.lease"export COTTON_BUILD_SLOT="$SLOT"cd "$SRC" || { log "cannot enter $SRC"; exit1; }started=$(date +%s)# `9>&-` is load-bearing on the flock path: a daemon the command starts must# not inherit the lease descriptor. On the mkdir path fd 9 was never opened."$@"7>&- 8>&- 9>&-status=$?python3 "$stamp_helper" finish "$SRC""$stamp_state""$status" || truecd / || truerm -rf "$SRC"log "released $SLOT for '$LABEL' (exit $status, $(( ($(date +%s) - started) / 60 ))m$(( ($(date +%s) - started) % 60 ))s)"exit"$status"