Cotton code
2644 lines · 123.9 KB · PythonRaw
#!/usr/bin/env python3"""One device floor for Mac workspaces, dependency caches and build output."""import argparseimport ctypesimport errnoimport fnmatchfrom contextlib import contextmanager, ExitStackimport fcntlimport jsonimport osimport reimport runpyfrom pathlib import Pathimport shutilimport signalimport statimport subprocessimport sysimport timedef 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 errordef 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_devdef 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 Falsedef 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-<lane>.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])))]@contextmanagerdef cut_lane_lease(home, lane):    """Hold `cut-leases/build-<lane>.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 Truedef 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 Truedef chrome_clone():    """This user's clone: X beside the user's temporary folder (…/<a>/<b>/T)."""    return Path(os.environ.get('TMPDIR', '/tmp')).resolve().parent / 'X' / CHROME_CLONEdef 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])))@contextmanagerdef 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-<sha>-<flavour> 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/<name> 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 = 3CUT_KEEP = {'real': 2}CUT_SERIES = re.compile(r'phone-([0-9a-f]{7,40})-([a-z][a-z0-9]*)')DERIVED_STALE_SECONDS = 24 * 3600SCCACHE_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 totaldef 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])))]@contextmanagerdef 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 namesdef 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 founddef 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# (`<target>.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 * 60CARGO_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])))@contextmanagerdef target_lock(target):    """Hold `<target>.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:                passdef 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 freeddef 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 freedef 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 floordef 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 floordef 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.rawdef 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 tabledef 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 Falsedef 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 succeededdef 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 ** 3MEMORY_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_816CUT_LARGEST_PEAK = 11_724_476_416CUT_KEPT_OUTPUT = 2_600_000_000CUT_DISK_NEED = 18_000_000_000SMALL_MAC = 16 * GIBSMALL_MAC_NEED = {'swift': 4 * GIB, 'rust': 2 * GIB}PEAKS_FOR_MEASURED_NEED = 20PEAKS_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 = 60EX_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 <holder> for <lock>`, `for RAM    behind <cut>: …`, `behind <cut>: …` — as it stands at this poll. The first    tick says WAITING <on> since <time>, unless `quiet` seconds of    grace are given (a lock every monitor takes for a moment); every    WAIT_SAY_SECONDS it is said again with the holder as it now stands; at    `limit` it gives up with HeldTooLong. `end()` closes the wait."""    def __init__(self, limit=WAIT_ADMIT_SECONDS, quiet=0.0, clock=None, prefix='build admission'):        # The module's clock, read at construction (a test fast-forwards it), never bound at definition.        self.limit, self.quiet, self.clock, self.prefix = limit, quiet, clock or time.time, prefix        self.since = None        self.said = None        self.on = None    def say(self, text):        print(f'{self.prefix}: {text}', file=sys.stderr, flush=True)    def tick(self, on, while_holder_lives=False):        """One poll held. With `while_holder_lives` (a cut behind a live holder) the        limit does not apply at this poll; the line says so instead of a give-up time."""        now = self.clock()        if self.since is None:            self.since = now        self.on = on        since = clock_text(self.since)        held = now - self.since        if held >= self.limit and not while_holder_lives:            raise HeldTooLong(f'{self.prefix}: TIMEOUT after {int(held // 60)}m — gave up waiting {on} since {since}')        if held < self.quiet:            return        if self.said is None or now - self.said >= WAIT_SAY_SECONDS:            again = 'still ' if self.said is not None else ''            ends = f'a cut waits while its holder runs ({int(held // 60)}m so far)' if while_holder_lives else f'gives up at {int(self.limit // 60)}m'            self.say(f'{again}WAITING {on} — since {since}; {ends}')            self.said = now# A LEASE FILE NAMES ITS LEADER (architect, 15 Oct 2026 18:00 IST). The# exclusive holder writes one JSON line into the lock file it holds: its pid,# the process group it owns (a cut's), when it took the lease (`since` for a# person, `started` for the pid-reuse check) and a command label — so the next# cut, and a person reading the file, can tell a live lease from a dead one.def lease_record(label='', pgid=None, now=None):    now = time.time() if now is None else now    started = process_start(os.getpid())    return {'pid': os.getpid(), 'pgid': os.getpgid(0) if pgid is None else pgid,            'since': clock_text(now), 'started': started[0] if started and not started[1] else now,            'command': label or Path(sys.argv[0]).name}def write_lease(handle, record):    os.ftruncate(handle.fileno(), 0)    os.write(handle.fileno(), (json.dumps(record, sort_keys=True) + '\n').encode())def read_lease(path):    """The record in a lock file, or None. A record written before leases were    JSON (`pid <n> (<label>) since <time>`) still names its pid."""    try:        text = Path(path).read_text().strip()    except OSError:        return None    try:        record = json.loads(text)        return record if isinstance(record, dict) and type(record.get('pid')) is int else None    except ValueError:        legacy = re.match(r'pid (\d+)\b', text)        return {'pid': int(legacy.group(1))} if legacy else Nonedef flock_holder(path):    """Who holds a lock file, as its holder wrote it: `pid <n> (<label>) since <time>`, or `an unnamed holder`."""    record = read_lease(path)    if record and 'since' in record:        command = record.get('command') or ''        return f'pid {record["pid"]}{f" ({command})" if command else ""} since {record["since"]}'    try:        text = Path(path).read_text().strip()    except OSError:        text = ''    return text or 'an unnamed holder'def leader_gone(record):    """Why the leader a lease record names no longer runs ('dead', 'pid reused'), or None while it may."""    if not record or record['pid'] <= 1:        return None    if not pid_alive(record['pid']):        return 'dead'    started = process_start(record['pid'])    if started is None:        return None    if started[1]:        return 'dead'    if type(record.get('started')) in (int, float) and started[0] > record['started'] + START_SLACK_SECONDS:        return 'pid reused'    return Nonedef process_args(pid):    """argv of a running pid, or None; read in-process (KERN_PROCARGS2), as seatbelt cannot exec ps."""    if sys.platform == 'darwin':        libc = ctypes.CDLL(None, use_errno=True)        mib = (ctypes.c_int * 3)(1, 49, pid)  # CTL_KERN, KERN_PROCARGS2        size = ctypes.c_size_t(0)        if libc.sysctl(mib, 3, None, ctypes.byref(size), None, 0) != 0 or not size.value:            return None        buffer = ctypes.create_string_buffer(size.value)        if libc.sysctl(mib, 3, buffer, ctypes.byref(size), None, 0) != 0:            return None        raw = buffer.raw[:size.value]        argc = int.from_bytes(raw[:4], sys.byteorder)        parts = raw[4:].split(b'\0')        first = 1  # the executable path, then its padding        while first < len(parts) and not parts[first]:            first += 1        return [part.decode(errors='replace') for part in parts[first:first + argc]]    try:        return [part.decode(errors='replace') for part in Path(f'/proc/{pid}/cmdline').read_bytes().split(b'\0')[:-1]]    except OSError:        return Nonedef is_cut_leader(pid):    """A process running `cut_stages.py lease`: the one process that takes a cut's leases."""    args = process_args(pid) or []    return any(Path(arg).name == 'cut_stages.py' and args[i + 1:i + 2] == ['lease'] for i, arg in enumerate(args))def lock_openers(path):    """{pid: (command, writes)} for every process with the file open; `writes` is    whether one of its descriptors was opened for writing — a lease is always    opened for append, while the disk policy's idle check only reads."""    path = Path(path).resolve()    openers = {}    if sys.platform == 'darwin' or shutil.which('lsof'):        result = subprocess.run(['lsof', '-n', '-F', 'pcfa', '--', str(path)], stdin=subprocess.DEVNULL,                                capture_output=True, text=True, timeout=60)        if result.returncode not in (0, 1) or (result.returncode == 1 and result.stderr.strip()):            raise OSError(f'lsof exited {result.returncode}: {result.stderr.strip()[:200]}')        pid = None        for line in result.stdout.splitlines():            tag, value = line[:1], line[1:]            if tag == 'p':                pid = int(value)                openers[pid] = ['', False]            elif tag == 'c' and pid is not None:                openers[pid][0] = value            elif tag == 'a' and pid is not None and value in ('w', 'u'):                openers[pid][1] = True        return {pid: tuple(value) for pid, value in openers.items()}    for entry in Path('/proc').iterdir():        if not entry.name.isdigit():            continue        try:            for fd in (entry / 'fd').iterdir():                if Path(os.readlink(fd)) == path:                    flags = int(re.search(r'flags:\s*(\d+)', (entry / 'fdinfo' / fd.name).read_text()).group(1), 8)                    command, writes = openers.get(int(entry.name), ((entry / 'comm').read_text().strip(), False))                    openers[int(entry.name)] = (command, writes or flags & 3 != 0)        except (OSError, AttributeError):            continue    return openersdef lease_holders(path, leader_self=True):    """(orphans, backed) among the processes holding a lease file open for writing.    A holder is BACKED when it, or a process above it, is a live cut leader:    a leader waiting its turn, or a live cut and its children. Every other    holder is an ORPHAN — it inherited a lease whose leader is gone. Never    listed: this process and its ancestors, pid 1, readers, and anything    running from CottonDB.app. `leader_self=False` is a leader ending its own    cut: its own leadership then backs nobody."""    me = os.getpid()    table = {pid: parent for pid, parent, _ in process_table()}    mine, current = {me}, me    for _ in range(64):        current = table.get(current, 0)        if current <= 1:            break        mine.add(current)    leaders = {}    def led(pid):        for _ in range(64):            if pid <= 1:                return False            if pid not in leaders:                leaders[pid] = (leader_self or pid != me) and is_cut_leader(pid)            if leaders[pid]:                return True            pid = table.get(pid, 0)        return False    orphans, backed = [], []    for pid, (command, writes) in sorted(lock_openers(path).items()):        if not writes or pid <= 1 or pid in mine:            continue        args = process_args(pid) or [command]        if any('CottonDB.app' in arg for arg in args):            continue        started = process_start(pid)        entry = (pid, ' '.join(args)[:160], started[0] if started else None)        (backed if led(pid) else orphans).append(entry)    return orphans, backeddef end_holders(holders, grace=5.0, interval=0.1):    """TERM, then after `grace` KILL, exactly the listed pids, each still the process the survey saw."""    def same(pid, started):        now = process_start(pid)        return pid_alive(pid) and not (now and now[1]) and (started is None or now is None or abs(now[0] - started) <= START_SLACK_SECONDS)    for signum in (signal.SIGTERM, signal.SIGKILL):        for pid, command, started in holders:            if same(pid, started):                try:                    os.kill(pid, signum)                except ProcessLookupError:                    pass                except PermissionError:                    print(f'cut lease: REFUSING TO SIGNAL pid {pid} ({command}): not ours', file=sys.stderr, flush=True)        deadline = time.monotonic() + grace        while time.monotonic() < deadline and any(same(pid, started) for pid, _, started in holders):            time.sleep(interval)    return not any(same(pid, started) for pid, _, started in holders)RECLAIM_SURVEY_SECONDS = 5.0def reclaim_lease(path, what, prefix):    """True when the lease's recorded leader is gone and its orphan holders were    ended; False to wait as before — a live leader, a live cut among the holders,    a lease taken meanwhile, or holders that cannot be surveyed."""    record = read_lease(path)    gone = leader_gone(record)    if not gone:        return False    try:        orphans, backed = lease_holders(path)    except (OSError, subprocess.SubprocessError, ValueError) as error:        print(f'{prefix}: cannot survey the holders of {path} ({error}); waiting', file=sys.stderr, flush=True)        return False    if any(not is_cut_leader(pid) for pid, _, _ in backed) or not orphans or read_lease(path) != record:        return False    names = ', '.join(f'pid {pid} ({command})' for pid, command, _ in orphans)    print(f'{prefix}: {what} is held by orphans of leader pid {record["pid"]} ({gone}): ending {names}', file=sys.stderr, flush=True)    end_holders(orphans)    return Truedef hold_flock(handle, path, mode, what, label='', limit=WAIT_ADMIT_SECONDS, quiet=1.0, interval=0.2, prefix='build admission', reclaim=False, cls='lane'):    """Take a flock on an open lock file without ever waiting silently, then name this holder inside it.    A shared lock writes nothing: its holders are many, and the file names the    exclusive one a waiter is behind. With `reclaim`, an exclusive lease whose    recorded leader is gone is taken from its orphan holders at once rather    than waited on (`reclaim_lease`). A `cls` of 'cut' waits past `limit`    while the recorded leader lives. Returns the record written, or None."""    wait = None    surveyed = None    reclaimed = None    while True:        try:            fcntl.flock(handle, mode | fcntl.LOCK_NB)            break        except BlockingIOError:            if reclaim and mode == fcntl.LOCK_EX and (surveyed is None or time.monotonic() - surveyed >= RECLAIM_SURVEY_SECONDS):                surveyed = time.monotonic()                held = flock_holder(path)                if reclaim_lease(path, what, prefix):                    reclaimed = held                    continue            wait = wait or Wait(limit, quiet, prefix=prefix)            record = read_lease(path)            lives = cls == 'cut' and record is not None and record['pid'] != os.getpid() and leader_gone(record) is None            wait.tick(f'on {flock_holder(path)} for {what}', while_holder_lives=lives)            time.sleep(interval)    if reclaimed:        print(f'{prefix}: RECLAIMED {what} from {reclaimed}, whose leader is gone', file=sys.stderr, flush=True)    if mode == fcntl.LOCK_EX:        record = lease_record(label)        write_lease(handle, record)        return record    return Nonedef total_memory():    if sys.platform == 'darwin':        return int(subprocess.check_output(['/usr/sbin/sysctl', '-n', 'hw.memsize'], text=True, timeout=5))    output = Path('/proc/meminfo').read_text()    return int(re.search(r'^MemTotal:\s+(\d+)', output, re.M).group(1)) * 1024def peaks_log(home):    return home / '.cottondb/build-peaks.log'def read_peaks(home, kind):    """The recorded peak RSS of this Mac's admitted builds of one kind, oldest first."""    try:        lines = peaks_log(home).read_text().splitlines()    except FileNotFoundError:        return []    peaks = []    for line in lines:        try:            row = json.loads(line)        except ValueError:            continue        if isinstance(row, dict) and row.get('kind') == kind and type(row.get('peak')) is int and row['peak'] > 0:            peaks.append(row['peak'])    return peaks[-PEAKS_KEPT:]def record_peak(home, kind, peak, total):    if type(peak) is not int or peak <= 0:        return    log = peaks_log(home)    log.parent.mkdir(parents=True, exist_ok=True)    with log.open('a') as handle:        handle.write(json.dumps({'at': time.time(), 'kind': kind, 'peak': peak, 'total': total}) + '\n')def memory_need(kind, home, total=None):    """The RAM a build of this kind needs on this Mac: measured once twenty peaks exist, else the class constant for the Mac's size."""    peaks = sorted(read_peaks(home, kind))    if len(peaks) >= PEAKS_FOR_MEASURED_NEED:        return peaks[min(len(peaks) - 1, (len(peaks) * 9 + 9) // 10 - 1)]    total = total_memory() if total is None else total    return (SMALL_MAC_NEED if total <= SMALL_MAC else MEMORY_NEED)[kind]def record_disk_peak(home, kind, peak):    log = peaks_log(home)    log.parent.mkdir(parents=True, exist_ok=True)    with log.open('a') as handle:        handle.write(json.dumps({'at': time.time(), 'kind': kind, 'disk_peak': peak}) + '\n')def measured_disk_peak(kind, home):    try:        lines = peaks_log(home).read_text().splitlines()    except FileNotFoundError:        lines = []    rows = []    for line in lines:        try:            rows.append(json.loads(line))        except ValueError:            # An interrupted tail write supplies no measurement.            pass    peaks = sorted([row['disk_peak'] for row in rows if isinstance(row, dict) and row.get('kind') == kind                    and type(row.get('disk_peak')) is int and row['disk_peak'] >= 0][-PEAKS_KEPT:])    if len(peaks) >= PEAKS_FOR_MEASURED_NEED:        return peaks[(len(peaks) * 9 + 9) // 10 - 1]    return Nonedef disk_need(kind, home):    measured = measured_disk_peak(kind, home)    return DISK_NEED[kind] if measured is None else measureddef cut_disk_need(kind, home):    """(bytes, the line that says where the figure comes from)."""    measured = measured_disk_peak(kind, home)    if measured is None:        return CUT_DISK_NEED, (f'cut disk need: {CUT_DISK_NEED} bytes, from the 159 cut measured on the signing Mac '                               f'(peak {CUT_MEASURED_PEAK} bytes; largest {CUT_LARGEST_PEAK}; kept output {CUT_KEPT_OUTPUT}; and a quarter again)')    need = (measured + CUT_KEPT_OUTPUT) * 5 // 4    return need, f'cut disk need: {need} bytes, from the 90th percentile of this Mac\'s {kind} peaks ({measured} bytes), the kept output and a quarter again'# A WALK'S DISK NEED IS WHAT A SWIFT BUILD REALLY GROWS (7 Nov# 2026). A walk's build asked for 1 byte, so it was admitted beside# builds that had reserved the disk and then KILLED at the floor half way# through its first Swift build: six walks failed that week on the harness, not# on code. A walk (BUILD_LOCK_CLASS=walk, rank_as_walk) that names no need of# its own now reserves the 90th percentile of this Mac's measured Swift growth# (build-peaks.log disk_peak rows), else WALK_DISK_NEED — one Mac's measured# p90 on 7 Nov 2026, 7,898,247,168 bytes over 152 builds, rounded up. Short of# room while other builds hold reservations, a walk WAITS for them (it says so# every minute and gives up at WAIT_ADMIT_SECONDS); alone and short it is# refused at once, because nothing will free the room.## A CI SWIFT BUILD RESERVES THE SAME (14 Nov 2026).# Verify-main run #10161's ios job (BUILD_LOCK_CLASS=ci) asked for 1 byte, was# admitted on one Mac with 5.7 GB above the floor, and was killed at the floor# in its tests — the walks' failure of 7 Nov, in the job that had no fix. A CI# build of kind swift that names no need now reserves this growth too, so the# admission reclaims (or waits behind other holders) before the build starts# instead of the monitor killing it half way.WALK_DISK_NEED = 8_000_000_000def is_walk(environ=None):    return (os.environ if environ is None else environ).get('BUILD_LOCK_CLASS') == 'walk'def is_ci(environ=None):    return (os.environ if environ is None else environ).get('BUILD_LOCK_CLASS') == 'ci'def walk_disk_need(home, who='walk'):    """(bytes, the line that says where the figure comes from)."""    measured = measured_disk_peak('swift', home)    if measured is None:        return WALK_DISK_NEED, (f'{who} disk need: {WALK_DISK_NEED} bytes, from the swift growth measured on one Mac '                                f'(90th percentile, 7 Nov 2026); this Mac has fewer than {PEAKS_FOR_MEASURED_NEED} measured')    return measured, f'{who} disk need: {measured} bytes, the 90th percentile of this Mac\'s swift growth'# A STANDING SIMULATOR IS TAKEN, NEVER SHARED, AND A MAC BOOTS ONLY SO MANY# (7 Nov 2026; the coordinator's corrections, 11:05 IST).# Each Mac keeps one standing simulator per walk slot, `standing-1` (and# `standing-2` where two fit), with every app installed on it side by side# (`pnpm sim:standing`), and boots at most simulator_cap() simulators: one# on 16 GB, two on 24 GB and up. RAM admission does not count simulators — it# already subtracts every admitted build's p90 from an `available` that# excludes their live use, and a third count would hold every 16 GB build.## A walk takes a standing simulator with `--take-simulator <udid>[,<udid>…]# --holder <pid>`: the first one no live walk holds is locked for it (a `mkdir`# lock, `~/.cottondb/simulators/<udid>.lock`, its holder's pid and start time# inside; a dead holder's lock is taken over) and booted under the cap; an idle# standing simulator — booted, held by no live walk — is shut down, never# erased, to make room. When every one is held, or the cap is reached by# simulators the walk may not touch (a person's, a CI job's), the walk WAITS:# a line a minute naming who holds each one and for how long (the label the# holder wrote in its lock, `--label`), giving up at WAIT_ADMIT_SECONDS# (COTTON_SIMULATOR_WAIT_SECONDS) with `no simulator: …` and exit 75: a walk# that gets no simulator stops and installs nothing (7 Nov# 2026). The lock is the walk's until `--release-simulator <udid># --holder <pid>` or its holder's exit. The locks live under# COTTON_STANDING_HOME (default ~), where `pnpm sim:standing` reads them.STANDING_PREFIX = 'standing-'def simulator_cap(total=None):    total = total_memory() if total is None else total    return 1 if total <= SMALL_MAC else 2def simulator_devices():    """Every simulator on this Mac as simctl lists it; [] where there is no xcrun."""    if sys.platform != 'darwin' and not shutil.which('xcrun'):        return []    listed = json.loads(subprocess.check_output(['xcrun', 'simctl', 'list', 'devices', '-j'], text=True, timeout=30))    return [device for group in listed['devices'].values() for device in group]def is_booted(device):    return device.get('state') in ('Booted', 'Booting')def simulator_lock(home, udid):    if not re.fullmatch(r'[A-F0-9-]{36}', udid or ''):        raise RuntimeError(f'not a simulator udid: {udid!r}')    return home / '.cottondb/simulators' / f'{udid}.lock'def simulator_holder(home, udid):    """The live walk holding this simulator's lock (its record), or None."""    try:        record = json.loads((simulator_lock(home, udid) / 'holder').read_text())    except (OSError, ValueError):        return None    if not isinstance(record, dict) or type(record.get('pid')) is not int or not isinstance(record.get('started'), (int, float)):        return None    return None if row_gone(record) else recorddef drop_simulator_lock(home, udid):    lock = simulator_lock(home, udid)    (lock / 'holder').unlink(missing_ok=True)    try:        lock.rmdir()    except FileNotFoundError:        passdef simulator_held(home, udid, name, now=None):    """`<name> held by <label> for <n> min` while a live walk holds it, or None."""    record = simulator_holder(home, udid)    if record is None:        return None    since = record.get('since')    if not isinstance(since, (int, float)):        try:            since = simulator_lock(home, udid).stat().st_mtime        except OSError:            since = record['started']    minutes = max(0, int(((now or time.time()) - since) // 60))    label = record.get('label') or f'walk pid {record["pid"]}'    return f'{name} held by {label} for {minutes} min'def try_take(home, udid, holder, started, label=''):    """Lock `udid` for `holder`: True once it holds it (already, or now)."""    lock = simulator_lock(home, udid)    lock.parent.mkdir(parents=True, exist_ok=True)    held = simulator_holder(home, udid)    if held is not None:        return held['pid'] == holder    if lock.exists():        drop_simulator_lock(home, udid)   # its holder is gone, or never wrote itself    try:        lock.mkdir()    except FileExistsError:        return False    record = {'pid': holder, 'started': started, 'since': time.time()}    if label:        record['label'] = label    (lock / 'holder').write_text(json.dumps(record))    return Truedef release_simulator(home, udid, holder):    held = simulator_holder(home, udid)    if held is not None and held['pid'] != holder:        raise RuntimeError(f'simulator {udid} is held by walk pid {held["pid"]}, not {holder}')    drop_simulator_lock(home, udid)    return 0def idle_standing(home, devices):    """Booted standing simulators no live walk holds."""    return [device for device in devices if is_booted(device) and device.get('name', '').startswith(STANDING_PREFIX)            and simulator_holder(home, device['udid']) is None]def xcrun_simctl(*args):    subprocess.run(['xcrun', 'simctl', *args], check=True, capture_output=True, text=True, timeout=300)def take_simulator(udids, holder, home, total=None, devices=None, simctl=None, wait_limit=WAIT_ADMIT_SECONDS, interval=5.0, label=''):    """Lock the first of `udids` no live walk holds for `holder`, boot it under this Mac's cap, and answer its udid.    Waiting, it says every minute who holds each standing simulator and for how    long; at `wait_limit` it gives up with HeldTooLong(`no simulator: …`)."""    devices = devices or simulator_devices    simctl = simctl or xcrun_simctl    started = process_start(holder)    if not pid_alive(holder) or started is None or started[1]:        raise RuntimeError(f'simulator admission: holder pid {holder} is not running')    cap = simulator_cap(total)    wait = Wait(wait_limit, prefix='simulator admission')    boot_lock = home / '.cottondb/simulator-boot.lock'    boot_lock.parent.mkdir(parents=True, exist_ok=True)    while True:        with boot_lock.open('a') as lock:            fcntl.flock(lock, fcntl.LOCK_EX)            listed = {device['udid']: device for device in devices()}            missing = [udid for udid in udids if udid not in listed]            if missing:                raise RuntimeError(f'simulator admission: no simulator {", ".join(missing)} on this Mac')            free = [udid for udid in udids                    if simulator_holder(home, udid) is None or simulator_holder(home, udid)['pid'] == holder]            on = None            if not free:                on = (', '.join(filter(None, (simulator_held(home, udid, listed[udid]['name']) for udid in udids)))                      or 'one was given back meanwhile')            else:                # A booted free one first: it needs no room.                udid = next((u for u in free if is_booted(listed[u])), free[0])                mine = listed[udid]                others = [device for device in listed.values() if is_booted(device) and device['udid'] != udid]                spare = cap - len(others)                if not is_booted(mine) and spare < 1:                    for device in idle_standing(home, others)[:1 - spare]:                        simctl('shutdown', device['udid'])                        print(f'simulator admission: shut down idle {device["name"]} ({device["udid"]}) to stay under this Mac\'s cap of {cap}',                              file=sys.stderr, flush=True)                        spare += 1                if is_booted(mine) or spare >= 1:                    if try_take(home, udid, holder, started[0], label):                        if not is_booted(mine):                            simctl('boot', udid)                        print(f'simulator admission: {mine["name"]} taken and booted for walk pid {holder}; '                              f'{len(others) + 1} of this Mac\'s cap of {cap} booted', file=sys.stderr, flush=True)                        return udid                    on = f'{mine["name"]} taken first by another walk'                else:                    on = (f'{len(others)} booted of this Mac\'s cap of {cap} '                          f'({", ".join(device["name"] for device in others)})')        try:            wait.tick(f'for a standing simulator: {on}')        except HeldTooLong:            raise HeldTooLong(f'no simulator: {on}') from None        time.sleep(min(interval, max(wait_limit / 4, 0.01)))def cut_lock():    """Only the live release lease named by an ancestor grants a cut admission."""    pid = os.environ.get('TINMEN_BUILD_LOCK_HELD', '')    folder = os.environ.get('TINMEN_BUILD_LOCK_DIR', '')    if not pid.isdigit() or not folder or not ancestor(int(pid)):        return None    lock = Path(folder)    try:        if int((lock / 'pid').read_text()) != int(pid) or (lock / 'class').read_text().strip() != 'release':            return None        started = process_start(int(pid))        if started is None or started[1]:            return None        return lock, int(pid), started[0]    except (OSError, ValueError):        return Nonedef cut_session():    """The live cut-stage leader spans the separate compile/sign build locks."""    folder = os.environ.get('COTTON_CUT_LEASE')    if not folder:        return None    out = Path(folder)    record = read_lease(out / '.stages.lock')    if not record or not ancestor(record['pid']) or not is_cut_leader(record['pid']):        return None    started = process_start(record['pid'])    if started is None or started[1] or started[0] != record.get('started'):        return None    return out, record['pid'], started[0]def cut_disk_admission(path, home):    """An existing admission belongs to this lease/ancestor, never its label alone."""    lock = cut_lock()    if lock is not None:        try:            row = json.loads((lock[0] / 'disk-admission.json').read_text())            if (isinstance(row, dict) and row.get('holder') == lock[1] and row.get('holder_started') == lock[2]                    and row.get('volume') == path.stat().st_dev):                return row        except (OSError, ValueError, TypeError):            pass    session = cut_session() if lock is not None or build_class() == 'cut' else None    if session is not None:        try:            row = json.loads((session[0] / '.disk-admission.json').read_text())            if (isinstance(row, dict) and row.get('cut_leader') == session[1]                    and row.get('cut_started') == session[2] and row.get('volume') == path.stat().st_dev):                return row        except (OSError, ValueError, TypeError):            pass    monitor = os.environ.get('COTTON_DISK_MONITOR_PID', '')    if monitor.isdigit() and ancestor(int(monitor)):        with reservation_ledger(home) as rows:            return next((row for row in rows if row['pid'] == int(monitor) and row_class(row) == 'cut'                         and not row.get('waiting') and row.get('volume') == path.stat().st_dev                         and 'keep_free_bytes' in row), None)    return Nonedef write_admission(target, row):    partial = target.with_suffix('.partial')    if target.is_symlink() or partial.is_symlink():        raise RuntimeError('REFUSING TO START: disk admission artifact is a symlink')    partial.write_text(json.dumps(row))    partial.replace(target)def keep_cut_admission(path, row):    lock = cut_lock()    if lock is not None:        row.update(holder=lock[1], holder_started=lock[2])        write_admission(lock[0] / 'disk-admission.json', row)    session = cut_session()    if session is not None:        # The stage leader changes on a retry even when OUT and the commit do        # not. An old archive's snapshot cannot admit the next attempt.        write_admission(session[0] / '.disk-admission.json',                        dict(row, cut_leader=session[1], cut_started=session[2]))def tree_rss(pgid):    """Resident bytes of a build's process group (session on Linux); 0 if unreadable."""    try:        if sys.platform == 'darwin':            resident = 0            for pid, _, group in process_table():                if group == pgid:                    try:                        resident += proc_uint(proc_info(pid, 4, 96), 8, 8)                    except OSError:                        pass  # Exited or inaccessible between the two reads.            return resident        resident = 0        for entry in Path('/proc').iterdir():            if entry.name.isdigit():                try:                    fields = (entry / 'stat').read_text().rsplit(')', 1)[1].split()                    if int(fields[3]) == pgid:                        resident += int(fields[21]) * os.sysconf('SC_PAGE_SIZE')                except (FileNotFoundError, ProcessLookupError, PermissionError):                    pass        return resident    except (OSError, ValueError, IndexError):        return 0def free_memory():    """Available physical RAM includes reclaimable inactive/speculative pages."""    if sys.platform == 'darwin':        output = subprocess.check_output(['/usr/bin/vm_stat'], text=True, timeout=5)        page_size = int(re.search(r'page size of (\d+) bytes', output).group(1))        pages = dict((name, int(count)) for name, count in re.findall(r'^([^:]+):\s+(\d+)\.', output, re.M))        return page_size * sum(pages[name] for name in ['Pages free', 'Pages inactive', 'Pages speculative'])    # The same accounting seam lets the guards run on Linux CI.    output = Path('/proc/meminfo').read_text()    return int(re.search(r'^MemAvailable:\s+(\d+)', output, re.M).group(1)) * 1024# xcodebuild answers these without building anything: a lookup by a build# script (cc's `xcodebuild -find clang` inside mupdf-sys) or a tool reading# settings. They take no room, so they are never admitted or reserved.XCODEBUILD_QUERIES = {'-find', '-find-executable', '-find-library', '-version', '-showsdks',                      '-showBuildSettings', '-showdestinations', '-list', '-help', '-usage',                      '-checkFirstLaunchStatus', '-license', '-runFirstLaunch'}# A toolchain asked its version builds nothing either: phone-cut's step 0 asks# `cargo +1.98.1 --version`, and admitted behind a CI swift-compile holding the# lock it timed out and the cut refused with "cargo +1.98.1 unavailable" on a# Mac that has it (9 Nov 2026). A `+toolchain` pin may lead the question.VERSION_QUERIES = {'--version', '-V', '-vV', '-version'}VERSION_TOOLS = {'cargo', 'rustc', 'swift', 'swiftc'}# Cargo's plugin tools answer `cargo <tool> --version` the same way: a question,# never a build. `cargo nextest --version` was admitted as a rust build and# waited 10 minutes for RAM on a 16 GB Mac ("held by no admitted build"), once# per probe, hiding behind spawnSync in cargo-target-shards.test.ts for half an# hour (14 Nov 2026). `cargo build --version` stays a# build: only these tool names are questions.CARGO_TOOL_QUERIES = {'nextest', 'clippy', 'fmt'}def is_query(command):    """A command that only asks a toolchain a question builds nothing."""    if not command:        return False    name = Path(command[0]).name    if name == 'xcodebuild':        return bool(XCODEBUILD_QUERIES & set(command[1:]))    if name in VERSION_TOOLS:        args = [arg for arg in command[1:] if not arg.startswith('+')]        if name == 'cargo' and args[:1] and args[0] in CARGO_TOOL_QUERIES:            args = args[1:]        return bool(args) and all(arg in VERSION_QUERIES | {'--verbose', '-v'} for arg in args) and bool(VERSION_QUERIES & set(args))    return Falsedef build_kind(command):    # Shell/release entrypoints may launch Swift later. Reserve the larger    # budget for unknown commands because nested wrappers share this admission.    names = {Path(arg).name for arg in command}    if names & {'swift', 'swiftc', 'xcodebuild'}:        return 'swift'    return 'rust' if names & {'cargo', 'rustc', 'sccache'} else 'swift'def pid_alive(pid):    try:        os.kill(pid, 0)        return True    except ProcessLookupError:        return False    except PermissionError:        return Truedef process_start(pid):    """(start time in epoch seconds, zombie) for a running pid, or None when the    platform cannot say. A zombie answers os.kill(pid, 0) but runs nothing."""    if sys.platform == 'darwin':        try:            info = proc_info(pid)            status = proc_uint(info, 4)            seconds = proc_uint(info, 120, 8)            micros = proc_uint(info, 128, 8)            return seconds + micros / 1e6, status == 5  # SZOMB        except OSError as error:            # A zombie still answers kill(pid, 0), but has no BSD info.            return (0.0, True) if error.errno == errno.ESRCH else None        except AttributeError:            return None    try:        fields = Path(f'/proc/{pid}/stat').read_text().rsplit(')', 1)[1].split()        boot = next(int(line.split()[1]) for line in Path('/proc/stat').read_text().splitlines() if line.startswith('btime '))        return boot + int(fields[19]) / os.sysconf('SC_CLK_TCK'), fields[0] == 'Z'    except (OSError, ValueError, IndexError, StopIteration):        return None# A RESERVATION IS A FACT ABOUT A LIVE PROCESS (coordinator, 14 Oct 2026). The# 0.29.57 Mac cut on one Mac was killed and restarted; its Swift build's row# outlived the process and the restarted cut sat 23 minutes in admission behind# it until the ledger was pruned by hand. A row whose pid is gone, a zombie, or# a pid reused by a process that started after the row was written holds no one.START_SLACK_SECONDS = 1.0def row_gone(row):    """Why this ledger row no longer stands for a live build, or None while it does."""    if not pid_alive(row['pid']):        return 'gone'    started = process_start(row['pid'])    if started is None:        return None    if started[1]:        return 'gone'    if started[0] > row['started'] + START_SLACK_SECONDS:        return 'pid reused'    return None@contextmanagerdef reservation_ledger(home):    """Only admission/accounting holds this lock; commands and waits never do."""    root = home / '.cottondb'    lock_path, ledger_path = root / 'build-disk.lock', root / 'build-reservations.json'    if lock_path.is_symlink() or ledger_path.is_symlink():        raise RuntimeError('REFUSING TO START: build disk lock or reservation ledger is a symlink')    with lock_path.open('a') as lock:        hold_flock(lock, lock_path, fcntl.LOCK_EX, 'the build reservation ledger', os.environ.get('BUILD_LOCK_LABEL', ''), cls=build_class())        rows = json.loads(ledger_path.read_text()) if ledger_path.exists() else []        if not isinstance(rows, list) or any(            not isinstance(row, dict) or type(row.get('pid')) is not int or row['pid'] <= 0            or type(row.get('need')) is not int or row['need'] < 1            or row.get('kind') not in MEMORY_NEED or not isinstance(row.get('started'), (int, float))            or row.get('class', 'lane') not in ('cut', 'lane')            for row in rows        ):            raise RuntimeError('REFUSING TO START: invalid build reservation ledger')        kept = []        for row in rows:            why = row_gone(row)            if why is None:                kept.append(row)            else:                print(f"build admission: dropped a reservation of pid {row['pid']} ({why})", file=sys.stderr, flush=True)        rows = kept        try:            yield rows        finally:            # Replace atomically: a killed writer leaves the last complete            # ledger, whose dead PID the next admission can safely reap.            partial = ledger_path.with_suffix('.partial')            if partial.is_symlink():                raise RuntimeError('REFUSING TO START: reservation temporary file is a symlink')            partial.write_text(json.dumps(rows))            partial.replace(ledger_path)# A RUNNING BUILD IS CHARGED ONCE FOR ITS OWN ROOM (coordinator, 8 Nov 2026).# deck-zoned-ground's core build was killed three times with 56-65 GB free on a# 49.4 GB floor: the monitor subtracted its whole 10 GB reservation while free# space had already fallen by what it wrote, so it needed twice its need above# the floor to finish. While a build runs, its own row (named by the pid and# start time build_reservation wrote, never by kind or label) counts only the# part it has not yet written; every other live row counts whole.def reserved_disk(rows, path, own=None, written=0):    volume = path.stat().st_dev    return sum(max(0, row['need'] - written) if own is not None and (row['pid'], row['started']) == own else row['need']               for row in rows if not row.get('waiting') and row.get('volume', volume) == volume)# A CUT GOES FIRST (architect, 14 Oct 2026 23:25 IST). Mac 0.29.57's cut sat in# RAM admission on one Mac behind two lane builds until the coordinator asked the# lanes by hand to hold. The owner's install is the gate, so a cut's build —# BUILD_LOCK_CLASS=release: prod-cut.sh, phone-cut.sh and the steps they run —# never waits on a lane: it counts only other cuts' reservations, and with no# other cut admitted it takes the next admission. While a cut waits its claim# sits in the ledger, and every lane build queues behind it; a lane admitted# later counts the cut's reservation, so it is the lane that is deferred, never# the cut. A lane build already running finishes: the policy never signals# another reservation's process.def build_class(environ=None):    """`cut` for a release caller (BUILD_LOCK_CLASS=release), `lane` for every other build."""    return 'cut' if (os.environ if environ is None else environ).get('BUILD_LOCK_CLASS') == 'release' else 'lane'def row_ram(row, home, total=None):    return row['ram'] if type(row.get('ram')) is int else memory_need(row['kind'], home, total)def row_class(row):    return 'cut' if row.get('class') == 'cut' else 'lane'def declared_ceiling(environ=None):    """The seconds this build's wrapper gives it (BUILD_LOCK_CEILING_SECONDS, else    BUILD_LOCK_MAX_MIN minutes), or 0 when it declared none."""    environ = os.environ if environ is None else environ    for key, scale in (('BUILD_LOCK_CEILING_SECONDS', 1), ('BUILD_LOCK_MAX_MIN', 60)):        value = environ.get(key, '')        if value.isdigit() and int(value) > 0:            return int(value) * scale    return 0# A CI JOB WAITS ITS OWN CEILING, NOT TEN MINUTES (pipeline-gate, 7 Nov 2026).# swift-compile run 7057's cotton job on one Mac gave up in RAM admission after# WAIT_ADMIT_SECONDS behind a red-main lane's swift build and went red: a red# main for no reason in the code, which the red-main tick then has to answer. A# check job (BUILD_LOCK_CLASS=ci) waits up to the ceiling it declared# (BUILD_LOCK_MAX_MIN / BUILD_LOCK_CEILING_SECONDS) and says so every minute;# a lane keeps the ten minutes, and a CI job that declared nothing keeps them too.def admission_limit(environ=None):    """Seconds a build waits in admission before it gives up."""    environ = os.environ if environ is None else environ    if environ.get('BUILD_LOCK_CLASS') == 'ci':        return max(WAIT_ADMIT_SECONDS, declared_ceiling(environ))    return WAIT_ADMIT_SECONDSdef live_holders(rows):    """The admitted rows whose build is alive — what a waiting build is actually behind."""    return [row for row in rows if not row.get('waiting') and pid_alive(row['pid'])]def holder_outlived_limit(row, now=None):    """True once an admitted build has run past the ceiling it declared: its own    wrapper should have ended it, so a cut waits on it no longer."""    limit = row.get('limit')    return type(limit) in (int, float) and limit > 0 and (time.time() if now is None else now) - row['started'] > limit# A BUILD WAITING ON THE BUILD LOCK HOLDS NO RAM FROM ITS HOLDER (lock-order,# 7 Nov 2026). On one Mac CI swift-compile run 7966 took /tmp/tinmen-build.lock and# then sat 32 minutes in RAM admission inside it, "held by swift build pid# 80020": a red-main lane's `swift test` whose outer policy (ui-stub-workspace.py)# had been admitted with a 2.55 GB reservation and was itself waiting in# with-build-lock.sh for the lock the CI job held. Neither could move until the# CI ceiling killed the job. Lanes admit RAM first and take the lock second; a# with-build-lock.sh caller takes the lock first and admits inside it.## So a build whose process (or an ancestor) HOLDS the build lock — the `pid` in# the lock folder or its `.slot-2` — does not count an admitted reservation whose# process is, or is an ancestor of, a live waiter on that lock: every waiter# files `<lock>.{release,ci,walk,local}-waiting/<pid>` (with-build-lock.sh,# "EVERY WAITER SAYS SO BESIDE THE LOCK"), and the reservation's pid is the policy# process that wraps the waiting wrapper, so the markers are read up through the# process tree. The floor stands: with those reservations left out the holder# still waits while RAM is genuinely short, and the line says how many it left out;# with only such reservations beside it, it is alone on this Mac for the# WAIT_ADMIT_SECONDS rule like any build that is.# What is left out is RAM promised to a build that cannot start until this one# ends.## A WAITER LEFT OUT TAKES NO SLOT WHILE ITS HOLDER RUNS (lock-slot, 9 Nov 2026).# On a two-slot Mac the other slot can free while this build runs, and# a waiter whose RAM it left out would then run beside it on promises that# overlap, under the floor. So the holder names every waiter it leaves out in# the slot it holds, `<slot>/excluded/<waiter pid>`, and with-build-lock.sh# gives no slot to a caller named in another slot: a waiter counts for a slot# only once it holds the lock. A waiter that took the other slot before it was# named runs beside this build, so its reservation counts again (each side# writes first and reads the other second, so one of them always sees it). The# slot folder goes with its holder, and the names with it; a third job that# admitted counting this build takes the free slot as before. A one-slot Mac# (the signing Mac, another) gave a waiter no slot while the lock was held anyway.## WHY NOT THE STRONGER RULE, ADMIT ONLY ONCE THE LOCK IS HELD. It would make the# inversion impossible, but it does not fit what this policy admits: the PATH# shims (install-mac-build-policy.py) admit every swift, xcodebuild, cargo and# rustc a lane runs, most of them never under the build lock, and a lane script# wrapped whole (ui-stub-workspace.py) holds one reservation across steps only# some of which take the lock. Deferring admission to the lock would either put# every shimmed build under the lock or leave those paths unadmitted. And a cut# carries ONE admission across its separate compile and sign locks (cut_session,# keep_cut_admission): admitting per lock would let a lane slip in between the# stages and re-ask a cut for room it already holds. Walks and claims keep their# order either way; the exclusion changes only what a lock holder counts and,# on a two-slot Mac, when the waiters it left out may take the other slot.# Guard: scripts/__tests__/build-admission-lock-holder.test.ts.BUILD_LOCK_DEFAULT = '/tmp/tinmen-build.lock'BUILD_LOCK_SLOTS = ('', '.slot-2')BUILD_LOCK_WAITING = ('release-waiting', 'ci-waiting', 'walk-waiting', 'local-waiting')def build_lock_path(environ=None):    """The build lock this build is under: the one its holder exported, else the one with-build-lock.sh would take."""    environ = os.environ if environ is None else environ    return Path(environ.get('TINMEN_BUILD_LOCK_DIR') or environ.get('BUILD_LOCK_DIR') or BUILD_LOCK_DEFAULT)def build_lock_slot_pids(lock):    """The pid written in each held slot of `lock`, by slot folder."""    held = {}    for suffix in BUILD_LOCK_SLOTS:        slot = Path(f'{lock}{suffix}')        try:            pid = int((slot / 'pid').read_text().strip())        except (OSError, ValueError):            continue        if pid > 0:            held[slot] = pid    return helddef build_lock_holder(lock):    """The slot of `lock` held by this process or an ancestor of it, else None."""    return next((slot for slot, pid in build_lock_slot_pids(lock).items() if ancestor(pid)), None)def build_lock_waiters(lock):    """The live pids that filed a waiting marker beside `lock`, of every class."""    waiters = set()    for kind in BUILD_LOCK_WAITING:        try:            names = [entry.name for entry in Path(f'{lock}.{kind}').iterdir()]        except OSError:            continue        waiters.update(int(name) for name in names if name.isdigit() and int(name) > 0 and pid_alive(int(name)))    return waitersdef rows_waiting_on_lock(rows, waiters, table):    """The pids of admitted rows whose process is one of `waiters` or an ancestor of one."""    if not waiters:        return set()    parents = {pid: parent for pid, parent, _ in table}    chains = set()    for current in waiters:        for _ in range(64):            chains.add(current)            current = parents.get(current)            if current is None or current < 2:                break    return {row['pid'] for row in rows if not row.get('waiting') and row['pid'] in chains}def lock_waiting_rows(rows, lock, slot):    """`rows_waiting_on_lock` for the holder of `slot` of `lock`, over one process    snapshot, naming in `slot` the waiters it leaves out (see A WAITER LEFT OUT    TAKES NO SLOT). A snapshot or a name that cannot be read or written leaves    nothing out, and says so."""    waiters = build_lock_waiters(lock)    if not waiters:        return set()    try:        table = process_table()        behind = {pid for pid in waiters if rows_waiting_on_lock(rows, {pid}, table)}        if behind:            (slot / 'excluded').mkdir(exist_ok=True)            for pid in behind:                (slot / 'excluded' / str(pid)).touch()    except OSError as error:        print(f'build admission: counting every reservation — cannot find or name the builds waiting on {lock} ({error})',              file=sys.stderr, flush=True)        return set()    # Named first, read second: a waiter already in a slot runs beside this build.    return rows_waiting_on_lock(rows, behind - set(build_lock_slot_pids(lock).values()), table)def admission(rows, cls, ram, available, home, claim=None, total=None, lock_waiting=frozenset()):    """Whether a build of this class is admitted now, the bytes it counts as promised, and the cut it waits behind (or None).    A cut counts only admitted cuts and cut claims filed before its own; a lane    counts every admitted build and queues behind any waiting cut claim. Neither    counts an admitted row whose pid is in `lock_waiting`: a build waiting on the    build lock this one holds (see A BUILD WAITING ON THE BUILD LOCK)."""    admitted = [row for row in rows if not row.get('waiting') and row['pid'] not in lock_waiting]    claims = [row for row in rows if row.get('waiting') and row_class(row) == 'cut' and row is not claim]    if cls == 'cut':        ahead = [row for row in claims if claim is None or (row['started'], row['pid']) < (claim['started'], claim['pid'])]        cuts = [row for row in admitted if row_class(row) == 'cut']        promised = sum(row_ram(row, home, total) for row in cuts + ahead)        if ahead:            return False, promised, ahead[0]        # With no other cut admitted, a cut is never held by a lane's promise.        return (not cuts or available - promised - ram > MEMORY_FLOOR), promised, (cuts[0] if cuts else None)    promised = sum(row_ram(row, home, total) for row in admitted + claims)    if claims:        return False, promised, claims[0]    return available - promised - ram > MEMORY_FLOOR, promised, Nonedef cut_name(row):    return f"cut {row.get('label') or 'unlabelled'} (pid {row['pid']})"@contextmanagerdef build_reservation(path, home, need, kind, usage, idle, protected, memory, interval, wait_limit=WAIT_ADMIT_SECONDS, total=None, cls='lane', label=None,                      disk_wait=False, held=None, measured=None):    if type(need) is not int or need < 1 or kind not in MEMORY_NEED or cls not in ('cut', 'lane'):        raise RuntimeError('REFUSING TO START: invalid build reservation')    # Who waits for disk, as its lines say it: `walk` or `ci` (True is a walk).    waiter = disk_wait if isinstance(disk_wait, str) else 'walk'    inherited = cut_disk_admission(path, home)    if inherited is not None:        yield inherited['keep_free_bytes']        return    policy = home / '.cottondb/disk-policy.json'    ram = memory_need(kind, home, total)    waited = False    wait_started = None    claim = None    reservation = None    reading = None    wait = Wait(wait_limit)    # A LONE BUILD IS ADMITTED AFTER TEN MINUTES WHATEVER ITS CLASS (coordinator,    # 7 Nov 2026 22:20 IST). swift-compile runs 8393 and 8407 on one Mac each held    # the build lock while waiting "for RAM: held by no admitted build" with    # 4.6 GB free against a 4.7 GB need: nothing admitted stood in their way, so    # no build would ever free that RAM, yet a CI job's wait_limit is its 50-min    # ceiling (admission_limit), so each sat the whole ceiling holding the lock    # that two lanes' walks waited on, then died red. The ceiling-long wait is    # for a CI job BEHIND another admitted build (run 7057); alone on the Mac the    # ten-minute rule above applies to every class.    alone_limit = min(wait_limit, WAIT_ADMIT_SECONDS)    refused_behind = None    # Holding the build lock is fixed for the whole admission: a holder that    # yields TERMs this process with the rest of its tree.    lock = build_lock_path()    holder = build_lock_holder(lock)    try:        while True:            if cls != 'cut':                read_floor(path, policy)            with reservation_ledger(home) as rows:                if claim is not None:                    claim = next((row for row in rows if row == claim), None)                available = memory()                lock_waiting = lock_waiting_rows(rows, lock, holder) if holder is not None else set()                ok, promised, behind = admission(rows, cls, ram, available, home, claim, total, lock_waiting)                others = [row for row in rows if row is not claim]                # A build waiting on this holder's lock is not beside it on the Mac.                counted = [row for row in others if row['pid'] not in lock_waiting]                left_out = (f'; not counting {len(lock_waiting)} reservation(s) waiting on the build lock this build holds'                            if lock_waiting else '')                short_of_disk = None                alone_too_long = (waited and not counted and wait_started is not None                                  and time.time() - wait_started >= alone_limit)                if ok or alone_too_long:                    # A cut checks once, with what a cut really uses.                    if cls == 'cut':                        cut_need, said = cut_disk_need(kind, home)                        print(said, file=sys.stderr, flush=True)                        disk_bytes = max(need, cut_need)                    else:                        disk_bytes = need                    reading = {}                    # Like RAM admission, a cut counts other cuts' promises;                    # a lane counts every admitted build's disk reservation.                    disk_rows = [row for row in rows if row_class(row) == 'cut'] if cls == 'cut' else rows                    holding = sorted(row['pid'] for row in others if not row.get('waiting'))                    if disk_wait and holding and holding == refused_behind:                        # Nothing has finished since the last refusal: the room is no nearer.                        short_of_disk = f'for disk: {waiter} {kind} needs {disk_bytes} bytes; held by {len(holding)} admitted build(s)'                    else:                        try:                            floor = admit(path, policy, home, disk_bytes + reserved_disk(disk_rows, path), usage, idle, protected, reading, inherit=False, measured=measured)                        except RuntimeError as error:                            if not (disk_wait and holding and str(error).startswith('REFUSING TO START')):                                raise                            refused_behind = holding                            short_of_disk = f'for disk: {waiter} {kind} needs {disk_bytes} bytes; held by {len(holding)} admitted build(s); {error}'                if short_of_disk is None and (ok or alone_too_long):                    free_at_admission = reading['disk_free_bytes']                    rows[:] = others                    reservation = {'pid': os.getpid(), 'need': disk_bytes, 'kind': kind, 'ram': ram, 'class': cls,                                   'started': time.time(), 'volume': path.stat().st_dev}                    if label:                        reservation['label'] = label                    if declared_ceiling():                        reservation['limit'] = declared_ceiling()                    if cls == 'cut':                        reservation.update(disk_free_bytes=free_at_admission, keep_free_bytes=floor)                        keep_cut_admission(path, reservation)                    rows.append(reservation)                    if held is not None:                        held.append((reservation['pid'], reservation['started']))                    claim = None                    how = 'admitted on timeout: alone on this Mac after waiting' if alone_too_long else ('waited for RAM' if waited else 'no wait')                    print(f'build admission: {cls} {kind}; RAM available {available} bytes; reserved {promised + ram} bytes; floor {MEMORY_FLOOR} bytes; {how}{left_out}', file=sys.stderr, flush=True)                    break                if cls == 'cut' and claim is None:                    # The claim is what makes every later lane queue behind this cut.                    claim = {'pid': os.getpid(), 'need': need, 'kind': kind, 'ram': ram, 'class': 'cut',                             'waiting': True, 'started': time.time()}                    if label:                        claim['label'] = label                    rows.append(claim)                if not waited:                    wait_started = time.time()                waited = True                # What holds it, as it stands at this poll: the cut it queues                # behind, or the reservations its RAM is short of.                if short_of_disk is not None:                    on = short_of_disk                elif cls == 'lane' and behind is not None and behind.get('waiting'):                    on = f'behind {cut_name(behind)}: a cut is admitted ahead of every lane build; lane {kind} needs {ram} bytes'                else:                    holders = ', '.join(cut_name(row) if row_class(row) == 'cut' else f"{row.get('kind')} build pid {row['pid']}"                                        for row in counted if not row.get('waiting')) or 'no admitted build'                    ahead = f' behind {cut_name(behind)}' if behind is not None else ''                    on = f'for RAM{ahead}: held by {holders}; {available} bytes available; {cls} counts {promised} bytes of reservations; {cls} {kind} needs {ram} bytes above floor {MEMORY_FLOOR} bytes{left_out}'                if short_of_disk is not None:                    # A walk short of disk waits on the builds holding it, never past the limit.                    wait.tick(on)                elif not alone_too_long:                    # A cut behind a live holder has no cap (see WAIT_ADMIT_SECONDS):                    # it gives up only once every holder is dead or past its own ceiling.                    alive = live_holders(counted) if cls == 'cut' else []                    wait.tick(on, while_holder_lives=bool(alive) and not all(holder_outlived_limit(row) for row in alive))            time.sleep(interval)        yield floor    finally:        # Admission can be interrupted before yield (including while its ledger        # is being published). Release both possible rows on that exit too.        if reservation is not None or claim is not None:            with reservation_ledger(home) as rows:                rows[:] = [row for row in rows if row != reservation and row != claim]# A BUILD NEVER WAITS ON A SILENT SCCACHE SERVER (coordinator, 15 Oct 2026). On# one Mac, 14 Oct, two concurrent lanes' sccache server stopped answering and every# rustc wrapper behind it sat at 0% CPU — one lane's cargo for 3 to 30 minutes# before anyone noticed. So the first rustc of each cargo run asks the server# for its stats with a bound; a silent server is started once and asked again,# and when it is still silent that cargo run compiles every crate without the# cache and says so once. The verdict is per cargo run (its pid and start time),# so the probe costs one round trip per build, not one per crate.SCCACHE_PROBE_SECONDS = 5.0SCCACHE_VERDICT_DAYS = 1def sccache_answers(sccache, args, limit, detach=False):    # subprocess.run's timeout kills only the child it started; a server the    # start spawns gets its own session so stopping this build never stops it.    try:        return subprocess.run([sccache, *args], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,                              stderr=subprocess.DEVNULL, timeout=limit, start_new_session=detach).returncode == 0    except (OSError, subprocess.TimeoutExpired):        return Falsedef sccache_server_answers(sccache, limit=None):    """True when the server answers, after one start if it was silent."""    limit = limit or float(os.environ.get('COTTON_SCCACHE_PROBE_SECONDS', SCCACHE_PROBE_SECONDS))    if sccache_answers(sccache, ['--show-stats'], limit):        return True    sccache_answers(sccache, ['--start-server'], limit, detach=True)    return sccache_answers(sccache, ['--show-stats'], limit)def is_rustc_query(args):    return any(arg == '-vV' or arg.startswith('--print') for arg in args)# Inside a lane a child inherits the lane's seatbelt profile or does not run (architect, 15 Oct 2026):# no lane profile entry runs free, so /usr/bin/sandbox-exec cannot apply a second profile there. SwiftPM# and Xcode skip their own manifest and plugin sandboxes inside a lane, and so does the compiler's macro# plugin server (swift-frontend wraps swift-plugin-server in sandbox-exec; refused, it answers "produced# malformed response" for every macro — SwiftPM's --disable-sandbox reaches swiftc, xcodebuild needs# -disable-sandbox in OTHER_SWIFT_FLAGS); the lane's profile is the one that holds. Outside a lane the# command is untouched.SWIFTPM_VERBS = {'build', 'test', 'run', 'package'}SWIFTPM_TOOLS = {'swift-build', 'swift-test', 'swift-run', 'swift-package'}XCODE_NO_SANDBOX = ['-IDEPackageSupportDisableManifestSandbox=YES', '-IDEPackageSupportDisablePluginExecutionSandbox=YES']XCODE_ACTIONS = {'build', 'test', 'archive', 'analyze', 'build-for-testing', 'test-without-building', 'installsrc', 'install', '-resolvePackageDependencies'}# THE HOME UNDER ITS FLOOR, A SWIFT BUILD ON THE LANES SSD (coordinator, 24 Nov# 2026). The signing Mac's home volume held 12 GB against its 24.5 GB keep-free with# nothing left to reclaim, so every lane's `swift test` and `pnpm ios:test` was# refused there, though the lane, its .build and its derived data can all live# on the SSD beside it (364 GB free): 4d0123f128 reached main with two red Swift# unit tests that way. The floor stays and still guards the home volume. While# the home is under it, a lane's Swift build that names every place it writes# (write_roots) on the build's own volume, never the home's, is admitted and# watched on that volume against the same floor; and the home may lose at most# HOME_ALLOWANCE while it runs (a simulator's install, a result bundle in# TMPDIR), or the build is stopped as at the floor. A place left to its default# (SwiftPM's cache in ~/Library, Xcode's DerivedData) is on the home volume, so# such a build is measured on the home as before. A lane on the signing Mac names its# places through COTTON_SWIFTPM_CACHE and COTTON_DERIVED_ROOT (lane-start.sh,# lane-macs.json's swiftCacheRoot); swiftpm_cache_args gives a bare `swift` the# cache.HOME_ALLOWANCE = 2 * GIBdef flag_value(command, flag):    for i, arg in enumerate(command):        if arg == flag:            return command[i + 1] if i + 1 < len(command) else None        if arg.startswith(flag + '='):            return arg.split('=', 1)[1]    return Nonedef write_roots(command, path, env=None):    """Every place a Swift build writes, when each is named; None when one is left to its default (the home volume)."""    env = os.environ if env is None else env    if not command:        return None    tool = Path(command[0]).name    def at(value):        return Path(value) if Path(value).is_absolute() else Path.cwd() / value    if (tool == 'swift' and command[1:2] and command[1] in SWIFTPM_VERBS) or tool in SWIFTPM_TOOLS:        cache = flag_value(command, '--cache-path')        if cache is None:            return None        package = at(flag_value(command, '--package-path') or path)        return [at(flag_value(command, '--scratch-path') or package / '.build'), at(cache)]    if tool in {'swift', 'swiftc'}:        return None    if tool == 'xcodebuild':        derived = flag_value(command, '-derivedDataPath')        if derived is None:            return None        return [at(derived)] + [at(v) for v in (flag_value(command, '-clonedSourcePackagesDirPath'), flag_value(command, '-packageCachePath')) if v]    # A wrapper (with-build-lock's `bash -c`, a script): the places the scripts    # take from the environment (scripts/lib/derived-data.sh, swiftpm-cache.sh).    derived = env.get('COTTON_DERIVED_DATA') or env.get('COTTON_DERIVED_ROOT')    cache = env.get('COTTON_SWIFTPM_CACHE')    if not derived or not cache:        return None    return [Path(path), at(derived), at(cache)]def off_home(command, path, policy, floor, usage, env=None):    """Whether this Swift build is admitted and watched on its own volume: the home is under the floor and it writes nothing there."""    roots = write_roots(command, path, env)    if not roots:        return False    own = volume(path)    if own == volume(Path.home()) or any(volume(root) != own for root in roots):        return False    return usage(floor_path(path, policy)).free < floordef swiftpm_cache_args(command, env=None):    """A bare SwiftPM command takes the lane's named cache (COTTON_SWIFTPM_CACHE), never SwiftPM's own in ~/Library."""    env = os.environ if env is None else env    cache = env.get('COTTON_SWIFTPM_CACHE')    if not cache or not command or '--cache-path' in command or any(arg.startswith('--cache-path=') for arg in command):        return command    tool = Path(command[0]).name    if tool == 'swift' and command[1:2] and command[1] in SWIFTPM_VERBS:        return command[:2] + ['--cache-path', cache] + command[2:]    if tool in SWIFTPM_TOOLS:        return command[:1] + ['--cache-path', cache] + command[1:]    return commanddef lane_args(command, env=None):    env = os.environ if env is None else env    if env.get('COTTON_LANE_SANDBOXED') != '1' or not command or '--disable-sandbox' in command:        return command    tool = Path(command[0]).name    if tool == 'swift' and command[1:2] and command[1] in SWIFTPM_VERBS:        return command[:2] + ['--disable-sandbox'] + command[2:]    if tool in SWIFTPM_TOOLS:        return command[:1] + ['--disable-sandbox'] + command[1:]    if tool == 'xcodebuild' and any(arg in XCODE_ACTIONS for arg in command[1:]):        extra = [arg for arg in XCODE_NO_SANDBOX if arg not in command]        if not any(arg.startswith('ENABLE_USER_SCRIPT_SANDBOXING=') for arg in command):            extra.append('ENABLE_USER_SCRIPT_SANDBOXING=NO')        flags = [i for i, arg in enumerate(command) if arg.startswith('OTHER_SWIFT_FLAGS=')]        if flags:            command = list(command)            for i in flags:                if '-disable-sandbox' not in command[i].split():                    command[i] += ' -disable-sandbox'        else:            extra.append('OTHER_SWIFT_FLAGS=$(inherited) -disable-sandbox')        return command + extra    return commanddef cache_wrapper(command, home, parent=None):    """The command to run: as given while the cache wrapper's server answers,    without the wrapper when it stayed silent for this cargo run."""    sccache = os.environ.get('COTTON_RUSTC_CACHE_WRAPPER', '')    if not sccache or command[:1] != [sccache] or len(command) < 2:        return command    parent = parent or os.getppid()    started = process_start(parent)    key = f'{parent}-{int(started[0]) if started else 0}'    folder = home / '.cottondb/sccache-probe'    folder.mkdir(parents=True, exist_ok=True)    verdict = folder / key    with open(folder / f'{key}.lock', 'w') as lock:        # Concurrent rustc of one cargo run wait for the one probe.        fcntl.flock(lock, fcntl.LOCK_EX)        if not verdict.exists():            verdict.write_text('answers' if sccache_server_answers(sccache) else 'silent')            for entry in folder.iterdir():                try:                    if time.time() - entry.stat().st_mtime > SCCACHE_VERDICT_DAYS * 86400:                        entry.unlink()                except OSError:                    pass        if verdict.read_text() == 'answers':            return command        said = folder / f'{key}.said'        if not is_rustc_query(command[2:]) and not said.exists():            said.touch()            print(f'sccache: the server behind {sccache} did not answer, nor after one start; this build compiles without the cache',                  file=sys.stderr)    return command[1:]def run_build(command, path, home, need=1, usage=None, idle=None, interval=0.2, memory=None, kind=None, wait_limit=None, total=None, cls=None):    usage = usage or shutil.disk_usage    wait_limit = admission_limit() if wait_limit is None else wait_limit    policy = home / '.cottondb/disk-policy.json'    if is_query(command):        return subprocess.call(command, pass_fds=ownership_fds())    if cut_disk_admission(path, home) is not None:        return subprocess.call(command, pass_fds=ownership_fds())    inherited = os.environ.get('COTTON_DISK_MONITOR_PID', '')    if inherited.isdigit() and ancestor(int(inherited)):        # The outer build owns the reservation and monitors its process tree.        read_floor(path, policy)        return subprocess.call(command, pass_fds=ownership_fds())    read_floor(path, policy)  # Validate before creating even a lock.    protected = [path, Path.cwd()]    for key in ['CARGO_TARGET_DIR', 'COTTON_DERIVED_DATA', 'COTTON_UI_TESTS_REPO_ROOT']:        if os.environ.get(key):            protected.append(Path(os.environ[key]))    kind = kind or build_kind(command)    cls = cls or build_class()    label = os.environ.get('BUILD_LOCK_LABEL') if cls == 'cut' else None    walk = cls == 'lane' and is_walk()    ci = cls == 'lane' and is_ci() and kind == 'swift'    if (walk or ci) and need <= 1:        need, said = walk_disk_need(home, 'walk' if walk else 'ci')        print(said, file=sys.stderr, flush=True)    off = cls == 'lane' and kind == 'swift' and off_home(command, path, policy, read_floor(path, policy), usage)    if off:        print(f'device keep free: the home volume is under the floor and this build writes only on {path}\'s volume; '              f'it is admitted and watched there, and may take at most {HOME_ALLOWANCE} bytes of the home', file=sys.stderr, flush=True)    # A RESERVATION IS RELEASED ON EVERY EXIT PATH (coordinator, 14 Oct 2026,    # after a killed cut's row held its restart 23 minutes). A TERM, INT or HUP    # while waiting for admission unwinds through build_reservation's finally,    # so the claim goes; one during the build stops the build tree first and    # then the reservation goes. Only a KILL skips this, and the ledger's prune    # of a gone pid (row_gone) is the backstop for it.    child = None    stopped = False    def terminate(signum, frame):        nonlocal stopped        if child is None:            raise SystemExit(128 + signum)        stopped = True        signal_build(child, signal.SIGTERM)    old_signals = {s: signal.signal(s, terminate) for s in [signal.SIGTERM, signal.SIGINT, signal.SIGHUP]}    held = []    try:        with build_reservation(path, home, need, kind, usage, idle,                               protected, memory or free_memory, interval, wait_limit, total, cls, label, 'walk' if walk else 'ci' if ci else False, held,                               measured=path if off else None) as floor:            own = held[0] if held else None            env = dict(os.environ, COTTON_DISK_MONITOR_PID=str(os.getpid()))            measured = path if off else floor_path(path, policy)            initial_free = usage(measured).free            home_start = usage(floor_path(path, policy)).free if off else None            child = subprocess.Popen(command, env=env, start_new_session=True, pass_fds=ownership_fds())            peak = 0            disk_peak = 0            sampled = 0.0            previous = initial_free            try:                while child.poll() is None:                    time.sleep(interval)                    if time.time() - sampled >= min(2.0, interval):                        peak = max(peak, tree_rss(child.pid))                        sampled = time.time()                    free = usage(measured).free                    disk_peak = max(disk_peak, initial_free - free)                    if cls == 'cut':                        # Admission belongs to the cut until it gives the lock back.                        # No live reading or reservation may refuse its descendants.                        if stopped:                            raise RuntimeError('STOPPED: the build was signalled; its reservation is released')                        continue                    # Watch growth as well as the floor; stop before another polling                    # interval at the observed growth rate would consume the reserve.                    growth = max(0, previous - free)                    previous = free                    unavailable = None                    try:                        floor = read_floor(path, policy)                    except RuntimeError as error:                        unavailable = str(error)                    with reservation_ledger(home) as rows:                        reserved = reserved_disk(rows, path, own, initial_free - free)                    if off and unavailable is None:                        home_lost = home_start - usage(floor_path(path, policy)).free                        if home_lost > HOME_ALLOWANCE:                            unavailable = (f'REFUSING TO CONTINUE: the home volume lost {home_lost} bytes; a build admitted on '                                           f'{path}\'s volume may take at most {HOME_ALLOWANCE} bytes of the home while it is under the floor')                    if stopped or unavailable or free - reserved - growth <= floor:                        # Disk pressure gets no write-through grace period. Freeze                        # all owned descendants before ending them; keep live outputs.                        signal_build(child, signal.SIGSTOP)                        signal_build(child, signal.SIGKILL)                        child.wait()                        if stopped:                            raise RuntimeError('STOPPED: the build was signalled; its reservation is released')                        raise RuntimeError(unavailable or f'REFUSING TO CONTINUE: {free} bytes free; this device keeps {floor} bytes free')                return child.returncode            finally:                record_peak(home, kind, peak, total_memory() if total is None else total)                if cls == 'cut':                    record_disk_peak(home, kind, max(disk_peak, initial_free - usage(measured).free))                if child.poll() is None:                    signal_build(child, signal.SIGTERM)                    try:                        child.wait(timeout=5)                    except subprocess.TimeoutExpired:                        signal_build(child, signal.SIGKILL)                        child.wait()    finally:        for signum, handler in old_signals.items():            signal.signal(signum, handler)def main():    parser = argparse.ArgumentParser()    parser.add_argument('--process-info', nargs='+', help='in-process alive, args, nice or ancestor lookup for shell scripts')    parser.add_argument('--path', default=os.getcwd())    parser.add_argument('--need-bytes', type=int, default=int(os.environ.get('COTTON_BUILD_DISK_BYTES', '1')))    parser.add_argument('--floor-gb', action='store_true')    parser.add_argument('--check', action='store_true')    parser.add_argument('--dry-run', action='store_true')    parser.add_argument('--prune', action='store_true', help='read the reservation ledger once, dropping every row whose process is gone')    parser.add_argument('--probe-sccache', metavar='SCCACHE', help='ask this sccache server to answer, starting it once if silent')    parser.add_argument('--take-simulator', metavar='UDID[,UDID]', help='lock the first free one of these standing simulators for a walk and boot it under this Mac\'s cap')    parser.add_argument('--release-simulator', metavar='UDID', help='give a standing simulator back')    parser.add_argument('--holder', type=int, help='with --take-simulator or --release-simulator: the walk process that holds it')    parser.add_argument('--label', default='', help='with --take-simulator: who the walk is, said to every walk that waits on it')    parser.add_argument('--simulator-holders', metavar='UDID=NAME[,UDID=NAME]', help='print who holds each of these standing simulators and for how long')    parser.add_argument('--simulator-cap', action='store_true', help='print how many simulators this Mac boots at once')    parser.add_argument('command', nargs=argparse.REMAINDER)    args = parser.parse_args()    if args.process_info:        return process_info_command(args.process_info)    command = args.command[1:] if args.command[:1] == ['--'] else args.command    # The lane gate first: a whole test suite is refused before any admission    # in a lane (the suite gate: COTTON_LANE is set by lane:start).    gate = runpy.run_path(str(Path(__file__).with_name('suite_gate.py')))['refusal'](command)    if gate:        print(gate, file=sys.stderr)        return 2    if args.simulator_cap:        print(simulator_cap())        return 0    standing_home = Path(os.environ.get('COTTON_STANDING_HOME') or Path.home())    if args.simulator_holders:        pairs = [pair.split('=', 1) for pair in args.simulator_holders.split(',')]        held = [simulator_held(standing_home, udid, name) for udid, name in pairs]        print(', '.join(filter(None, held)) or f'{", ".join(name for _, name in pairs)} free; this Mac\'s simulator cap is full')        return 0    if args.take_simulator or args.release_simulator:        if not args.holder:            raise RuntimeError('--take-simulator and --release-simulator need --holder <pid>')        if args.release_simulator:            return release_simulator(standing_home, args.release_simulator, args.holder)        limit = float(os.environ.get('COTTON_SIMULATOR_WAIT_SECONDS') or WAIT_ADMIT_SECONDS)        print(take_simulator(args.take_simulator.split(','), args.holder, standing_home, wait_limit=limit, label=args.label))        return 0    if args.probe_sccache:        if sccache_server_answers(args.probe_sccache):            return 0        print(f'sccache: the server behind {args.probe_sccache} did not answer, nor after one start; '              'each build probes it again and compiles without the cache while it stays silent', file=sys.stderr)        return 1    command = cache_wrapper(command, Path.home())    command = swiftpm_cache_args(command)    command = lane_args(command)    if sys.platform != 'darwin':        return subprocess.call(command) if command else 0    path = Path(args.path).resolve()    while not path.exists():        path = path.parent    home = Path.home()    if args.prune:        # The wrapper's last act after it KILLs a build tree that would not        # stop: the killed policy's row goes now, not at the next admission.        with reservation_ledger(home):            pass        return 0    if args.floor_gb:        print((read_floor(path, home / '.cottondb/disk-policy.json') + 1_073_741_823) // 1_073_741_824)        return 0    if args.dry_run:        # The reclaim a cut's admission runs, removing nothing: for a cut's        # own need unless --need-bytes names another.        policy = home / '.cottondb/disk-policy.json'        floor = read_floor(path, policy)        need = args.need_bytes if args.need_bytes > 1 else cut_disk_need('swift', home)[0]        print(f'device keeps {floor} bytes free; work needs {need} bytes; dry run removes nothing', flush=True)        free = reclaim(path, policy, home, need, floor, protected=[Path.cwd()], dry_run=True)        print(f'after the reclaim: {free} bytes free; {"admitted" if free - need >= floor else "still short"}')        return 0    if command:        return run_build(command, path, home, args.need_bytes)    admit(path, home / '.cottondb/disk-policy.json', home, args.need_bytes,          protected=[Path.cwd()] if Path.cwd() not in [home, Path('/')] else [])    return 0if __name__ == '__main__':    try:        sys.exit(main())    except HeldTooLong as error:        print(error, file=sys.stderr)        sys.exit(EX_TEMPFAIL)    except (RuntimeError, OSError, ValueError) as error:        print(error, file=sys.stderr)        sys.exit(1)