#!/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: # /.cache/cottondb/{cargo-target,rust/targets,derived,ios-smoke}/* # /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 (`.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: # /.cache/cottondb/cargo-target/* COTTON_CAP_CARGO_TARGET (120G) # /.cache/cottondb/derived/* COTTON_CAP_DERIVED (60G) # /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 — # \t\t\t # — 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 pipefail HERE="$(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=0 DRY=0 HOMES=() TMPS=() SEATS=() CAPS=() SCCACHES=() LANES=() NO_TMP=0 while [ $# -gt 0 ]; do case "$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; exit 2 ;; esac shift done [ ${#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; exit 2; } refuse_wide_root "a capped cache (--cap / --sccache)" "${BASH_REMATCH[1]}" done for lanes_root in ${LANES[@]+"${LANES[@]}"}; do refuse_wide_root "a lane root (--lanes)" "$lanes_root" done for 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." >&2 exit 2 ;; esac done log() { echo "[daily-sweep] $*"; } if [ "$IF_DUE" -eq 1 ] && [ -f "$STAMP" ] && [ -z "$(find "$STAMP" -mmin +1200 2>/dev/null)" ]; then exit 0 fi # 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" exit 0 fi # 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' fi done protected() { if evidence_kept "$1"; then return 0; fi case "$1" in /srv/cotton-relay | /srv/cotton-relay/*) return 0 ;; *[Cc]redential* | *[Ss]ecret* | *[Tt]oken* | *[Kk]eychain* | */.ssh | */.ssh/*) return 0 ;; */tinmen-build.lock*) return 0 ;; */.cache/cottondb/cargo-target/shared | */.cache/cottondb/rust/targets/shared) return 0 ;; /Applications | /Applications/* | */Applications | */Applications/*) return 0 ;; */CottonDB/runs/work/*) return 1 ;; */CottonDB | */CottonDB/*) return 0 ;; esac return 1 } cargo_lock_held() { local dir="$1" holder if [ -f "$dir.lock" ] && command -v flock >/dev/null 2>&1; then flock -n "$dir.lock" true 2>/dev/null || return 0 fi if [ -d "$dir.lock.d" ]; then holder="$(cat "$dir.lock.d/pid" 2>/dev/null || true)" case "$holder" in '' | *[!0-9]*) return 0 ;; *) kill -0 "$holder" 2>/dev/null && return 0 ;; esac fi return 1 } freed=0 removed=0 kept=0 AGE_RULE=1 consider() { local dir="$1" why="$2" kb [ -d "$dir" ] || return 0 [ -L "$dir" ] && return 0 if protected "$dir"; then kept=$((kept + 1)); return 0; fi if [ "$AGE_RULE" -eq 1 ] && [ -n "$(find "$dir" -mtime "-$DAYS" -print -quit 2>/dev/null)" ]; then return 0; fi if [ -n "$held_names" ] && grep -qxF "$(basename "$dir")" <<<"$held_names"; then log "kept $dir — the build lock's holder is building it" kept=$((kept + 1)); return 0 fi if cargo_lock_held "$dir"; then log "kept $dir — a job holds its cargo lock" kept=$((kept + 1)); return 0 fi if [ -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)); return 0 fi if [ -n "$(lsof -t +D "$dir" 2>/dev/null | head -n 1)" ]; then log "kept $dir — a process has it open" kept=$((kept + 1)); return 0 fi 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)) return 0 fi if 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 || true else log "could not remove all of $dir" fi } untouched="untouched for ${DAYS} days and open by no process" for home in "${HOMES[@]}"; do for sub in cargo-target rust/targets derived ios-smoke; do for dir in "$home/.cache/cottondb/$sub"/*/; do [ -d "$dir" ] && consider "${dir%/}" "build output $untouched" done done for dir in "$home/CottonDB/runs/work"/*/; do [ -d "$dir" ] && consider "${dir%/}" "a check job's work folder $untouched" done done # 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" ] || continue while 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 || true fi done < <(find "$root" -xdev -maxdepth 2 -type f -name 'CottonDB*.zip' -mtime "+$DAYS" 2>/dev/null) done for seat in ${SEATS[@]+"${SEATS[@]}"}; do [ -d "$seat" ] || continue if [ "$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" fi done # 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, sys root = sys.argv[1] def newest(top): best = os.lstat(top).st_mtime for 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: pass return best rows = [] 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 # "\t\t", oldest read first, staying on its filesystem. oldest_read_files() { python3 - "$1" <<'PY' import os, sys, time root = sys.argv[1]; dev = os.lstat(root).st_dev; hour = time.time() - 3600 rows = [] 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: continue if 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" ] || return 0 total="$(kb_of "$dir")"; limit="$(cap_kb "$gb")" if [ "$total" -le "$limit" ]; then log "$dir holds $(mb "$total"), within its $gb cap"; return 0 fi log "$dir holds $(mb "$total"), over its $gb cap" AGE_RULE=0 while 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" ] || return 0 total="$(kb_of "$dir")"; limit="$(cap_kb "$gb")" if [ "$total" -le "$limit" ]; then log "sccache $dir holds $(mb "$total"), within its $gb cap"; return 0 fi while IFS=$'\t' read -r at kb file; do [ $(( total - freed_kb )) -gt "$limit" ] || break if [ "$DRY" -eq 1 ] || rm -f "$file" 2>/dev/null; then freed_kb=$(( freed_kb + kb )); n=$(( n + 1 )); fi done < <(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[@]}"; do case "$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}" done done for pair in ${CAPS[@]+"${CAPS[@]}"}; do cap_children "${pair%=*}" "${pair##*=}" "a shared cache's entry" done for 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,sys rows=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") fi for 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] /' || true elif 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: /" || true fi done # Each swept account's sccache cap — as that account, never as root. if [ -f "$HERE/ensure-sccache-cap.sh" ] && [ "$DRY" -eq 0 ]; then if [ "$(id -u)" -ne 0 ]; then bash "$HERE/ensure-sccache-cap.sh" | sed 's/^/[daily-sweep] /' || true elif command -v runuser >/dev/null 2>&1; then for 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: /" || true done fi fi log "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 || true exit 0