Cotton code
1105 lines · 50.3 KB · ShellRaw
#!/usr/bin/env bash# Machine-wide build slots — bounds heavy builds across EVERYTHING running# on this Mac: CI runner jobs, Claude sessions, and manual shells.## Archives saturate a 16 GB Mac alone. Ordinary builds can share two slots# on a Mac with at least 24 GB; smaller machines keep one. A caller wrapping# xcodebuild archive, fastlane gym or release-app.sh declares# BUILD_LOCK_EXCLUSIVE=1 on its outermost lock. Releases are always exclusive.# The first slot keeps the shared Tinmen lock address; old holders that lack# an exclusivity marker are treated as exclusive while they finish.## Usage:#   scripts/with-build-lock.sh <command...>#   BUILD_LOCK_LABEL=ci-user scripts/with-build-lock.sh bundle exec fastlane ios user_release## Semantics:#   - Atomic acquire via mkdir; the holder records its pid + label inside.#   - Waiters poll every 30s. A lock whose holder pid is DEAD is reclaimed#     immediately (crash without cleanup). A lock directory with no pid file#     older than BUILD_LOCK_STALE_MIN is reclaimed (holder died mid-acquire).#     A lock whose holder is ALIVE is honored indefinitely up to the timeout —#     long legit builds are never stolen.#   - Timeout exits 75 (EX_TEMPFAIL) so a CI step fails loudly instead of#     silently piling on.#   - RE-ENTRANT. A command run under the lock may wrap one of its own steps in#     this script again — `scripts/ios-test.sh` and `scripts/build-xcframework.sh`#     take the lock themselves, so any caller wrapping them nests by accident —#     and the inner call runs straight through instead of waiting on a lock its#     own ancestor holds. Wrapping is harmless; nothing has to remember not to.## HOW RE-ENTRANCY IS DECIDED, AND WHY THE ENVIRONMENT VARIABLE IS NOT ENOUGH.# The holder exports TINMEN_BUILD_LOCK_HELD=<its pid> (plus the lock path and# label) for its children. An inner call trusts that marker only after walking# its OWN parent chain (in-process parent reads) and finding that pid in it, and only when# the marker names the SAME lock path. A bare variable would be a skeleton key:# an export left in a long-lived shell (or inherited by a build kicked off after# the holder exited, with the pid recycled onto some unrelated process) would# wave every later build past a lock somebody else is really holding, which is# the swap-crash this whole file exists to prevent. An ancestor is different in# kind — the holder is still alive, and it is still running the thing that is# asking. Guard: `scripts/__tests__/build-lock-reentrant.test.ts`.## WHY THE LOCK IS STILL CALLED tinmen-build.lock. It is machine-wide, and this# machine also runs the Tinmen monorepo's CI and dev sessions. The lock's whole# job is to make every heavy build on this Mac queue behind every other one — so# both repos MUST agree on the path. Renaming it to something CottonDB-flavoured# would give this repo its own private lock, which is the same as having no lock# at all: two archives would run concurrently and swap-crash the machine. The# name is a shared address, not a brand.## Env knobs:#   BUILD_LOCK_DIR         lock path (default /tmp/tinmen-build.lock — /tmp is#                          machine-local and cleared on reboot, which is#                          exactly the lifetime a build lock should have)#   BUILD_LOCK_LABEL       who's asking (default user-pid; CI sets ci-<app>)#   BUILD_LOCK_TIMEOUT_MIN max minutes to wait for the lock (default 10 — the#                          build policy's admit timeout; see "NOTHING WAITS#                          WITHOUT A LINE")#   BUILD_LOCK_STALE_MIN   reclaim an owner-less lock after this (default 5)#   BUILD_LOCK_LOG         the wait log (default ~/.cache/cottondb/build-lock.log)#   BUILD_LOCK_MAX_MIN     per-job CEILING on the wrapped command (default 0 =#                          off). See below.#   BUILD_LOCK_CEILING_SECONDS / _GRACE_SECONDS#                          the ceiling and the TERM→KILL grace in seconds — the#                          seam the guard drives; no lane sets either.#   BUILD_LOCK_EXCLUSIVE   1 for archives (xcodebuild archive, fastlane gym,#                          release-app.sh); declare on the outermost caller#   BUILD_LOCK_MEMORY_BYTES test seam; normally sysctl -n hw.memsize decides#   BUILD_LOCK_CLASS       release | ci | walk | local — overrides the runner's#                          CI variables (`scripts/lib/caller-class.sh`); a#                          release or install lane sets `release`, a walk's#                          simulator build `walk` (`rank_as_walk`)#   BUILD_LOCK_YIELD       `never` — a local run that must not be interrupted#                          (the Mac release lane). It still waits behind claims.#   BUILD_LOCK_LOCAL_NICE  the niceness a local run's command runs at (default 19, 0 = off)#   BUILD_LOCK_POLL_SECONDS / _CI_POLL_SECONDS / _YIELD_POLL_SECONDS /#   BUILD_LOCK_YIELD_GRACE_SECONDS#                          the intervals (30, 5, 5) and the TERM→KILL grace on a#                          yield (20) — seams the guard drives#   BUILD_LOCK_TIMEOUT_SECONDS the lock wait in seconds, over the minutes — a seam#   BUILD_LOCK_SAY_SECONDS / _TERM_GRACE_SECONDS#                          how often a wait is said again (60), and the#                          TERM→KILL grace when this wrapper is itself stopped#                          (20) — seams## NOTHING WAITS WITHOUT A LINE (architect, 14 Oct 2026 23:45 IST). Cut #3 of# 0.29.57 sat 28 minutes held with no line printed, and cut #2's wrapper kept# the lock through SIGTERM until a KILL. So every wait here — on the lock, on a# claim that outranks this caller — says what it waits on and since when as it# starts and every minute after, and gives up with that line at# BUILD_LOCK_TIMEOUT_MIN, ten by default — the policy's RAM admission (inside# the lock, scripts/lib/mac_disk_policy.py) does the same with the same clock.# Every sleep is a background `sleep` this shell `wait`s on, so a TERM is taken# at once, never after the poll. A TERM, INT or HUP stops the command's whole# tree — TERM, a bounded grace, then KILL — and only then releases the lock and# the claim and drops the tree's reservations from the ledger: nothing it held# is left to a KILL from outside. Guard: `scripts/__tests__/build-lock-held.test.ts`.## THE CEILING, AND WHY IT IS OFF BY DEFAULT. Waiting is correct; waiting on a# holder that has stopped making progress is not. Measured on one Mac on 23 Sep# (PR #915, run 100): sccache's server wedged, three `sccache … rustc` children# sat at 0% CPU for 77 minutes, and the `swift` job held this lock for the whole# household while doing nothing. Nothing timed out, because a job that never# fails never releases.## So a CALLER may declare how long its lane can honestly take —# `BUILD_LOCK_MAX_MIN=50` on the swift and ios steps, which measure ~50 min at# their slowest — and a command that outlives that is TERMed, then KILLed, and# this script exits 124 (the exit `timeout(1)` uses, which macOS does not ship).# The lock is released by the same EXIT trap that releases it on success, so the# next job starts instead of queueing behind a corpse.## It is OFF unless a caller sets it: a ceiling guessed for someone else's lane# is a build killed for being slow, which is worse than the wedge it was meant# to catch. A re-entrant call never applies one either — the outer call owns the# clock as it owns the lock.## THE WAIT LOG. One TAB-separated line per ACQUIRE, appended:##   <iso8601-Z>\t<label>\t<seconds waited>\t<label it waited on, or ->## Nothing knew what this lock actually costs. "Waiting is correct" is the rule,# and it is the right rule, but a rule with no measurement behind it cannot tell# a healthy queue from the two-hour self-deadlock that `build-lock-reentrant`# exists for, nor answer the only question worth asking of a mutex on a shared# machine: how long did anyone actually spend behind it, and behind WHOM. Four# fields answer both, and `sort`/`awk` are the whole reporting layer.## The seconds are QUEUEING, not elapsed wall clock: a call that found the lock# free on its first try never read the clock and logs 0, so the field can never# report a wait that did not happen.## A re-entrant call appends NOTHING: it takes no lock, so it waited zero seconds# on nobody, and a line for it would only dilute the file. A failed append is# said out loud on stderr and never fails the build — the log is a record of# builds, not a precondition for one. Guard:# `scripts/__tests__/build-lock-wait-log.test.ts`.## CHECK JOBS GO FIRST. A builder's local run and a CI check job are not equals# on a machine they share: the check job is what a pull request is waiting on,# the local run is one agent's second opinion. On 28 Sep 2026 a pull request's# `rust` job waited 35 minutes here on a local `rust:verify` that held the lock# for its whole run, first come first served. So the caller's CLASS is read# (`scripts/lib/caller-class.sh`: `ci` when the runner set `CI`/`GITHUB_ACTIONS`,# else `local`) and the queue is ranked by it:##   - A check job that has to wait FILES A CLAIM — `<lock>.ci-waiting/<pid>`,#     its label inside — and polls every 5 s instead of 30, so it takes the lock#     the moment it frees. The claim goes when it acquires, or when it dies.#   - A local caller never takes the lock while a live claim exists. It queues#     behind every waiting check job, not only behind the holder.#   - A local HOLDER YIELDS. Its command runs in its own process group with a#     watcher beside it; a claim appears, the WHOLE GROUP is TERMed (KILLed#     after a grace), the lock is released, and the run waits behind the check#     job and then STARTS AGAIN from the top. A verify is a pure function of#     the tree, so a restart costs time and nothing else — and the incremental#     cargo target it leaves means it costs less than the first attempt.#     `BUILD_LOCK_YIELD=never` is the one exception a local run may declare,#     for work that must not be cut in half (the Mac release lane: a notarised#     bundle half-stapled is worse than a check job that waited). It still#     queues behind claims; it is only never interrupted.#   - A local run's command runs at nice 19 — behind the Mac runner's jobs,#     which run at +15 (`RUNNER_NICE`), and behind the person's own work at 0.## Equal-rank ordinary jobs share available slots; one never interrupts another.# Guard: `scripts/__tests__/build-lock-ci-first.test.ts`.## RELEASES GO FIRST, AHEAD OF CHECK JOBS. On 29 Sep 2026 a TestFlight build# waited 18 minutes, and a Mac release install over 40, behind check jobs on a# Mac's lock. A release is what a person is standing at the machine for; a# check job can run again a minute later and nothing is lost. So a caller that# says `BUILD_LOCK_CLASS=release` (the TestFlight and Mac release steps, the# Mac release lane) is ranked above `ci` exactly as `ci` is above `local`:##   - a waiting release files ITS claim — `<lock>.release-waiting/<pid>`;#   - a check job, like a local run, never takes the lock while one is live;#   - a HOLDING check job yields to it the way a local run yields to a check#     job: its whole group is stopped, and it waits and then starts again from#     the top inside the SAME job step. It is handed back and re-run, never#     marked failed — the step's exit is the re-run's;#   - a release is never interrupted, and two releases take turns in order.## Guard: `scripts/__tests__/build-lock-release-first.test.ts`.## A WALK GOES BEFORE OTHER LOCAL RUNS. Measured 27 Oct 2026 on one Mac: the# coordinator's walk build (`build-xcframework.sh --simulator-only`, then the# Cotton scheme for the simulator) waited 40 minutes here behind three# subagents' cargo builds, then compiled in about four. All four were `local`,# and local runs take a freed lock by whoever polls first. A walk is a person# standing at a simulator; a subagent's build is one agent's step. So a walk# script says `BUILD_LOCK_CLASS=walk` (`rank_as_walk` in caller-class.sh:# `ios-sim-release.sh`, `walk-board.sh`, `walk-deck.sh`, `recopy-sim.sh`,# `release-walk.sh`, `faces-walk/walk.sh`), ranked between `ci` and `local`:##   - a waiting walk files ITS claim — `<lock>.walk-waiting/<pid>` — and polls#     every 5 s, so it is next in line however many local runs queued first;#   - a local run never takes a free lock while a walk claim is live;#   - but a local HOLDER is never stopped for a walk: it finishes, and the walk#     goes next. Only a check job's or a release's claim makes a holder yield;#   - otherwise a walk is a local run: it waits behind releases and check jobs#     and runs at the local nice — but a HOLDING walk yields only to a release,#     never to a check job. On 8 Nov 2026 one Mac's half-hour swift-compile tick#     (caab590b7f) stopped a lane's Music walk build three times in an hour;#     each restart began the XCFramework and the app from the top, so a build#     longer than one tick window could never finish. A walk is a person at a#     simulator and a check job can run again a minute later (the same reason a#     release goes ahead of a check job), so the check job files its claim and#     waits — at most its own BUILD_LOCK_MAX_MIN.## Guard: `scripts/__tests__/build-lock-walk-first.test.ts`.## EVERY WAITER SAYS SO BESIDE THE LOCK (lock-order, 7 Nov 2026). On one Mac a CI# swift-compile took this lock and then sat 32 minutes in the policy's RAM# admission behind a lane's `swift test` whose 2.55 GB reservation stood in the# ledger while that lane waited HERE for the lock the CI job held: neither could# move until the CI ceiling killed the job. The policy now leaves out of the# holder's admission every reservation whose build waits on this lock# (scripts/lib/mac_disk_policy.py, "A BUILD WAITING ON THE BUILD LOCK HOLDS NO# RAM FROM ITS HOLDER"), and it finds those builds by their marker. So a local# run that waits files one too — `<lock>.local-waiting/<pid>`, its label inside.# It is a marker, never a claim: nothing queues behind it and nothing yields to# it. It goes when the wait ends, as a claim does.# Guard: `scripts/__tests__/build-admission-lock-holder.test.ts`.## Exported for children (read by a nested call, never set by hand):#   TINMEN_BUILD_LOCK_HELD  pid of the process holding the lock#   TINMEN_BUILD_LOCK_DIR   the lock path it holds#   TINMEN_BUILD_LOCK_LABEL its label, for the re-entry log lineset -uo pipefail# Even direct lane builds share the device policy; the monitor forwards signals# to its own build tree and holds disk admission until that tree has ended.## WHICH MACS HAVE THE POLICY. Its installer (pnpm mac-build-policy:install)# writes `activated` in ~/.cotton-agent/mac-build-policy as its last step: that# file says the policy is installed. A Mac the fleet file lists by hostname# (the fleet file, read when it is there: scripts/lib/build-policy-state.sh) must have it, so there a# missing marker stops the build with what to run, never a quiet build without# the RAM and disk gates. Any other Mac (a checkout of the public source, which# carries no fleet file) builds straight through: no policy and no lock.# Guard: the with-build-lock policy test.. "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib/build-policy-state.sh"if [ "$(uname -s)" = Darwin ]; then  case "$(build_policy_state "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)")" in    installed)      [ "$#" -gt 0 ] && set -- bash "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/mac-build-policy.sh" -- "$@"      ;;    fleet-missing)      build_policy_missing_message with-build-lock >&2      exit 2      ;;    absent)      [ "$#" -gt 0 ] || exit 0      exec "$@"      ;;  esacfiLOCK_DIR="${BUILD_LOCK_DIR:-/tmp/tinmen-build.lock}"LABEL="${BUILD_LOCK_LABEL:-$(whoami)-$$}"TIMEOUT_MIN="${BUILD_LOCK_TIMEOUT_MIN:-10}"[[ "$TIMEOUT_MIN" =~ ^[0-9]+$ ]] || TIMEOUT_MIN=10# Seconds, so the guard can watch a wait be said and given up without waiting# minutes for it; no caller sets it.TIMEOUT_S="${BUILD_LOCK_TIMEOUT_SECONDS:-$(( TIMEOUT_MIN * 60 ))}"STALE_MIN="${BUILD_LOCK_STALE_MIN:-5}"LOG_FILE="${BUILD_LOCK_LOG:-$HOME/.cache/cottondb/build-lock.log}"MAX_MIN="${BUILD_LOCK_MAX_MIN:-0}"[[ "$MAX_MIN" =~ ^[0-9]+$ ]] || MAX_MIN=0# THE CALLER'S RANK — see "CHECK JOBS GO FIRST" above.# shellcheck source=lib/caller-class.sh# A copy of this script without its lib is a broken install, and a caller# whose rank cannot be read must not run unranked — it stops here.. "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib/caller-class.sh" || {  echo "[build-lock] scripts/lib/caller-class.sh is missing beside this script" >&2  exit 2}# A dead or stale holder's lock directory is removed whole, and BUILD_LOCK_DIR# can name any folder: never a home folder or anything above one.# shellcheck source=lib/owned-root.sh. "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib/owned-root.sh" || {  echo "[build-lock] scripts/lib/owned-root.sh is missing beside this script" >&2  exit 2}refuse_wide_root "the build lock (BUILD_LOCK_DIR)" "$LOCK_DIR"CLASS="$(caller_class)"# ON LINUX THE KERNEL SHARES, NOT THIS LOCK (15 Nov 2026). The lock exists for a# 16 GB Mac that an archive saturates alone. The box has 125 GB and its limit is# CPU, which box-priority.sh's cgroup weights already share between the runners,# the lanes and box:cargo; a file lock there only queued eight lanes behind one# another with 16 threads idle. So on Linux a caller runs straight through,# unlocked and unlogged, except a release (the Play cut), which still takes the# lock whole. BUILD_LOCK_HOST_KIND (linux | mac) overrides uname for the guards,# which drive the queue on the Linux runners (scripts/__tests__/setup-build-lock.ts).HOST_KIND="${BUILD_LOCK_HOST_KIND:-$( [ "$(uname -s)" = Linux ] && echo linux || echo mac )}"if [ "$HOST_KIND" = linux ] && [ "$CLASS" != release ]; then  [ "$#" -gt 0 ] || exit 0  exec "$@"fiBASE_LOCK_DIR="$LOCK_DIR"ADMISSION_DIR="${LOCK_DIR}.admission"refuse_wide_root "the build lock's admission folder" "$ADMISSION_DIR"# Ordinary builds share two slots on machines with enough RAM; an archive# caller declares exclusivity. Releases drain both slots through their existing# claim. The RAM is sysctl's on a Mac and /proc/meminfo's on Linux: sysctl# alone read 0 on the box (125 GB), which gave every box lane one slot between# them (15 Nov 2026).host_memory_bytes() {  if [ "$(uname -s)" = Darwin ]; then    sysctl -n hw.memsize 2>/dev/null || echo 0  else    awk '/^MemTotal:/ { printf "%d", $2 * 1024; found = 1 } END { if (!found) print 0 }' /proc/meminfo 2>/dev/null || echo 0  fi}MEMORY_BYTES="${BUILD_LOCK_MEMORY_BYTES:-$(host_memory_bytes)}"CAPACITY=1if [[ "$MEMORY_BYTES" =~ ^[0-9]+$ ]] && [ "$MEMORY_BYTES" -ge 25769803776 ]; then CAPACITY=2; fiEXCLUSIVE="${BUILD_LOCK_EXCLUSIVE:-0}"[ "$CLASS" = release ] && EXCLUSIVE=1CLAIMS_DIR="${LOCK_DIR}.ci-waiting"RELEASE_CLAIMS_DIR="${LOCK_DIR}.release-waiting"WALK_CLAIMS_DIR="${LOCK_DIR}.walk-waiting"LOCAL_WAITING_DIR="${LOCK_DIR}.local-waiting"# Where THIS caller files its claim while it waits (a local run's is only a# marker, outranking nobody — see "EVERY WAITER SAYS SO BESIDE THE LOCK"),# the claims that outrank it in the queue, highest first, and the claims that# make it YIELD the lock while it holds. A walk claim is in a local run's queue# but never stops one that holds (see "A WALK GOES BEFORE OTHER LOCAL RUNS").case "$CLASS" in  release) MY_CLAIMS_DIR="$RELEASE_CLAIMS_DIR"; OUTRANKED_BY=(); PREEMPTED_BY=() ;;  ci) MY_CLAIMS_DIR="$CLAIMS_DIR"; OUTRANKED_BY=("$RELEASE_CLAIMS_DIR"); PREEMPTED_BY=("$RELEASE_CLAIMS_DIR") ;;  walk) MY_CLAIMS_DIR="$WALK_CLAIMS_DIR"; OUTRANKED_BY=("$RELEASE_CLAIMS_DIR" "$CLAIMS_DIR"); PREEMPTED_BY=("$RELEASE_CLAIMS_DIR") ;;  *) MY_CLAIMS_DIR="$LOCAL_WAITING_DIR"; OUTRANKED_BY=("$RELEASE_CLAIMS_DIR" "$CLAIMS_DIR" "$WALK_CLAIMS_DIR"); PREEMPTED_BY=("$RELEASE_CLAIMS_DIR" "$CLAIMS_DIR") ;;esacPOLL_S="${BUILD_LOCK_POLL_SECONDS:-30}"CI_POLL_S="${BUILD_LOCK_CI_POLL_SECONDS:-5}"YIELD_POLL_S="${BUILD_LOCK_YIELD_POLL_SECONDS:-5}"YIELD_GRACE_S="${BUILD_LOCK_YIELD_GRACE_SECONDS:-20}"LOCAL_NICE="${BUILD_LOCK_LOCAL_NICE:-19}"SAY_S="${BUILD_LOCK_SAY_SECONDS:-60}"TERM_GRACE_S="${BUILD_LOCK_TERM_GRACE_SECONDS:-20}"[[ "$LOCAL_NICE" =~ ^[0-9]+$ ]] || LOCAL_NICE=19# A local run or a walk yields to a check job or a release, a check job to a# release, and a release to nobody.YIELDS=1if [ "$CLASS" = release ]; then  YIELDS=0elif { [ "$CLASS" = local ] || [ "$CLASS" = walk ]; } && [ "${BUILD_LOCK_YIELD:-}" = never ]; then  YIELDS=0fiif [ $# -lt 1 ]; then  echo "usage: with-build-lock.sh <command...>" >&2  exit 2filog() { echo "[build-lock] $(date '+%H:%M:%S') $*" >&2; }now_s() { date +%s; }# GNU date reads an epoch with -d @, BSD date with -r.clock_text() { date -d "@$1" '+%Y-%m-%d %H:%M:%S %Z' 2>/dev/null || date -r "$1" '+%Y-%m-%d %H:%M:%S %Z'; }# A sleep a signal cuts short: bash runs a trap only between commands, so a# foreground `sleep 30` would hold a TERM for up to thirty seconds.SLEEP_PID=""nap() {  sleep "$1" &  SLEEP_PID=$!  wait "$SLEEP_PID" 2>/dev/null  SLEEP_PID=""}# ── The wait, said — see "NOTHING WAITS WITHOUT A LINE" ─────────────────────WAIT_SINCE=""WAIT_SAID=""# One poll of a wait: said at the start and every SAY_S, given up (exit 75) at# the timeout.# A RELEASE WAITS WHILE ITS HOLDER LIVES (architect, 17 Oct 2026 07:20 IST):# a cut's wait on the lock has no timeout while the holder (its pid, `$2`) is# alive and has not outlived the ceiling it wrote beside its pid; the policy's# RAM admission does the same (scripts/lib/mac_disk_policy.py). A check job's# or local run's wait keeps the timeout.holder_lives() {  local pid="$1" ceiling  [ "$CLASS" = release ] && [ -n "$pid" ] && pid_is_alive "$pid" || return 1  ceiling="$(cat "$LOCK_DIR/ceiling_s" 2>/dev/null || echo 0)"  [[ "$ceiling" =~ ^[0-9]+$ ]] || ceiling=0  [ "$ceiling" -eq 0 ] || [ $(( $(lock_age_min) * 60 )) -le "$ceiling" ]}# How long this wait may last, in seconds. A HOLDING WALK never yields to a# check job (see "A WALK GOES BEFORE OTHER LOCAL RUNS"), so a check job behind# one waits up to its own ceiling, BUILD_LOCK_MAX_MIN, where that is longer than# the lock timeout: swift-main run 8301 (8 Nov, one Mac) gave loom up at 10m behind# a lane's walk build, and the job went red for a build it was meant to wait on.wait_limit_s() {  local holder="$1" ceiling  if [ "$CLASS" = ci ] && [ "$MAX_MIN" -gt 0 ] && [ -n "$holder" ] \    && [ "$(cat "$LOCK_DIR/pid" 2>/dev/null)" = "$holder" ] \    && [ "$(cat "$LOCK_DIR/class" 2>/dev/null)" = walk ]; then    ceiling="${BUILD_LOCK_CEILING_SECONDS:-$(( MAX_MIN * 60 ))}"    if [[ "$ceiling" =~ ^[0-9]+$ ]] && [ "$ceiling" -gt "$TIMEOUT_S" ]; then      echo "$ceiling"      return    fi  fi  echo "$TIMEOUT_S"}said_s() {  if [ "$1" -ge 60 ]; then echo "$(( $1 / 60 ))m"; else echo "${1}s"; fi}held_tick() {  local on="$1" holder="${2:-}" now limit_s  now="$(now_s)"  [ -n "$WAIT_SINCE" ] || WAIT_SINCE="$now"  limit_s="$(wait_limit_s "$holder")"  if [ $(( now - WAIT_SINCE )) -ge "$limit_s" ] && ! holder_lives "$holder"; then    log "TIMEOUT after $(said_s "$limit_s") waiting on $on since $(clock_text "$WAIT_SINCE")"    held_end    exit 75  fi  if [ -z "$WAIT_SAID" ]; then    if holder_lives "$holder"; then      log "WAITING on $on for the build lock since $(clock_text "$WAIT_SINCE"); a release waits while it runs"    else      log "WAITING on $on for the build lock since $(clock_text "$WAIT_SINCE"); gives up at $(said_s "$limit_s")"    fi    WAIT_SAID="$now"  elif [ $(( now - WAIT_SAID )) -ge "$SAY_S" ]; then    log "still WAITING on $on for the build lock since $(clock_text "$WAIT_SINCE") ($(( (now - WAIT_SINCE) / 60 ))m)"    WAIT_SAID="$now"  fi}# The wait is over — admitted, given up or stopped.held_end() {  WAIT_SINCE=""  WAIT_SAID=""}lock_mtime_s() {  # GNU stat is Linux CI's implementation; BSD stat is macOS's. Do not use a  # failed BSD-only invocation as an implicit "just created" answer on Linux.  local mtime  mtime="$(stat -c %Y "$LOCK_DIR" 2>/dev/null)" || true  if [ -n "$mtime" ] && [[ "$mtime" =~ ^[0-9]+$ ]]; then    printf '%s\n' "$mtime"    return  fi  mtime="$(stat -f %m "$LOCK_DIR" 2>/dev/null)" || true  if [ -n "$mtime" ] && [[ "$mtime" =~ ^[0-9]+$ ]]; then    printf '%s\n' "$mtime"    return  fi  now_s}lock_age_min() {  local mtime now  mtime="$(lock_mtime_s)"  now="$(now_s)"  echo $(( (now - mtime) / 60 ))}# kill(2) returns EPERM when another user owns a live CI process. Its non-zero# status alone therefore does not say a holder is dead. Python's kill(2)# distinguishes EPERM from ESRCH without exec of a privileged binary.# Return 0 alive, 1 dead.PROCESS_POLICY="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib/mac_disk_policy.py"pid_is_alive() {  kill -0 "$1" 2>/dev/null && return 0  python3 "$PROCESS_POLICY" --process-info alive "$1"}# Never turn a failed reclaim into a tight loop. A different user can own the# directory even after its pid died; keep waiting and let the ordinary timeout# say so rather than deleting around the mutex or spinning rm(1) forever.reclaim_lock() {  local reason="$1"  log "$reason — reclaiming lock"  if rm -rf "$LOCK_DIR"; then    return 0  fi  log "$reason — could not reclaim '$LOCK_DIR'; continuing to wait"  return 1}# Is $1 one of the parents of $2? Walks the ppid chain rather than trusting a# single hop, because the holder is usually a grandparent: it runs a build# script, which wraps a step in this script again. The hop cap is a guard# against a chain that never reaches 1. The shared reader never execs a# privileged binary, which seatbelt would deny inside a lane.is_ancestor() {  python3 "$PROCESS_POLICY" --process-info ancestor "$1" "$2"}# Already inside a build this same process tree holds the lock for? Then run and# return — no second acquire, no wait, and deliberately no trap: the outer call# owns the lock directory and is the one that removes it.# Cargo users share a target lock; unrelated commands can still use both# admission slots. Use the same command shape for initial and nested calls.prepare_command() {  local here target config  here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"  target="${CARGO_TARGET_DIR:-}"  if [ -z "$target" ]; then    for config in "$here/../crates/.cargo/config.toml" "$here/../.cargo/config.toml"; do      [ -f "$config" ] || continue      target="$(sed -n 's/^[[:space:]]*target-dir[[:space:]]*=[[:space:]]*"\(.*\)"[[:space:]]*$/\1/p' "$config" | head -1)"      [ -z "$target" ] || break    done  fi  case "${1-}" in cargo|*/cargo) target="${target:-$(bash "$here/ci/cargo-target-dir.sh" shared)}" ;; esac  GUARDED_COMMAND=("$@")  if [ "$(basename "${target:-unused}")" = shared ]; then    GUARDED_COMMAND=(env "CARGO_TARGET_DIR=$target" bash "$here/cargo-target-guard.sh" --run "$@")  fi}HELD_PID="${TINMEN_BUILD_LOCK_HELD:-}"HELD_DIR="${TINMEN_BUILD_LOCK_DIR:-}"HELD_LABEL="${TINMEN_BUILD_LOCK_LABEL:-unknown}"if [ -n "$HELD_PID" ]; then  if ! [[ "$HELD_PID" =~ ^[0-9]+$ ]]; then    log "ignoring TINMEN_BUILD_LOCK_HELD='$HELD_PID' — that is not a pid"  elif [ "$HELD_DIR" != "$BASE_LOCK_DIR" ]; then    log "ignoring TINMEN_BUILD_LOCK_HELD=$HELD_PID — it holds '${HELD_DIR:-nothing}', not '$LOCK_DIR'"  elif ! is_ancestor "$HELD_PID" "$$"; then    log "ignoring TINMEN_BUILD_LOCK_HELD=$HELD_PID — pid $HELD_PID is not an ancestor of $$"  else    if [ "$EXCLUSIVE" = 1 ] && [ "${TINMEN_BUILD_LOCK_EXCLUSIVE:-1}" != 1 ]; then      log "exclusive build cannot re-enter a shared holder; declare BUILD_LOCK_EXCLUSIVE=1 on the outer caller"      exit 2    fi    log "re-entered under '$HELD_LABEL' (pid $HELD_PID) — running without taking the lock again"    prepare_command "$@"    "${GUARDED_COMMAND[@]}"    status=$?    log "re-entry under '$HELD_LABEL' finished (exit $status)"    exit "$status"  fifi# A label with whitespace in it would break the field count of a TSV line, and# the label is the one field a caller chooses.field() { printf '%s' "$1" | tr -s '[:space:]' '-'; }# One line per acquire. Never fatal: a read-only HOME or a full disk must not# fail a build, but it must not go quiet either, so the line goes to stderr# instead and says it was not recorded.record_wait() {  local waited="$1" on="$2" line  line="$(printf '%s\t%s\t%s\t%s' \    "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$(field "$LABEL")" "$waited" "$(field "${on:--}")")"  if ! { mkdir -p "$(dirname "$LOG_FILE")" && printf '%s\n' "$line" >>"$LOG_FILE"; } 2>/dev/null; then    log "could not append to $LOG_FILE — unrecorded: $line"  fi}# ── Claims: a release, check job or walk that is waiting, said where all can see it ──## One file per waiting release, check job or walk, named by its pid, its label inside,# in its rank's directory; a waiting local run's marker is the same file in# `<lock>.local-waiting`, which no caller's queue reads. The# directory is created world-writable and sticky (as /tmp is), because the# machine's callers are not all one user; a claim that cannot be filed is said# on stderr and the job simply waits unranked — the claim is a priority, never# a precondition.CLAIMED=0file_claim() {  [ -n "$MY_CLAIMS_DIR" ] || return 0  { mkdir -p "$MY_CLAIMS_DIR" && chmod 1777 "$MY_CLAIMS_DIR"; } 2>/dev/null || true  if printf '%s\n' "$LABEL" >"$MY_CLAIMS_DIR/$$" 2>/dev/null; then    CLAIMED=1  else    log "could not file a claim in $MY_CLAIMS_DIR — waiting without one"  fi}drop_claim() {  [ "$CLAIMED" -eq 1 ] || return 0  rm -f "$MY_CLAIMS_DIR/$$" 2>/dev/null  CLAIMED=0}# A LIVE claim that outranks this caller, as `<kind> '<label>'` on the first# line and the bare label on the second; status 1 when there is none. The# directories asked are the arguments, the queue's (OUTRANKED_BY) when none are# given. A claim whose pid is gone is removed on sight — a job that was# cancelled mid-wait must not keep every lower rank out for ever.live_claim() {  local dir claim pid kind label  [ "$#" -gt 0 ] || set -- ${OUTRANKED_BY[@]+"${OUTRANKED_BY[@]}"}  for dir in "$@"; do    [ -d "$dir" ] || continue    case "$dir" in      "$RELEASE_CLAIMS_DIR") kind=release ;;      "$WALK_CLAIMS_DIR") kind=walk ;;      *) kind="check job" ;;    esac    for claim in "$dir"/*; do      [ -f "$claim" ] || continue      pid="$(basename "$claim")"      [[ "$pid" =~ ^[0-9]+$ ]] || continue      [ "$pid" = "$$" ] && continue      if pid_is_alive "$pid"; then        label="$(head -n 1 "$claim" 2>/dev/null)"        printf "%s '%s'\n%s\n" "$kind" "${label:-unknown}" "${label:-unknown}"        return 0      fi      rm -f "$claim" 2>/dev/null    done  done  return 1}# ── The lock ────────────────────────────────────────────────────────────────HOLDING=0# The label of the job this run last yielded to — who its next wait is behind.YIELDED_LABEL=""# Only ever the directory THIS process holds: after a yield the same path is a# check job's lock, and an exit trap that removed it blindly would hand the# machine to a third build mid-way through the second.release_lock() {  [ "$HOLDING" -eq 1 ] || return 0  if [ "$(cat "$LOCK_DIR/pid" 2>/dev/null)" = "$$" ]; then    rm -rf "$LOCK_DIR"  fi  HOLDING=0}# Admission is short and atomic: checking all holders and publishing the new# holder happen in one turn, so an exclusive build cannot race a second slot.# Each slot retains the existing pid/label contract for lock readers.try_acquire() {  local slot pid candidate="" blocked="" exclusive_seen=0  LOCK_DIR="$ADMISSION_DIR"  if ! mkdir "$ADMISSION_DIR" 2>/dev/null; then    pid="$(cat "$ADMISSION_DIR/pid" 2>/dev/null || true)"    if { [ -n "$pid" ] && ! pid_is_alive "$pid"; } || \       { [ -z "$pid" ] && [ "$(lock_age_min)" -ge "$STALE_MIN" ]; }; then      reclaim_lock "dead admission owner" || true    fi    LOCK_DIR="$BASE_LOCK_DIR"    return 1  fi  echo "$$" > "$ADMISSION_DIR/pid"  for slot in "$BASE_LOCK_DIR" "${BASE_LOCK_DIR}.slot-2"; do    LOCK_DIR="$slot"    if [ -d "$slot" ]; then      pid="$(cat "$slot/pid" 2>/dev/null || true)"      if { [ -n "$pid" ] && ! pid_is_alive "$pid"; } || \         { [ -z "$pid" ] && [ "$(lock_age_min)" -ge "$STALE_MIN" ]; }; then        [ -n "$wait_started" ] || wait_started="$(now_s)"        [ -n "$waited_on" ] || waited_on="$(cat "$slot/label" 2>/dev/null || echo unknown)"        reclaim_lock "dead or stale slot owner" || true      fi    fi    if [ -d "$slot" ]; then      [ -n "$blocked" ] || blocked="$slot"      # Older holders did not declare their capacity: treat them as exclusive.      [ "$(cat "$slot/exclusive" 2>/dev/null || echo 1)" = 0 ] || exclusive_seen=1    elif [ -z "$candidate" ] && { [ "$slot" = "$BASE_LOCK_DIR" ] || [ "$CAPACITY" = 2 ]; }; then      candidate="$slot"    fi  done  if [ -n "$candidate" ] && [ "$exclusive_seen" = 0 ] && \     { [ "$EXCLUSIVE" != 1 ] || [ -z "$blocked" ]; }; then    LOCK_DIR="$candidate"    if mkdir "$LOCK_DIR" 2>/dev/null; then      echo "$$" > "$LOCK_DIR/pid"      # A holder that left this caller's RAM out named it in its slot: no slot      # until that holder ends (mac_disk_policy.py, "A WAITER LEFT OUT TAKES NO      # SLOT WHILE ITS HOLDER RUNS"). Read after the pid is written.      if [ -e "$BASE_LOCK_DIR/excluded/$$" ] || [ -e "${BASE_LOCK_DIR}.slot-2/excluded/$$" ]; then        rm -rf "$LOCK_DIR"        rm -rf "$ADMISSION_DIR"        LOCK_DIR="${blocked:-$BASE_LOCK_DIR}"        return 1      fi      echo "$LABEL" > "$LOCK_DIR/label"      echo "$EXCLUSIVE" > "$LOCK_DIR/exclusive"      echo "${BUILD_LOCK_CEILING_SECONDS:-$(( MAX_MIN * 60 ))}" > "$LOCK_DIR/ceiling_s"      HOLDING=1      rm -rf "$ADMISSION_DIR"      return 0    fi  fi  rm -rf "$ADMISSION_DIR"  LOCK_DIR="${blocked:-$BASE_LOCK_DIR}"  return 1}acquire() {  local announced=0 wait_started="" waited_on="" claim claim_on waited  local holder_pid holder_label  # WHEN THIS CALL FIRST FOUND THE LOCK TAKEN. Empty means it never queued at  # all, and a call that never queued waited exactly ZERO seconds — the number  # is not a clock reading. `now_s` is a `date` fork, so timing an uncontended  # acquire means two forks around one `mkdir`; on a loaded machine they  # straddle a second often enough that the log claimed a one-second wait for a  # lock nobody was holding (CI flake, run #2880). The clock is read only on the  # path that really waited. `waited_on` is the label this call queued BEHIND —  # the first holder (or claim) it saw, which is the one it actually waited for.  while :; do    # A caller queues behind every waiting claim that outranks it — a local    # run behind releases and check jobs, a check job behind releases — lock    # free or not.    if claim="$(live_claim)"; then      claim_on="$(sed -n 1p <<<"$claim")"      [ -n "$wait_started" ] || wait_started="$(now_s)"      [ -n "$waited_on" ] || waited_on="$(sed -n 2p <<<"$claim")"      if [ "$announced" -eq 0 ]; then        log "$claim_on goes first — waiting for it…"        announced=1      fi      held_tick "$claim_on (it outranks '$LABEL')"      # A check job or a walk keeps its own claim filed while it defers, so no      # local run slips in between the claim above it and it; a local run files      # its waiting marker.      [ "$CLAIMED" -eq 0 ] && file_claim      if [ "$CLASS" = local ]; then nap "$POLL_S"; else nap "$CI_POLL_S"; fi      continue    fi    try_acquire && break    [ -n "$wait_started" ] || wait_started="$(now_s)"    [ "$CLAIMED" -eq 0 ] && file_claim    holder_pid="$(cat "$LOCK_DIR/pid" 2>/dev/null || true)"    holder_label="$(cat "$LOCK_DIR/label" 2>/dev/null || echo unknown)"    # THE LOCK IS A `mkdir`, AND ITS LABEL IS WRITTEN A MOMENT LATER. A waiter    # that looks between the two finds a held lock with no label yet; taking    # that look as final recorded a wait on `unknown` behind a holder that had    # a name (CI flake, verify-main run 2904). So an unlabelled lock is read    # again for up to half a second, and `unknown` is never what is latched    # while a later look can still learn the name.    if [ "$holder_label" = unknown ] && [ -d "$LOCK_DIR" ]; then      for _ in 1 2 3 4 5; do        sleep 0.1        holder_label="$(cat "$LOCK_DIR/label" 2>/dev/null || echo unknown)"        [ "$holder_label" = unknown ] || break      done    fi    if [ -z "$waited_on" ] || [ "$waited_on" = unknown ]; then waited_on="$holder_label"; fi    if [ "$announced" -eq 0 ]; then      if [ "$CLAIMED" -eq 1 ] && [ "$CLASS" = release ]; then        log "waiting for '$holder_label' (pid ${holder_pid:-?}) to finish building — claimed as a release, a check job or local run yields to it…"      elif [ "$CLAIMED" -eq 1 ] && [ "$CLASS" = walk ]; then        log "waiting for '$holder_label' (pid ${holder_pid:-?}) to finish building — claimed as a walk, it goes next and a local run waits behind it…"      elif [ "$CLAIMED" -eq 1 ] && [ "$CLASS" = ci ]; then        log "waiting for '$holder_label' (pid ${holder_pid:-?}) to finish building — claimed as a check job, a local run yields to it…"      else        log "waiting for '$holder_label' (pid ${holder_pid:-?}) to finish building…"      fi      announced=1    fi    held_tick "'$holder_label' (pid ${holder_pid:-?})" "$holder_pid"    if [ "$CLASS" != local ]; then nap "$CI_POLL_S"; else nap "$POLL_S"; fi  done  HOLDING=1  drop_claim  held_end  # The wait ended at the ACQUIRE above, not after the bookkeeping below it.  if [ -n "$wait_started" ]; then    waited=$(( $(now_s) - wait_started ))  else    waited=0  fi  echo "$$" > "$LOCK_DIR/pid"  echo "$LABEL" > "$LOCK_DIR/label"  echo "$CLASS" > "$LOCK_DIR/class"  echo "${BUILD_LOCK_CEILING_SECONDS:-$(( MAX_MIN * 60 ))}" > "$LOCK_DIR/ceiling_s"  # Record the actual target before the command starts: an explicit target  # beats config, and a generated worktree config also works on detached HEAD.  # Sweeps read its basename to spare both live holders' build output.  local lock_here lock_branch lock_target config  lock_here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"  lock_target="${CARGO_TARGET_DIR:-}"  if [ -z "$lock_target" ]; then    for config in "$lock_here/../crates/.cargo/config.toml" "$lock_here/../.cargo/config.toml"; do      [ -f "$config" ] || continue      lock_target="$(sed -n 's/^[[:space:]]*target-dir[[:space:]]*=[[:space:]]*"\(.*\)"[[:space:]]*$/\1/p' "$config" | head -1)"      [ -z "$lock_target" ] || break    done  fi  if [ -z "$lock_target" ] && lock_branch="$(git -C "$lock_here/.." rev-parse --abbrev-ref HEAD 2>/dev/null)" \    && [ -n "$lock_branch" ] && [ "$lock_branch" != HEAD ] \    && [ -f "$lock_here/ci/cargo-target-dir.sh" ]; then    lock_target="$(bash "$lock_here/ci/cargo-target-dir.sh" "$lock_branch" 2>/dev/null || true)"  fi  [ -z "$lock_target" ] || basename "$lock_target" > "$LOCK_DIR/target" 2>/dev/null  # A run that YIELDED queued behind the job it yielded to, whatever the looks  # above caught: a check job that takes and gives the lock back between two  # polls leaves no label to read.  if [ "$waited_on" = unknown ] && [ -n "$YIELDED_LABEL" ]; then waited_on="$YIELDED_LABEL"; fi  record_wait "$waited" "$waited_on"  log "acquired by '$LABEL'"}# ── The wrapped command ─────────────────────────────────────────────────────CMD_PID=""CMD_GROUP=0CMD_TREE=""# Every descendant of $1, one pid a line.descendants() {  local child  for child in $(pgrep -P "$1" 2>/dev/null); do    echo "$child"    descendants "$child"  done}# Is any pid written to `$CMD_TREE` still alive?tree_alive() {  local pid  for pid in $(sort -u "$CMD_TREE" 2>/dev/null); do    kill -0 "$pid" 2>/dev/null && return 0  done  return 1}# Signal the command — its whole process group when it has one, because a# `cargo test` TERMed alone leaves its rustc and test binaries running, and a# yield that leaves them running has yielded nothing.## A CHECK JOB'S COMMAND HAS NO GROUP OF ITS OWN: it stays in the runner step's# group, so a cancel the runner sends to that group still reaches every process# of it. It is signalled as a TREE instead — every descendant, written to# `$CMD_TREE` so the KILL after the grace reaches the ones the leader's exit# re-parented away.signal_command() {  local sig="$1" pid  [ -n "$CMD_PID" ] || return 0  if [ -n "$CMD_TREE" ]; then    { echo "$CMD_PID"; descendants "$CMD_PID"; } >>"$CMD_TREE" 2>/dev/null    for pid in $(sort -u "$CMD_TREE" 2>/dev/null); do      kill "-$sig" "$pid" 2>/dev/null || true    done  elif [ "$CMD_GROUP" -eq 1 ]; then    kill "-$sig" -- "-$CMD_PID" 2>/dev/null || kill "-$sig" "$CMD_PID" 2>/dev/null || true  else    kill "-$sig" "$CMD_PID" 2>/dev/null || true  fi}# THIS WRAPPER STOPPED — see "NOTHING WAITS WITHOUT A LINE". Its own watchers# and nap go first, then the command's whole tree: every pid in it is written# down BEFORE the TERM (a leader that exits re-parents its children away), is# TERMed, gets TERM_GRACE_S to end, and whatever is left is KILLed. Only then# does the EXIT trap release the lock and the claim; the ledger read after it# drops the reservation of any policy process the KILL took.STOPPING=0WATCHDOG_PID=""WATCHER_PID=""stop_command() {  local pid waited_s=0 tree alive=0  [ -n "$CMD_PID" ] || return 0  tree="$(mktemp "${TMPDIR:-/tmp}/build-lock-stop.XXXXXX")"  { echo "$CMD_PID"; descendants "$CMD_PID"; } >"$tree" 2>/dev/null  if [ "$CMD_GROUP" -eq 1 ]; then kill -TERM -- "-$CMD_PID" 2>/dev/null || true; fi  for pid in $(sort -u "$tree"); do kill -TERM "$pid" 2>/dev/null || true; done  while :; do    # A process the tree forks while it winds down is part of it too.    for pid in $(sort -u "$tree"); do descendants "$pid"; done >>"$tree" 2>/dev/null    alive=0    for pid in $(sort -u "$tree"); do kill -0 "$pid" 2>/dev/null && { alive=1; break; }; done    [ "$alive" -eq 1 ] && [ "$waited_s" -lt "$TERM_GRACE_S" ] || break    nap 1    waited_s=$(( waited_s + 1 ))  done  if [ "$alive" -eq 1 ]; then    log "the build tree of '$LABEL' outlived ${TERM_GRACE_S}s after TERM — KILLing it"    if [ "$CMD_GROUP" -eq 1 ]; then kill -KILL -- "-$CMD_PID" 2>/dev/null || true; fi    for pid in $(sort -u "$tree"); do kill -KILL "$pid" 2>/dev/null || true; done  fi  # Reap the leader so its pid is gone, not a zombie, when the ledger is read.  wait "$CMD_PID" 2>/dev/null || true  rm -f -- "$tree"  CMD_PID=""}on_signal() {  [ "$STOPPING" -eq 0 ] || return 0  STOPPING=1  log "stopped by $2 — stopping '$LABEL' and releasing what it holds"  local w  for w in $SLEEP_PID $WATCHDOG_PID $WATCHER_PID; do    pkill -P "$w" >/dev/null 2>&1 || true    kill "$w" 2>/dev/null || true  done  stop_command  exit "$1"}release_all() {  held_end  drop_claim  release_lock  if [ "$(cat "$ADMISSION_DIR/pid" 2>/dev/null)" = "$$" ]; then rm -rf "$ADMISSION_DIR"; fi  # A killed policy process left its row; this read drops it now.  if [ "$STOPPING" -eq 1 ] && [ "$(uname -s)" = Darwin ]; then    python3 "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib/mac_disk_policy.py" --prune >/dev/null 2>&1 || true  fi}trap release_all EXITtrap 'on_signal 130 INT' INTtrap 'on_signal 143 TERM' TERMtrap 'on_signal 129 HUP' HUP# A LOCAL RUN'S (OR A WALK'S) COMMAND, at nice 19 — see "CHECK JOBS GO FIRST". `nice -n` is# an INCREMENT, and Linux clamps it at 19 but macOS at 20: a caller already# niced (a lane's shell at 5, a runner at 15) went to 20 on a Mac, behind even# the work it was meant to sit beside, and the guard went red (run 5510). So the# increment is what takes this process TO the level, and a caller already there# or beyond stays where it is. `BUILD_LOCK_LOCAL_NICE=0` turns it off.NICE_PREFIX=()if { [ "$CLASS" = local ] || [ "$CLASS" = walk ]; } && [ "$LOCAL_NICE" -gt 0 ]; then  current_nice="$(python3 "$PROCESS_POLICY" --process-info nice "$$")" || exit 2  [[ "$current_nice" =~ ^-?[0-9]+$ ]] || current_nice=0  if [ $((LOCAL_NICE - current_nice)) -gt 0 ]; then    NICE_PREFIX=(nice -n "$((LOCAL_NICE - current_nice))")  fifi# ONE ATTEMPT AT THE COMMAND. With no ceiling and nothing to yield to — a check# job, or a local run that declared it never yields — it runs in the foreground# exactly as it always has: one process, one exit status, nothing between it# and the caller.## Otherwise it runs in the BACKGROUND with watchers beside it, and `wait` is# what returns the status, so a command that finishes early is not slowed by a# millisecond and the watchers are killed unread:##   - the CEILING watchdog is a single `sleep`: it wakes once, at the deadline,#     writes down that it was IT that ended the command, and signals. TERM#     first (xcodebuild and cargo both clean up on it), KILL 30 s later.#   - the YIELD watcher looks for a live claim every few seconds; on one it#     writes down whose and TERMs the command's group. The grace and the KILL#     after it are the main shell's, below `wait`.## A yielding command gets its OWN PROCESS GROUP (`set -m` for the one fork), so# a yield takes the whole tree. Its stdin is /dev/null when ours is a terminal:# a background group that reads the terminal is stopped by the kernel, and a# stopped verify holds the lock for ever. A piped stdin is passed through.## `>/dev/null 2>&1` on each watcher IS LOAD-BEARING, not tidiness. A background# subshell inherits this script's stdout, and so does the `sleep` inside it —# so a caller reading our output to EOF (every CI step, every `$( )`) would# block until the watcher's sleep ended. Measured while writing the ceiling's# guard.YIELDED_TO=""run_once() {  local ceiling_s fired yielded watchdog_pid="" watcher_pid="" st grace waited_s w on  YIELDED_TO=""  if [ "$MAX_MIN" -le 0 ] && [ "$YIELDS" -eq 0 ]; then    # In the background and waited on, never in the foreground: bash holds a    # trap until a foreground child exits, and that is how cut #2's wrapper    # kept the lock through a TERM. Our stdin is handed on explicitly — an    # asynchronous command's stdin is otherwise /dev/null.    ${NICE_PREFIX[@]+"${NICE_PREFIX[@]}"} "$@" <&0 &    CMD_PID=$!    CMD_GROUP=0    wait "$CMD_PID"    st=$?    CMD_PID=""    return "$st"  fi  fired="$(mktemp "${TMPDIR:-/tmp}/build-lock-ceiling.XXXXXX")"  yielded="$(mktemp "${TMPDIR:-/tmp}/build-lock-yield.XXXXXX")"  rm -f "$fired" "$yielded"  if [ "$YIELDS" -eq 1 ] && [ "$CLASS" = ci ]; then    CMD_TREE="$(mktemp "${TMPDIR:-/tmp}/build-lock-tree.XXXXXX")"    ${NICE_PREFIX[@]+"${NICE_PREFIX[@]}"} "$@" &    CMD_PID=$!    CMD_GROUP=0  elif [ "$YIELDS" -eq 1 ]; then    set -m    if [ -t 0 ]; then      ${NICE_PREFIX[@]+"${NICE_PREFIX[@]}"} "$@" </dev/null &    else      ${NICE_PREFIX[@]+"${NICE_PREFIX[@]}"} "$@" &    fi    CMD_PID=$!    set +m    CMD_GROUP=1  else    ${NICE_PREFIX[@]+"${NICE_PREFIX[@]}"} "$@" &    CMD_PID=$!    CMD_GROUP=0  fi  if [ "$MAX_MIN" -gt 0 ]; then    # SECONDS, so the guard can drive a real ceiling without waiting a minute    # for it. Nothing in CI sets it; `BUILD_LOCK_MAX_MIN` is the knob a lane    # declares.    ceiling_s="${BUILD_LOCK_CEILING_SECONDS:-$(( MAX_MIN * 60 ))}"    grace="${BUILD_LOCK_CEILING_GRACE_SECONDS:-30}"    log "ceiling: this command has ${MAX_MIN}m"    (      sleep "$ceiling_s"      kill -0 "$CMD_PID" 2>/dev/null || exit 0      : > "$fired"      signal_command TERM      sleep "$grace"      signal_command KILL    ) >/dev/null 2>&1 &    watchdog_pid=$!    WATCHDOG_PID=$watchdog_pid  fi  if [ "$YIELDS" -eq 1 ]; then    (      while kill -0 "$CMD_PID" 2>/dev/null; do        if on="$(live_claim ${PREEMPTED_BY[@]+"${PREEMPTED_BY[@]}"})"; then          sed -n 1p <<<"$on" > "$yielded"          signal_command TERM          exit 0        fi        sleep "$YIELD_POLL_S"      done    ) >/dev/null 2>&1 &    watcher_pid=$!    WATCHER_PID=$watcher_pid  fi  wait "$CMD_PID"  st=$?  # The subshells AND the `sleep` each is blocked in: killing only the parent  # leaves an orphan sleeping for the rest of its interval.  for w in $watchdog_pid $watcher_pid; do    pkill -P "$w" >/dev/null 2>&1 || true    kill "$w" 2>/dev/null || true    wait "$w" 2>/dev/null || true  done  WATCHDOG_PID=""  WATCHER_PID=""  # `wait` returns when the group's LEADER exits; its children may still be  # dying. Give them the grace, then KILL whatever is left — the lock is about  # to change hands, and it must not change hands under a live rustc.  if [ "$CMD_GROUP" -eq 1 ]; then    waited_s=0    while kill -0 -- "-$CMD_PID" 2>/dev/null && [ "$waited_s" -lt "$YIELD_GRACE_S" ]; do      sleep 1      waited_s=$(( waited_s + 1 ))    done    kill -KILL -- "-$CMD_PID" 2>/dev/null || true  fi  # A check job's tree, the same way: only when a yield or a ceiling signalled  # it is anything written down to wait on.  if [ -n "$CMD_TREE" ]; then    if [ -s "$CMD_TREE" ]; then      waited_s=0      while tree_alive && [ "$waited_s" -lt "$YIELD_GRACE_S" ]; do        sleep 1        waited_s=$(( waited_s + 1 ))      done      signal_command KILL    fi    rm -f "$CMD_TREE"    CMD_TREE=""  fi  CMD_PID=""  CMD_GROUP=0  if [ -f "$yielded" ]; then    YIELDED_TO="$(head -n 1 "$yielded")"    rm -f "$yielded" "$fired"    return 0  fi  rm -f "$yielded"  if [ -f "$fired" ]; then    rm -f "$fired"    log "CEILING: '$LABEL' ran past ${MAX_MIN}m and was stopped — the lock is being released"    log "         (a lane that really needs longer raises BUILD_LOCK_MAX_MIN on its own step;"    log "          a lane that used to fit and no longer does is a wedge, not a slow build)"    return 124  fi  return "$st"}acquire# The marker every nested call reads. Exported here and nowhere else; the pid# is this process's for every attempt, so it holds across a yield.export TINMEN_BUILD_LOCK_EXCLUSIVE="$EXCLUSIVE"export TINMEN_BUILD_LOCK_HELD="$$"export TINMEN_BUILD_LOCK_DIR="$BASE_LOCK_DIR"export TINMEN_BUILD_LOCK_LABEL="$LABEL"attempt=1while :; do  prepare_command "$@"  run_once "${GUARDED_COMMAND[@]}"  status=$?  [ -n "$YIELDED_TO" ] || break  log "YIELDED: $YIELDED_TO needs this machine — '$LABEL' was stopped (attempt $attempt)"  log "         and starts again from the top when the jobs ranked above it are done"  release_lock  attempt=$(( attempt + 1 ))  YIELDED_LABEL="$(sed -n "s/^[^']*'\(.*\)'$/\1/p" <<<"$YIELDED_TO")"  acquiredonelog "released by '$LABEL' (exit $status)"exit "$status"