Debian Codegraph @

tests/test_fork_coordination.py

raw
1 from __future__ import annotations
2
3 import os
4 import subprocess # ruff:ignore[suspicious-subprocess-import] # isolated interpreters control at-fork registration order
5 import sys
6 import threading
7 from typing import TYPE_CHECKING, Final, Literal
8
9 import pytest
10
11 from filelock import BaseFileLock, Timeout, has_fcntl
12 from tests.capability_marks import NEEDS_FORK, NEEDS_FORK1
13 from tests.fork_helpers import exit_child, fork_process
14
15 if TYPE_CHECKING:
16 from pathlib import Path
17
18 _FORK_WARNING: Final[pytest.MarkDecorator] = pytest.mark.filterwarnings(
19 "ignore:.*multi-threaded, use of fork.*:DeprecationWarning"
20 )
21
22
23 @NEEDS_FORK # pragma: needs fork
24 @_FORK_WARNING
25 def test_callbacks_registered_before_filelock_can_use_locks(tmp_path: Path) -> None:
26 script = """
27 from __future__ import annotations
28
29 import os
30 import sys
31
32 callback_lock = None
33 child_ok = False
34 parent_callback_ran = False
35
36 def before() -> None:
37 global callback_lock
38 callback_lock = FileLock(sys.argv[2], is_singleton=True)
39 callback_lock.acquire()
40
41 def parent() -> None:
42 global parent_callback_ran
43 if callback_lock is None or not callback_lock.is_locked:
44 return
45 callback_lock.release()
46 parent_callback_ran = True
47
48 def child() -> None:
49 global child_ok
50 if callback_lock is None:
51 return
52 child_singleton = FileLock(sys.argv[1], is_singleton=True)
53 child_ok = (
54 not callback_lock.is_locked
55 and callback_lock.lock_counter == 0
56 and child_singleton is not parent_singleton
57 )
58
59 os.register_at_fork(before=before, after_in_parent=parent, after_in_child=child)
60
61 from filelock import FileLock
62
63 parent_singleton = FileLock(sys.argv[1], is_singleton=True)
64 child_pid = os.fork()
65 if child_pid == 0:
66 os._exit(0 if child_ok else 1)
67 _, status = os.waitpid(child_pid, 0)
68 if (
69 os.waitstatus_to_exitcode(status) != 0
70 or not parent_callback_ran
71 or callback_lock is None
72 or callback_lock.is_locked
73 ):
74 sys.exit(2)
75 """
76 result = subprocess.run(
77 [sys.executable, "-c", script, str(tmp_path / "singleton.lock"), str(tmp_path / "callback.lock")],
78 check=False,
79 capture_output=True,
80 text=True,
81 timeout=10,
82 )
83
84 assert (result.returncode, result.stderr) == (0, "")
85
86
87 @NEEDS_FORK # pragma: needs fork
88 @_FORK_WARNING
89 @pytest.mark.parametrize(
90 "audit_mode",
91 [pytest.param("installed", id="audit-installed"), pytest.param("rejected", id="audit-rejected")],
92 )
93 def test_concurrent_fork_after_first_snapshot_does_not_deadlock(
94 tmp_path: Path, audit_mode: Literal["installed", "rejected"]
95 ) -> None:
96 script = """
97 from __future__ import annotations
98
99 import os
100 import sys
101 import threading
102 from queue import Queue
103
104 entered = threading.Event()
105 release = threading.Event()
106 statuses: Queue[int] = Queue()
107
108 def block_before_fork() -> None:
109 if threading.current_thread().name == "fork-owner":
110 entered.set()
111 if not release.wait(timeout=5):
112 raise RuntimeError("fork owner was not released")
113
114 os.register_at_fork(before=block_before_fork)
115
116 if sys.argv[2] == "rejected":
117 from typing import TYPE_CHECKING
118
119 if TYPE_CHECKING:
120 from _typeshed import Unused
121
122 def reject_add_hook(event: str, _args: Unused) -> None:
123 if event == "sys.addaudithook":
124 raise RuntimeError
125
126 sys.addaudithook(reject_add_hook)
127
128 from filelock import FileLock
129
130 FileLock(sys.argv[1], is_singleton=False)
131
132 def fork_once() -> None:
133 child_pid = os.fork()
134 if child_pid == 0:
135 os._exit(0)
136 _, status = os.waitpid(child_pid, 0)
137 statuses.put(os.waitstatus_to_exitcode(status))
138
139 owner = threading.Thread(target=fork_once, name="fork-owner")
140 owner.start()
141 if not entered.wait(timeout=5):
142 sys.exit(1)
143 try:
144 child_pid = os.fork()
145 except RuntimeError as exception:
146 second_status = 0 if "unsafe while filelock is changing descriptor ownership" in str(exception) else 1
147 else:
148 if child_pid == 0:
149 os._exit(0)
150 _, status = os.waitpid(child_pid, 0)
151 second_status = os.waitstatus_to_exitcode(status)
152 release.set()
153 owner.join(timeout=5)
154 if second_status != 0 or owner.is_alive() or statuses.get(timeout=1) != 0:
155 sys.exit(2)
156 """
157 result = subprocess.run(
158 [sys.executable, "-c", script, str(tmp_path / "parent.lock"), audit_mode],
159 check=False,
160 capture_output=True,
161 text=True,
162 timeout=10,
163 )
164
165 assert result.returncode == 0, result.stderr
166
167
168 @NEEDS_FORK # pragma: needs fork
169 def test_audit_hook_survives_interpreter_shutdown() -> None:
170 script = """
171 from __future__ import annotations
172
173 from collections.abc import Callable
174
175 import filelock._api as api
176
177 class LateAudit:
178 def __del__(self, object_id: Callable[[LateAudit], int] = id) -> None:
179 object_id(self)
180
181 api.__dict__["_late_shutdown_audit"] = LateAudit()
182 """
183 result = subprocess.run(
184 [sys.executable, "-c", script],
185 check=False,
186 capture_output=True,
187 text=True,
188 timeout=10,
189 )
190
191 assert (result.returncode, result.stderr) == (0, "")
192
193
194 @NEEDS_FORK # pragma: needs fork
195 @pytest.mark.parametrize(
196 "event",
197 [
198 pytest.param("os.fork", id="fork"),
199 pytest.param("os.forkpty", id="forkpty"),
200 pytest.param("_posixsubprocess.fork_exec", id="fork-exec"),
201 ],
202 )
203 def test_audit_rejects_process_creation_inside_descriptor_transition(
204 tmp_path: Path,
205 event: Literal["os.fork", "os.forkpty", "_posixsubprocess.fork_exec"],
206 ) -> None:
207 class AuditedLock(BaseFileLock):
208 def _acquire(self) -> None:
209 self._context.lock_file_fd = None
210 if event == "_posixsubprocess.fork_exec":
211 sys.audit(event, (), (), None)
212 else:
213 sys.audit(event)
214
215 _release = _acquire
216
217 with pytest.raises(RuntimeError, match="unsafe while filelock is changing descriptor ownership"):
218 AuditedLock(str(tmp_path / "audit.lock"), is_singleton=False).acquire(timeout=0)
219
220
221 @NEEDS_FORK # pragma: needs fork
222 @_FORK_WARNING
223 @pytest.mark.parametrize(
224 "fork_mode",
225 [
226 pytest.param("rejected-audit", id="rejected-audit-hook"),
227 pytest.param(
228 "fork1",
229 marks=NEEDS_FORK1,
230 id="fork1",
231 ),
232 ],
233 )
234 def test_fork_without_audit_guard_snapshots_current_transition(
235 tmp_path: Path, fork_mode: Literal["rejected-audit", "fork1"]
236 ) -> None:
237 script = """
238 from __future__ import annotations
239
240 import os
241 import sys
242 from errno import EBADF
243
244 if sys.argv[1] == "rejected-audit":
245 from typing import TYPE_CHECKING
246
247 if TYPE_CHECKING:
248 from _typeshed import Unused
249
250 def reject_filelock_hook(event: str, _args: Unused) -> None:
251 if event == "sys.addaudithook":
252 raise RuntimeError
253
254 sys.addaudithook(reject_filelock_hook)
255
256 from filelock import BaseFileLock
257
258 fork = os.fork if sys.argv[1] == "rejected-audit" else os.fork1
259
260 class ForkingLock(BaseFileLock):
261 child_status = -1
262
263 def _acquire(self) -> None:
264 descriptor = self._context.lock_file_fd = os.open(self.lock_file, os.O_CREAT | os.O_RDWR, 0o600)
265 child_pid = fork()
266 if child_pid == 0:
267 try:
268 os.fstat(descriptor)
269 except OSError as exception:
270 os._exit(0 if exception.errno == EBADF else 1)
271 os._exit(1)
272 _, status = os.waitpid(child_pid, 0)
273 self.child_status = os.waitstatus_to_exitcode(status)
274
275 def _release(self) -> None:
276 os.close(self._context.lock_file_fd if self._context.lock_file_fd is not None else -1)
277 self._context.lock_file_fd = None
278
279 lock = ForkingLock(sys.argv[2], is_singleton=False)
280 lock.acquire()
281 lock.release()
282 raise SystemExit(lock.child_status)
283 """
284 result = subprocess.run(
285 [sys.executable, "-c", script, fork_mode, str(tmp_path / "transition.lock")],
286 check=False,
287 capture_output=True,
288 text=True,
289 timeout=10,
290 )
291
292 assert (result.returncode, result.stderr) == (0, "")
293
294
295 @NEEDS_FORK # pragma: needs fork
296 @_FORK_WARNING
297 @pytest.mark.skipif(not has_fcntl, reason="fcntl.flock required")
298 @pytest.mark.skipif(sys.implementation.name != "cpython", reason="CPython fcntl audit event required")
299 @pytest.mark.parametrize(
300 "fork_mode",
301 [
302 pytest.param("rejected-audit", id="rejected-audit-hook"),
303 pytest.param(
304 "fork1",
305 marks=NEEDS_FORK1,
306 id="fork1",
307 ),
308 ],
309 )
310 def test_native_descriptor_is_visible_during_flock_audit(
311 tmp_path: Path, fork_mode: Literal["rejected-audit", "fork1"]
312 ) -> None:
313 script = """
314 from __future__ import annotations
315
316 import os
317 import sys
318 from errno import EBADF
319
320 child_status = -1
321 forked = False
322
323 # Typed for the fcntl.flock payload (fd, cmd); every other event returns before touching args.
324 def audit_hook(event: str, args: tuple[int, int]) -> None:
325 global child_status, forked
326 if event == "sys.addaudithook" and sys.argv[1] == "rejected-audit":
327 raise RuntimeError
328 if event != "fcntl.flock" or forked:
329 return
330 forked = True
331 descriptor = args[0]
332 child_pid = (os.fork if sys.argv[1] == "rejected-audit" else os.fork1)()
333 if child_pid == 0:
334 try:
335 os.fstat(descriptor)
336 except OSError as exception:
337 os._exit(0 if exception.errno == EBADF else 1)
338 os._exit(1)
339 _, status = os.waitpid(child_pid, 0)
340 child_status = os.waitstatus_to_exitcode(status)
341
342 sys.addaudithook(audit_hook)
343
344 from filelock import FileLock
345
346 lock = FileLock(sys.argv[2], is_singleton=False)
347 lock.acquire()
348 lock.release()
349 raise SystemExit(child_status)
350 """
351 result = subprocess.run(
352 [sys.executable, "-c", script, fork_mode, str(tmp_path / "native.lock")],
353 check=False,
354 capture_output=True,
355 text=True,
356 timeout=10,
357 )
358
359 assert (result.returncode, result.stderr) == (0, "")
360
361
362 @NEEDS_FORK # pragma: needs fork
363 @_FORK_WARNING
364 def test_child_unwinds_pre_fork_transition_before_new_acquire(tmp_path: Path) -> None:
365 script = """
366 from __future__ import annotations
367
368 import os
369 import sys
370 from errno import EBADF
371
372 from typing import TYPE_CHECKING
373
374 if TYPE_CHECKING:
375 from _typeshed import Unused
376
377 def reject_filelock_hook(event: str, _args: Unused) -> None:
378 if event == "sys.addaudithook":
379 raise RuntimeError
380
381 sys.addaudithook(reject_filelock_hook)
382
383 from filelock import BaseFileLock
384
385 class ForkingLock(BaseFileLock):
386 child_pid = -1
387
388 def _acquire(self) -> None:
389 self._context.lock_file_fd = os.open(self.lock_file, os.O_CREAT | os.O_RDWR, 0o600)
390 self.child_pid = os.fork()
391
392 def _release(self) -> None:
393 os.close(self._context.lock_file_fd if self._context.lock_file_fd is not None else -1)
394 self._context.lock_file_fd = None
395
396 first = ForkingLock(sys.argv[1], is_singleton=False)
397 try:
398 first.acquire()
399 except RuntimeError as exception:
400 if first.child_pid != 0 or "inherited across fork" not in str(exception):
401 raise
402
403 class ProbeLock(BaseFileLock):
404 child_status = -1
405
406 def _acquire(self) -> None:
407 descriptor = self._context.lock_file_fd = os.open(self.lock_file, os.O_CREAT | os.O_RDWR, 0o600)
408 child_pid = os.fork()
409 if child_pid == 0:
410 try:
411 os.fstat(descriptor)
412 except OSError as error:
413 os._exit(0 if error.errno == EBADF else 1)
414 os._exit(1)
415 _, status = os.waitpid(child_pid, 0)
416 self.child_status = os.waitstatus_to_exitcode(status)
417
418 def _release(self) -> None:
419 os.close(self._context.lock_file_fd if self._context.lock_file_fd is not None else -1)
420 self._context.lock_file_fd = None
421
422 probe = ProbeLock(sys.argv[2], is_singleton=False)
423 probe.acquire()
424 probe.release()
425 os._exit(probe.child_status)
426
427 _, status = os.waitpid(first.child_pid, 0)
428 first.release()
429 raise SystemExit(os.waitstatus_to_exitcode(status))
430 """
431 result = subprocess.run(
432 [
433 sys.executable,
434 "-c",
435 script,
436 str(tmp_path / "first.lock"),
437 str(tmp_path / "probe.lock"),
438 ],
439 check=False,
440 capture_output=True,
441 text=True,
442 timeout=10,
443 )
444
445 assert (result.returncode, result.stderr) == (0, "")
446
447
448 @NEEDS_FORK # pragma: needs fork
449 @_FORK_WARNING
450 def test_overlapping_coroutine_transitions_close_every_pending_descriptor(tmp_path: Path) -> None:
451 script = """
452 from __future__ import annotations
453
454 import asyncio
455 import os
456 import sys
457 from errno import EBADF
458
459 from typing import TYPE_CHECKING
460
461 if TYPE_CHECKING:
462 from _typeshed import Unused
463
464 def reject_filelock_hook(event: str, _args: Unused) -> None:
465 if event == "sys.addaudithook":
466 raise RuntimeError
467
468 sys.addaudithook(reject_filelock_hook)
469
470 from filelock import BaseAsyncFileLock
471
472 both_pending = asyncio.Event()
473 allow_return = asyncio.Event()
474 descriptors: list[int] = []
475 child_status = -1
476
477 class OverlapLock(BaseAsyncFileLock):
478 async def _acquire(self) -> None: # ty: ignore[invalid-method-override] # coroutine backends are supported
479 global child_status
480 descriptor = self._context.lock_file_fd = os.open(self.lock_file, os.O_CREAT | os.O_RDWR, 0o600)
481 descriptors.append(descriptor)
482 if len(descriptors) == 2:
483 both_pending.set()
484 await both_pending.wait()
485 if self.lock_file != sys.argv[1]:
486 await allow_return.wait()
487 return
488 child_pid = os.fork()
489 if child_pid == 0:
490 for inherited in descriptors:
491 try:
492 os.fstat(inherited)
493 except OSError as exception:
494 if exception.errno == EBADF:
495 continue
496 os._exit(1)
497 os._exit(0)
498 _, status = os.waitpid(child_pid, 0)
499 child_status = os.waitstatus_to_exitcode(status)
500 allow_return.set()
501
502 async def _release(self) -> None: # ty: ignore[invalid-method-override] # coroutine backends are supported
503 os.close(self._context.lock_file_fd if self._context.lock_file_fd is not None else -1)
504 self._context.lock_file_fd = None
505
506 async def main() -> None:
507 first = OverlapLock(sys.argv[1], thread_local=False, is_singleton=False, run_in_executor=False)
508 second = OverlapLock(sys.argv[2], thread_local=False, is_singleton=False, run_in_executor=False)
509 await asyncio.gather(first.acquire(timeout=0), second.acquire(timeout=0))
510 await asyncio.gather(first.release(), second.release())
511 raise SystemExit(child_status)
512
513 asyncio.run(main())
514 """
515 result = subprocess.run(
516 [sys.executable, "-c", script, str(tmp_path / "first.lock"), str(tmp_path / "second.lock")],
517 check=False,
518 capture_output=True,
519 text=True,
520 timeout=10,
521 )
522
523 assert (result.returncode, result.stderr) == (0, "")
524
525
526 @NEEDS_FORK # pragma: needs fork
527 @_FORK_WARNING
528 def test_pending_descriptor_with_unknown_identity_is_preserved_in_child(tmp_path: Path) -> None:
529 script = """
530 from __future__ import annotations
531
532 import os
533 import sys
534
535 from typing import TYPE_CHECKING
536
537 if TYPE_CHECKING:
538 from _typeshed import Unused
539
540 def reject_filelock_hook(event: str, _args: Unused) -> None:
541 if event == "sys.addaudithook":
542 raise RuntimeError
543
544 sys.addaudithook(reject_filelock_hook)
545
546 from filelock import BaseFileLock
547
548 real_fstat = os.fstat
549
550 class PendingLock(BaseFileLock):
551 child_status = -1
552
553 def _acquire(self) -> None:
554 descriptor = os.open(self.lock_file, os.O_CREAT | os.O_RDWR, 0o600)
555 self._context.pending_lock_file_fd = descriptor
556
557 def fail_pending_identity(fd: int) -> os.stat_result:
558 if fd == descriptor:
559 raise OSError("identity unavailable")
560 return real_fstat(fd)
561
562 os.fstat = fail_pending_identity
563 child_pid = os.fork()
564 os.fstat = real_fstat
565 if child_pid == 0:
566 real_fstat(descriptor)
567 raise SystemExit(0)
568 _, status = os.waitpid(child_pid, 0)
569 self.child_status = os.waitstatus_to_exitcode(status)
570 stat_result = real_fstat(descriptor)
571 self._context.pending_lock_file_fd = None
572 self._context.lock_file_fd = descriptor
573 self._context.lock_file_fd_identity = stat_result.st_dev, stat_result.st_ino
574
575 def _release(self) -> None:
576 os.close(self._context.lock_file_fd if self._context.lock_file_fd is not None else -1)
577 self._context.lock_file_fd = None
578
579 lock = PendingLock(sys.argv[1], is_singleton=False)
580 lock.acquire(timeout=0)
581 lock.release()
582 raise SystemExit(lock.child_status)
583 """
584 result = subprocess.run(
585 [sys.executable, "-c", script, str(tmp_path / "pending.lock")],
586 check=False,
587 capture_output=True,
588 text=True,
589 timeout=10,
590 )
591
592 assert (result.returncode, result.stderr) == (0, "")
593
594
595 @NEEDS_FORK # pragma: needs fork
596 @_FORK_WARNING
597 def test_child_replaces_parameter_model_mutex_held_during_construction(tmp_path: Path) -> None:
598 script = """
599 from __future__ import annotations
600
601 import inspect
602 import os
603 import sys
604 import threading
605 import warnings
606 from collections.abc import Callable
607 from queue import Queue
608
609 warnings.filterwarnings("ignore", message=".*multi-threaded, use of fork.*", category=DeprecationWarning)
610
611 from typing import TYPE_CHECKING
612
613 if TYPE_CHECKING:
614 from _typeshed import Unused
615
616 def reject_filelock_hook(event: str, _args: Unused) -> None:
617 if event == "sys.addaudithook":
618 raise RuntimeError
619
620 sys.addaudithook(reject_filelock_hook)
621
622 from filelock import BaseFileLock
623
624 parent_pid = os.getpid()
625 forked = False
626 paused = threading.Event()
627 release = threading.Event()
628 children: Queue[int] = Queue()
629 real_signature = inspect.signature
630
631 class BlockingLock(BaseFileLock):
632 def _acquire(self) -> None:
633 self._context.lock_file_fd = None
634
635 def _release(self) -> None:
636 self._context.lock_file_fd = None
637
638 class ChildLock(BaseFileLock):
639 def _acquire(self) -> None:
640 self._context.lock_file_fd = None
641
642 def _release(self) -> None:
643 self._context.lock_file_fd = None
644
645 def blocking_signature(target: Callable[..., BaseFileLock | None]) -> inspect.Signature:
646 global forked
647 if target is BlockingLock.__init__ and not forked:
648 forked = True
649 child_pid = os.fork()
650 if child_pid == 0:
651 ChildLock(sys.argv[2], is_singleton=False)
652 os._exit(0)
653 children.put(child_pid)
654 paused.set()
655 if not release.wait(timeout=5):
656 raise RuntimeError("parent construction was not released")
657 return real_signature(target)
658
659 inspect.signature = blocking_signature
660
661 def construct() -> None:
662 BlockingLock(sys.argv[1], is_singleton=False)
663
664 worker = threading.Thread(target=construct)
665 worker.start()
666 if not paused.wait(timeout=5):
667 sys.exit(1)
668 child_pid = children.get(timeout=1)
669 _, status = os.waitpid(child_pid, 0)
670 release.set()
671 worker.join(timeout=5)
672 if os.waitstatus_to_exitcode(status) != 0 or worker.is_alive() or os.getpid() != parent_pid:
673 sys.exit(2)
674 """
675 result = subprocess.run(
676 [sys.executable, "-c", script, str(tmp_path / "parent.lock"), str(tmp_path / "child.lock")],
677 check=False,
678 capture_output=True,
679 text=True,
680 timeout=10,
681 )
682
683 assert (result.returncode, result.stderr) == (0, "")
684
685
686 @NEEDS_FORK # pragma: needs fork
687 @_FORK_WARNING
688 def test_registration_transition_completes_after_fork_closes_admission(tmp_path: Path) -> None:
689 script = """
690 from __future__ import annotations
691
692 import os
693 import sys
694 import threading
695 import warnings
696 from queue import Queue
697
698 warnings.filterwarnings("ignore", message=".*multi-threaded, use of fork.*", category=DeprecationWarning)
699
700 admission_waiting = threading.Event()
701 real_condition_wait = threading.Condition.wait
702
703 def observed_wait(condition: threading.Condition, timeout: float | None = None) -> bool:
704 if threading.current_thread().name == "forker":
705 admission_waiting.set()
706 return real_condition_wait(condition, timeout)
707
708 threading.Condition.wait = observed_wait
709
710 from filelock import BaseFileLock
711
712 entered = threading.Event()
713 release = threading.Event()
714 failures: Queue[str] = Queue()
715 fork_status: Queue[int] = Queue()
716
717 class BlockingLock(BaseFileLock):
718 def _acquire(self) -> None:
719 self._context.lock_file_fd = os.open(self.lock_file, os.O_CREAT | os.O_RDWR, 0o600)
720 entered.set()
721 if not release.wait(timeout=5):
722 raise RuntimeError("backend acquisition was not released")
723
724 def _release(self) -> None:
725 os.close(self._context.lock_file_fd if self._context.lock_file_fd is not None else -1)
726 self._context.lock_file_fd = None
727
728 lock = BlockingLock(sys.argv[1], is_singleton=False)
729
730 def acquire() -> None:
731 try:
732 lock.acquire(timeout=0)
733 except BaseException as exception:
734 failures.put(f"acquire: {exception!r}")
735
736 def fork() -> None:
737 try:
738 child_pid = os.fork()
739 if child_pid == 0:
740 os._exit(0)
741 _, status = os.waitpid(child_pid, 0)
742 fork_status.put(os.waitstatus_to_exitcode(status))
743 except BaseException as exception:
744 failures.put(f"fork: {exception!r}")
745
746 worker = threading.Thread(target=acquire, name="acquirer")
747 worker.start()
748 if not entered.wait(timeout=5):
749 sys.exit(1)
750 forker = threading.Thread(target=fork, name="forker")
751 forker.start()
752 if not admission_waiting.wait(timeout=5):
753 sys.exit(2)
754 release.set()
755 worker.join(timeout=5)
756 forker.join(timeout=5)
757 if worker.is_alive() or forker.is_alive() or not failures.empty() or fork_status.get(timeout=1) != 0:
758 sys.exit(3)
759 lock.release()
760 """
761 result = subprocess.run(
762 [sys.executable, "-c", script, str(tmp_path / "admission.lock")],
763 check=False,
764 capture_output=True,
765 text=True,
766 timeout=10,
767 )
768
769 assert (result.returncode, result.stderr) == (0, "")
770
771
772 @NEEDS_FORK # pragma: needs fork
773 @_FORK_WARNING
774 @pytest.mark.skipif(not has_fcntl, reason="fcntl.flock required")
775 def test_cancelled_async_acquire_unregisters_reused_descriptor(tmp_path: Path) -> None:
776 script = """
777 from __future__ import annotations
778
779 import asyncio
780 import faulthandler
781 import os
782 import signal
783 import sys
784 import threading
785 import time
786 import warnings
787
788 from filelock import AsyncFileLock
789
790 warnings.filterwarnings("ignore", message=".*multi-threaded, use of fork.*", category=DeprecationWarning)
791
792 child_pid = 0
793
794 def report_stall(_signum: int, _frame: object) -> None:
795 # Every wait below is bounded, so reaching this means something wedged: the NetBSD fork deadlock (#707, #689)
796 # arrived as a bare SIGKILL naming nothing. Print every stack, then kill the child, which holds the captured
797 # pipes: subprocess.run() waits for those to close even after it has killed this process.
798 faulthandler.dump_traceback(all_threads=True)
799 if child_pid:
800 os.kill(child_pid, signal.SIGKILL)
801 os._exit(7)
802
803 faulthandler.enable()
804 signal.signal(signal.SIGALRM, report_stall)
805 signal.alarm(15)
806
807 async def main() -> tuple[int, tuple[int, int]]:
808 callback_started = asyncio.Event()
809 finish_callback = threading.Event()
810 loop = asyncio.get_running_loop()
811 descriptor = -1
812 identity = (-1, -1)
813
814 def block_after_acquire(fd: int) -> None:
815 nonlocal descriptor, identity
816 descriptor = fd
817 stat_result = os.fstat(fd)
818 identity = stat_result.st_dev, stat_result.st_ino
819 loop.call_soon_threadsafe(callback_started.set)
820 if not finish_callback.wait(timeout=5):
821 raise RuntimeError("acquisition callback was not released")
822
823 lock = AsyncFileLock(sys.argv[1], on_acquired=block_after_acquire)
824 acquire_task = asyncio.create_task(lock.acquire())
825 await asyncio.wait_for(callback_started.wait(), timeout=5)
826 acquire_task.cancel()
827 finish_callback.set()
828 try:
829 await acquire_task
830 except asyncio.CancelledError:
831 pass
832 else:
833 raise SystemExit(1)
834 if lock.is_locked or lock.lock_counter != 0:
835 raise SystemExit(2)
836 return descriptor, identity
837
838 descriptor, identity = asyncio.run(main())
839
840 path_stat = os.stat(sys.argv[1])
841 if (path_stat.st_dev, path_stat.st_ino) != identity:
842 raise SystemExit(3)
843
844 occupant = os.open(os.devnull, os.O_RDONLY)
845 if occupant != descriptor:
846 os.dup2(occupant, descriptor)
847 source = os.open(sys.argv[1], os.O_RDWR)
848 if source == descriptor:
849 raise SystemExit(4)
850 if (source_stat := os.fstat(source)).st_dev != identity[0] or source_stat.st_ino != identity[1]:
851 raise SystemExit(5)
852 os.dup2(source, descriptor)
853 os.close(source)
854 if occupant != descriptor:
855 os.close(occupant)
856
857 # The canceled acquire ran the flock backend in the default executor. asyncio.run() joins that worker on the way out,
858 # but Thread.join() returns while the OS thread is still unwinding, and NetBSD deadlocks a child forked from a process
859 # that still carries one (#707). So fork from module scope with the loop closed, leave the worker time to go, and
860 # report a thread that is still counted rather than wedging the fork on it.
861 time.sleep(0.5)
862 if threading.active_count() != 1:
863 raise SystemExit(6)
864
865 child_pid = os.fork()
866 if child_pid == 0:
867 try:
868 replacement_stat = os.fstat(descriptor)
869 except OSError:
870 os._exit(1)
871 os._exit(0 if (replacement_stat.st_dev, replacement_stat.st_ino) == identity else 2)
872 _, status = os.waitpid(child_pid, 0)
873 signal.alarm(0)
874 os.close(descriptor)
875 raise SystemExit(os.waitstatus_to_exitcode(status))
876 """
877 result = subprocess.run(
878 [sys.executable, "-c", script, str(tmp_path / "canceled.lock")],
879 check=False,
880 capture_output=True,
881 text=True,
882 timeout=30,
883 )
884
885 assert (result.returncode, result.stderr) == (0, "")
886
887
888 @NEEDS_FORK # pragma: needs fork
889 @_FORK_WARNING
890 def test_parent_callback_rejects_reentrant_singleton_construction(tmp_path: Path) -> None:
891 script = """
892 from __future__ import annotations
893
894 import os
895 import sys
896 from collections.abc import Callable
897
898 active_constructor: Callable[[], BaseFileLock | SoftReadWriteLock] | None = None
899 callback_errors: list[str] = []
900 callback_instances: list[BaseFileLock | SoftReadWriteLock] = []
901
902 def construct_in_parent_callback() -> None:
903 if active_constructor is None:
904 return
905 try:
906 callback_instances.append(active_constructor())
907 except RuntimeError as exception:
908 callback_errors.append(str(exception))
909
910 os.register_at_fork(after_in_parent=construct_in_parent_callback)
911
912 from filelock import BaseFileLock, SoftReadWriteLock
913
914 fork_in_progress = False
915 children: list[int] = []
916
917 def fork_once() -> None:
918 global fork_in_progress
919 if fork_in_progress:
920 return
921 fork_in_progress = True
922 child_pid = os.fork()
923 if child_pid == 0:
924 os._exit(0)
925 children.append(child_pid)
926 fork_in_progress = False
927
928 class ForkingFileLock(BaseFileLock):
929 def __init__(
930 self, lock_file: str, timeout: float = -1, thread_local: bool = True, *, is_singleton: bool = False
931 ) -> None:
932 fork_once()
933 super().__init__(lock_file, timeout, thread_local=thread_local, is_singleton=is_singleton)
934
935 def _acquire(self) -> None:
936 self._context.lock_file_fd = None
937
938 def _release(self) -> None:
939 self._context.lock_file_fd = None
940
941 class ForkingSoftReadWriteLock(SoftReadWriteLock):
942 def __init__(
943 self,
944 lock_file: str,
945 timeout: float = -1,
946 *,
947 blocking: bool = True,
948 is_singleton: bool = True,
949 heartbeat_interval: float = 30.0,
950 stale_threshold: float | None = None,
951 poll_interval: float = 0.25,
952 ) -> None:
953 fork_once()
954 super().__init__(
955 lock_file,
956 timeout,
957 blocking=blocking,
958 is_singleton=is_singleton,
959 heartbeat_interval=heartbeat_interval,
960 stale_threshold=stale_threshold,
961 poll_interval=poll_interval,
962 )
963
964 file_path, read_write_path = sys.argv[1:]
965 active_constructor = lambda: ForkingFileLock(file_path, thread_local=False, is_singleton=True)
966 file_lock = ForkingFileLock(file_path, thread_local=False, is_singleton=True)
967 active_constructor = lambda: ForkingSoftReadWriteLock(read_write_path, is_singleton=True)
968 read_write_lock = ForkingSoftReadWriteLock(read_write_path, is_singleton=True)
969 active_constructor = None
970
971 statuses = [os.waitstatus_to_exitcode(os.waitpid(child_pid, 0)[1]) for child_pid in children]
972 if (
973 statuses != [0, 0]
974 or callback_instances
975 or len(callback_errors) != 2
976 or not all("Singleton lock construction is already active" in error for error in callback_errors)
977 or ForkingFileLock(file_path, thread_local=False, is_singleton=True) is not file_lock
978 or ForkingSoftReadWriteLock(read_write_path, is_singleton=True) is not read_write_lock
979 ):
980 sys.exit(1)
981 """
982 result = subprocess.run(
983 [sys.executable, "-c", script, str(tmp_path / "file.lock"), str(tmp_path / "read-write.lock")],
984 check=False,
985 capture_output=True,
986 text=True,
987 timeout=10,
988 )
989
990 assert (result.returncode, result.stderr) == (0, "")
991
992
993 @NEEDS_FORK # pragma: needs fork
994 @_FORK_WARNING
995 def test_singleton_construction_crossing_fork_does_not_poison_child_cache(tmp_path: Path) -> None:
996 script = """
997 from __future__ import annotations
998
999 import os
1000 import sys
1001
1002 from filelock import BaseFileLock
1003
1004 parent_pid = os.getpid()
1005 forked = False
1006 children: list[int] = []
1007
1008 class ForkingLock(BaseFileLock):
1009 def __init__(self, lock_file: str, thread_local: bool = True, *, is_singleton: bool = False) -> None:
1010 global forked
1011 if not forked:
1012 forked = True
1013 child_pid = os.fork()
1014 if child_pid != 0:
1015 children.append(child_pid)
1016 super().__init__(lock_file, thread_local=thread_local, is_singleton=is_singleton)
1017
1018 def _acquire(self) -> None:
1019 self._context.lock_file_fd = None
1020
1021 def _release(self) -> None:
1022 self._context.lock_file_fd = None
1023
1024 try:
1025 parent_lock = ForkingLock(sys.argv[1], thread_local=False, is_singleton=True)
1026 except RuntimeError as exception:
1027 if os.getpid() == parent_pid or "Lock construction cannot continue after fork" not in str(exception):
1028 raise
1029 child_lock = ForkingLock(sys.argv[1], thread_local=False, is_singleton=True)
1030 raise SystemExit(0 if ForkingLock(sys.argv[1], thread_local=False, is_singleton=True) is child_lock else 1)
1031
1032 _, status = os.waitpid(children[0], 0)
1033 if (
1034 os.waitstatus_to_exitcode(status) != 0
1035 or ForkingLock(sys.argv[1], thread_local=False, is_singleton=True) is not parent_lock
1036 ):
1037 sys.exit(2)
1038 """
1039 result = subprocess.run(
1040 [sys.executable, "-c", script, str(tmp_path / "singleton.lock")],
1041 check=False,
1042 capture_output=True,
1043 text=True,
1044 timeout=10,
1045 )
1046
1047 assert (result.returncode, result.stderr) == (0, "")
1048
1049
1050 @NEEDS_FORK # pragma: needs fork
1051 @_FORK_WARNING
1052 def test_soft_read_write_construction_crossing_fork_does_not_poison_child_cache(
1053 tmp_path: Path,
1054 ) -> None:
1055 script = """
1056 from __future__ import annotations
1057
1058 import os
1059 import sys
1060
1061 from filelock import SoftReadWriteLock
1062
1063 parent_pid = os.getpid()
1064 forked = False
1065 children: list[int] = []
1066
1067 class ForkingLock(SoftReadWriteLock):
1068 def __init__(
1069 self,
1070 lock_file: str,
1071 timeout: float = -1,
1072 *,
1073 blocking: bool = True,
1074 is_singleton: bool = True,
1075 heartbeat_interval: float = 30.0,
1076 stale_threshold: float | None = None,
1077 poll_interval: float = 0.25,
1078 ) -> None:
1079 global forked
1080 if not forked:
1081 forked = True
1082 child_pid = os.fork()
1083 if child_pid != 0:
1084 children.append(child_pid)
1085 super().__init__(
1086 lock_file,
1087 timeout,
1088 blocking=blocking,
1089 is_singleton=is_singleton,
1090 heartbeat_interval=heartbeat_interval,
1091 stale_threshold=stale_threshold,
1092 poll_interval=poll_interval,
1093 )
1094
1095 try:
1096 parent_lock = ForkingLock(sys.argv[1], is_singleton=True)
1097 except RuntimeError as exception:
1098 if os.getpid() == parent_pid or "Lock construction cannot continue after fork" not in str(exception):
1099 raise
1100 child_lock = ForkingLock(sys.argv[1], is_singleton=True)
1101 child_cached = ForkingLock(sys.argv[1], is_singleton=True)
1102 child_lock.close()
1103 raise SystemExit(0 if child_cached is child_lock else 1)
1104
1105 _, status = os.waitpid(children[0], 0)
1106 parent_cached = ForkingLock(sys.argv[1], is_singleton=True)
1107 parent_lock.close()
1108 if os.waitstatus_to_exitcode(status) != 0 or parent_cached is not parent_lock:
1109 sys.exit(2)
1110 """
1111 result = subprocess.run(
1112 [sys.executable, "-c", script, str(tmp_path / "singleton.lock")],
1113 check=False,
1114 capture_output=True,
1115 text=True,
1116 timeout=10,
1117 )
1118
1119 assert (result.returncode, result.stderr) == (0, "")
1120
1121
1122 def test_fork_exec_from_another_thread_remains_available(tmp_path: Path) -> None:
1123 entered, release, finished = threading.Event(), threading.Event(), threading.Event()
1124
1125 class BlockingTransitionLock(BaseFileLock):
1126 def _acquire(self) -> None:
1127 entered.set()
1128 release.wait(timeout=5)
1129 self._context.lock_file_fd = None
1130
1131 _release = _acquire
1132
1133 def acquire() -> None:
1134 try:
1135 BlockingTransitionLock(str(tmp_path / "transition.lock"), is_singleton=False).acquire(timeout=0)
1136 except Timeout:
1137 finished.set()
1138
1139 worker = threading.Thread(target=acquire)
1140 worker.start()
1141 assert entered.wait(timeout=5)
1142 sys.audit("_posixsubprocess.fork_exec", (), (), None)
1143 result = subprocess.run([sys.executable, "-c", ""], check=False, timeout=5)
1144 release.set()
1145 worker.join(timeout=5)
1146
1147 assert (result.returncode, finished.is_set(), worker.is_alive()) == (0, True, False)
1148
1149
1150 @NEEDS_FORK # pragma: needs fork
1151 @_FORK_WARNING
1152 def test_child_replaces_singleton_mutex_held_by_vanished_thread(tmp_path: Path) -> None:
1153 entered, release = threading.Event(), threading.Event()
1154 parent_pid = os.getpid()
1155
1156 class BlockingLock(BaseFileLock):
1157 def __init__(self, lock_file: str, *, is_singleton: bool = False) -> None:
1158 if os.getpid() == parent_pid:
1159 entered.set()
1160 release.wait(timeout=5)
1161 super().__init__(lock_file, thread_local=False, is_singleton=is_singleton)
1162
1163 def _acquire(self) -> None:
1164 self._context.lock_file_fd = os.open(self.lock_file, os.O_CREAT | os.O_RDWR, 0o600)
1165
1166 def _release(self) -> None:
1167 os.close(self._context.lock_file_fd if self._context.lock_file_fd is not None else -1)
1168 self._context.lock_file_fd = None
1169
1170 worker = threading.Thread(target=BlockingLock, args=(str(tmp_path / "mutex.lock"),), kwargs={"is_singleton": True})
1171 worker.start()
1172 assert entered.wait(timeout=5)
1173
1174 if (child_pid := fork_process()) == 0: # pragma: forked child
1175 child_lock = BlockingLock(str(tmp_path / "mutex.lock"), is_singleton=True)
1176 child_lock.acquire(timeout=0)
1177 child_lock.release()
1178 exit_child(0)
1179 _, status = os.waitpid(child_pid, 0)
1180 release.set()
1181 worker.join(timeout=5)
1182
1183 assert (os.waitstatus_to_exitcode(status), worker.is_alive()) == (0, False)