#!/usr/bin/env bash# THE DAILY SWEEP: BUILD OUTPUT NOBODY HAS TOUCHED FOR 3 DAYS, AND NOBODY HAS# OPEN, GOES — ON EVERY MACHINE.## scripts/daily-sweep.sh [--if-due] [--dry-run] [--home DIR]... [--tmp DIR]...# [--seats DIR]... [--cap DIR=SIZE]... [--sccache DIR=SIZE]...# [--lanes DIR]... [--no-tmp]## --no-tmp sweeps no scratch root at all (by default /tmp): the lanes account's# own nightly run leaves /tmp to the root# timer, which sees every account's leftovers there.## On 29 Sep 2026 all four Macs and the Linux box reached the 60 GB disk floor.# The sweeps that existed each watched one folder against an age or a budget,# and between them a week of build output lay where nothing looked: check jobs'# work folders, launch-smoke runs, cargo targets left in /tmp, the seat image on# the Linux box. This one looks everywhere build output lands, once a day.## WHAT IS BUILD OUTPUT. Each child of these, as one candidate:# <home>/.cache/cottondb/{cargo-target,rust/targets,derived,ios-smoke}/*# <home>/CottonDB/runs/work/* a Mac check job's work folder — the# runner leaves one behind when its job is# cut off, and nothing else removes it# and, under each --tmp and --seats root, any directory that says it is a cache# (a `CACHEDIR.TAG`, which cargo writes into every target directory), an Xcode# `DerivedData*` or `*.xcarchive`, or a release or install copy# (`cotton-install-*`, `CottonDB*.zip`, `CottonDB*.app`).## WHAT GOES. A candidate is removed only when ALL hold:# - nothing in it was modified in the last 3 days (COTTON_SWEEP_DAYS);# - no process has it open or works in it (`lsof +D`; without lsof, nothing# can be proven idle and nothing goes);# - it is not the target the live build-lock holder is building, nor one a# job's cargo lock (`<dir>.lock`, flock / `.lock.d/pid`) holds;# - it is a real directory (never a symlink) and not under anything below.## WHAT NEVER GOES, WHATEVER ITS AGE: the relay (/srv/cotton-relay), a# credential (any path naming credential, secret, token, keychain or `.ssh`),# a database (a candidate holding a `*.db`, `*.sqlite*` or `*.db-wal` is kept# whole), CottonDB's data folder outside `runs/work`, and the build lock itself.## THEN, on each --seats root, `fstrim` — the seat image on the Linux box is a# sparse file, and space freed inside it returns to the host disk only when it# is trimmed. Needs root; without it the sweep says so and goes on.## THEN, NIGHTLY CAPS ON THE SHARED CACHES (19 Nov 2026: the owner's disks# filled while every entry was younger than 3 days). Over its cap, a cache# loses its least recently used entries until it fits, each one judged as# above but for its age:# <home>/.cache/cottondb/cargo-target/* COTTON_CAP_CARGO_TARGET (120G)# <home>/.cache/cottondb/derived/* COTTON_CAP_DERIVED (60G)# <home>/Library/Developer/Xcode/DerivedData/* COTTON_CAP_XCODE (40G)# --cap DIR=SIZE, each child of DIR one entry (a Mac's cargo target root off# the home disk, a lane machine's own shared cache)# sccache: the account's own (~/.cache/sccache, ~/Library/Caches/# Mozilla.sccache) at COTTON_CAP_SCCACHE (15G, ensure-sccache-cap's), and# each --sccache DIR=SIZE, its oldest-read files first, none written in the# last hour (sccache takes a missing file as a miss). The box's# /srv/sccache is the CI runner's as much as the lanes', so it is not# capped here: SCCACHE_CACHE_SIZE holds it.# A SIZE is 120G or 500M; a bare number is GB.# A home under /srv/forgejo-runner is never capped: the runner's caches are the# runner's (its own steps size them). The shared cargo target stays protected.## THEN, LANES NOBODY WORKS IN: each --lanes ROOT, as# the root's owner, has its finished lanes cleared as lane:stop clears them.# Without --lanes, a Mac reads its own lane root from the table of lane Macs.## THE ACCOUNT'S SCCACHE CAP is made sure of on each run# (`scripts/ensure-sccache-cap.sh`), so a builder's account carries one too.## THE REPORT. One TAB-separated line per directory removed —# <iso8601-Z>\t<host>\t<kilobytes>\t<path (why)># — appended to ~/.cache/cottondb/sweep.log (COTTON_SWEEP_REPORT), and a# closing line with the total. `--if-due` makes it a no-op unless 20 hours have# passed since the last run, so the disk guard (every 6 hours on the Macs)# can call it and it still runs once a day. On the Linux box a root timer runs# it.## Guard: the daily-sweep test.set -uo pipefailHERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"# A systemd unit starts this with no HOME (the root timer on the Linux box did,# and every night died on the line below); bash's ~ then reads the account's home.[ -n "${HOME:-}" ] || HOME=~DAYS="${COTTON_SWEEP_DAYS:-3}"CACHE="${COTTON_CACHE_ROOT:-$HOME/.cache/cottondb}"REPORT="${COTTON_SWEEP_REPORT:-$CACHE/sweep.log}"STAMP="${COTTON_SWEEP_STAMP:-$CACHE/.daily-sweep-stamp}"BUILD_LOCK_DIR="${BUILD_LOCK_DIR:-/tmp/tinmen-build.lock}"HOST="$(hostname -s 2>/dev/null || hostname)"IF_DUE=0DRY=0HOMES=()TMPS=()SEATS=()CAPS=()SCCACHES=()LANES=()NO_TMP=0while [ $# -gt 0 ]; docase"$1"in --if-due) IF_DUE=1 ;; --dry-run) DRY=1 ;; --home) HOMES+=("$2"); shift ;; --tmp) TMPS+=("$2"); shift ;; --seats) SEATS+=("$2"); shift ;; --cap) CAPS+=("$2"); shift ;; --sccache) SCCACHES+=("$2"); shift ;; --lanes) LANES+=("$2"); shift ;; --no-tmp) NO_TMP=1 ;; *) echo "usage: daily-sweep.sh [--if-due] [--dry-run] [--home DIR]... [--tmp DIR]... [--seats DIR]... [--cap DIR=SIZE]... [--sccache DIR=SIZE]... [--lanes DIR]... [--no-tmp]" >&2; exit2 ;;esacshiftdone[ ${#HOMES[@]} -gt 0 ] || HOMES=("$HOME")if [ ${#TMPS[@]} -eq 0 ] && [ "$NO_TMP" -eq 0 ]; then TMPS=(/tmp) [ -d /private/tmp ] && TMPS=(/private/tmp)fi# A scratch root is searched for build output to remove: never a home folder,# anything above one, or the folder installed apps live in.# shellcheck source=/dev/null. "$HERE/lib/owned-root.sh"for pair in ${CAPS[@]+"${CAPS[@]}"} ${SCCACHES[@]+"${SCCACHES[@]}"}; do [[ "$pair" =~ ^(/.+)=([0-9]+[GM]?)$ ]] || { echo "REFUSED: a cap is DIR=SIZE (120G, 500M; a bare number is GB) with an absolute DIR, not '$pair'" >&2; exit2; } refuse_wide_root "a capped cache (--cap / --sccache)""${BASH_REMATCH[1]}"donefor lanes_root in ${LANES[@]+"${LANES[@]}"}; do refuse_wide_root "a lane root (--lanes)""$lanes_root"donefor scratch_root in ${TMPS[@]+"${TMPS[@]}"} ${SEATS[@]+"${SEATS[@]}"}; do refuse_wide_root "a scratch root (--tmp / --seats)""$scratch_root"case"${scratch_root%/}"in /Applications | /Applications/* | */Applications | */Applications/*) echo "REFUSED: a scratch root (--tmp / --seats) is '$scratch_root' — installed apps live there, and this sweep removes CottonDB*.app copies." >&2exit2 ;;esacdonelog() { echo "[daily-sweep] $*"; }if [ "$IF_DUE" -eq 1 ] && [ -f "$STAMP" ] && [ -z "$(find "$STAMP" -mmin +1200 2>/dev/null)" ]; thenexit0fi# A dry run is not a sweep: it must not tell --if-due that today's is done.[ "$DRY" -eq 1 ] || { mkdir -p "$(dirname "$STAMP")"2>/dev/null && touch "$STAMP"2>/dev/null; }if ! command -v lsof >/dev/null 2>&1; then log "no lsof on this machine — nothing can be proven idle, so nothing is removed"exit0fi# Every live build slot's target name, if any. Detached worktrees and explicit# target directories are recorded by the lock from the caller's Cargo config.held_names=""for slot in"$BUILD_LOCK_DIR""${BUILD_LOCK_DIR}.slot-2"; do lock_pid="$(cat "$slot/pid" 2>/dev/null || true)"if [ -n "$lock_pid" ] && { kill -0"$lock_pid"2>/dev/null || ps -p "$lock_pid" >/dev/null 2>&1; }; then name="$(cat "$slot/target" 2>/dev/null || true)" [ -z "$name" ] || held_names="$held_names$name"$'\n'fidoneprotected() {if evidence_kept "$1"; thenreturn0; ficase"$1"in /srv/cotton-relay | /srv/cotton-relay/*) return0 ;; *[Cc]redential* | *[Ss]ecret* | *[Tt]oken* | *[Kk]eychain* | */.ssh | */.ssh/*) return0 ;; */tinmen-build.lock*) return0 ;; */.cache/cottondb/cargo-target/shared | */.cache/cottondb/rust/targets/shared) return0 ;; /Applications | /Applications/* | */Applications | */Applications/*) return0 ;; */CottonDB/runs/work/*) return1 ;; */CottonDB | */CottonDB/*) return0 ;;esacreturn1}cargo_lock_held() {local dir="$1" holderif [ -f "$dir.lock" ] && command -v flock >/dev/null 2>&1; then flock -n "$dir.lock" true 2>/dev/null || return0fiif [ -d "$dir.lock.d" ]; then holder="$(cat "$dir.lock.d/pid" 2>/dev/null || true)"case"$holder"in'' | *[!0-9]*) return0 ;; *) kill -0"$holder"2>/dev/null && return0 ;;esacfireturn1}freed=0removed=0kept=0AGE_RULE=1consider() {local dir="$1" why="$2" kb [ -d "$dir" ] || return0 [ -L "$dir" ] && return0if protected "$dir"; then kept=$((kept + 1)); return0; fiif [ "$AGE_RULE" -eq 1 ] && [ -n "$(find "$dir" -mtime "-$DAYS" -print -quit 2>/dev/null)" ]; thenreturn0; fiif [ -n "$held_names" ] && grep -qxF "$(basename "$dir")" <<<"$held_names"; then log "kept $dir — the build lock's holder is building it" kept=$((kept + 1)); return0fiif cargo_lock_held "$dir"; then log "kept $dir — a job holds its cargo lock" kept=$((kept + 1)); return0fiif [ -n "$(find "$dir" \( -name '*.db' -o -name '*.sqlite*' -o -name '*.db-wal' \) -print -quit 2>/dev/null)" ]; then log "kept $dir — it holds a database" kept=$((kept + 1)); return0fiif [ -n "$(lsof -t +D "$dir" 2>/dev/null | head -n 1)" ]; then log "kept $dir — a process has it open" kept=$((kept + 1)); return0fi kb="$(du -sk "$dir" 2>/dev/null | cut -f1)" kb="${kb:-0}"if [ "$DRY" -eq 1 ]; then log "would remove $dir ($(( kb / 1024 )) MB) — $why" freed=$(( freed + kb )); removed=$((removed + 1))return0fiif rm -rf "$dir"2>/dev/null && [ ! -e "$dir" ]; then freed=$(( freed + kb )); removed=$((removed + 1)) log "removed $dir ($(( kb / 1024 )) MB) — $why" { mkdir -p "$(dirname "$REPORT")" && printf '%s\t%s\t%s\t%s\n' \"$(date -u '+%Y-%m-%dT%H:%M:%SZ')""$HOST""$kb""$dir ($why)" >>"$REPORT"; } 2>/dev/null || trueelse log "could not remove all of $dir"fi}untouched="untouched for ${DAYS} days and open by no process"for home in"${HOMES[@]}"; dofor sub in cargo-target rust/targets derived ios-smoke; dofor dir in"$home/.cache/cottondb/$sub"/*/; do [ -d "$dir" ] && consider "${dir%/}""build output $untouched"donedonefor dir in"$home/CottonDB/runs/work"/*/; do [ -d "$dir" ] && consider "${dir%/}""a check job's work folder $untouched"donedone# Build output under a scratch root: a cache directory, DerivedData, an archive,# a release or install copy. The outermost match is the candidate — a# CACHEDIR.TAG inside one already chosen is not considered again.scratch_candidates() {local root="$1" { find "$root" -xdev -maxdepth 6 -name CACHEDIR.TAG -type f 2>/dev/null | sed 's#/CACHEDIR.TAG$##' find "$root" -xdev -maxdepth 4 -type d \( -name 'DerivedData*' -o -name '*.xcarchive' \ -o -name 'cotton-install-*' -o -name 'CottonDB*.app' \) -prune -print 2>/dev/null } | sort -u | awk 'NR == 1 || index($0, last "/") != 1 { print; last = $0 }'}for root in ${TMPS[@]+"${TMPS[@]}"} ${SEATS[@]+"${SEATS[@]}"}; do [ -d "$root" ] || continuewhile IFS= read -r dir; do [ -n "$dir" ] && [ "$dir" != "$root" ] && consider "$dir""build output in $root $untouched"done < <(scratch_candidates "$root")# A release zip is a file, not a directory.while IFS= read -r zip; do [ -n "$zip" ] || continue protected "$zip" && continue [ -n "$(lsof -t "$zip" 2>/dev/null | head -n 1)" ] && continue kb="$(du -sk "$zip" 2>/dev/null | cut -f1)"if [ "$DRY" -eq 1 ] || rm -f "$zip"2>/dev/null; then freed=$(( freed + ${kb:-0} )); removed=$((removed + 1)) log "$([ "$DRY" -eq 1 ] && echo 'would remove' || echo removed) $zip — a release copy $untouched" [ "$DRY" -eq 1 ] || { printf '%s\t%s\t%s\t%s\n'"$(date -u '+%Y-%m-%dT%H:%M:%SZ')""$HOST""${kb:-0}" \"$zip (a release copy)" >>"$REPORT"; } 2>/dev/null || truefidone < <(find "$root" -xdev -maxdepth 2 -type f -name 'CottonDB*.zip' -mtime "+$DAYS"2>/dev/null)donefor seat in ${SEATS[@]+"${SEATS[@]}"}; do [ -d "$seat" ] || continueif [ "$DRY" -eq 1 ]; then log "would fstrim $seat"elif [ "$(id -u)" -eq 0 ] && command -v fstrim >/dev/null 2>&1; then log "fstrim $seat: $(fstrim -v "$seat" 2>&1 | tail -n 1)"else log "fstrim $seat skipped — it needs root"fidone# THE CAPS. `cap_children DIR GB WHY`: over GB, DIR's children go least# recently used first (the newest mtime in their top three levels), each judged# by `consider` without its age rule, until DIR fits.kb_of() { local kb; kb="$(du -sk "$1" 2>/dev/null | cut -f1)"; echo "${kb:-0}"; }# A cap's size in KB: 120G, 500M, or a bare number of GB.cap_kb() {case"$1"in *M) echo $(( ${1%M} * 1024 )) ;; *G) echo $(( ${1%G} * 1024 * 1024 )) ;; *) echo $(( $1 * 1024 * 1024 )) ;;esac}mb() { echo "$(( $1 / 1024 )) MB"; }# Portable to the Macs' BSD tools: python3 is on every machine this runs on.# Each real child directory of $1, least recently used first (the newest mtime# in its top three levels), never following a link.lru_children() { python3 - "$1" <<'PY'import os, sysroot = sys.argv[1]def newest(top): best = os.lstat(top).st_mtimefor path, dirs, files in os.walk(top): depth = path[len(top):].count(os.sep)if depth >= 3: dirs[:] = []for name in dirs + files: try: best = max(best, os.lstat(os.path.join(path, name)).st_mtime) except OSError: passreturn bestrows = []for name in os.listdir(root): child = os.path.join(root, name)if os.path.isdir(child) and not os.path.islink(child): rows.append((newest(child), child))for _, child in sorted(rows): print(child)PY}# Every file under $1 not written in the last hour and not a lock, as# "<last read>\t<KB>\t<path>", oldest read first, staying on its filesystem.oldest_read_files() { python3 - "$1" <<'PY'import os, sys, timeroot = sys.argv[1]; dev = os.lstat(root).st_dev; hour = time.time() - 3600rows = []for path, dirs, files in os.walk(root): dirs[:] = [d for d in dirs if not os.path.islink(os.path.join(path, d)) and os.lstat(os.path.join(path, d)).st_dev == dev]for name in files:if name.endswith('.lock'): continue full = os.path.join(path, name) try: st = os.lstat(full) except OSError: continueif os.path.islink(full) or st.st_mtime > hour: continue rows.append((st.st_atime, (st.st_blocks * 512) // 1024, full))for at, kb, full in sorted(rows): print(f"{at:.0f}\t{kb}\t{full}")PY}cap_children() {local dir="$1" gb="$2" why="$3" total limit child kb before [ -d "$dir" ] && [ ! -L "$dir" ] || return0 total="$(kb_of "$dir")"; limit="$(cap_kb "$gb")"if [ "$total" -le "$limit" ]; then log "$dir holds $(mb "$total"), within its $gb cap"; return0fi log "$dir holds $(mb "$total"), over its $gb cap" AGE_RULE=0while IFS= read -r child; do [ "$total" -gt "$limit" ] || break kb="$(kb_of "$child")"; before="$removed" consider "$child""$why, least recently used, while $dir was over its $gb cap" [ "$removed" -gt "$before" ] && total=$(( total - kb ))done < <(lru_children "$dir") AGE_RULE=1 [ "$total" -le "$limit" ] || log "$dir is still over its $gb cap: what is left is in use or protected"}# `cap_sccache DIR GB`: over GB, DIR's oldest-read files go (none written in the# last hour) until it fits. sccache reads a missing entry as a miss.cap_sccache() {local dir="$1" gb="$2" total limit freed_kb=0 n=0 at kb file [ -d "$dir" ] && [ ! -L "$dir" ] || return0 total="$(kb_of "$dir")"; limit="$(cap_kb "$gb")"if [ "$total" -le "$limit" ]; then log "sccache $dir holds $(mb "$total"), within its $gb cap"; return0fiwhile IFS=$'\t' read -r at kb file; do [ $(( total - freed_kb )) -gt "$limit" ] || breakif [ "$DRY" -eq 1 ] || rm -f "$file"2>/dev/null; then freed_kb=$(( freed_kb + kb )); n=$(( n + 1 )); fidone < <(oldest_read_files "$dir") freed=$(( freed + freed_kb )) log "$([ "$DRY" -eq 1 ] && echo 'would trim' || echo trimmed) sccache $dir by $(mb "$freed_kb") in $n files, oldest read first, to its $gb cap" [ "$DRY" -eq 1 ] || { printf '%s\t%s\t%s\t%s\n'"$(date -u '+%Y-%m-%dT%H:%M:%SZ')""$HOST""$freed_kb" \"$dir (sccache over its $gb cap, $n files)" >>"$REPORT"; } 2>/dev/null || true}for home in"${HOMES[@]}"; docase"$home"in /srv/forgejo-runner | /srv/forgejo-runner/*) continue ;; esac cap_children "$home/.cache/cottondb/cargo-target""${COTTON_CAP_CARGO_TARGET:-120G}""a cargo target" cap_children "$home/.cache/cottondb/derived""${COTTON_CAP_DERIVED:-60G}""derived data" cap_children "$home/Library/Developer/Xcode/DerivedData""${COTTON_CAP_XCODE:-40G}""Xcode's derived data"for sc in"$home/.cache/sccache""$home/Library/Caches/Mozilla.sccache"; do cap_sccache "$sc""${COTTON_CAP_SCCACHE:-15G}"donedonefor pair in ${CAPS[@]+"${CAPS[@]}"}; do cap_children "${pair%=*}""${pair##*=}""a shared cache's entry"donefor pair in ${SCCACHES[@]+"${SCCACHES[@]}"}; do cap_sccache "${pair%=*}""${pair##*=}"done# LANES NOBODY WORKS IN. A Mac with no --lanes names its own root in lane-macs.json.if [ ${#LANES[@]} -eq 0 ] && [ -f "$HERE/lane-macs.json" ] && command -v python3 >/dev/null 2>&1; then own_root="$(python3 -c 'import json,sysrows=json.load(open(sys.argv[1]))["macs"]for key,row in rows.items():if sys.argv[2] in (key, row.get("hostname")) and row.get("kind","mac")=="mac": print(row["root"]); break' "$HERE/lane-macs.json" "$HOST" 2>/dev/null)" [ -n "$own_root" ] && [ -d "$own_root" ] && LANES=("$own_root")fifor lanes_root in ${LANES[@]+"${LANES[@]}"}; do [ -d "$lanes_root" ] && [ -f "$HERE/lane-sweep.sh" ] || { log "no lane sweep for $lanes_root (missing, or lane-sweep.sh is not beside this script)"; continue; } dry=(); [ "$DRY" -eq 1 ] && dry=(--dry-run)if [ "$(id -u)" -ne 0 ]; then bash "$HERE/lane-sweep.sh" --root "$lanes_root" ${dry[@]+"${dry[@]}"} 2>&1 | sed 's/^/[daily-sweep] /' || trueelif command -v runuser >/dev/null 2>&1; then owner="$(stat -c %U "$lanes_root" 2>/dev/null || true)" [ -n "$owner" ] && [ "$owner" != root ] || { log "no lane sweep for $lanes_root: it is root's, and lanes are never swept as root"; continue; } runuser -u "$owner" -- env HOME="$(getent passwd "$owner" | cut -d: -f6)" \ bash "$HERE/lane-sweep.sh" --root "$lanes_root" ${dry[@]+"${dry[@]}"} 2>&1 | sed "s/^/[daily-sweep] $owner: /" || truefidone# Each swept account's sccache cap — as that account, never as root.if [ -f "$HERE/ensure-sccache-cap.sh" ] && [ "$DRY" -eq 0 ]; thenif [ "$(id -u)" -ne 0 ]; then bash "$HERE/ensure-sccache-cap.sh" | sed 's/^/[daily-sweep] /' || trueelif command -v runuser >/dev/null 2>&1; thenfor home in"${HOMES[@]}"; do owner="$(stat -c %U "$home" 2>/dev/null || true)" [ -n "$owner" ] && [ "$owner" != root ] || continue runuser -u "$owner" -- env HOME="$home" XDG_CONFIG_HOME="$home/.config" \ bash "$HERE/ensure-sccache-cap.sh"2>&1 | sed "s/^/[daily-sweep] $owner: /" || truedonefifilog "freed $(( freed / 1024 )) MB in $removed director$([ "$removed" -eq 1 ] && echo y || echo ies); kept $kept in use or protected"[ "$DRY" -eq 1 ] || { printf '%s\t%s\t%s\t%s\n'"$(date -u '+%Y-%m-%dT%H:%M:%SZ')""$HOST""$freed" \"TOTAL ($removed removed, $kept kept)" >>"$REPORT"; } 2>/dev/null || trueexit0