Skip to content

Library lock stays held after LibraryLock is dropped while another thread spawns a process (flaky second_opener_is_refused_until_the_first_lets_go) #680

Closed

Description

@cajax

Summary

LibraryLock (crates/catalog/src/lock.rs) frees the library by closing its File: Drop removes the owner note, then the handle closes and the OS is expected to release the lock. On Unix the lock is an flock lock. Those belong to the open file description, not to the descriptor, and stay held until every descriptor that refers to it is closed.

When any thread of the process spawns a child, posix_spawn (or fork) copies the whole descriptor table into the child, catalog.lock included. O_CLOEXEC closes the copy only when the child reaches execve. If another thread drops a LibraryLock inside that window, the lock outlives it. Re-acquiring the library then fails with LockError::InUse(None), i.e. "This library is already open in another LightCraft program", even though nobody has it open. None because the owner note is already gone.

That is the flake in tests_lock::second_opener_is_refused_until_the_first_lets_go: tests_lock::lock_held_by_another_process_is_released_when_it_dies spawns the test binary on a parallel libtest thread at the same moment. The cause is in the product code, not the test: the test only exposes it. The fix is three lines: release explicitly with File::unlock() in Drop (see Proposed fix).

Impact

  • CI / developers: cargo xtask ci fails intermittently. The catalog test binary fails 15/30 (reported) and 6/20 (re-measured) runs, always on this one test.
  • Users: nothing reproduces it today in the shipped app or CLI (see Is the product affected?). The race is in the product code, though, and the symptom is a false "already open" refusal that sends the user looking for another program. It doesn't crash and doesn't damage the library: a retry succeeds.
  • Other test binaries (suspected): the engine test binary has the same mix. One test spawns a child: demo::tests::scenes_are_generated_when_the_global_pool_is_broken (crates/engine/src/demo.rs). Others drop a session and reopen the same library: edits_survive_restart_without_close and a_library_open_elsewhere_is_refused (crates/engine/src/tests_library.rs).

Environment

  • Linux x86_64 (Ubuntu 26.04.1 LTS), kernel 7.0.0-38-generic (PREEMPT_DYNAMIC), glibc 2.43, 22 CPUs
  • rustc 1.99.0 (b940084d7 2026-09-28), the compiler that built the test binary; strace 6.19
  • Temp dir on tmpfs; machine moderately loaded (load average 1.4–4.8, a parallel build running)

Reproduce

cargo test -p lightcraft-catalog --lib --no-run   # note the test binary path
BIN=target/debug/deps/lightcraft_catalog-<hash>
# flaky (about 2 in 3 runs here):
$BIN --exact tests_lock::second_opener_is_refused_until_the_first_lets_go \
             tests_lock::lock_held_by_another_process_is_released_when_it_dies
# deterministic: strace holds the spawned child between clone and execve for 1 s
strace -f -o /dev/null -e trace=execve -e inject=execve:delay_enter=1000000 \
  $BIN --exact tests_lock::second_opener_is_refused_until_the_first_lets_go \
               tests_lock::lock_held_by_another_process_is_released_when_it_dies

Failure: panicked at crates/catalog/src/tests_lock.rs:32:62: called Result::unwrap() on an Err value: InUse(None) (the let again = LibraryLock::acquire(..) after drop(first)).

Measurements

The same test binary was used throughout (catalog crate as on main). "Reported" numbers are from the first investigation, "re-measured" from this one.

Run Failed
second_opener… alone 0/30 reported · 0/30 re-measured
second_opener… + lock_held_by_another_process… (--exact) 22/30 reported · 19/30 and 10/10 re-measured
the same pair with --test-threads=1 0/30
whole binary with --skip lock_held_by_another_process 0/30 reported
whole binary 15/30 reported · 6/20 re-measured (only second_opener… ever fails)
the pair with the child's execve delayed by strace (above) 5/5

The flake needs both tests running concurrently: run one at a time, the pair never fails. That rules out the child touching the other test's directory. strace confirms the child only opens its own lc-lock-child-* files.

A standalone program reproduces it outside LightCraft. It mimics LibraryLock exactly (same OpenOptions, File::try_lock, owner note removed in Drop, then the File closes). One thread spawns /bin/true (or true through a PATH search, like xdg-open) in a loop. Another locks, drops and re-locks the same directory:

Release on drop Re-locks refused
close only (what LibraryLock does) 437 / 20 000 (2.2 %), about 4 960 children
close only, PATH lookup (true) 410 / 20 000 (2.1 %)
close only, no spawning thread 0 / 20 000
OFD lock (fcntl F_OFD_SETLK), close only 447 / 20 000 (2.2 %): OFD locks don't help
File::unlock(), then close 0 / 200 000, about 5 300 children
OFD lock, explicit unlock, then close 0 / 200 000
one thread only: lock, Command::spawn() returns, close, re-lock 32 / 50 000
the same with File::unlock() 0 / 50 000

The last two rows matter for the fix: "wait until spawn() has returned" doesn't close the window. See the mechanism below.

Mechanism (verified)

  1. The lock is flock and the descriptor is close-on-exec. strace shows openat(…catalog.lock, O_RDWR|O_CREAT|O_CLOEXEC) and then flock(3, LOCK_EX|LOCK_NB); /proc/<pid>/fdinfo reports flags: 02100002 (O_RDWR | O_LARGEFILE | O_CLOEXEC). Nothing is leaked past exec. (The toolchain has no rust-src component, so this comes from strace rather than from reading std's source.)
  2. std's Command::spawn uses glibc posix_spawn: clone3({flags=CLONE_VM|CLONE_VFORK|CLONE_CLEAR_SIGHAND, …}). That copies the parent's descriptor table into the child, and the child sets up stdio with dup2 and then calls execve. Only the calling thread is suspended. The other threads keep running, and the child holds copies of all descriptors until execve closes the O_CLOEXEC ones.
  3. The failing run (strace -f -tt). T1 = second_opener…, T2 = lock_held_by_another_process…, C = the child T2 spawns:
T1 .154381 openat(AT_FDCWD, "$TMPDIR/lc-lock-twice-<pid>/catalog.lock", O_RDWR|O_CREAT|O_CLOEXEC, 0666) = 3
T1 .154434 flock(3, LOCK_EX|LOCK_NB) = 0                       # first acquire
T1 .154844 openat(AT_FDCWD, "$TMPDIR/lc-lock-twice-<pid>/catalog.lock", …) = 6
T1 .154870 flock(6, LOCK_EX|LOCK_NB) = -1 EAGAIN               # second opener refused (expected)
T2 .154981 clone3({flags=CLONE_VM|CLONE_VFORK|CLONE_CLEAR_SIGHAND, exit_signal=SIGCHLD, …}, 88) = C
                                                               # C now has a copy of T1's fd 3
T1 .155009 close(6) = 0
T1 .155208 close(3) = 0                                        # drop(first): T1's descriptor is closed…
T1 .155253 openat(AT_FDCWD, "$TMPDIR/lc-lock-twice-<pid>/catalog.lock", …) = 3
T1 .155273 flock(3, LOCK_EX|LOCK_NB) = -1 EAGAIN               # …but re-acquiring fails: InUse(None)
C  .155441 dup2(4, 1) = 1
C  .155474 dup2(5, 2) = 2
C  .155508 execve("<test binary>", [… "--exact", "tests_lock::lock_holder_child", "--ignored", …], …) = 0
                                                               # only now are C's O_CLOEXEC copies closed
  1. Who holds the lock at the failing moment. strace delays the child's execve (-e inject=execve:delay_enter=3000000), and the files under /proc are read while it waits. Here the parent is process 3666680 and the child 3666684:
$ ls -l /proc/3666684/fd                  # the child, stuck in its delayed execve
0 -> /dev/null   1 -> /dev/null   2 -> /dev/null
3 -> $TMPDIR/lc-lock-twice-3666680/catalog.lock
4 -> /dev/null   5 -> /dev/null
$ ls -l /proc/3666680/fd | grep catalog.lock
(nothing: the test thread already closed its descriptor)
$ cat /proc/3666684/fdinfo/3
pos:    0
flags:  02100002
ino:    1516086
lock:   1: FLOCK  ADVISORY  WRITE 3666680 00:31:1516086 0 EOF
$ grep ':1516086 ' /proc/locks
114: FLOCK  ADVISORY  WRITE 3666680 00:31:1516086 0 EOF

The only open descriptor on the locked file is the child's inherited copy. /proc/locks still names the parent, which created the lock, even though the parent no longer has a descriptor on it.

  1. spawn() returning isn't the end of the window. The single-thread row above (32/50 000) shows it. The kernel wakes the vforked parent while the child is still inside execve, before the child's close-on-exec descriptors are closed. In fs/exec.c begin_new_exec(), exec_mmap() → mm_release() → complete_vfork_done() runs before do_close_on_exec(). That ordering is from reading the kernel source and wasn't checked against this exact 7.0 build. The 32/50 000 measurement does fit it.

So the window runs from clone until just after execve: microseconds normally, 0.5 ms under strace, longer when the CPU is busy. The two tests start together, and T2's spawn lands right in T1's ~1 ms of lock/drop/re-lock, so the pair fails most of the time.

Is the product affected?

  • Verified: the race is in the product code. LibraryLock is used unchanged by the engine (crates/engine/src/library.rs, Session::open_library). The standalone mimic and a verbatim copy of lock.rs + tests_lock.rs (below) both show it.
  • Verified: a long-lived child does not keep a library locked. The mimic held the lock, spawned two sleep 5 children (one from the locking thread, one from another thread, standing in for xdg-open, an external editor or zenity), dropped the lock and re-locked: re-locking succeeded while both still ran, and neither child's /proc/<pid>/fd had catalog.lock. Once a child has exec'd, its copy is gone. "The library stays in use after LightCraft quits because of a child process" does not happen.
  • Not found in today's flows (code review, not exhaustive):
    • The app's own spawns are open_with, open_url and reveal (apps/lightcraft/src/main.rs, services(); xdg-open/open/explorer/the chosen editor). They run on the UI thread, which is also where libraries are opened and closed.
    • Reopening the library a session already has open hands its lock over instead of re-acquiring it (crates/engine/src/library.rs, open_library, let reused = …).
    • lightcraft-cli (including mcp) and the library crates spawn nothing outside tests.
    • Concurrent spawners do exist. rfd 0.17 (default xdg-portal feature) falls back to spawning zenity from its own thread when no xdg-desktop-portal answers. Commands' file dialogs already run on the file-dialog thread. On macOS and FreeBSD, crates/engine/src/memory.rs total_ram() runs sysctl the first time the memory budget is needed, from whichever thread asks first.
    • Hitting it would need a library to be closed and then reopened (by LightCraft or by another program) within microseconds of one of those spawns. That is unlikely by hand today, but it becomes likely once code that spawns processes or closes and reopens libraries runs on worker threads (e.g. background tasks).
  • Suspected, not verified:
    • FreeBSD: libc posix_spawn is vfork-based, so the same as Linux.
    • macOS: flock is per open file, but posix_spawn is a kernel call, so any window would be inside the kernel. Not tested.
    • Windows: std opens handles as non-inheritable, so CreateProcess doesn't copy them; likely unaffected. Not tested.

Proposed fix

Product (recommended). Release the lock explicitly in Drop. flock(LOCK_UN) through any descriptor frees the lock for the open file description, whatever copies a child still holds (and UnlockFile on Windows):

impl Drop for LibraryLock {
    /// Remove the owner note while still holding the lock (so it can't delete the next holder's),
    /// then release the lock explicitly: closing the handle isn't enough on Unix, where `flock`
    /// lasts while any copy of the descriptor is open, and a process another thread is spawning
    /// holds a copy of every descriptor until it execs.
    fn drop(&mut self) {
        if self.held {
            let _ = std::fs::remove_file(self.dir.join(OWNER));
            if let Some(f) = &self._file
                && let Err(e) = f.unlock()
            {
                log::warn!("library {}: can't release {LOCK}: {e}", self.dir.display());
            }
        }
    }
}

(_file could then lose its underscore. The module doc's "released when the LibraryLock is dropped" becomes true as written.)

I checked this on a scratch crate holding a verbatim copy of lock.rs + tests_lock.rs plus the new test below, built with the same toolchain:

before after
the flaky pair, 30 runs 28 failed 0 failed
whole (copied) binary, 30 runs 26 failed (second_opener…) 0 failed
the pair with strace delaying the child's execve, 5 runs 5 failed 0 failed
new regression test, 5 runs 5 failed (InUse(None)) 0 failed

Alternatives considered:

  • OFD locks (F_OFD_SETLK): also per open file description, so close-only release fails at the same 2.2 % rate. They would need the same explicit unlock, plus raw fcntl.
  • Classic POSIX fcntl locks (F_SETLK): per process, so children don't inherit them, but they break the design. A second opener in the same process is not refused, and closing any descriptor on the file (such as the refused opener's) silently drops the lock. Both verified with the mimic.
  • Stopping children from inheriting the descriptor: std has no way to keep a descriptor out of a posix_spawn child. O_CLOEXEC is already set and only acts at exec.
  • A mutex around spawns and lock release: incomplete. spawn() can return before the child's copies are closed (32/50 000 above), and spawns in dependencies (rfd's zenity) wouldn't take it.
  • Retrying on WouldBlock for a few milliseconds: hides the race and delays every genuine refusal. Not a fix.

Tests. The product fix also fixes the flaky pair, so no test needs to move. If the product change were not wanted, the test-only workaround would be to give lock_held_by_another_process_is_released_when_it_dies (and lock_holder_child) its own integration-test binary (crates/catalog/tests/), or to serialize the lock tests. That leaves the product race and the engine test binary's exposure in place.

Regression test

The test is deterministic and fails before the fix. A File::try_clone() of the lock's descriptor stands in for the copy a child holds between fork and exec (a dup refers to the same open file description, which is exactly what the child gets):

// crates/catalog/src/lock.rs, impl LibraryLock
/// Another descriptor on the locked file, like the copy a process spawned by another thread
/// holds between fork and exec (tests).
#[cfg(test)]
pub(crate) fn descriptor_copy(&self) -> Option<File> {
    self._file.as_ref().and_then(|f| f.try_clone().ok())
}

// crates/catalog/src/tests_lock.rs
/// A process spawned by any thread holds a copy of every descriptor until it execs (close-on-exec
/// only closes them then), and `flock` lasts while any copy is open: dropping the LibraryLock must
/// still free the library.
#[cfg(unix)]
#[test]
fn the_library_is_free_once_dropped_even_if_a_child_holds_a_copy() {
    let dir = temp_dir("copy");
    let first = LibraryLock::acquire(&dir, "LightCraft").unwrap();
    let copy = first.descriptor_copy().unwrap(); // what a child between fork and exec holds
    drop(first);
    let again = LibraryLock::acquire(&dir, "lightcraft-cli").expect("the library is free once its LibraryLock is dropped");
    assert!(again.held());
    drop((again, copy));
    let _ = std::fs::remove_dir_all(&dir);
}

Before the fix it fails every time with the library is free once its LibraryLock is dropped: InUse(None); after the fix it passes. It is cfg(unix) because duplicated-handle lock semantics differ on Windows, which doesn't have this problem. Optionally, a probabilistic test can drive a spawning thread against 2 000 lock/drop/re-lock cycles and assert no refusals: before the fix 2 % of cycles fail, so a run of that size fails essentially always. The deterministic test is the one CI needs.

Notes

Found while working on #345 (PR #601). The flaky test failed cargo xtask ci on that branch, whose catalog crate is identical to main. Outside that PR's scope: it touches only crates/catalog/src/lock.rs and its tests.

🤖 Generated with Claude Code

Activity

  1. AlexChambers commented on Oct 10, 2026

    @AlexChambers
    Contributor

    Confirmed on macOS (M3 Max) with the fix you propose: with file.unlock() in LibraryLock's Drop and no change to the tests, tests_lock failed 0 of 400 runs (four loops of 100 in parallel). Unmodified main failed 3 of 400 under the same load.

    That fits your analysis: an explicit unlock releases the lock on the open file description itself, which a spawned child's copy shares, so it fixes the product side. My #679 only keeps the tests from overlapping the spawn, so once your fix lands, #679 isn't needed and I'll close it.

  2. added 2 commits that reference this issue on Oct 20, 2026
  3. added a commit that references this issue on Oct 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions