This one is about a small locking problem on my own machine, which I think applies to any setup where a long job made of many short steps shares a machine with something that sometimes needs the whole machine to itself. In my case the long job was a mutation-testing runner and the thing that needed the whole machine was the build gate I run before opening a pull request, and the way they were wired together meant that the runner threw away the results it had collected whenever a gate started waiting.
The setup
I run a lot of coding-agent sessions in parallel on one Mac, across several projects (a few iOS apps, Maven builds for Java services, Playwright and Jest test runs), and they all build and test on the same CPU. One of those iOS apps has several sessions going at once in separate worktrees, and to keep them from trampling each other its scripts share a machine-wide hold, which is just flock on a lock file. Only that app’s scripts know about the hold, so everything else on the machine still adds load without asking. Its ordinary builds and test runs take the hold shared, so any number of them can run at once, and the pre-PR gate, which runs the whole suite and wants as quiet a machine as it can get, waits for it exclusive. While the gate waits it also leaves an “intent” behind (a second lock), and a new shared take is refused right away with exit code 76 while the lock is held exclusive or an intent is live, so the gate doesn’t starve behind a constant stream of new builds.
A take looks roughly like this, with the lock taken before the intent is read:
import fcntl
def take_shared(self):
if self.inside_parent_hold(): # descriptor 7 is already open on the lock file
return # a child of a holder is already inside the hold
try:
fcntl.flock(HOLD_FD, fcntl.LOCK_SH | fcntl.LOCK_NB)
except BlockingIOError: # someone holds it exclusive
self.close_hold_fd()
raise HoldRefused("held exclusive") # the shell scripts exit 76 here
if self.intent_is_live(): # read after taking the lock, not before
self.close_hold_fd()
raise HoldRefused("a gate is waiting")
Reading the intent after taking the lock means that a gate recording its intent at the same moment can’t be passed by, which it could be if we checked first and locked second. The hold lives on a fixed descriptor (7), so a child process that inherits it is already inside the parent’s hold, and its own take returns before it looks at any intent.
That works well for short things like a build, which takes a few minutes and holds shared while the gate waits for it to finish, and then the gate gets the machine.
How the runner asked for the lock
The mutation runner is a long job that takes a list of mutants (small deliberate breaks in production code), applies them one at a time, and runs the tests that are supposed to catch each one. A mutant counts as killed when the test named to catch it fails on the expected assertion, and each test-and-assertion pair the runner has to prove is a claim. For the branch I was checking that was 74 mutants, and with the follow-up runs that settle a verdict (a second run to rule out a flaky test, a run of a test on its own, a run with no mutant at all) about 160 test runs, roughly 2 h 40 min when nothing gets refused, on a machine whose load average swung from single digits to several hundred during a check.
The runner itself never took the hold, so each test run it started went through the normal test script, which took the hold shared for itself and released it, and the next test run took it again. A check asked for the lock around 160 times, and the moment another session’s gate started waiting, every remaining ask was refused, most of them in under a second.
A check finishes by running all of its selected tests once more on the restored code, and if that run shows a new red, every kill is voided, because you can’t trust a kill when the suite is red without any mutant. The runner read a refused final run (exit 76, no result bundle) as unreadable, and unreadable counted the same as red. Seven full checks of that branch over four days ended the same way, and in the last one a final run refused in 2.2 seconds voided 50 kill verdicts covering 39 of the 70 claims.
A refused run tells you nothing about the code, since none of the tests in it ran.
Holding the lock once and stepping aside
Retrying on 76 would only move the problem around, because a retry still lets the gate cut off runs, and since the lock gives no signal for when trying again makes sense, it would also need its own rule about which runs are safe to retry.
The cause is that the runner asks for the lock 160 times. If it asks once and hands the lock down to its children, there’s nothing left in the middle of a check for the gate to refuse. So the runner now takes the hold shared before its first build, keeps it until the report is written, and starts every child with the hold’s descriptors passed through (Python’s subprocess closes them by default, so this has to be explicit):
subprocess.Popen(cmd, pass_fds=hold.pass_fds())
On its own that would leave the gate waiting for the whole three hours of a check, and the design of the hold assumes shared work is short, so before each build or test run the runner checks whether someone is waiting for exclusive, and if so, it releases its hold, lets the gate go first, and polls until it can take the hold shared again:
def between_runs(self):
if self.hold.mode != "shared": # inside a parent's hold: not ours to give up
return
waiter = self.hold.waiting()
if waiter is None:
return
say(f"{waiter} is waiting for the Mac; letting it go first")
self.hold.release()
self.take(limit=None) # retry take_shared once a second until it succeeds
The guard at the top matters if the runner itself runs inside someone else’s hold, since releasing a descriptor it inherited wouldn’t free anything. Between two steps the runner has nothing running in its scratch worktree, so stepping aside there is safe. A flock belongs to the open file, though, so the lock is only free once no leftover child process still has the inherited descriptor open, and the runner’s simulator stays booted while it waits, so the gate gets the CPU but not a perfectly idle machine.
The gate now waits at most for the one build or test run in flight. Before the change a test run took around 40 seconds at the median but close to ten minutes at its slowest, a rebuild took 155 to 225 seconds, and the check’s first build can take longer than a rebuild, so those are the expected waits rather than measured ones. The runner never takes the intent while it polls to get back in, so a waiting gate always goes first, and a busy afternoon should only make a check longer on the clock instead of costing it runs. That last part is what the change is designed for and what its unit tests cover (a child inside the run isn’t refused while a gate’s intent is live, and a gate that’s waiting gets the machine and hands it back), but no real check has run on the new runner yet.
Where the wait limit belongs
My first version bounded every wait for the hold by the same limit the gate uses for its own wait (three hours by default), which looked tidy, since the runner shouldn’t wait longer than a gate would. A review of the branch found that this broke the retake after stepping aside, because the runner starts waiting the moment it steps aside, while the gate may still be waiting for other builds, so it waits for the rest of the gate’s wait plus the gate’s whole run, and the gate’s limit only covers the first of those. Giving up at that point raised an error that threw away every verdict the check had already settled, so now only the first take has a limit (if the machine isn’t free when you start, it’s fine to give up and say so), and a retake waits until the gate is done or a signal stops the run.
Recording a final run that never ran
Holding the lock fixes refusals, but a final run can still be lost in other ways, like a full disk or a Ctrl-C at the wrong moment, and the verdict logic now tells those apart from a red. A final run that ran and showed a red still voids every kill, as before. A final run that didn’t run, or left nothing readable behind, now leaves its kills as “waiting for the final run”, and if no claim is open for some other reason, the check exits with the “nothing proven” status (75) instead of the failure one (1).
That only helps if you can supply the missing run without redoing the other 159, so there’s a small finish command that takes the branch’s last check (and refuses if it has no waiting kills), checks that the tree is byte-for-byte the snapshot the check ran on, runs only the final runs, and weighs them the way the original check would have.
Keeping the tests off the real lock
While building this, one of the runner’s own test files took 49 minutes, because the tests were taking the real machine hold while a gate from another session had it or was waiting for it, so they waited behind the gate with no output at all. Pointing the tests at a private lock directory brought that file back to 4 seconds, which is worth doing for any test of code that takes a machine-wide lock.
Summary
If a long job is made of many short heavy steps, it should take a shared lock once for its whole run and step aside between steps for anyone waiting exclusively, instead of asking for the lock before every step, because every separate ask is a point where a waiting gate can refuse it, while stepping aside still lets the gate in after at most one step. Inside the take, lock first and check for a waiter second, and put a deadline only on the first wait, where giving up loses nothing. And when a step didn’t run, record it as missing evidence that can be supplied later, rather than reading it as a failure, since a run that never started says nothing about the code.