#!/usr/bin/env python3 """One device floor for Mac workspaces, dependency caches and build output.""" import argparse import ctypes import errno import fnmatch from contextlib import contextmanager, ExitStack import fcntl import json import os import re import runpy from pathlib import Path import shutil import signal import stat import subprocess import sys import time def read_floor(path, policy_path): try: policy = json.loads(policy_path.read_text()) floor = policy['keepFreeBytes'] if type(floor) is not int or floor <= 0: raise ValueError('keepFreeBytes is not a positive byte count') if not 0 <= time.time() - policy['sampledAt'] <= 3 * 180: raise ValueError('the device floor reading is stale or in the future') # The reading is of the volume the app serves from — the home volume, # where its caches and DerivedData live — and that is the volume the # floor protects (architect, 21 Oct 2026). A build path on another # volume (the lanes SSD) is admitted when the home floor holds (callers # measure the home volume, floor_path) and its own volume holds at # least the floor: one floor, two volumes, no second reading. if policy['volumeId'] != volume(Path.home()): raise ValueError('the device reading belongs to another volume (not the home volume)') if volume(path) != volume(Path.home()): own = os.statvfs(path) own_free = own.f_bavail * own.f_frsize if own_free < floor: raise ValueError(f"the build's own volume ({path}) has {own_free} bytes free; this device keeps {floor} bytes free") print(f"device reading is for the home volume; the build's own volume has {own_free} bytes free", file=sys.stderr, flush=True) return floor except (OSError, ValueError, KeyError, TypeError) as error: raise RuntimeError(f"REFUSING TO START: the device's keep free reading is unavailable. scripts/dev/machine-row.sh publishes it every five minutes under the launchd agent com.cottondb.machine-row, and it has not on this Mac — install it with the machine-row installer ({policy_path}: {error})") from error def floor_path(path, policy_path): """The path the floor is measured on: the home volume (the reading's), so a build on another volume is admitted against the home floor.""" try: if volume(path) == volume(Path.home()): return path except OSError: return path return Path.home() def volume(path): """The device a path is on: the nearest folder above it that exists, for a cache not made yet.""" path = Path(path) while not path.exists() and path != path.parent: path = path.parent return path.stat().st_dev def unused(path): """Unknown ownership is never permission to reclaim a cache or target.""" try: command = ['lsof', '-t', '+D', str(path)] if path.is_dir() else ['lsof', '-t', str(path)] result = subprocess.run(command, capture_output=True, timeout=5) return result.returncode == 1 and not result.stdout and not result.stderr except (OSError, subprocess.TimeoutExpired): return False def safe_child(path, root): if path == root or path.is_symlink(): return False current = path while current != root: if current.is_symlink() or root not in current.parents: return False current = current.parent return not root.is_symlink() # A CUT LANE'S BUILD DIRECTORY: the persistent cargo # target, Swift scratch and derived data that let a cut rebuild only what # changed since the lane's previous cut. It is never an idle lane target and # never a shared cache: emptying it turns that lane's next cut into an # hour-long cold build. So it is the reclaim's LAST tier (`idle_cut_lanes`): # another flavour's lane, only while its `cut-leases/build-.lock` is free # and held by the reclaim for the removal, never a lane this process's cut # leases (COTTON_CUT_BUILD_LANES), and only for what everything before it left # short. The release tick cuts few apps; the other flavours' lanes are what a # hand cut left behind (coordinator, 19 Nov 2026). CUT_BUILD = '.cache/cottondb/cut-build' CUT_LANE = re.compile(r'[a-z]+(-[a-z]+)*-(mac|ios)') def idle_cut_lanes(home, protected=()): """Cut lanes' build directories a reclaim may take, least recently used first. Never this process's own cut lanes, a protected path, a symlink or a folder holding anything not this user's. Idleness is the lane lease, asked again at removal (`cut_lane_lease`).""" root = cut_build_root(home) if root.is_symlink() or not root.is_dir(): return [] own = set(os.environ.get('COTTON_CUT_BUILD_LANES', '').split()) found = [] for entry in survey_glob(root, '*'): if not CUT_LANE.fullmatch(entry.name) or entry.name in own or entry.is_symlink() or not entry.is_dir(): continue if not safe_child(entry, root) or is_protected(entry, protected): continue try: items = survey_tree(entry) if any(item.lstat().st_uid != os.getuid() for item in items): continue found.append((max([entry.lstat().st_mtime, *(item.lstat().st_mtime for item in items)]), entry)) except OSError: continue return [entry for _, entry in sorted(found, key=lambda lane: (lane[0], str(lane[1])))] @contextmanager def cut_lane_lease(home, lane): """Hold `cut-leases/build-.lock` exclusively for a removal; answer False when a cut holds it.""" leases = home / '.cache/cottondb/cut-leases' lock = leases / f'build-{lane}.lock' if leases.is_symlink() or lock.is_symlink(): yield False return try: leases.mkdir(parents=True, exist_ok=True) handle = lock.open('a') except OSError: yield False return with handle: try: fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError: yield False return yield True def cut_build_root(home): return home / CUT_BUILD # THE SURVEY NEVER FOLLOWS A SYMLINK (architect, 20 Oct 2026). On 20 Oct the # 158 cut hung in this survey's opendir: ~/.cache/cottondb/{cargo-target, # derived,swiftpm,xcframework} are links to the lanes SSD, Path.glob walked # through them, and a process started by a GUI LaunchAgent blocks, headless, on # the removable-volume consent the first time it opens a directory there. So # every pattern is matched one directory at a time: a symlinked directory is # never listed, at any depth, and a matched link is left to safe_child, which # never counts it. def survey_glob(root, pattern): found = [root] parts = pattern.split('/') for depth, part in enumerate(parts): last = depth == len(parts) - 1 matched = [] for base in found: try: with os.scandir(base) as entries: for entry in entries: if entry.name.startswith('.') and not part.startswith('.'): continue if fnmatch.fnmatchcase(entry.name, part) and (last or entry.is_dir(follow_symlinks=False)): matched.append(Path(entry.path)) except OSError: continue found = matched return sorted(found) def survey_tree(top): """top and everything under it, never entering a symlinked directory.""" items = [top] for folder, dirs, files in os.walk(top, followlinks=False): items.extend(Path(folder) / name for name in dirs + files) return items # CHROME'S CODE-SIGN CLONE (/private/var/folders/*/*/X/com.google.Chrome. # code_sign_clone, 79 GB on one Mac on 20 Oct 2026) is a copy Chrome makes of # itself while it runs and makes again at its next start. It counts as this # user's reclaimable bytes only while no Chrome process runs; an unanswered # question is a running Chrome. CHROME_CLONE = 'com.google.Chrome.code_sign_clone' def chrome_running(): try: return subprocess.run(['/usr/bin/pgrep', '-q', '-f', '/Google Chrome.app/Contents/'], timeout=5).returncode != 1 except (OSError, subprocess.TimeoutExpired): return True def chrome_clone(): """This user's clone: X beside the user's temporary folder (…///T).""" return Path(os.environ.get('TMPDIR', '/tmp')).resolve().parent / 'X' / CHROME_CLONE def is_chrome_clone(entry): return entry.name == CHROME_CLONE and entry.parent.name == 'X' def candidates(home, protected): root = home / '.cache/cottondb' protected = [*protected, cut_build_root(home), home / ".cache/cottondb/cargo-target/shared"] found = [] # Dependency caches precede every lane's build output. Never remove cache # infrastructure (binaries, logs, credentials, the sccache directory itself). # sccache is not listed here: its objects go in one least-recently-used # pass of their own (`evict_sccache`), and only once everything else in # this tier has been asked. patterns = [ (0, 'xcframework/*'), (0, 'swiftpm/repositories/*'), (0, 'swiftpm/artifacts/*'), (0, 'swiftpm/xcode/*/*'), (0, 'swiftpm/checkouts/*'), (1, 'cargo-target/*'), (1, 'rust/targets/*'), (1, 'rust/slots/*/target'), (1, 'ui-tests/*'), ] seen = set() for tier, pattern in patterns: for entry in ([] if root.is_symlink() or not root.is_dir() else survey_glob(root, pattern)): if entry in seen or not safe_child(entry, root) or entry.name.startswith('.') or '.partial' in entry.name or entry.name.endswith('.lock'): continue if any(entry == p or entry in p.parents or p in entry.parents for p in protected): continue try: # Snapshot each directory's access time before listing it: # the reclaim survey itself must not make an old cache newer. # rmtree unlinks a nested link, never its target, and the # survey never follows one either (Swift builds have links). stats = [item.lstat() for item in survey_tree(entry)] if any(stat.st_uid != os.getuid() for stat in stats): continue last_used = max(item.st_mtime if stat.S_ISDIR(item.st_mode) else max(item.st_atime, item.st_mtime) for item in stats) found.append((tier, last_used, entry)) seen.add(entry) except OSError: continue # Legacy and current UI-stub workspaces live in this user's TMPDIR. # They are a later tier than shared dependencies, and must prove ownership. legacy = Path(os.environ.get('TMPDIR', '/tmp')) / 'cotton-ui-tests-stub' if legacy.is_dir() and not legacy.is_symlink(): for entry in legacy.iterdir(): if not safe_child(entry, legacy) or not entry.is_dir(): continue if any(entry == p or entry in p.parents or p in entry.parents for p in protected): continue manifest = entry / 'Package.swift' if not manifest.is_file() or manifest.is_symlink(): continue try: stamp = manifest.stat() text = manifest.read_text() if stamp.st_uid == os.getuid() and '// Written by scripts/ui-tests-stub.sh' in text and 'name: "CottonUITestsStub"' in text: log = entry / 'last-run.log' last_used = max(stamp.st_mtime, log.stat().st_mtime if log.is_file() and not log.is_symlink() else stamp.st_mtime) found.append((1, last_used, entry)) except OSError: continue # Only this cache protocol's marked outputs are reclaimable. Older running # cuts have no marker and are never admitted into the candidate set. releases = home / 'prod-release' for entry in ([] if releases.is_symlink() else survey_glob(releases, '*/stages/*/*')): if not safe_child(entry, releases) or not entry.is_dir() or not re.fullmatch('[a-f0-9]{64}', entry.name): continue if any(entry == p or entry in p.parents or p in entry.parents for p in protected): continue owner = entry.parents[2] / '.cut-stage-owner.json' try: if owner.is_symlink() or not re.fullmatch('[a-f0-9]{40}', json.loads(owner.read_text())['sha']): continue if not (entry / 'inputs.json').is_file(): continue items = survey_tree(entry) if any(item.lstat().st_uid != os.getuid() for item in items): continue found.append((1, max(item.lstat().st_mtime for item in items), entry)) except (OSError, ValueError, KeyError, TypeError): continue clone = chrome_clone() if clone.is_dir() and not clone.is_symlink() and not chrome_running(): try: stats = [item.lstat() for item in survey_tree(clone)] if all(item.st_uid == os.getuid() for item in stats): found.append((1, max(item.st_mtime for item in stats), clone)) except OSError: pass return sorted(found, key=lambda item: (item[0], item[1], str(item[2]))) @contextmanager def idle_lease(entry): # UI and XCFramework caches lock siblings; cargo slots lock their parent. # Keep any existing locks through deletion, not only through the survey. locks = ExitStack() owned = True try: if entry.parent.parent.name == 'stages': out = entry.parents[2] sha = json.loads((out / '.cut-stage-owner.json').read_text())['sha'] if not re.fullmatch('[a-f0-9]{40}', sha): raise OSError('invalid stage owner') # Shared for every active cut of this SHA; exclusive while reclaiming, # so even the other flavour's cache survives a currently running cut. home = out.parent.parent for path in [home / '.cache/cottondb/cut-leases' / (sha + '.lock'), out / '.stages.lock']: if path.is_symlink() or not path.is_file(): raise OSError('unknown stage lease') handle = locks.enter_context(path.open('r')) fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) if (entry.parent / '.lease.d').exists(): owned = False # An ownerless lease is the slot manager's too. for path in [entry.parent / (entry.name + '.lock'), entry.parent / '.lease']: if path.is_symlink(): owned = False break if path.is_file(): handle = locks.enter_context(path.open('r')) fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) except (OSError, ValueError, KeyError, TypeError): owned = False try: yield owned finally: locks.close() # WHAT A RECLAIM FREES, AND IN WHAT ORDER (measured 27 Oct 2026). Cut 328 on # one Mac took its lock at 18:01:42 and said its disk need at 18:18:50: the # seventeen minutes between were this reclaim walking sccache one hashed object # at a time — an `lsof` of each (about two seconds apiece on a busy Mac), a # removal, a line and a fresh disk reading — while the outputs of cuts already # superseded sat untouched behind it. So the reclaim is ONE function, which # every admission (a cut's reservation included) and the `--dry-run` reading # call, and it frees what is worth nothing first, whole folders at a time: # # 1. superseded cut outputs: ~/prod-release/phone-- beyond the # newest CUT_KEEP_LAST of each flavour (the keep_last:3 rule phone-cut.sh # claims its output under), the real app's beyond its newest two; # 2. stale derived data: ~/.cache/cottondb/derived/ that no live # worktree of this repository names, untouched for DERIVED_STALE_SECONDS; # 3. the other shared caches, one entry at a time, oldest used first; # 4. sccache, only for what is still short, in ONE pass in its own # least-recently-used order, said in one line; # 5. idle lane targets, one at a time; # 6. other flavours' idle cut lanes (`idle_cut_lanes`), one at a time. # # (0, before them all: the shared cargo target's stale test binaries — below.) # # It never takes a cut lane this cut leases or another cut holds, the shared cargo target, a cut # whose stages lock or SHA lease is held, anything protected, marked evidence, # a folder behind a symlink, or bytes on a volume the floor is not measured on. CUT_KEEP_LAST = 3 CUT_KEEP = {'real': 2} CUT_SERIES = re.compile(r'phone-([0-9a-f]{7,40})-([a-z][a-z0-9]*)') DERIVED_STALE_SECONDS = 24 * 3600 SCCACHE_OBJECT = re.compile(r'[a-f0-9]{40,128}') def is_protected(entry, protected): return any(entry == p or entry in p.parents or p in entry.parents for p in protected) def owned_bytes(entry): """Bytes on disk under entry, or None when any of it is not this user's.""" total = 0 for item in survey_tree(entry): info = item.lstat() if info.st_uid != os.getuid(): return None total += info.st_blocks * 512 return total def superseded_cuts(home, protected=()): releases = home / 'prod-release' if releases.is_symlink() or not releases.is_dir(): return [] series = {} for entry in survey_glob(releases, 'phone-*'): match = CUT_SERIES.fullmatch(entry.name) if not match or entry.is_symlink() or not entry.is_dir() or not safe_child(entry, releases): continue try: with os.scandir(entry) as children: last = max([entry.lstat().st_mtime, *(child.stat(follow_symlinks=False).st_mtime for child in children)]) except OSError: continue series.setdefault(match[2], []).append((last, entry)) found = [] for flavour, cuts in series.items(): cuts.sort(key=lambda cut: (cut[0], str(cut[1])), reverse=True) found += [cut for cut in cuts[CUT_KEEP.get(flavour, CUT_KEEP_LAST):] if not is_protected(cut[1], protected)] # Oldest first, whatever the flavour. return [entry for _, entry in sorted(found, key=lambda cut: (cut[0], str(cut[1])))] @contextmanager def cut_idle(out): """A cut's output is idle only while nobody holds its stages lock or its SHA's lease.""" locks = ExitStack() owned = True try: paths = [out / '.stages.lock'] owner = out / '.cut-stage-owner.json' if owner.is_symlink(): raise OSError('unknown stage owner') if owner.exists(): sha = json.loads(owner.read_text())['sha'] if not re.fullmatch('[a-f0-9]{40}', sha): raise OSError('invalid stage owner') paths.append(out.parent.parent / '.cache/cottondb/cut-leases' / (sha + '.lock')) for path in paths: if path.is_symlink(): raise OSError('unknown stage lease') if path.is_file(): handle = locks.enter_context(path.open('r')) fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) except (OSError, ValueError, KeyError, TypeError): owned = False try: yield owned finally: locks.close() def live_derived_names(path, root): """The derived folder name of every live worktree of path's repository, each asked of that worktree's own scripts/lib/derived-data.sh; None when any one cannot be named, so an unknown worktree never makes a folder stale.""" try: listed = subprocess.run(['git', '-C', str(path), 'worktree', 'list', '--porcelain'], capture_output=True, text=True, timeout=30) except (OSError, subprocess.TimeoutExpired): return None if listed.returncode != 0: return None env = {k: v for k, v in os.environ.items() if k not in ('COTTON_DERIVED_DATA', 'COTTON_HEAD_REF', 'GITHUB_HEAD_REF', 'GITHUB_REF_NAME')} env['COTTON_DERIVED_ROOT'] = str(root) names = set() for block in listed.stdout.strip().split('\n\n'): lines = block.splitlines() if not lines or not lines[0].startswith('worktree ') or 'bare' in lines: continue tree = Path(lines[0][len('worktree '):]) if any(line.startswith('prunable') for line in lines) or not tree.is_dir(): continue script = tree / 'scripts/lib/derived-data.sh' if not script.is_file(): return None try: named = subprocess.run(['bash', str(script)], capture_output=True, text=True, timeout=30, env=env, cwd=tree) except (OSError, subprocess.TimeoutExpired): return None answer = Path(named.stdout.strip()) if named.returncode != 0 or answer.parent != root: return None names.add(answer.name) return names def stale_derived(home, path, protected=(), now=None): root = home / '.cache/cottondb/derived' if (home / '.cache/cottondb').is_symlink() or root.is_symlink() or not root.is_dir(): return [] live = live_derived_names(path, root) if live is None: return [] now = time.time() if now is None else now found = [] for entry in survey_glob(root, '*'): if entry.name in live or entry.is_symlink() or not entry.is_dir() or not safe_child(entry, root) or is_protected(entry, protected): continue try: # Xcode rewrites info.plist each time it opens a derived folder. touched = max(item.lstat().st_mtime for item in [entry, entry / 'info.plist', entry / 'Build', entry / 'Logs/Build'] if os.path.lexists(item)) except OSError: continue if now - touched >= DERIVED_STALE_SECONDS: found.append(entry) return found def sccache_objects(home): """(last used, bytes, path) of every hashed object, least recently used first.""" root = home / '.cache/cottondb/rust/sccache' if (home / '.cache/cottondb').is_symlink() or root.is_symlink() or not root.is_dir(): return [] found = [] for pattern in ('*/*/*', '*/*'): for entry in survey_glob(root, pattern): if not SCCACHE_OBJECT.fullmatch(entry.name): continue try: info = entry.lstat() except OSError: continue if stat.S_ISREG(info.st_mode) and info.st_uid == os.getuid(): found.append((max(info.st_atime, info.st_mtime), info.st_blocks * 512, entry)) return sorted(found, key=lambda item: (item[0], str(item[2]))) def evict_sccache(home, short, volume, keep_evidence, dry_run=False): """Evict the least recently used sccache objects that cover `short` bytes, in one pass. No `lsof` per object: the server opens an object only to read or write it, and an object gone under it is a cache miss, never a failed build. Only the directory itself must outlive the server (scripts/reclaim-sccache.sh says why), and this removes files inside it, never it.""" root = home / '.cache/cottondb/rust/sccache' objects = sccache_objects(home) try: if not objects or short <= 0 or root.stat().st_dev != volume or keep_evidence(root, file=sys.stderr): return 0 except OSError: return 0 chosen, total = [], 0 for last_used, size, entry in objects: if total >= short: break chosen.append((last_used, size, entry)) total += size freed = 0 for _, size, entry in chosen: if dry_run: freed += size continue try: entry.unlink() freed += size except OSError: pass when = lambda at: time.strftime('%d %b %H:%M', time.localtime(at)) print(f'device keep free: {"would evict" if dry_run else "evicted"} {len(chosen)} of {len(objects)} sccache objects, ' f'least recently used first ({freed} bytes; last used {when(chosen[0][0])} to {when(chosen[-1][0])})', file=sys.stderr, flush=True) return freed # STALE TEST BINARIES IN THE SHARED CARGO TARGET GO FIRST (14 Nov # 2026). Verify-main run #10161's ios job on one Mac was killed at the # floor in its tests: the home volume held 55 GB against a 49.4 GB keep-free, # and 132 GB of it was the shared target's debug/deps, 54 GB of that test and # example executables older than three hours. The Linux lanes prune exactly these # every hour (since 22 Oct 2026); the Macs never did, # because the shared target is otherwise never reclaimed. They are build OUTPUTS: # no compile reads them, cargo relinks a missing one on demand. So the reclaim # takes them first, oldest first, for what is short — executables in a `deps` # folder of the shared target untouched for TARGET_BINARY_STALE_SECONDS, never a # cargo input — and only while it holds the target's own cargo lock # (`.lock.d`, scripts/ci/with-cargo-lock.sh): a target a build holds is # never touched, so no running `cargo test` loses the binary it is about to run. TARGET_BINARY_STALE_SECONDS = 180 * 60 CARGO_INPUTS = ('.rlib', '.rmeta', '.d', '.so', '.dylib', '.a') def shared_target(home): return home / '.cache/cottondb/cargo-target/shared' def stale_target_binaries(home, now=None): """(last used, bytes, path) of the shared target's stale test executables, oldest first.""" shared = shared_target(home) if (home / '.cache/cottondb').is_symlink() or shared.is_symlink() or not shared.is_dir(): return [] now = time.time() if now is None else now found = [] for pattern in ('*/deps', '*/*/deps'): for deps in survey_glob(shared, pattern): if deps.is_symlink() or not deps.is_dir() or not safe_child(deps, shared) or deps.parent.name not in ('debug', 'release'): continue try: with os.scandir(deps) as entries: for entry in entries: info = entry.stat(follow_symlinks=False) if (not stat.S_ISREG(info.st_mode) or not info.st_mode & stat.S_IXUSR or info.st_uid != os.getuid() or entry.name.endswith(CARGO_INPUTS)): continue last_used = max(info.st_atime, info.st_mtime) if now - last_used >= TARGET_BINARY_STALE_SECONDS: found.append((last_used, info.st_blocks * 512, Path(entry.path))) except OSError: continue return sorted(found, key=lambda item: (item[0], str(item[2]))) @contextmanager def target_lock(target): """Hold `.lock.d` the way with-cargo-lock.sh does; yield False when a build holds it.""" lock = target.parent / (target.name + '.lock.d') try: lock.mkdir() except OSError: yield False return pid = lock / 'pid' try: pid.write_text(f'{os.getpid()}\n') yield True finally: # The lock holds its pid file and nothing else: no recursive delete. for give_back in (pid.unlink, lock.rmdir): try: give_back() except OSError: pass def evict_target_binaries(home, short, volume, dry_run=False): """Remove the oldest stale test executables of the shared target that cover `short` bytes; answer the bytes freed.""" shared = shared_target(home) binaries = stale_target_binaries(home) try: if not binaries or short <= 0 or shared.stat().st_dev != volume: return 0 except OSError: return 0 with target_lock(shared) as owned: if not owned: print(f'device keep free: the shared cargo target holds {sum(size for _, size, _ in binaries)} bytes of stale test ' f'binaries, but a build holds {shared.name}.lock.d; they wait for the next reclaim', file=sys.stderr, flush=True) return 0 freed = count = 0 for _, size, entry in binaries: if freed >= short: break if not dry_run: try: entry.unlink() except OSError: continue freed += size count += 1 print(f'device keep free: {"would remove" if dry_run else "removed"} {count} of {len(binaries)} stale test binaries ' f'of the shared cargo target, oldest first ({freed} bytes)', file=sys.stderr, flush=True) return freed def reclaim(path, policy_path, home, need, floor, usage=None, idle=None, protected=(), dry_run=False): """Free what work of `need` bytes is short of above the floor (WHAT A RECLAIM FREES); answer the free bytes after. A dry run removes nothing and answers the free bytes the same reclaim would leave.""" usage = usage or shutil.disk_usage idle = idle or unused measured = floor_path(path, policy_path) volume = measured.stat().st_dev free = usage(measured).free # Loaded beside the installed policy as well as from the checkout. import runpy keep_evidence = runpy.run_path(str(Path(__file__).with_name('evidence.py')))['keep_evidence'] def removable(entry): # A candidate another sweep removed between the survey and here (the # cut's own evidence ledger keeps the last three, 24 Oct 2026: # phone-d6080e664-nancy went while this loop walked) supplies no # bytes and stops nothing. try: return not keep_evidence(entry, file=sys.stderr) and entry.stat().st_dev == volume except FileNotFoundError: return False def short(): return floor + need - free # 0. The shared target's stale test binaries: worth nothing, relinked on demand. if dry_run or short() > 0: removed = evict_target_binaries(home, short() if not dry_run else max(short(), 1 << 62), volume, dry_run) free = free + removed if dry_run else usage(measured).free # 1 and 2 are counted before anything goes. bulk = [] for kind, entries in (('superseded cut output', superseded_cuts(home, protected)), ('stale derived data', stale_derived(home, path, protected))): for entry in entries: try: size = owned_bytes(entry) except OSError: continue if size is not None: bulk.append((kind, size, entry)) print(f'device keep free: short by {max(short(), 0)} bytes; superseded cut outputs and stale derived data hold ' f'{sum(size for _, size, _ in bulk)} bytes in {len(bulk)} folders', file=sys.stderr, flush=True) # Whole folders until what they were counted at covers the shortfall, then # one disk reading; again only if the reading says it is still short. while bulk and (dry_run or short() > 0): freed = 0 while bulk and (dry_run or short() - freed > 0): kind, size, entry = bulk.pop(0) if not removable(entry) or not idle(entry): continue with (cut_idle(entry) if kind == 'superseded cut output' else idle_lease(entry)) as owned: if not owned: continue if not dry_run: try: shutil.rmtree(entry) except OSError: # An unremovable folder supplies no promised bytes. continue freed += size print(f'device keep free: {"would reclaim" if dry_run else "reclaimed"} {kind} {entry} ({size} bytes)', file=sys.stderr, flush=True) free = free + freed if dry_run else usage(measured).free def one_by_one(entries, what): nonlocal free for entry in entries: if short() <= 0: return if not removable(entry): continue if dry_run: print(f'device keep free: would reclaim {what} {entry} if still short', file=sys.stderr, flush=True) continue # The clone's idleness is no running Chrome, asked again at the moment of removal. if not (chrome_running() is False if is_chrome_clone(entry) else idle(entry)): continue try: with idle_lease(entry) as owned: if not owned: continue if entry.is_dir(): shutil.rmtree(entry) else: entry.unlink() print(f'device keep free: reclaimed {what} {entry}', file=sys.stderr, flush=True) except OSError: # An unread or unremovable cache supplies no promised bytes. pass free = usage(measured).free listed = candidates(home, protected) one_by_one([entry for tier, _, entry in listed if tier == 0], 'shared cache') if short() > 0: evicted = evict_sccache(home, short(), volume, keep_evidence, dry_run) free = free + evicted if dry_run else usage(measured).free one_by_one([entry for tier, _, entry in listed if tier == 1], 'idle target') for entry in idle_cut_lanes(home, protected): if short() <= 0: break if not removable(entry): continue if dry_run: print(f'device keep free: would reclaim idle cut lane {entry} if still short', file=sys.stderr, flush=True) continue with cut_lane_lease(home, entry.name) as owned: if not owned: continue try: shutil.rmtree(entry) except OSError: pass else: print(f'device keep free: reclaimed idle cut lane {entry}', file=sys.stderr, flush=True) free = usage(measured).free return free def admit(path, policy_path, home, need=1, usage=None, idle=None, protected=(), reading=None, inherit=True, measured=None): usage = usage or shutil.disk_usage idle = idle or unused if type(need) is not int or need < 1: raise RuntimeError('REFUSING TO START: required build bytes must be a positive integer') if inherit: inherited = cut_disk_admission(path, home) if inherited is not None: return inherited['keep_free_bytes'] floor = read_floor(path, policy_path) free = usage(measured or floor_path(path, policy_path)).free # Off the home (off_home): the caches reclaim() knows are on the home volume, # and none of them makes room on the build's own. if free - need < floor and measured is None: free = reclaim(path, policy_path, home, need, floor, usage, idle, [Path(p).resolve() for p in protected]) if reading is not None: reading.update(disk_free_bytes=free, keep_free_bytes=floor) where = f' on {measured}, the build\'s own volume (the home volume is under the floor and this build writes nothing there)' if measured else '' if free - need < floor: raise RuntimeError(f'REFUSING TO START: {free} bytes free{where}; this device keeps {floor} bytes free; work needs {need} bytes and no idle cache can supply them') print(f'device keep free: {floor} bytes; available: {free} bytes{where}; work: {need} bytes', file=sys.stderr, flush=True) return floor def require_room(path, policy_path): # Read-only admission seam used by the pre-checkout job gate. Reclamation # is owned by the build/lane entrypoint with an explicit cache owner. floor = read_floor(path, policy_path) free = shutil.disk_usage(floor_path(path, policy_path)).free if free < floor: raise RuntimeError(f'REFUSING TO START: {free} bytes free; this device keeps {floor} bytes free') print(f'device keep free: {floor} bytes; available: {free} bytes', file=sys.stderr, flush=True) return floor def proc_info(pid, flavor=3, size=136): """Read libproc in-process: seatbelt cannot exec macOS's setuid ps. PROC_PIDTBSDINFO is struct proc_bsdinfo (136 bytes); PROC_PIDTASKINFO is struct proc_taskinfo (96 bytes), from sys/proc_info.h. """ libproc = ctypes.CDLL('/usr/lib/libproc.dylib', use_errno=True) libproc.proc_pidinfo.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_uint64, ctypes.c_void_p, ctypes.c_int] libproc.proc_pidinfo.restype = ctypes.c_int info = ctypes.create_string_buffer(size) ctypes.set_errno(0) if libproc.proc_pidinfo(pid, flavor, 0, info, size) != size: error = ctypes.get_errno() or errno.EIO raise OSError(error, os.strerror(error)) return info.raw def proc_uint(info, offset, size=4): return int.from_bytes(info[offset:offset + size], sys.byteorder) def parent_pid(pid): if sys.platform == 'darwin': return proc_uint(proc_info(pid), 16) # pbi_ppid return int(Path(f'/proc/{pid}/stat').read_text().rsplit(')', 1)[1].split()[1]) def process_table(): """Snapshot (pid, parent, group) without starting another process.""" if sys.platform == 'darwin': libproc = ctypes.CDLL('/usr/lib/libproc.dylib', use_errno=True) libproc.proc_listpids.argtypes = [ctypes.c_uint32, ctypes.c_uint32, ctypes.c_void_p, ctypes.c_int] libproc.proc_listpids.restype = ctypes.c_int # PROC_ALL_PIDS = 1; leave room for forks between sizing and reading. size = libproc.proc_listpids(1, 0, None, 0) if size <= 0: raise OSError(ctypes.get_errno() or errno.EIO, 'cannot list processes') while True: pids = (ctypes.c_int * (size // 4 + 256))() used = libproc.proc_listpids(1, 0, pids, ctypes.sizeof(pids)) if used <= 0: raise OSError(ctypes.get_errno() or errno.EIO, 'cannot list processes') if used < ctypes.sizeof(pids): break size = ctypes.sizeof(pids) * 2 table = [] for pid in pids[:used // 4]: if pid <= 0: continue try: info = proc_info(pid) table.append((pid, proc_uint(info, 16), proc_uint(info, 100))) except OSError as error: if error.errno not in (errno.ESRCH, errno.EPERM, errno.EACCES): raise return table table = [] for entry in Path('/proc').iterdir(): if entry.name.isdigit(): try: fields = (entry / 'stat').read_text().rsplit(')', 1)[1].split() table.append((int(entry.name), int(fields[1]), int(fields[2]))) except (FileNotFoundError, ProcessLookupError, PermissionError): pass return table def ancestor(pid): current = os.getpid() for _ in range(64): if current == pid: return True try: current = parent_pid(current) except (OSError, ValueError, IndexError): break if current < 2: break return False def process_info_command(args): """Small shell interface to the same in-process reads the build policy uses.""" action, *values = args pids = [int(value) for value in values] if any(pid <= 0 for pid in pids): raise ValueError('process ids must be positive') if action == 'alive' and len(pids) == 1: return 0 if pid_alive(pids[0]) else 1 if action == 'args' and len(pids) == 1: args = process_args(pids[0]) if args is None: return 1 print(' '.join(args)) return 0 if action == 'nice' and len(pids) == 1: print(os.getpriority(os.PRIO_PROCESS, pids[0])) return 0 if action == 'ancestor' and len(pids) == 2: target, current = pids for _ in range(64): if current <= 1: break try: current = parent_pid(current) except (OSError, ValueError, IndexError): break if current == target: return 0 return 1 raise ValueError('process-info: alive PID | args PID | nice PID | ancestor TARGET PID') def signal_build(child, signum): # Process groups are not ownership: helpers can change session or uid, # and a reparented process can remain in the same group. Survey this exact # child's descendants and signal each pid independently instead. if child.poll() is not None: return True try: table = process_table() except OSError as error: print(f'REFUSING TO SIGNAL build {child.pid}: cannot survey descendants ({error})', file=sys.stderr, flush=True) return False owned = {child.pid} while True: more = {pid for pid, parent, _ in table if parent in owned} if more <= owned: break owned |= more succeeded = True for pid in sorted(owned): try: os.kill(pid, signum) except ProcessLookupError: # A completed descendant needs no signal. pass except OSError as error: succeeded = False reason = 'not ours' if isinstance(error, PermissionError) else str(error) print(f'REFUSING TO SIGNAL pid {pid} with {signal.Signals(signum).name}: {reason}', file=sys.stderr, flush=True) return succeeded def ownership_fds(): inherited = [] for key in ['COTTON_STUB_LOCK_FD', 'COTTON_JOB_LOCK_FD']: value = os.environ.get(key, '') if value.isdigit(): try: os.fstat(int(value)) inherited.append(int(value)) except OSError: pass return tuple(inherited) GIB = 1024 ** 3 MEMORY_FLOOR = 2 * GIB # The class constants are the STARTING need, per Mac size (architect, 14 Oct # 2026 17:30 IST): a 16 GB Mac serving the app beside two lanes keeps ~6.6 GB # available, so a 6 GiB Swift need above the 2 GiB floor never admitted a # CottonUI build there. Once twenty admitted builds of a kind have recorded # their peak RSS on this Mac, the need is the 90th percentile of those peaks — # measured, no constant. MEMORY_NEED = {'swift': 6 * GIB, 'rust': 2 * GIB} # Cold-build disk budgets until this device has twenty measured peaks. The # separate 30 GB admission margin absorbs variance; it is never a moving floor. DISK_NEED = {'swift': 20_000_000_000, 'rust': 10_000_000_000} # A CUT'S DISK NEED IS WHAT A CUT REALLY USES (architect, 20 Oct 2026). It was # the cold Swift budget plus a fixed 30 GB margin, 50 GB, which beside the # 24.5 GB keep-free refused the 228 GB signing Mac with 67 GB free, twice. Measured on # the signing Mac from the 159 cut (~/prod-release/1141cb1a0): its Mac build drew # 9.91 GB of free space at its peak (build-peaks.log, 16:18Z), the signing Mac's two # cuts before it 10.85 and 11.72 GB, and the cut kept 2.6 GB of output. The # need is the largest peak plus the kept output, and a quarter again: 18 GB. # Once twenty peaks are measured the need is their 90th percentile plus the # kept output, and a quarter again. CUT_MEASURED_PEAK = 9_913_122_816 CUT_LARGEST_PEAK = 11_724_476_416 CUT_KEPT_OUTPUT = 2_600_000_000 CUT_DISK_NEED = 18_000_000_000 SMALL_MAC = 16 * GIB SMALL_MAC_NEED = {'swift': 4 * GIB, 'rust': 2 * GIB} PEAKS_FOR_MEASURED_NEED = 20 PEAKS_KEPT = 200 # A build never waits forever: alone on the Mac (no other admitted build) it is # admitted after this long and says so — an idle Mac holding a build is the # worst outcome; ten minutes of swap beats a lane blocked for an hour. WAIT_ADMIT_SECONDS = 600 # A BUILD HELD IN ADMISSION IS NEVER SILENT (architect, 14 Oct 2026 23:45 IST, # after cut #3 of 0.29.57 sat 28 minutes inside this policy with no line). Every # wait — RAM admission, the reservation ledger's lock, a cut's stage lease — # says what it waits on and since when as it starts, says it again every # minute, and gives up with that line at WAIT_ADMIT_SECONDS. Nothing waits # without a line. WAIT_SAY_SECONDS = 60 EX_TEMPFAIL = 75 # A CUT WAITS WHILE ITS HOLDER LIVES (architect, 17 Oct 2026 07:20 IST). Mac # cuts 145, 146 and 147 of 0.29.7x were each refused at this ten-minute cap # behind a phone archive that was simply still running, and every refusal cost # a restart by hand. So a CUT's wait — RAM admission, the ledger lock — has no # cap while the build holding it is alive: it says the holder's pid and what it # is every minute, and gives up only when every holder is dead or has outlived # the ceiling it declared (BUILD_LOCK_MAX_MIN / BUILD_LOCK_CEILING_SECONDS, # kept in its reservation row as `limit`). A LANE's wait keeps the cap: a lane # blocked an hour is the lesser harm, and the owner's install is the gate. # Guard: scripts/__tests__/build-admission-cut-first.test.ts. class HeldTooLong(RuntimeError): """A wait reached its limit; the build exits 75 with the line naming what held it.""" def clock_text(at): return time.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime(at)) class Wait: """One wait a build is held in. `tick(on)` on every poll while held; `end()` once it is over. `on` is the phrase after WAITING — `on for `, `for RAM behind : …`, `behind : …` — as it stands at this poll. The first tick says WAITING since