fix: Make Cached metaclass instance instantiation thread-safe and fork-safe
Fix #2065
Scope
This PR tackles a race condition in the _Cached metaclass.
The Problem
There were three distinct overlapping lock gaps around system forks:
- Unprotected Instantiation: The
super().__call__instantiation process inside_Cachedwas entirely unprotected, allowing concurrent cache misses to spin up disjoint raw instances independently. - Post-fork Cache Clearing Race: When a process forks,
os.getpid() != cls._pidattempts to clear the inherited cache. When 10 new threads simultaneously wake up post-fork and evaluate this, they concurrently bypass the cache logic. - Ghost Tokenization:
token = tokenize(cls, cls._pid, ...)historically evaluated before any locking boundary. The very first thread running post-fork evaluatedtokenize()utilizing the lingering parent's PID before updatingcls._pidinside the lock. Subsequence threads would then evaluatetokenize()natively under the child's PID, resulting in permanently ghosted, duplicated Cache hashes for identically parameterized filesystems.
The Solution
- Double-Checked Locking: Re-instated a standard
_instantiation_lockin_Cached.__call__that strictly gates the underlying filesystem instantiation and cache updates. We also updatedclear_instance_cache()to respect this exact lock. - Encapsulated Fork Boundaries: Moved the
os.getpid() != cls._pidcache clearing evaluation strictly inside the boundaries of the lock. Furthermore, we explicitly re-initializecls._instantiation_lock = threading.RLock()across forks so child processes do not natively inherit and permanent-deadlock on parent-locked states. - Deterministic Tokenizing: Altered
tokenize()targeting to natively utilizeos.getpid()rather than evaluating acrosscls._pid, ensuring deterministic key hashes pre-and-post fork regardless of strict thread scheduling. - Testing: Added
test_instance_cache_concurrency,test_clear_instance_cache_concurrency, andtest_fork_deadlockheavily simulating asynchronous thread congestion across cache misses, explicit cache-clear injections, and native OS forks to guarantee locking determinism.
Hi @martindurant, could you take a look at this PR please? Thanks.
To check: there is no way to un-register a function passed via register-at-fork, nor even a way to list them. Is there any way the function can get registered multiple times?
A thorny problem you are solving! Can we really not just say "don't use fork"?
This pattern exists in major upstream libraries. Fixing the race condition ensures we enforce only one instance per process, allowing for safe, efficient resource sharing after a fork.
To check: there is no way to un-register a function passed via register-at-fork, nor even a way to list them. Is there any way the function can get registered multiple times?
Re-instantiating the lock and calling .clear() should be idempotent.