Skip to content

Commit 4668ddd

Browse files
committed
šŸ› fix(fork): preserve holds across PID namespaces
A child in a new PID namespace can have its parent’s numeric PID. Invalidate inherited locks in the child hook and check the namespace in earlier callbacks. Only a known namespace change on the forking thread can invalidate locks before the hook runs. Fixes #1021
1 parent c2e7855 commit 4668ddd

6 files changed

Lines changed: 323 additions & 10 deletions

File tree

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix forked file and soft reader/writer locks releasing their parent's hold when both processes have the same numeric PID
2+
in different Linux PID namespaces. Inherited locks are invalidated even when those PIDs match.

ā€Ždocs/concepts.rstā€Ž

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -643,6 +643,11 @@ writes ``filelock: fork child exits: ...`` to stderr and leaves through ``os._ex
643643
half-finished descriptor state, so no ``atexit`` handler or ``finally`` block runs in it. An operation that never
644644
finishes delays every later fork by the same 30 seconds.
645645

646+
On Linux and Android, a child in a new PID namespace can have the same numeric PID as its parent. The child
647+
invalidates inherited locks even in that case. Construct a new lock in the child before acquiring it. If you register
648+
a child callback before importing filelock, defer lock operations until after the fork when procfs is unavailable.
649+
Such a callback runs before filelock can invalidate inherited locks with matching PIDs.
650+
646651
On normal interpreter exit, an ``atexit`` handler registered when filelock is imported releases every lock the process
647652
still references, before module teardown can break the release; handlers registered earlier run after it. Daemon
648653
threads still run while ``atexit`` handlers do, so a hold of one that is alive stays in place, and a lock built with

ā€Žsrc/filelock/_api.pyā€Ž

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
"inspect",
1313
"math",
1414
"numbers",
15+
"pathlib",
1516
"secrets",
1617
"types",
1718
"warnings",
@@ -25,6 +26,7 @@
2526
import logging
2627
import math
2728
import os
29+
import pathlib
2830
import secrets
2931
import stat
3032
import sys
@@ -1060,6 +1062,7 @@ def acquire(
10601062
raise
10611063

10621064
def _raise_if_inherited(self) -> None:
1065+
ensure_current_process()
10631066
if self._creator_pid != os.getpid(): # pragma: forked child
10641067
msg = f"{type(self).__name__} on {self.lock_file} was inherited across fork; construct a new instance"
10651068
raise RuntimeError(msg)
@@ -1454,6 +1457,7 @@ def release(self, force: bool = False) -> None: # ruff:ignore[boolean-type-hint
14541457
running, and a ``thread_local=False`` lock while any other thread runs.
14551458
14561459
"""
1460+
ensure_current_process()
14571461
release_snapshot: tuple[int, int] | None = None
14581462
transition_entered = False
14591463
try: # ruff:ignore[too-many-statements-in-try-clause] # gate-entry signals and release failures need separate recovery
@@ -1864,6 +1868,8 @@ def _mark_descriptor_released(self) -> None:
18641868
def _reset_after_fork_in_child(self) -> None: # pragma: forked child
18651869
# fork copies the lock in whatever state the parent's threads left it, so give the child an unheld one.
18661870
self._transition_lock = RLock()
1871+
# A different PID namespace may give the child the same numeric PID.
1872+
self._creator_pid = -1
18671873
if isinstance(self._context, ThreadLocalFileContext):
18681874
self._thread_holds.clear()
18691875
self._thread_pending.clear()
@@ -2201,6 +2207,16 @@ class _OwnedDescriptor:
22012207
inode: int | None
22022208

22032209

2210+
def _pid_namespace() -> tuple[int, int] | None:
2211+
if sys.platform not in {"linux", "android"}: # pragma: linux no cover # pragma: android no cover
2212+
return None
2213+
try:
2214+
namespace = pathlib.Path("/proc/self/ns/pid").stat()
2215+
except OSError:
2216+
return None
2217+
return namespace.st_dev, namespace.st_ino
2218+
2219+
22042220
class _ForkState:
22052221
def __init__(self) -> None:
22062222
self.gate = Condition(RLock())
@@ -2214,7 +2230,7 @@ def __init__(self) -> None:
22142230
self.pinned_classes: dict[int, list[tuple[_ForkResettableClass, ...]]] = {}
22152231
self.provisional_descriptor_tokens: dict[int, list[tuple[int, ...]]] = {}
22162232
self.undrained_forks: set[int] = set()
2217-
self.pid = os.getpid()
2233+
self.process_identity = os.getpid(), _pid_namespace()
22182234

22192235
def reset_synchronization(self) -> None: # pragma: forked child
22202236
self.gate = Condition(RLock())
@@ -2251,7 +2267,7 @@ def _register_fork_hooks() -> None:
22512267
_REGISTER_AT_FORK( # pragma: needs fork
22522268
before=_pin_fork_objects,
22532269
after_in_parent=_resume_parent_after_fork,
2254-
after_in_child=_reset_child_after_fork,
2270+
after_in_child=partial(_reset_child_after_fork, from_hook=True),
22552271
)
22562272

22572273

@@ -2342,21 +2358,25 @@ def ensure_current_process() -> None:
23422358
_reset_child_after_fork()
23432359

23442360

2345-
def _reset_child_after_fork() -> None: # pragma: forked child
2346-
if (pid := os.getpid()) == _FORK_STATE.pid:
2347-
return
2361+
def _reset_child_after_fork(*, from_hook: bool = False) -> None: # pragma: forked child
2362+
pid = os.getpid()
23482363
thread_id = get_ident()
2364+
if pid == _FORK_STATE.process_identity[0]:
2365+
if thread_id not in _FORK_STATE.fork_owner_depths:
2366+
return
2367+
if not from_hook:
2368+
previous = _FORK_STATE.process_identity[1]
2369+
if previous is None or (current := _pid_namespace()) is None or current == previous:
2370+
return
23492371
if thread_id in _FORK_STATE.undrained_forks:
23502372
os.write(2, b"filelock: fork child exits: another thread was still changing a lock's descriptor ownership\n")
23512373
os._exit(70) # the inherited descriptor state is unsafe; the parent continues
23522374
pinned_objects = _FORK_STATE.pinned_objects.get(thread_id, [()])[-1]
23532375
pinned_classes = _FORK_STATE.pinned_classes.get(thread_id, [()])[-1]
2354-
descriptors: list[_OwnedDescriptor] = []
2355-
for token, descriptor in tuple(_OWNED_DESCRIPTORS.items()):
2356-
if descriptor.creator_pid != pid:
2357-
descriptors.append(_OWNED_DESCRIPTORS.pop(token))
2376+
descriptors = list(_OWNED_DESCRIPTORS.values())
2377+
_OWNED_DESCRIPTORS.clear()
23582378
_FORK_STATE.reset_synchronization()
2359-
_FORK_STATE.pid = pid
2379+
_FORK_STATE.process_identity = pid, _pid_namespace()
23602380
_INIT_PARAMETER_MODELS.clear()
23612381
_detach_child_state(descriptors, pinned_objects, pinned_classes)
23622382

ā€Žsrc/filelock/_soft_rw/_async.pyā€Ž

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,9 @@
3939

4040
from ._sync import (
4141
SoftReadWriteLock,
42+
ensure_current_process,
4243
lost_hold_error,
44+
register_fork_object,
4345
)
4446

4547
if TYPE_CHECKING:
@@ -114,6 +116,7 @@ def __init__( # ruff:ignore[too-many-arguments] # public constructor: one para
114116
self._owners = task_owners_for(self._lock)
115117
self._loop = loop
116118
self._executor = executor
119+
register_fork_object(self)
117120

118121
@property
119122
def timeout(self) -> float:
@@ -192,6 +195,7 @@ async def acquire_read(
192195
return AsyncAcquireSoftReadWriteReturnProxy(lock=self)
193196

194197
def _raise_if_unusable(self) -> None:
198+
ensure_current_process()
195199
if self._creator_pid != os.getpid(): # pragma: forked child
196200
msg = f"AsyncSoftReadWriteLock on {self.lock_file} was inherited across fork; construct a new instance"
197201
raise RuntimeError(msg)
@@ -288,6 +292,7 @@ async def release(self, *, force: bool = False) -> None:
288292
:raises SoftFileLockProtocolError: if peers keep winning generation updates until the holder's stale threshold
289293
290294
"""
295+
ensure_current_process()
291296
if self._creator_pid == os.getpid():
292297
await self._owners.release(
293298
force=force,
@@ -354,6 +359,7 @@ async def close(self) -> None:
354359
between that check and the admission still admits the task into the ended hold.
355360
356361
"""
362+
ensure_current_process()
357363
if self._creator_pid != os.getpid() or self._closed:
358364
return
359365
# Refuse acquires from here on, so none is admitted into a hold the backend is letting go of.
@@ -370,6 +376,9 @@ async def close(self) -> None:
370376
self._closed = False
371377
raise
372378

379+
def _reset_after_fork_in_child(self) -> None: # pragma: forked child
380+
self._creator_pid = -1
381+
373382

374383
class AsyncAcquireSoftReadWriteReturnProxy:
375384
"""

ā€Žsrc/filelock/_soft_rw/_sync.pyā€Ž

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,7 @@ def _acquire(
378378
holder: int | None = None,
379379
cancel_check: Callable[[], bool] | None = None,
380380
) -> AcquireReturnProxy:
381+
ensure_current_process()
381382
if self._creator_pid != os.getpid(): # pragma: forked child
382383
msg = f"SoftReadWriteLock on {self.lock_file} was invalidated by fork(); construct a new instance"
383384
raise RuntimeError(msg)
@@ -568,6 +569,7 @@ def release(self, *, force: bool = False) -> None:
568569
:raises SoftFileLockProtocolError: if peers keep winning generation updates until the holder's stale threshold
569570
570571
"""
572+
ensure_current_process()
571573
if self._creator_pid != os.getpid(): # pragma: forked child
572574
return
573575
self._release(threading.get_ident(), force=force)
@@ -681,6 +683,7 @@ def close(self) -> None:
681683
:class:`RuntimeError`, and so does an acquire another thread is still waiting in, which gives up its claim
682684
instead of taking the lock. A fork-invalidated instance is closed without raising.
683685
"""
686+
ensure_current_process()
684687
if self._creator_pid != os.getpid(): # pragma: forked child
685688
return
686689
# Closed first, under the lock an acquire publishes its hold under: an acquire still waiting then sees the flag
@@ -705,6 +708,7 @@ def _holds_level_of(self, holder: int) -> bool:
705708
return (hold := self._hold) is not None and (holder == hold.write_thread_id or holder in hold.read_depths)
706709

707710
def _reset_after_fork_in_child(self) -> None: # pragma: forked child
711+
self._creator_pid = -1
708712
self._locks = _Locks(internal=threading.Lock(), transaction=threading.Lock())
709713
self._hold = None
710714

0 commit comments

Comments
Ā (0)