Debian Codegraph @

tests/test_fork_ownership.py

raw
1 from __future__ import annotations
2
3 import asyncio
4 import gc
5 import os
6 import subprocess # ruff:ignore[suspicious-subprocess-import] # fresh interpreter must register the callback before importing filelock
7 import sys
8 import threading
9 from errno import EBADF
10 from queue import Queue
11 from stat import S_ISDIR
12 from typing import TYPE_CHECKING, Final, Literal, NoReturn
13
14 import pytest
15
16 from filelock import (
17 AcquireReturnProxy,
18 AsyncFileLock,
19 AsyncSoftFileLock,
20 BaseAsyncFileLock,
21 BaseFileLock,
22 FileLock,
23 SoftFileLock,
24 SoftReadWriteLock,
25 Timeout,
26 )
27 from tests.capability_marks import NEEDS_FORK, NEEDS_REGISTER_AT_FORK
28 from tests.fork_helpers import exit_child, fork_process
29
30 if sys.version_info >= (3, 11):
31 from builtins import BaseExceptionGroup # pragma: >=3.11 cover
32 else: # pragma: <3.11 cover
33 from exceptiongroup import BaseExceptionGroup
34
35 if TYPE_CHECKING:
36 from pathlib import Path
37
38 from pytest_mock import MockerFixture
39
40 _FORK_WARNING: Final[pytest.MarkDecorator] = pytest.mark.filterwarnings(
41 "ignore:.*multi-threaded, use of fork.*:DeprecationWarning"
42 )
43
44
45 @NEEDS_FORK # pragma: needs fork
46 @_FORK_WARNING
47 @pytest.mark.parametrize(
48 ("lock_type", "action"),
49 [
50 pytest.param(FileLock, "release", id="native-release"),
51 pytest.param(FileLock, "context", id="native-context"),
52 pytest.param(FileLock, "collect", id="native-collect"),
53 pytest.param(SoftFileLock, "release", id="soft-release"),
54 pytest.param(SoftFileLock, "context", id="soft-context"),
55 pytest.param(SoftFileLock, "collect", id="soft-collect"),
56 ],
57 )
58 def test_child_cleanup_preserves_parent_lock(
59 tmp_path: Path,
60 lock_type: type[BaseFileLock],
61 action: Literal["release", "context", "collect"],
62 ) -> None:
63 path = str(tmp_path / "parent.lock")
64 lock = lock_type(path, thread_local=False, is_singleton=False)
65 proxy = lock.acquire()
66
67 def cleanup_child() -> NoReturn:
68 _run_child_cleanup(lock, proxy, action)
69
70 child_pid = fork_process(cleanup_child)
71 _, status = os.waitpid(child_pid, 0)
72
73 assert os.waitstatus_to_exitcode(status) == 0
74 assert not _probe_lock(lock_type, path)
75 lock.release()
76 assert _probe_lock(lock_type, path)
77
78
79 @NEEDS_FORK # pragma: needs fork
80 @_FORK_WARNING
81 @pytest.mark.parametrize(
82 ("async_lock_type", "sync_lock_type"),
83 [
84 pytest.param(AsyncFileLock, FileLock, id="native"),
85 pytest.param(AsyncSoftFileLock, SoftFileLock, id="soft"),
86 ],
87 )
88 def test_async_child_release_preserves_parent_lock(
89 tmp_path: Path,
90 async_lock_type: type[BaseAsyncFileLock],
91 sync_lock_type: type[BaseFileLock],
92 ) -> None:
93 path = str(tmp_path / "parent.lock")
94 lock = async_lock_type(path, thread_local=False, is_singleton=False)
95 asyncio.run(lock.acquire())
96
97 def release_child() -> NoReturn:
98 state = lock.is_locked, lock.lock_counter
99 asyncio.run(lock.release(force=True))
100 exit_child(0 if state == (False, 0) else 1)
101
102 child_pid = fork_process(release_child)
103 _, status = os.waitpid(child_pid, 0)
104
105 assert os.waitstatus_to_exitcode(status) == 0
106 assert not _probe_lock(sync_lock_type, path)
107 asyncio.run(lock.release())
108 assert _probe_lock(sync_lock_type, path)
109
110
111 @NEEDS_FORK # pragma: needs fork
112 @_FORK_WARNING
113 def test_soft_read_write_resets_older_same_path_instance(tmp_path: Path) -> None:
114 path = str(tmp_path / "parent.lock")
115 older = SoftReadWriteLock(path, is_singleton=False, heartbeat_interval=0.1, stale_threshold=0.5)
116 newer = SoftReadWriteLock(path, is_singleton=False, heartbeat_interval=0.1, stale_threshold=0.5)
117 del newer
118 gc.collect()
119 older.acquire_write()
120
121 def inherited_child() -> NoReturn:
122 with pytest.raises(RuntimeError, match="invalidated by fork"):
123 older.acquire_read(timeout=0)
124 older.release()
125 exit_child(0)
126
127 child_pid = fork_process(inherited_child)
128 _, status = os.waitpid(child_pid, 0)
129
130 assert os.waitstatus_to_exitcode(status) == 0
131 contender = SoftReadWriteLock(path, is_singleton=False, heartbeat_interval=0.1, stale_threshold=0.5)
132 with pytest.raises(Timeout):
133 contender.acquire_write(timeout=0)
134 contender.close()
135 older.release()
136 older.close()
137
138
139 @NEEDS_FORK # pragma: needs fork
140 @_FORK_WARNING
141 def test_child_closes_descriptor_held_by_vanished_thread(tmp_path: Path) -> None:
142 path = str(tmp_path / "parent.lock")
143 descriptor: Queue[int] = Queue()
144 acquired, release = threading.Event(), threading.Event()
145
146 def hold_lock() -> None:
147 lock = FileLock(path, thread_local=True, is_singleton=False, on_acquired=descriptor.put)
148 with lock:
149 acquired.set()
150 release.wait()
151
152 worker = threading.Thread(target=hold_lock)
153 worker.start()
154 assert acquired.wait(timeout=5)
155 fd = descriptor.get(timeout=5)
156
157 def descriptor_child() -> NoReturn:
158 _assert_descriptor_closed(fd)
159
160 child_pid = fork_process(descriptor_child)
161 _, status = os.waitpid(child_pid, 0)
162 release.set()
163 worker.join(timeout=5)
164
165 assert (os.waitstatus_to_exitcode(status), worker.is_alive()) == (0, False)
166
167
168 @NEEDS_FORK # pragma: needs fork
169 @_FORK_WARNING
170 def test_fork_waits_for_descriptor_registration(tmp_path: Path, mocker: MockerFixture) -> None:
171 path = str(tmp_path / "parent.lock")
172 lock = FileLock(path, thread_local=False, is_singleton=False)
173 entered, proceed, acquired = threading.Event(), threading.Event(), threading.Event()
174 descriptors: list[int] = []
175 real_fstat = os.fstat
176
177 def delayed_fstat(fd: int) -> os.stat_result:
178 if threading.current_thread() is worker and not entered.is_set():
179 descriptors.append(fd)
180 entered.set()
181 proceed.wait()
182 return real_fstat(fd)
183
184 mocker.patch("os.fstat", side_effect=delayed_fstat)
185
186 def acquire_lock() -> None:
187 lock.acquire()
188 acquired.set()
189
190 worker = threading.Thread(target=acquire_lock)
191 worker.start()
192 assert entered.wait(timeout=5)
193 timer = threading.Timer(0.05, proceed.set)
194 timer.start()
195
196 def descriptor_child() -> NoReturn:
197 _assert_descriptor_closed(descriptors[0])
198
199 child_pid = fork_process(descriptor_child)
200 _, status = os.waitpid(child_pid, 0)
201 timer.join(timeout=5)
202 worker.join(timeout=5)
203
204 assert (os.waitstatus_to_exitcode(status), acquired.is_set(), worker.is_alive()) == (0, True, False)
205 lock.release()
206
207
208 @NEEDS_REGISTER_AT_FORK
209 def test_unrelated_acquisitions_reach_filesystem_boundary_concurrently( # pragma: needs fork
210 tmp_path: Path, mocker: MockerFixture
211 ) -> None:
212 boundary = threading.Barrier(3, timeout=5)
213 real_fstat = os.fstat
214
215 def wait_at_boundary(fd: int) -> os.stat_result:
216 # Only the two named workers stat while the patch is installed, so the guard never takes its false arc.
217 if threading.current_thread().name.startswith("concurrent-acquire-"): # pragma: no branch
218 boundary.wait()
219 return real_fstat(fd)
220
221 mocker.patch("os.fstat", side_effect=wait_at_boundary)
222
223 def acquire_lock(path: str) -> None:
224 with FileLock(path, is_singleton=False):
225 pass
226
227 workers = [
228 threading.Thread(
229 target=acquire_lock,
230 args=(str(tmp_path / f"{index}.lock"),),
231 name=f"concurrent-acquire-{index}",
232 )
233 for index in range(2)
234 ]
235 for worker in workers:
236 worker.start()
237 try:
238 boundary.wait()
239 finally:
240 for worker in workers:
241 worker.join(timeout=5)
242
243 assert [worker.is_alive() for worker in workers] == [False, False]
244
245
246 @NEEDS_FORK # pragma: needs fork
247 @_FORK_WARNING
248 @pytest.mark.parametrize("lock_type", [pytest.param(FileLock, id="native"), pytest.param(SoftFileLock, id="soft")])
249 def test_child_singleton_registry_drops_parent_instance(tmp_path: Path, lock_type: type[BaseFileLock]) -> None:
250 path = str(tmp_path / "parent.lock")
251 parent_lock = lock_type(path, is_singleton=True)
252
253 def singleton_child() -> NoReturn:
254 child_lock = lock_type(path, is_singleton=True)
255 exit_child(0 if child_lock is not parent_lock else 1)
256
257 child_pid = fork_process(singleton_child)
258 _, status = os.waitpid(child_pid, 0)
259
260 assert os.waitstatus_to_exitcode(status) == 0
261
262
263 @NEEDS_FORK # pragma: needs fork
264 @_FORK_WARNING
265 @pytest.mark.parametrize("lock_type", [pytest.param(FileLock, id="native"), pytest.param(SoftFileLock, id="soft")])
266 def test_inherited_idle_lock_rejects_acquire(tmp_path: Path, lock_type: type[BaseFileLock]) -> None:
267 lock = lock_type(str(tmp_path / "parent.lock"), is_singleton=False)
268
269 def inherited_child() -> NoReturn:
270 try:
271 lock.acquire(timeout=0)
272 except RuntimeError as exception:
273 exit_child(0 if "inherited across fork" in str(exception) else 1)
274 exit_child(1)
275
276 child_pid = fork_process(inherited_child)
277 _, status = os.waitpid(child_pid, 0)
278
279 assert os.waitstatus_to_exitcode(status) == 0
280
281
282 @NEEDS_FORK # pragma: needs fork
283 @_FORK_WARNING
284 @pytest.mark.parametrize(
285 "lock_type", [pytest.param(AsyncFileLock, id="native"), pytest.param(AsyncSoftFileLock, id="soft")]
286 )
287 def test_inherited_idle_async_lock_rejects_acquire(tmp_path: Path, lock_type: type[BaseAsyncFileLock]) -> None:
288 lock = lock_type(str(tmp_path / "parent.lock"), is_singleton=False)
289
290 def inherited_child() -> NoReturn:
291 try:
292 asyncio.run(lock.acquire(timeout=0))
293 except RuntimeError as exception:
294 exit_child(0 if "inherited across fork" in str(exception) else 1)
295 exit_child(1)
296
297 child_pid = fork_process(inherited_child)
298 _, status = os.waitpid(child_pid, 0)
299
300 assert os.waitstatus_to_exitcode(status) == 0
301
302
303 @NEEDS_FORK # pragma: needs fork
304 @_FORK_WARNING
305 def test_fork_from_on_acquired_invalidates_child_acquire(tmp_path: Path) -> None:
306 path = str(tmp_path / "parent.lock")
307 fork_result = -1
308 lock: FileLock
309
310 def inherited_child() -> NoReturn:
311 try:
312 lock.acquire(timeout=0)
313 except RuntimeError as exception:
314 exit_child(0 if "inherited across fork" in str(exception) else 1)
315 exit_child(1)
316
317 def fork_from_hook(_fd: int) -> None:
318 nonlocal fork_result
319 fork_result = fork_process(inherited_child)
320
321 lock = FileLock(path, thread_local=False, is_singleton=False, on_acquired=fork_from_hook)
322 lock.acquire()
323 _, status = os.waitpid(fork_result, 0)
324 assert (os.waitstatus_to_exitcode(status), _probe_lock(FileLock, path)) == (0, False)
325 lock.release()
326
327
328 @NEEDS_REGISTER_AT_FORK
329 def test_reader_directory_registration_failure_closes_descriptor( # pragma: needs fork
330 tmp_path: Path, mocker: MockerFixture
331 ) -> None:
332 lock = SoftReadWriteLock(
333 str(tmp_path / "parent.lock"),
334 is_singleton=False,
335 heartbeat_interval=0.1,
336 stale_threshold=0.5,
337 )
338 real_fstat = os.fstat
339 directory_fds: list[int] = []
340
341 def fail_directory_fstat(fd: int) -> os.stat_result:
342 stat_result = real_fstat(fd)
343 assert S_ISDIR(stat_result.st_mode)
344 directory_fds.append(fd)
345 msg = "directory identity unavailable"
346 raise OSError(msg)
347
348 mocker.patch("os.fstat", side_effect=fail_directory_fstat)
349 with pytest.raises(OSError, match="directory identity unavailable"):
350 lock.acquire_read()
351
352 with pytest.raises(OSError, match=rf"\[Errno {EBADF}\]"):
353 real_fstat(directory_fds[0])
354 lock.close()
355
356
357 @NEEDS_REGISTER_AT_FORK
358 def test_reader_directory_registration_and_close_errors_are_grouped( # pragma: needs fork
359 tmp_path: Path, mocker: MockerFixture
360 ) -> None:
361 lock = SoftReadWriteLock(
362 str(tmp_path / "parent.lock"),
363 is_singleton=False,
364 heartbeat_interval=0.1,
365 stale_threshold=0.5,
366 )
367 real_close, real_fstat = os.close, os.fstat
368 directory_fds: list[int] = []
369
370 def fail_directory_fstat(fd: int) -> os.stat_result:
371 stat_result = real_fstat(fd)
372 assert S_ISDIR(stat_result.st_mode)
373 directory_fds.append(fd)
374 msg = "directory identity unavailable"
375 raise OSError(msg)
376
377 def fail_directory_close(fd: int) -> None:
378 assert fd == directory_fds[0]
379 msg = "directory close failed"
380 raise OSError(msg)
381
382 mocker.patch("os.fstat", side_effect=fail_directory_fstat)
383 mocker.patch("os.close", side_effect=fail_directory_close)
384 with pytest.raises(BaseExceptionGroup) as info:
385 lock.acquire_read()
386 real_close(directory_fds[0])
387 lock.close()
388
389 assert [(type(error), str(error)) for error in info.value.exceptions] == [
390 (OSError, "directory identity unavailable"),
391 (OSError, "directory close failed"),
392 ]
393
394
395 @NEEDS_FORK # pragma: needs fork
396 @_FORK_WARNING
397 def test_child_callback_registered_before_filelock_can_acquire(tmp_path: Path) -> None:
398 script = """
399 import os
400 import sys
401
402 parent_path, child_path = sys.argv[1:]
403 callback_succeeded = False
404
405 def acquire_in_early_child_callback() -> None:
406 global callback_succeeded
407 with FileLock(child_path, is_singleton=False):
408 pass
409 callback_succeeded = True
410
411 os.register_at_fork(after_in_child=acquire_in_early_child_callback)
412
413 from filelock import FileLock, Timeout
414
415 parent = FileLock(parent_path, is_singleton=False)
416 parent.acquire()
417 child_pid = os.fork()
418 if child_pid == 0:
419 os._exit(0 if callback_succeeded else 3)
420 _, status = os.waitpid(child_pid, 0)
421 if os.waitstatus_to_exitcode(status) != 0:
422 sys.exit(1)
423
424 contender = FileLock(parent_path, is_singleton=False)
425 try:
426 contender.acquire(timeout=0)
427 except Timeout:
428 pass
429 else:
430 sys.exit(2)
431 parent.release()
432 """
433 result = subprocess.run(
434 [sys.executable, "-c", script, str(tmp_path / "parent.lock"), str(tmp_path / "child.lock")],
435 check=False,
436 capture_output=True,
437 text=True,
438 timeout=10,
439 )
440
441 assert (result.returncode, result.stderr) == (0, "")
442
443
444 @NEEDS_FORK # pragma: needs fork
445 @_FORK_WARNING
446 @pytest.mark.parametrize(
447 "kind",
448 [
449 pytest.param("native", id="native"),
450 pytest.param("soft", id="soft"),
451 pytest.param("soft-rw", id="soft-read-write"),
452 ],
453 )
454 def test_child_interpreter_exit_preserves_parent_lock(
455 tmp_path: Path, kind: Literal["native", "soft", "soft-rw"]
456 ) -> None:
457 script = """
458 from __future__ import annotations
459
460 import os
461 import sys
462
463 from filelock import BaseFileLock, FileLock, SoftFileLock, SoftReadWriteLock, Timeout
464
465 def acquire(lock: BaseFileLock | SoftReadWriteLock, timeout: float = -1) -> None:
466 if isinstance(lock, SoftReadWriteLock):
467 lock.acquire_write(timeout=timeout)
468 else:
469 lock.acquire(timeout=timeout)
470
471 def release(lock: BaseFileLock | SoftReadWriteLock) -> None:
472 if isinstance(lock, SoftReadWriteLock):
473 lock.release()
474 lock.close()
475 else:
476 lock.release()
477
478 kind, path = sys.argv[1:]
479 lock: BaseFileLock | SoftReadWriteLock
480 if kind == "soft-rw":
481 lock = SoftReadWriteLock(path, is_singleton=False, heartbeat_interval=0.1, stale_threshold=30)
482 elif kind == "soft":
483 lock = SoftFileLock(path, is_singleton=False)
484 else:
485 lock = FileLock(path, is_singleton=False)
486 acquire(lock)
487
488 child_pid = os.fork()
489 if child_pid == 0:
490 sys.exit(0)
491 _, status = os.waitpid(child_pid, 0)
492 if os.waitstatus_to_exitcode(status) != 0:
493 sys.exit(1)
494
495 contender_pid = os.fork()
496 if contender_pid == 0:
497 contender: BaseFileLock | SoftReadWriteLock
498 if kind == "soft-rw":
499 contender = SoftReadWriteLock(path, is_singleton=False, heartbeat_interval=0.1, stale_threshold=30)
500 elif kind == "soft":
501 contender = SoftFileLock(path, is_singleton=False)
502 else:
503 contender = FileLock(path, is_singleton=False)
504 try:
505 acquire(contender, timeout=0)
506 except Timeout:
507 os._exit(0)
508 release(contender)
509 os._exit(2)
510 _, status = os.waitpid(contender_pid, 0)
511 release(lock)
512 sys.exit(os.waitstatus_to_exitcode(status))
513 """
514 result = subprocess.run(
515 [sys.executable, "-c", script, kind, str(tmp_path / "parent.lock")],
516 check=False,
517 capture_output=True,
518 text=True,
519 timeout=15,
520 )
521
522 assert result.returncode == 0, result.stderr
523
524
525 def _run_child_cleanup(
526 lock: BaseFileLock,
527 proxy: AcquireReturnProxy,
528 action: Literal["release", "context", "collect"],
529 ) -> NoReturn:
530 assert (lock.is_locked, lock.lock_counter) == (False, 0)
531 if action == "release":
532 lock.release(force=True)
533 elif action == "context":
534 proxy.__exit__(None, None, None)
535 else:
536 del proxy
537 del lock
538 gc.collect()
539 exit_child(0)
540
541
542 def _probe_lock(lock_type: type[BaseFileLock], path: str) -> bool: # pragma: needs fork
543 read_fd, write_fd = os.pipe()
544
545 def probe_child() -> NoReturn:
546 os.close(read_fd)
547 candidate = lock_type(path, is_singleton=False)
548 try:
549 candidate.acquire(timeout=0)
550 except Timeout:
551 acquired = False
552 else:
553 acquired = True
554 candidate.release()
555 os.write(write_fd, b"1" if acquired else b"0")
556 os.close(write_fd)
557 exit_child(0)
558
559 child_pid = fork_process(probe_child)
560 os.close(write_fd)
561 result = os.read(read_fd, 1)
562 os.close(read_fd)
563 _, status = os.waitpid(child_pid, 0)
564 assert os.waitstatus_to_exitcode(status) == 0
565 return result == b"1"
566
567
568 def _assert_descriptor_closed(fd: int) -> NoReturn:
569 try:
570 os.fstat(fd)
571 except OSError as exception:
572 exit_child(0 if exception.errno == EBADF else 1)
573 exit_child(1)