ReplacementSemLock loses cross-process identity when pickled for spawn/forkserver
Describe the bug
When Scalene profiles a program using the spawn or forkserver multiprocessing context, ReplacementSemLock does not preserve the identity of its underlying semaphore during pickling.
Its custom __reduce__ reconstructs a new ReplacementSemLock using only the multiprocessing context name. Consequently, the parent and child receive independent locks. A child can acquire its lock while the parent holds what should be the same lock.
This can introduce races into otherwise correctly synchronized programs and may also affect multiprocessing queues and pools used while profiling.
To Reproduce
Save the following as repro.py:
import multiprocessing as mp
def try_acquire(lock, connection):
acquired = lock.acquire(timeout=0.25)
connection.send(acquired)
if acquired:
lock.release()
connection.close()
if __name__ == "__main__":
ctx = mp.get_context("spawn")
lock = ctx.Lock()
receive, send = ctx.Pipe(duplex=False)
process = ctx.Process(
target=try_acquire,
args=(lock, send),
)
lock.acquire()
try:
process.start()
send.close()
if receive.poll(5):
acquired = receive.recv()
print("Child acquired while parent held lock:", acquired)
else:
print("Child did not respond")
finally:
lock.release()
process.join()
print("Child exit code:", process.exitcode)Run it normally:
python3 repro.pyExpected output:
Child acquired while parent held lock: False
Child exit code: 0Run the same program under Scalene:
python3 -m scalene run --cpu-only --no-browser repro.pyObserved output:
Child acquired while parent held lock: True
Child exit code: 0The same failure can be reproduced with the forkserver context on platforms where it is available.
The cause is the custom reducer:
def __reduce__(self):
return (_make_replacement_semlock, (self._ctx_method,))The reconstruction helper calls the constructor:
return ReplacementSemLock(ctx=ctx)This allocates a new semaphore instead of rebuilding the original semaphore from its handle, kind, maximum value, and name.
Expected behavior
A ReplacementSemLock passed to a spawned child should refer to the same underlying semaphore as the parent’s lock.
While the parent holds the lock, the child’s timed acquisition should fail:
Child acquired while parent held lock: FalseReplacementSemLock should use the standard multiprocessing.synchronize.SemLock serialization behavior, including its platform-specific handle transfer and reconstruction.
Screenshots
Not applicable.
Desktop (please complete the following information):
- OS: Linux
- Browser: Not applicable
- Scalene version: Current repository
masterate62a5000 - Python version: 3.14.7
- Multiprocessing contexts reproduced:
spawnandforkserver
The issue was reproduced with the current repository version.
Additional context
The existing tests verify that a pickled and unpickled lock can be acquired and released. They do not verify mutual exclusion between the original lock and its reconstructed counterpart.
Python’s standard SemLock implementation serializes the underlying semaphore state during Process.start() and rebuilds a reference to the shared semaphore in the child. Arbitrary pickle.dumps(lock) calls are intentionally rejected outside the multiprocessing spawning machinery.
A suitable regression test should:
- Create a
ReplacementSemLockusingspawnorforkserver. - Acquire it in the parent.
- pass it to a child process;
- verify that the child’s timed acquisition returns
False.
The artificial qualified-name assignment in replacement_mp_lock.py also prevents default class lookup:
ReplacementSemLock.__qualname__ = (
"replacement_semlock.ReplacementSemLock"
)ReplacementSemLock is already a top-level class in scalene.replacement_sem_lock. Removing this assignment and the custom __reduce__ allows Python’s inherited SemLock.__getstate__ and SemLock.__setstate__ behavior to preserve the shared semaphore correctly.
The custom __reduce__ was originally added while fixing [issue #651](https://github.com/plasma-umass/scalene/issues/651). At that time, ReplacementSemLock was defined inside the replacement_mp_semlock shim function. Classes defined inside functions are not importable by name in a spawned child, so multiprocessing failed with:
Can't pickle local object
'replacement_mp_semlock.<locals>.ReplacementSemLock'[PR #665](https://github.com/plasma-umass/scalene/pull/665) moved the class into the top-level scalene.replacement_sem_lock module and added __reduce__. The reducer returned an importable reconstruction function, bypassing pickle’s inability to locate the original nested/artificial class name:
def __reduce__(self):
return (_recreate_replacement_sem_lock, ())Later versions extended this to preserve the selected multiprocessing context:
def __reduce__(self):
return (_make_replacement_semlock, (self._ctx_method,))The historical purpose was therefore valid: make the replacement class reconstructible under Windows/spawn. However, the reconstruction function called ReplacementSemLock(...), creating a new semaphore instead of preserving the existing semaphore’s identity.
Source: plasma-umass/scalene