#!/usr/bin/env bash # ONE cargo at a time against the machine's SHARED cargo target directory. # # scripts/ci/with-cargo-lock.sh # # The directory survives each checkout. The lock covers preparation, build, # tests and teardown; cargo-target-guard.sh refreshes workspace mtimes on a # tree switch while registry dependencies stay warm. No lane wipes shared. # # WHAT THIS ADDS OVER CARGO'S OWN LOCK. Cargo already takes an advisory lock on # the build directory ("Blocking waiting for file lock on build directory"), so # two LIVE cargos do not interleave. It takes that lock per invocation, though, # and it is gone the instant a cancelled job's cargo is killed. This lock is # held across a job's whole cargo section — the builds, the tests, clippy, the # conformance build, and the retry wrapper's `cargo clean` — so a job that is # being torn down cannot hand a half-written target directory to a job that has # already started building into it. It is the belt; the braces is # `cargo-test-with-one-retry.sh`, which recovers when a stale artifact survives # anyway. # # WHERE THE LOCK LIVES. Beside the cache it protects, under HOME, so it is # per-MACHINE by construction: the Linux `rust` job and the Mac `swift` job take # different files on different boxes and never wait on each other. Override with # COTTON_CARGO_LOCK when the cache is elsewhere. # # HOW IT IS HELD. `flock` on Linux: the kernel drops the lock when the holding # process dies, SIGKILL included, so a cancelled job can never wedge the next # run. macOS ships no `flock(1)`, so there the fallback is the mkdir + live-pid # shape `scripts/with-build-lock.sh` already uses on that machine — a dead # holder's lock is reclaimed on the next poll rather than by the kernel. # # Env knobs: # COTTON_CARGO_LOCK lock file (default $HOME/.cache/cottondb/rust/.lock) # COTTON_CARGO_LOCK_WAIT_S max seconds to wait (default 2700; exit 75 after) # COTTON_CARGO_LOCK_POLL_S fallback poll interval (default 5) # COTTON_CARGO_LOCK_STALE_S fallback: reclaim an OWNERLESS lock after this (300) # COTTON_CARGO_LOCK_LABEL who is asking, for the log line set -uo pipefail if [ $# -lt 1 ]; then echo "usage: with-cargo-lock.sh " >&2 exit 2 fi LOCK="${COTTON_CARGO_LOCK:-$HOME/.cache/cottondb/rust/.lock}" # Shared users cannot accidentally take different locks for the same artifacts. if [ -n "${CARGO_TARGET_DIR:-}" ] && [ "$(basename "$CARGO_TARGET_DIR")" = shared ]; then LOCK="$CARGO_TARGET_DIR.lock" fi WAIT_S="${COTTON_CARGO_LOCK_WAIT_S:-2700}" POLL_S="${COTTON_CARGO_LOCK_POLL_S:-5}" STALE_S="${COTTON_CARGO_LOCK_STALE_S:-300}" LABEL="${COTTON_CARGO_LOCK_LABEL:-$(whoami)-$$}" log() { echo "[cargo-lock] $*" >&2; } prepare_target() { if [ -n "${CARGO_TARGET_DIR:-}" ] && [ "$(basename "$CARGO_TARGET_DIR")" = shared ]; then bash "$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/cargo-target-guard.sh" || return $? fi } # Only a live ancestor can lend its lock. A daemon may inherit the environment # after the holder exits; its stale marker must never bypass serialization. # The parent chain is read in-process (scripts/lib/mac_disk_policy.py), never # through the setuid `ps` a lane's seatbelt refuses: a refused read made every # nested call wait on its own ancestor's lock until the timeout (syncpage5, # 17 Oct 2026). held_by_ancestor() { local owner="${COTTON_CARGO_LOCK_OWNER:-}" case "$owner" in ''|*[!0-9]*|0) return 1 ;; esac [ "$owner" != "$$" ] || return 0 python3 "$(cd "$(dirname "${BASH_SOURCE[0]}")/../lib" && pwd)/mac_disk_policy.py" --process-info ancestor "$owner" "$$" } if [ "${COTTON_CARGO_LOCK_HELD:-}" = "$LOCK" ] && held_by_ancestor; then prepare_target || exit $? exec "$@" fi mkdir -p "$(dirname "$LOCK")" if command -v flock >/dev/null 2>&1; then # fd 9 stays open for the life of this shell; the kernel releases the lock # when the process dies however it dies. exec 9>"$LOCK" || { log "cannot open $LOCK for locking"; exit 1; } if ! flock -w "$WAIT_S" 9; then log "TIMEOUT after ${WAIT_S}s waiting on $LOCK" exit 75 fi log "held by '$LABEL' ($LOCK, flock)" else # macOS. `mkdir` is the atomic acquire; the holder's pid inside says whether # a lock left behind by a killed job is still owned by anything. LOCK_DIR="$LOCK.d" deadline=$(( $(date +%s) + WAIT_S )) announced=0 until mkdir "$LOCK_DIR" 2>/dev/null; do holder="$(cat "$LOCK_DIR/pid" 2>/dev/null || true)" if [ -n "$holder" ] && ! kill -0 "$holder" 2>/dev/null; then log "holder pid $holder is dead — reclaiming $LOCK_DIR" rm -rf "$LOCK_DIR" continue fi if [ -z "$holder" ]; then # Killed between the mkdir and the pid write: nothing will ever own it, # and the pid check above cannot fire. Age it out. (BSD stat — this # branch is the macOS one by construction.) created="$(stat -f %m "$LOCK_DIR" 2>/dev/null || date +%s)" if [ $(( $(date +%s) - created )) -ge "$STALE_S" ]; then log "ownerless lock at $LOCK_DIR is older than ${STALE_S}s — reclaiming" rm -rf "$LOCK_DIR" continue fi fi if [ "$(date +%s)" -ge "$deadline" ]; then log "TIMEOUT after ${WAIT_S}s waiting on ${holder:-an ownerless} lock at $LOCK_DIR" exit 75 fi if [ "$announced" -eq 0 ]; then log "waiting for pid ${holder:-?} to finish its cargo section…" announced=1 fi sleep "$POLL_S" done echo "$$" > "$LOCK_DIR/pid" # An ownerless directory (killed between mkdir and the write above) would # otherwise be honoured for ever; the pid check above only fires once a pid # is there, so clean up after ourselves on every exit path we can see. trap 'rm -rf "$LOCK_DIR"' EXIT INT TERM log "held by '$LABEL' ($LOCK_DIR, mkdir)" fi # The command runs with the lock's path in its environment. Anything that # REMOVES artifacts from the shared target directory — `cargo-test-with-one-retry.sh` # and its `cargo clean -p` — refuses to do so without this, so a clean can never # run beside another job's build. export COTTON_CARGO_LOCK_HELD="$LOCK" export COTTON_CARGO_LOCK_OWNER="$$" prepare_target || exit $? # Check responsiveness after queueing, then watch only this command's wrappers. # The supervisor retains the lock across its single uncached retry. cargo_command=("$@") case "${RUSTC_WRAPPER:-}" in *sccache*) cargo_command=(bash "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/sccache-up.sh" --run "$@") ;; esac # `9>&-` — AND IT IS LOAD-BEARING. On the `flock` path the lock lives on file # descriptor 9 of THIS shell, and an fd is inherited by every child unless it is # closed: `flock` is held as long as ANY process holds an open descriptor on the # file, so a DAEMON the command starts keeps this lock for ever after the # command, and the shell that took it, are both long gone. # # Measured on 2026-09-09, PR #418 run 2413: the first cargo step ran # `sccache rustc …`, sccache's client started its SERVER, the server daemonised # with fd 9 open (`ls -l /proc//fd` showed `9 -> …/targets/ci-sccache.lock`), # and the job's NEXT cargo step blocked on `flock` against its own compile # cache's daemon. The run had to be cancelled. `SCCACHE_IDLE_TIMEOUT=0` — which # is what makes `--show-stats` readable — turns "for a while" into "for ever". # # The sccache step starts the server itself, outside any locked section, so this # particular daemon is born without the descriptor. This closes the class: # nothing the command spawns can ever hold the lock, whatever it is. # On the macOS path fd 9 was never opened and closing it is a no-op. # Guard: "does not leak the lock to a DAEMON the command starts" in the # cargo-cache test. "${cargo_command[@]}" 9>&- status=$? log "released by '$LABEL' (exit $status)" exit "$status"