My build scripts point TMPDIR at one scratch directory that every build and test run on the machine shares, and a small reaper cleans up whatever Xcode, SwiftPM and the scripts leave in it once it's a few days old. It was told never to touch SwiftPM's lock files, which are zero-byte files with names like _Users_me_Code_project_.build.lock, and by the time I looked there were 621 of them. They take no space, but there's one for every path SwiftPM ever locked, nothing ever removes them, and they clutter every listing of the directory, so this post is about which of them we can delete without pulling a lock out from under a build that holds it, and about the signals that look like they'd tell us that and don't.
What SwiftPM does with these files
SwiftPM's FileLock (in swift-tools-support-core, Sources/TSCBasic/Lock.swift) opens <TMPDIR>/<name> with O_CREAT and takes a flock on it, exclusive by default. Unlocking only releases the flock, the descriptor is closed when the lock object goes away, and nothing ever unlinks the file. The name is the locked path with the symlinks in its parent directory resolved first (so a checkout under /tmp shows up as _private_tmp_...), and then roughly this:
def lock_name(resolved_path: str) -> str: # components joined by "_", ":" also becomes "_", then ".lock" on the end return "_" + resolved_path.strip("/").replace("/", "_").replace(":", "_") + ".lock" If that name, .lock included, is longer than 255 bytes, SwiftPM keeps its last 255 bytes and then drops up to three more bytes so that a multi-byte character isn't split in half. So a name that was cut is 252 to 255 bytes long, and the beginning of the path (the part that would tell us its root) is gone.
None of this is a bug. A lock file has to exist for flock to work, and deleting it on unlock would race with the next process that wants it, so leaving it there is the simple and correct choice for SwiftPM. It just means whoever cleans them up has to be careful, because if we remove a lock file while a process has it open, the next build creates a new file under the same name and locks that one, and two builds both think they hold the lock.
What a lock file doesn't tell us
Its age
SwiftPM never writes to the file, it only opens and locks it, so its modification time is the moment it was created and stays that way. On my machine every one of the 621 locks had a birth time equal to its mtime, which means a lock that every single build takes looks exactly as old as one nobody has touched in months. The reaper still requires a lock to be three days old, since that costs nothing, but the age floor proves nothing on its own.
Its name
We can't decode the name back into a path, because the encoding is lossy. _Users_me_my_app.lock could be /Users/me/my_app, /Users/me/my/app or /Users/me_my/app, and with : also mapped to _ there are even more candidates. So we go the other way and walk the filesystem from /, looking for any existing path that encodes to the name. The walk is called with the name minus its leading _ and its .lock suffix (Users_me_my_app here):
def encodes_to(directory: str, rest: str) -> bool: entries = listing(directory) # sorted os.listdir, each directory listed once per pass if entries is None: # can't list it, so assume it matches return True for entry in entries: encoded = entry.replace(":", "_") if rest == encoded: return True if rest.startswith(encoded + "_") and encodes_to( os.path.join(directory, entry), rest[len(encoded) + 1:] ): return True return False Every entry whose encoded name is a prefix of what's left gets tried, so my_app and my/app are both found, and since os.listdir follows links, a path that some tool named through a symlink is found too. It only ever lists directories along matching prefixes (/, /Users, /Users/me, ...), so it touches a few hundred directories rather than the whole disk, and since locks share long prefixes, listing each directory once per pass and reusing that listing is what keeps it cheap. A directory we can't list (no permission, a privacy-protected folder like ~/Documents, too many levels of symlinks) counts as a match, so the locks under it are kept. os.listdir has no timeout though, so a lock for a path on a network volume that has gone away can hang the walk, which is worth knowing before pointing this at a machine with network mounts. A name that is 252 bytes or longer is never reaped, because the walk can't know which root it started from.
On the real directory this found 176 locks that no existing path encodes to.
Whether its path still exists
A missing path sounds like proof that nobody needs the lock, but it isn't. SwiftPM's own machine-wide state (the caches under ~/Library/Caches/org.swift.swiftpm, ~/Library/org.swift.swiftpm, ~/.swiftpm and ~/.config/swiftpm) has locks too, and when that cache is purged their paths are gone until the next resolve recreates them under the very same lock names. These are some of the busiest locks on the machine, since every resolve takes some of them, so removing them frees nothing and only gives the race below more chances to happen. The reaper skips any lock whose name falls under those four roots before it walks the filesystem.
Is anyone holding it?
Before asking which processes have a file open, we only consider files we own (st_uid == os.getuid()). lsof run as a normal user can't see other users' processes, and it doesn't tell us that it left them out, so a lock that sudo swift build left behind (owned by root, in our own directory) would look free.
We will take our own non-blocking flock before removing anything (more on that below), but that only catches a process that holds the lock at that moment. A process that has opened the file and not locked it yet, or one that locked and unlocked it and still keeps the lock object (and with it the descriptor), is invisible to flock, so we also ask lsof which files in the directory are open.
lsof +d <dir> exits 1 when it lists files, when it lists nothing, and on an error, and only the error writes to stderr. The man page explains why (with +d every file in the directory is something it was asked to find, and not finding one counts as an error), so the check accepts 0 or 1 with an empty stderr and reads the output either way.
The other thing is that lsof escapes file names it thinks the terminal can't show. Without a UTF-8 locale it prints a non-ASCII byte as literal \xNN text, so under env -i a lock for a path with é in it comes out as _Users_\xc3\xa9_x.lock, which matches nothing in the directory (my first version compared names and would have called that lock free). Device and inode numbers don't have that problem, and we can compare them with what lstat gives us:
def open_files(directory: str) -> set[tuple[int, int]] | None: """(device, inode) of every file under `directory` that is open, or None if lsof can't say.""" try: completed = subprocess.run( ["lsof", "-nP", "-F", "Di", "+d", directory], capture_output=True, text=True, errors="surrogateescape", timeout=60, ) except (OSError, subprocess.SubprocessError): return None if completed.returncode not in (0, 1) or completed.stderr != "": return None opened = set() device = inode = None # each "p" (process) or "f" (file descriptor) line starts a new record for line in [*completed.stdout.splitlines(), "f"]: tag, value = line[:1], line[1:] try: if tag in ("p", "f"): if device is not None and inode is not None: opened.add((device, inode)) device = inode = None elif tag == "D": device = int(value, 16) elif tag == "i": inode = int(value) except ValueError: return None return opened When it returns None, nothing is removed, since no lock can be shown to be free. A lock is a candidate only when its (st_dev, st_ino) isn't in the set.
Removing it
Between the survey and the removal a build may have taken the lock, or another reaper may have removed the file and a build created a new one under the same name. So right before removing a lock we run the whole survey for it again, against an lsof snapshot taken for the removal pass, and then open the file, take our own non-blocking flock, and check the file we're holding (not just whatever is at the name now) against the file-level tests once more. It has to be a regular, empty file we own, old enough, not under SwiftPM's shared state, with no existing path that encodes to its name, and still the file at that name. With two reapers running, the file at the name may be one a build created a moment ago, so checking only that the name still points at the held file isn't enough.
def unlink_unheld_lock(path: str, still_qualifies) -> str: try: # never follow a symlink planted at the name, never block opening a FIFO descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) except OSError: return "kept" if not os.path.lexists(path) else "failed" try: try: fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError: return "kept" # someone holds it held = os.fstat(descriptor) if not still_qualifies(held): # owner, regular, empty, age, shared state, path gone return "kept" try: current = os.lstat(path) except FileNotFoundError: return "kept" if (held.st_dev, held.st_ino) != (current.st_dev, current.st_ino): return "kept" # the name points at another file now os.unlink(path) return "removed" except OSError: return "failed" finally: os.close(descriptor) There are a few cases left that no outside check can see. A process that opened the file after lsof ran and hasn't called flock yet, a process that still holds an unlocked FileLock with its descriptor open, and a process that opens the file while we hold our own lock (it waits on the file we're about to unlink) all end up locking a file that no longer has a name, while the next build creates and locks a new one. The gap between our lstat and unlink is also only closed against other cleaners that take the same flock, so a plain rm or a system temp cleaner isn't covered by any of this. The "path is gone" rule narrows all of these down to checkouts that were deleted or haven't been rebuilt yet, which is about as far as we can get from outside SwiftPM.
Summary
Nothing we can check from outside SwiftPM proves that a lock file is free. Our own flock catches a process that holds the lock right now, lsof (compared by device and inode) catches one that only has the file open, and re-checking the file we're holding catches a file that was swapped under the name, but a process that opens the file after lsof ran slips past all three, so the best we can do is make the set of locks we try small enough that this hardly matters. The age doesn't change because SwiftPM never writes to the file, the name is lossy and cut at 255 bytes so it has to be matched by walking the filesystem, a missing path means nothing for the cache locks that lose their paths on every purge, and lsof can't see other users' processes, doesn't say through its exit code whether it found anything, and escapes the names it prints, so we only touch files we own and compare by device and inode. What's left after all that are locks for checkouts that were deleted or haven't been rebuilt yet, which is a small enough set to clean up.
