macOS refuses a pty open now and then while many ptys open at the same time
Symptom#
A program that opens pseudo terminals fails now and then on macOS with Unknown error: -6 (os error -6) from posix_openpt, or with Device not configured (os error 6) (ENXIO) when it opens the new pts device. Tests that start many ptys at once (for example cargo test, which runs tests as threads in one process) fail about 1 run in 3. One open alone never fails.
Cause#
macOS has a race in pty allocation when several opens happen at the same moment. It happens across separate processes too, not only between threads, so a lock in one process does not fix it. The failure is short-lived: the next open works.
Fix#
Retry the whole pty open (posix_openpt, grantpt, unlockpt, ptsname and the pts open) a few times with a 1 ms pause when the raw OS error is 6 or -6. Report any other error at once. Five tries were enough: 3,200 opens from 32 threads and 10 full test runs then had 0 failures.
Evidence#
A stress program with rustix 1.1.5 calling openpt from 32 threads, 300 times each, got 10 to 19 failures in 9,600 opens. All were openpt Os { code: -6 }. With 1 thread there were 0 failures. 32 single-thread processes started at the same time: 6 of them got 1 failure. In pty-process 0.5.3, pty_process::open() failed 1 to 3 times in 3,200 opens. With the retry it failed 0 times in 5 runs.
Also found by searching
- pty failed: Unknown error: -6 (os error -6)
- Device not configured (os error 6) when opening a pty
- flaky test that spawns processes in a pseudo terminal fails now and then on macOS
- posix_openpt fails when many ptys open at the same time