Skip to content

Commit a8a2b5a

Browse files
authored
🐛 fix(fork): preserve holds across PID namespaces (#1075)
1 parent 7007387 commit a8a2b5a

8 files changed

Lines changed: 364 additions & 28 deletions

File tree

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
A child with its parent's numeric PID in a different Linux PID namespace now preserves the parent's file and soft
2+
reader/writer locks. Finalizing an inherited SQLite lock connection in the child leaves the parent's private database
3+
link in place.

‎docs/concepts.rst‎

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

672+
On Linux and Android, a child in a new PID namespace can have the same numeric PID as its parent. The child
673+
invalidates inherited locks even in that case. Construct a new lock in the child before acquiring it. If you register
674+
a child callback before importing filelock, defer lock operations until after the fork when procfs is unavailable.
675+
Such a callback runs before filelock can invalidate inherited locks with matching PIDs.
676+
672677
On normal interpreter exit, an ``atexit`` handler registered when filelock is imported releases every lock the process
673678
still references unless another live thread owns a hold. An async soft reader/writer hold stays while its owning event
674679
loop runs, even if the task has finished. A lock built with ``thread_local=False`` cannot identify its owner, so its

‎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
@@ -1062,6 +1064,7 @@ def acquire(
10621064
raise
10631065

10641066
def _raise_if_inherited(self) -> None:
1067+
ensure_current_process()
10651068
if self._creator_pid != os.getpid(): # pragma: forked child
10661069
msg = f"{type(self).__name__} on {self.lock_file} was inherited across fork; construct a new instance"
10671070
raise RuntimeError(msg)
@@ -1459,6 +1462,7 @@ def release(self, force: bool = False) -> None: # ruff:ignore[boolean-type-hint
14591462
running, and a ``thread_local=False`` lock while any other thread runs.
14601463
14611464
"""
1465+
ensure_current_process()
14621466
release_snapshot: tuple[int, int] | None = None
14631467
transition_entered = False
14641468
try: # ruff:ignore[too-many-statements-in-try-clause] # gate-entry signals and release failures need separate recovery
@@ -1866,6 +1870,8 @@ def _mark_descriptor_released(self) -> None:
18661870
def _reset_after_fork_in_child(self) -> None: # pragma: forked child
18671871
# fork copies the lock in whatever state the parent's threads left it, so give the child an unheld one.
18681872
self._transition_lock = RLock()
1873+
# A different PID namespace may give the child the same numeric PID.
1874+
self._creator_pid = -1
18691875
if isinstance(self._context, ThreadLocalFileContext):
18701876
self._thread_holds.clear()
18711877
self._thread_pending.clear()
@@ -2208,6 +2214,16 @@ class _OwnedDescriptor:
22082214
inode: int | None
22092215

22102216

2217+
def _pid_namespace() -> tuple[int, int] | None:
2218+
if sys.platform not in {"linux", "android"}: # pragma: linux no cover # pragma: android no cover
2219+
return None
2220+
try:
2221+
namespace = pathlib.Path("/proc/self/ns/pid").stat()
2222+
except OSError:
2223+
return None
2224+
return namespace.st_dev, namespace.st_ino
2225+
2226+
22112227
class _ForkState:
22122228
def __init__(self) -> None:
22132229
self.gate = Condition(RLock())
@@ -2221,7 +2237,7 @@ def __init__(self) -> None:
22212237
self.pinned_classes: dict[int, list[tuple[_ForkResettableClass, ...]]] = {}
22222238
self.provisional_descriptor_tokens: dict[int, list[tuple[int, ...]]] = {}
22232239
self.undrained_forks: set[int] = set()
2224-
self.pid = os.getpid()
2240+
self.process_identity = os.getpid(), _pid_namespace()
22252241

22262242
def reset_synchronization(self) -> None: # pragma: forked child
22272243
self.gate = Condition(RLock())
@@ -2258,7 +2274,7 @@ def _register_fork_hooks() -> None:
22582274
_REGISTER_AT_FORK( # pragma: needs fork
22592275
before=_pin_fork_objects,
22602276
after_in_parent=_resume_parent_after_fork,
2261-
after_in_child=_reset_child_after_fork,
2277+
after_in_child=partial(_reset_child_after_fork, from_hook=True),
22622278
)
22632279

22642280

@@ -2349,21 +2365,25 @@ def ensure_current_process() -> None:
23492365
_reset_child_after_fork()
23502366

23512367

2352-
def _reset_child_after_fork() -> None: # pragma: forked child
2353-
if (pid := os.getpid()) == _FORK_STATE.pid:
2354-
return
2368+
def _reset_child_after_fork(*, from_hook: bool = False) -> None: # pragma: forked child
2369+
pid = os.getpid()
23552370
thread_id = get_ident()
2371+
if pid == _FORK_STATE.process_identity[0]:
2372+
if thread_id not in _FORK_STATE.fork_owner_depths:
2373+
return
2374+
if not from_hook:
2375+
previous = _FORK_STATE.process_identity[1]
2376+
if previous is None or (current := _pid_namespace()) is None or current == previous:
2377+
return
23562378
if thread_id in _FORK_STATE.undrained_forks:
23572379
os.write(2, b"filelock: fork child exits: another thread was still changing a lock's descriptor ownership\n")
23582380
os._exit(70) # the inherited descriptor state is unsafe; the parent continues
23592381
pinned_objects = _FORK_STATE.pinned_objects.get(thread_id, [()])[-1]
23602382
pinned_classes = _FORK_STATE.pinned_classes.get(thread_id, [()])[-1]
2361-
descriptors: list[_OwnedDescriptor] = []
2362-
for token, descriptor in tuple(_OWNED_DESCRIPTORS.items()):
2363-
if descriptor.creator_pid != pid:
2364-
descriptors.append(_OWNED_DESCRIPTORS.pop(token))
2383+
descriptors = list(_OWNED_DESCRIPTORS.values())
2384+
_OWNED_DESCRIPTORS.clear()
23652385
_FORK_STATE.reset_synchronization()
2366-
_FORK_STATE.pid = pid
2386+
_FORK_STATE.process_identity = pid, _pid_namespace()
23672387
_INIT_PARAMETER_MODELS.clear()
23682388
_detach_child_state(descriptors, pinned_objects, pinned_classes)
23692389

‎src/filelock/_read_write.py‎

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,7 @@ class _InodeProbes:
302302

303303

304304
class _ForkSafeConnection(sqlite3.Connection):
305-
_creator_pid: int
305+
creator_pid: int | None
306306
_decrement_escrow: Callable[[sqlite3.Connection], None] | None
307307
_database_directory: _LinkDirectory | None
308308
database_identity: _DatabaseIdentity | None = None
@@ -314,7 +314,7 @@ def __new__(
314314
**_kwargs: _ConnectionParameter,
315315
) -> Self:
316316
connection = super().__new__(cls)
317-
connection._creator_pid = _GETPID()
317+
connection.creator_pid = _GETPID()
318318
connection._decrement_escrow = None
319319
connection._database_directory = None
320320
return connection
@@ -327,22 +327,21 @@ def __del__(
327327
self.close()
328328

329329
def close(self) -> None:
330-
with _sqlite_transition():
331-
if _GETPID() != self._creator_pid: # pragma: needs fork
330+
with _sqlite_transition(), fork_transition():
331+
if _GETPID() != self.creator_pid: # pragma: needs fork
332332
return
333-
with fork_transition():
334-
sqlite3.Connection.close(self)
335-
try:
336-
if (directory := self._database_directory) is not None: # pragma: needs posix-hard-link
337-
self._database_directory = None
338-
_remove_link_directory(directory)
339-
finally:
340-
if (probe := self._probe) is not None: # pragma: win32 no cover
341-
self._probe = self.database_identity = None
342-
_PROBE_DESCRIPTORS.release(probe)
343-
if (decrement := self._decrement_escrow) is not None: # pragma: <3.12 cover # pragma: needs fork
344-
self._decrement_escrow = None
345-
decrement(self)
333+
sqlite3.Connection.close(self)
334+
try:
335+
if (directory := self._database_directory) is not None: # pragma: needs posix-hard-link
336+
self._database_directory = None
337+
_remove_link_directory(directory)
338+
finally:
339+
if (probe := self._probe) is not None: # pragma: win32 no cover
340+
self._probe = self.database_identity = None
341+
_PROBE_DESCRIPTORS.release(probe)
342+
if (decrement := self._decrement_escrow) is not None: # pragma: <3.12 cover # pragma: needs fork
343+
self._decrement_escrow = None
344+
decrement(self)
346345

347346
def retain_link(self, directory: _LinkDirectory | None) -> None: # pragma: win32 cover
348347
# Keep the private link directory, if there is one, until SQLite no longer uses it.
@@ -1136,7 +1135,9 @@ def _holds_level_of(self, thread_id: int) -> bool:
11361135
return False
11371136

11381137
def _reset_after_fork_in_child(self) -> None: # pragma: forked child
1139-
if self._con is not None:
1138+
if (connection := self._con) is not None:
1139+
# The child can have the same numeric PID as the owner of the private database link.
1140+
connection.creator_pid = None
11401141
_FORKED_DATABASES.poison_after_fork(self._canonical_path, self._owned_connection.identity)
11411142
self._owned_connection.connection = None
11421143
self._owned_connection.transaction_released = True

‎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
@@ -385,6 +385,7 @@ def _acquire(
385385
holder: int | None = None,
386386
cancel_check: Callable[[], bool] | None = None,
387387
) -> AcquireReturnProxy:
388+
ensure_current_process()
388389
if self._creator_pid != os.getpid(): # pragma: forked child
389390
msg = f"SoftReadWriteLock on {self.lock_file} was invalidated by fork(); construct a new instance"
390391
raise RuntimeError(msg)
@@ -577,6 +578,7 @@ def release(self, *, force: bool = False) -> None:
577578
:raises SoftFileLockProtocolError: if peers keep winning generation updates until the holder's stale threshold
578579
579580
"""
581+
ensure_current_process()
580582
if self._creator_pid != os.getpid(): # pragma: forked child
581583
return
582584
self._release(threading.get_ident(), force=force)
@@ -696,6 +698,7 @@ def close(self) -> None:
696698
:class:`RuntimeError`, and so does an acquire another thread is still waiting in, which gives up its claim
697699
instead of taking the lock. A fork-invalidated instance is closed without raising.
698700
"""
701+
ensure_current_process()
699702
if self._creator_pid != os.getpid(): # pragma: forked child
700703
return
701704
# Closed first, under the lock an acquire publishes its hold under: an acquire still waiting then sees the flag
@@ -720,6 +723,7 @@ def _holds_level_of(self, holder: int) -> bool:
720723
return (hold := self._hold) is not None and (holder == hold.write_thread_id or holder in hold.read_depths)
721724

722725
def _reset_after_fork_in_child(self) -> None: # pragma: forked child
726+
self._creator_pid = -1
723727
self._locks = _Locks(internal=threading.Lock(), transaction=threading.Lock())
724728
self._hold = None
725729

0 commit comments

Comments
 (0)