freePort closed its listener before returning, so the kernel was free to hand the next call the same port. An instance asks for three in a row:
port: freePort(t),
httpPort: freePort(t),
gitPort: freePort(t),
On a collision gitbayd binds the first and fails the second, and the test that started it times out. The failure lands on whichever test drew the collision, so it moved around and never looked like the same bug twice.
Caught in build 157:
INFO git-daemon listening addr=[::]:33767
INFO http listening addr=127.0.0.1:33767 tls=off
gitbayd: listen tcp 127.0.0.1:33767: bind: address already in use
--- FAIL: TestCLI (11.06s)
ssh_test.go:50: gitbayd did not start listening
freePorts holds every listener open until all the ports are picked, then closes them together. TestACMEServe and the backup restore allocated in pairs and had the same bug.
Evidence
Measured on the runner host, 200 rounds of three picks:
sequential (close before next): 1 collisions in 200 rounds of 3
held open until all picked: 0 collisions in 200 rounds of 3
About half a percent per instance, and a suite run starts many instances, which is the right order of magnitude for how often this bit.
On the test
TestFreePortsAreDistinct is honest but weak: it passes with the buggy implementation on macOS, whose kernel does not immediately reuse a freed port. It is meaningful on Linux CI and vacuous on a Mac. The measurement above is the real verification; the test is there to hold the invariant.
This is a narrowing rather than an elimination — another process can still take a port between the close here and gitbayd's bind. Distinctness within one instance is the part that is ours, and the part that was failing.
Full suite green.