Debian Codegraph @

tests/soft_rw/test_soft_rw_sync.py

raw
1 from __future__ import annotations
2
3 import multiprocessing as mp
4 import os
5 import signal
6 import socket
7 import stat
8 import sys
9 import threading
10 import time
11 from contextlib import suppress
12 from errno import EIO, ENOENT
13 from multiprocessing import Event, Process
14 from pathlib import Path
15 from typing import TYPE_CHECKING, Final, Literal
16
17 import pytest
18 from capabilities import CAPABILITIES
19
20 from filelock import Timeout
21 from filelock import _util as util_mod
22 from filelock._soft_rw import SoftReadWriteLock
23 from filelock._soft_rw import _sync as sync_mod
24 from tests.capability_marks import NEEDS_FILE_MODE, NEEDS_FORK, NEEDS_POSIX_SIGNALS, SKIP_ON_UNRELIABLE_PROCESS_SYNC
25 from tests.process_helpers import cleanup_processes
26
27 if TYPE_CHECKING:
28 from collections.abc import Callable, Generator
29 from multiprocessing.synchronize import Event as EventType
30
31 from pytest_mock import MockerFixture
32
33
34 _OWNER_READ_WRITE: Final[int] = 0o600
35
36 # Bounds how long a spawned process or thread may take to reach the lock, not how fast it must be: an interpreter
37 # that starts slowly under a loaded suite is not a locking failure. The short negative waits below are deliberate,
38 # since those assert a contender stays blocked and have to stay brief.
39 _PROCESS_DEADLINE: Final[int] = 30
40
41
42 @pytest.fixture(autouse=True)
43 def _clear_singletons() -> Generator[None]:
44 SoftReadWriteLock._instances.clear()
45 yield
46 for lock in filter(None, (ref() for ref in list(SoftReadWriteLock._instances.valuerefs()))):
47 lock.close()
48 SoftReadWriteLock._instances.clear()
49
50
51 @pytest.fixture
52 def lock_file(tmp_path: Path) -> str:
53 return str(tmp_path / "test.lock")
54
55
56 def test_rejects_non_positive_heartbeat_interval(lock_file: str) -> None:
57 with pytest.raises(ValueError, match="heartbeat_interval must be positive"):
58 SoftReadWriteLock(lock_file, heartbeat_interval=0, is_singleton=False)
59
60
61 def test_rejects_stale_threshold_not_greater_than_heartbeat(lock_file: str) -> None:
62 with pytest.raises(ValueError, match="stale_threshold must exceed"):
63 SoftReadWriteLock(lock_file, heartbeat_interval=10, stale_threshold=5, is_singleton=False)
64
65
66 def test_rejects_non_positive_poll_interval(lock_file: str) -> None:
67 with pytest.raises(ValueError, match="poll_interval must be positive"):
68 SoftReadWriteLock(lock_file, poll_interval=0, is_singleton=False)
69
70
71 def test_public_attributes(lock_file: str) -> None:
72 lock = SoftReadWriteLock(
73 lock_file,
74 timeout=5,
75 blocking=False,
76 heartbeat_interval=10,
77 stale_threshold=45,
78 poll_interval=0.5,
79 is_singleton=False,
80 )
81 try:
82 assert lock.lock_file == lock_file
83 assert lock.timeout == 5
84 assert lock.blocking is False
85 assert lock.heartbeat_interval == 10
86 assert lock.stale_threshold == 45
87 assert lock.poll_interval == pytest.approx(0.5)
88 finally:
89 lock.close()
90
91
92 def test_default_stale_threshold_is_triple_heartbeat(lock_file: str) -> None:
93 lock = SoftReadWriteLock(lock_file, heartbeat_interval=12, is_singleton=False)
94 try:
95 assert lock.stale_threshold == 36
96 finally:
97 lock.close()
98
99
100 def test_singleton_returns_same_instance(lock_file: str) -> None:
101 first = SoftReadWriteLock(lock_file)
102 second = SoftReadWriteLock(lock_file)
103 try:
104 assert first is second
105 finally:
106 first.close()
107
108
109 def test_non_singleton_returns_distinct_instances(lock_file: str) -> None:
110 first = SoftReadWriteLock(lock_file, is_singleton=False)
111 second = SoftReadWriteLock(lock_file, is_singleton=False)
112 try:
113 assert first is not second
114 finally:
115 first.close()
116 second.close()
117
118
119 def test_singleton_mismatch_raises(lock_file: str) -> None:
120 first = SoftReadWriteLock(lock_file, timeout=5)
121 try:
122 with pytest.raises(ValueError, match="cannot be changed"):
123 SoftReadWriteLock(lock_file, timeout=10)
124 finally:
125 first.close()
126
127
128 def test_get_lock_returns_singleton(lock_file: str) -> None:
129 first = SoftReadWriteLock.get_lock(lock_file)
130 second = SoftReadWriteLock.get_lock(lock_file)
131 try:
132 assert first is second
133 finally:
134 first.close()
135
136
137 def test_leaked_acquired_singleton_is_closed_on_teardown(lock_file: str) -> None:
138 # A live heartbeat thread keeps the singleton reachable, so the autouse teardown finds and closes it.
139 lock = SoftReadWriteLock(lock_file, heartbeat_interval=0.5)
140 lock.acquire_write(timeout=2)
141 assert Path(f"{lock_file}.write").exists()
142
143
144 def test_reentrant_read_holds_and_releases(lock_file: str) -> None:
145 lock = _make_lock(lock_file)
146 try:
147 with lock.read_lock(timeout=2), lock.read_lock(timeout=2):
148 pass
149 with lock.read_lock(timeout=2):
150 pass
151 finally:
152 lock.close()
153
154
155 def test_reentrant_write_holds_and_releases(lock_file: str) -> None:
156 lock = _make_lock(lock_file)
157 try:
158 with lock.write_lock(timeout=2), lock.write_lock(timeout=2):
159 assert Path(f"{lock_file}.write").exists()
160 assert not Path(f"{lock_file}.write").exists()
161 finally:
162 lock.close()
163
164
165 def test_upgrade_from_read_to_write_raises(lock_file: str) -> None:
166 lock = _make_lock(lock_file)
167 try:
168 with lock.read_lock(timeout=2), pytest.raises(RuntimeError, match="upgrade not allowed"):
169 lock.acquire_write(timeout=1)
170 finally:
171 lock.close()
172
173
174 def test_downgrade_from_write_to_read_raises(lock_file: str) -> None:
175 lock = _make_lock(lock_file)
176 try:
177 with lock.write_lock(timeout=2), pytest.raises(RuntimeError, match="downgrade not allowed"):
178 lock.acquire_read(timeout=1)
179 finally:
180 lock.close()
181
182
183 def test_write_lock_is_thread_pinned(lock_file: str) -> None:
184 lock = _make_lock(lock_file)
185 errors: list[BaseException] = []
186 lock.acquire_write(timeout=2)
187
188 def other() -> None:
189 try:
190 lock.acquire_write(timeout=1, blocking=False)
191 except BaseException as exc:
192 errors.append(exc)
193
194 thread = threading.Thread(target=other)
195 thread.start()
196 thread.join()
197 lock.release()
198 lock.close()
199 assert len(errors) == 1
200 assert isinstance(errors[0], (RuntimeError, Timeout))
201
202
203 def test_blocking_acquire_without_timeout_waits_for_release(lock_file: str) -> None:
204 # Without a deadline the poll loop sleeps a full interval each round rather than clamping to a budget.
205 holder = _make_lock(lock_file)
206 holder.acquire_write(timeout=2)
207 acquired = threading.Event()
208
209 def waiter() -> None:
210 contender = _make_lock(lock_file)
211 try:
212 contender.acquire_read(timeout=-1)
213 acquired.set()
214 contender.release()
215 finally:
216 contender.close()
217
218 thread = threading.Thread(target=waiter)
219 thread.start()
220 try:
221 assert not acquired.wait(timeout=0.2)
222 holder.release()
223 assert acquired.wait(timeout=_PROCESS_DEADLINE)
224 finally:
225 thread.join(timeout=_PROCESS_DEADLINE)
226 holder.close()
227
228
229 def test_release_without_hold_raises(lock_file: str) -> None:
230 lock = SoftReadWriteLock(lock_file)
231 try:
232 with pytest.raises(RuntimeError, match="not held"):
233 lock.release()
234 finally:
235 lock.close()
236
237
238 def test_release_force_without_hold_is_noop(lock_file: str) -> None:
239 lock = SoftReadWriteLock(lock_file)
240 try:
241 lock.release(force=True)
242 finally:
243 lock.close()
244
245
246 def test_release_force_on_reentrant_lock_drops_all(lock_file: str) -> None:
247 lock = _make_lock(lock_file)
248 try:
249 lock.acquire_read(timeout=2)
250 lock.acquire_read(timeout=2)
251 lock.release(force=True)
252 with lock.write_lock(timeout=2):
253 pass
254 finally:
255 lock.close()
256
257
258 def test_close_is_idempotent(lock_file: str) -> None:
259 lock = SoftReadWriteLock(lock_file)
260 lock.close()
261 lock.close()
262
263
264 def test_acquire_on_closed_raises(lock_file: str) -> None:
265 lock = SoftReadWriteLock(lock_file)
266 lock.close()
267 with pytest.raises(RuntimeError, match="has been closed"):
268 lock.acquire_read(timeout=1)
269 with pytest.raises(RuntimeError, match="has been closed"):
270 lock.acquire_write(timeout=1)
271
272
273 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
274 @pytest.mark.timeout(_PROCESS_DEADLINE * 5)
275 def test_multiple_readers_can_hold_simultaneously(lock_file: str) -> None:
276 r1, r2, release = Event(), Event(), Event()
277 p1 = Process(target=_worker, args=(lock_file, "read", r1, release))
278 p2 = Process(target=_worker, args=(lock_file, "read", r2, release))
279 with cleanup_processes([p1, p2]):
280 p1.start()
281 p2.start()
282 assert r1.wait(timeout=_PROCESS_DEADLINE)
283 assert r2.wait(timeout=_PROCESS_DEADLINE)
284 release.set()
285 p1.join(timeout=_PROCESS_DEADLINE)
286 p2.join(timeout=_PROCESS_DEADLINE)
287
288
289 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
290 @pytest.mark.timeout(_PROCESS_DEADLINE * 4)
291 def test_write_lock_excludes_writers(lock_file: str) -> None:
292 held, release = Event(), Event()
293 second = Event()
294 holder = Process(target=_worker, args=(lock_file, "write", held, release))
295 contender = Process(target=_worker, args=(lock_file, "write", second, None, 0.3, True))
296 with cleanup_processes([holder, contender]):
297 holder.start()
298 assert held.wait(timeout=_PROCESS_DEADLINE)
299 contender.start()
300 assert not second.wait(timeout=0.5)
301 release.set()
302 holder.join(timeout=_PROCESS_DEADLINE)
303 contender.join(timeout=_PROCESS_DEADLINE)
304
305
306 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
307 @pytest.mark.timeout(_PROCESS_DEADLINE * 4)
308 def test_write_lock_excludes_readers(lock_file: str) -> None:
309 held, release = Event(), Event()
310 reader_acquired = Event()
311 writer = Process(target=_worker, args=(lock_file, "write", held, release))
312 reader = Process(target=_worker, args=(lock_file, "read", reader_acquired, None, 0.3, True))
313 with cleanup_processes([writer, reader]):
314 writer.start()
315 assert held.wait(timeout=_PROCESS_DEADLINE)
316 reader.start()
317 assert not reader_acquired.wait(timeout=0.5)
318 release.set()
319 writer.join(timeout=_PROCESS_DEADLINE)
320 reader.join(timeout=_PROCESS_DEADLINE)
321
322
323 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
324 @pytest.mark.timeout(_PROCESS_DEADLINE * 5)
325 def test_writer_drains_existing_readers(lock_file: str) -> None:
326 r_held, r_release = Event(), Event()
327 w_held = Event()
328 reader = Process(target=_worker, args=(lock_file, "read", r_held, r_release))
329 writer = Process(target=_worker, args=(lock_file, "write", w_held))
330 with cleanup_processes([reader, writer]):
331 reader.start()
332 assert r_held.wait(timeout=_PROCESS_DEADLINE)
333 writer.start()
334 assert not w_held.wait(timeout=0.5)
335 r_release.set()
336 reader.join(timeout=_PROCESS_DEADLINE)
337 assert w_held.wait(timeout=_PROCESS_DEADLINE)
338 writer.join(timeout=_PROCESS_DEADLINE)
339
340
341 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
342 @pytest.mark.timeout(_PROCESS_DEADLINE * 7)
343 def test_writer_preference_blocks_new_readers(lock_file: str) -> None:
344 r1_held, r1_release = Event(), Event()
345 w_held, w_release = Event(), Event()
346 r2_held = Event()
347 reader1 = Process(target=_worker, args=(lock_file, "read", r1_held, r1_release))
348 writer = Process(target=_worker, args=(lock_file, "write", w_held, w_release))
349 reader2 = Process(target=_worker, args=(lock_file, "read", r2_held, None, 10, True))
350 with cleanup_processes([reader1, writer, reader2]):
351 reader1.start()
352 assert r1_held.wait(timeout=_PROCESS_DEADLINE)
353 writer.start()
354 # Start reader2 only once the writer's marker is on disk: a fixed sleep undershoots on a Windows runner still
355 # spawning the writer's interpreter, and reader2 then slips in ahead of the writer's intent.
356 deadline = time.monotonic() + _PROCESS_DEADLINE
357 while not Path(f"{lock_file}.write").exists():
358 assert time.monotonic() < deadline
359 time.sleep(0.01)
360 reader2.start()
361 assert not r2_held.wait(timeout=0.5)
362 r1_release.set()
363 assert w_held.wait(timeout=_PROCESS_DEADLINE)
364 assert not r2_held.wait(timeout=0.3)
365 w_release.set()
366 assert r2_held.wait(timeout=_PROCESS_DEADLINE)
367 reader1.join(timeout=_PROCESS_DEADLINE)
368 writer.join(timeout=_PROCESS_DEADLINE)
369 reader2.join(timeout=_PROCESS_DEADLINE)
370
371
372 @pytest.mark.timeout(_PROCESS_DEADLINE * 4)
373 def test_transaction_lock_timeout_across_threads(lock_file: str) -> None:
374 # Two threads share one lock instance. Thread A holds the transaction lock while spinning on a peer
375 # writer; thread B times out on the transaction lock, exercising the in-process Timeout path rather
376 # than cross-process contention.
377 # Staleness is not under test: a peer heartbeat that stalls past a short threshold on a loaded runner would let
378 # thread A evict the peer and take the lock, turning thread B's Timeout into a same-instance ownership error.
379 peer = SoftReadWriteLock(
380 lock_file,
381 is_singleton=False,
382 heartbeat_interval=0.1,
383 stale_threshold=_PROCESS_DEADLINE,
384 poll_interval=0.02,
385 )
386 peer.acquire_write(timeout=2)
387 try:
388 lock = SoftReadWriteLock(
389 lock_file,
390 is_singleton=False,
391 heartbeat_interval=0.1,
392 stale_threshold=_PROCESS_DEADLINE,
393 poll_interval=0.02,
394 )
395 try:
396 thread_ready = threading.Event()
397 release_thread = threading.Event()
398
399 def target_a() -> None:
400 thread_ready.set()
401 with suppress(Timeout):
402 lock.acquire_write(timeout=2)
403 release_thread.wait(timeout=_PROCESS_DEADLINE)
404
405 thread_a = threading.Thread(target=target_a)
406 thread_a.start()
407 try:
408 thread_ready.wait(timeout=_PROCESS_DEADLINE)
409 time.sleep(0.05)
410 with pytest.raises(Timeout):
411 lock.acquire_write(timeout=0.1)
412 finally:
413 release_thread.set()
414 thread_a.join(timeout=_PROCESS_DEADLINE)
415 finally:
416 lock.close()
417 finally:
418 peer.release()
419 peer.close()
420
421
422 @pytest.mark.timeout(_PROCESS_DEADLINE * 3)
423 def test_two_readers_in_same_process_share_slot(lock_file: str) -> None:
424 # Many threads take a read lock on one instance; one hits the inner reentrant branch (lock level
425 # above 0 after waiting on the transaction lock).
426 lock = SoftReadWriteLock(
427 lock_file,
428 is_singleton=False,
429 heartbeat_interval=0.1,
430 stale_threshold=0.5,
431 poll_interval=0.02,
432 )
433 try:
434 barrier = threading.Barrier(8)
435
436 def target() -> None:
437 barrier.wait(timeout=_PROCESS_DEADLINE)
438 with lock.read_lock(timeout=5):
439 time.sleep(0.05)
440
441 threads = [threading.Thread(target=target) for _ in range(8)]
442 for thread in threads:
443 thread.start()
444 for thread in threads:
445 thread.join(timeout=_PROCESS_DEADLINE)
446 finally:
447 lock.close()
448
449
450 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
451 @pytest.mark.timeout(_PROCESS_DEADLINE * 3)
452 def test_timeout_raises(lock_file: str) -> None:
453 held, release = Event(), Event()
454 holder = Process(target=_worker, args=(lock_file, "write", held, release))
455 with cleanup_processes([holder]):
456 holder.start()
457 assert held.wait(timeout=_PROCESS_DEADLINE)
458 lock = _make_lock(lock_file)
459 try:
460 with pytest.raises(Timeout):
461 lock.acquire_write(timeout=0.3)
462 finally:
463 lock.close()
464 release.set()
465 holder.join(timeout=_PROCESS_DEADLINE)
466
467
468 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
469 @pytest.mark.timeout(_PROCESS_DEADLINE * 3)
470 def test_non_blocking_writer_contended_raises(lock_file: str) -> None:
471 held, release = Event(), Event()
472 holder = Process(target=_worker, args=(lock_file, "write", held, release))
473 with cleanup_processes([holder]):
474 holder.start()
475 assert held.wait(timeout=_PROCESS_DEADLINE)
476 lock = _make_lock(lock_file)
477 try:
478 with pytest.raises(Timeout):
479 lock.acquire_write(timeout=1, blocking=False)
480 with pytest.raises(Timeout):
481 lock.acquire_read(timeout=1, blocking=False)
482 finally:
483 lock.close()
484 release.set()
485 holder.join(timeout=_PROCESS_DEADLINE)
486
487
488 @pytest.mark.timeout(10)
489 def test_writer_phase2_timeout_releases_marker(lock_file: str) -> None:
490 # A live reader whose heartbeat stays fresh blocks the phase-2 drain; the writer must abandon its
491 # phase-1 claim so the next writer can retry.
492 reader = _make_lock(lock_file)
493 reader.acquire_read(timeout=2)
494 try:
495 writer = _make_lock(lock_file)
496 try:
497 with pytest.raises(Timeout):
498 writer.acquire_write(timeout=0.3)
499 finally:
500 writer.close()
501 assert not Path(f"{lock_file}.write").exists()
502 finally:
503 reader.release()
504 reader.close()
505
506
507 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
508 @NEEDS_POSIX_SIGNALS
509 @pytest.mark.timeout(_PROCESS_DEADLINE * 3)
510 def test_dead_writer_evicted_by_reader(lock_file: str) -> None: # pragma: needs posix-signals
511 held = Event()
512 holder = Process(target=_sigkill_worker, args=(lock_file, "write", held, 0.1, 0.5))
513 with cleanup_processes([holder]):
514 holder.start()
515 assert held.wait(timeout=_PROCESS_DEADLINE)
516 pid = holder.pid
517 assert pid is not None
518 os.kill(pid, getattr(signal, "SIGKILL")) # ruff:ignore[get-attr-with-constant] - signal.SIGKILL is POSIX-only
519 holder.join(timeout=_PROCESS_DEADLINE)
520 time.sleep(0.8)
521 lock = _make_lock(lock_file)
522 try:
523 with lock.read_lock(timeout=5):
524 pass
525 finally:
526 lock.close()
527 assert not Path(f"{lock_file}.write").exists()
528
529
530 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
531 @NEEDS_POSIX_SIGNALS
532 @pytest.mark.timeout(_PROCESS_DEADLINE * 3)
533 def test_dead_reader_evicted_by_writer(lock_file: str) -> None: # pragma: needs posix-signals
534 held = Event()
535 holder = Process(target=_sigkill_worker, args=(lock_file, "read", held, 0.1, 0.5))
536 with cleanup_processes([holder]):
537 holder.start()
538 assert held.wait(timeout=_PROCESS_DEADLINE)
539 pid = holder.pid
540 assert pid is not None
541 os.kill(pid, getattr(signal, "SIGKILL")) # ruff:ignore[get-attr-with-constant] - signal.SIGKILL is POSIX-only
542 holder.join(timeout=_PROCESS_DEADLINE)
543 time.sleep(0.8)
544 lock = _make_lock(lock_file)
545 try:
546 with lock.write_lock(timeout=5):
547 pass
548 finally:
549 lock.close()
550
551
552 def test_heartbeat_self_stops_when_marker_vanishes(lock_file: str) -> None:
553 lock = _make_lock(lock_file, heartbeat_interval=0.05, stale_threshold=0.2)
554 lock.acquire_write(timeout=2)
555 try:
556 Path(f"{lock_file}.write").unlink()
557 time.sleep(0.15) # two-plus heartbeat ticks to observe the vanished marker and self-stop
558 finally:
559 lock.release(force=True)
560 lock.close()
561 # The vanished marker leaves nothing to evict, so a peer can acquire.
562 peer = _make_lock(lock_file, heartbeat_interval=0.05, stale_threshold=0.2)
563 try:
564 with peer.write_lock(timeout=1):
565 pass
566 finally:
567 peer.close()
568
569
570 def test_heartbeat_self_stops_on_token_replacement(lock_file: str) -> None:
571 lock = _make_lock(lock_file, heartbeat_interval=0.05, stale_threshold=0.2)
572 lock.acquire_write(timeout=2)
573 try:
574 # A well-formed marker holding a different token.
575 Path(f"{lock_file}.write").write_bytes(b"0" * 32 + b"\n1\nhost\n")
576 time.sleep(0.15)
577 finally:
578 lock.release(force=True)
579 lock.close()
580
581
582 def test_release_keeps_a_peers_writer_marker(lock_file: str) -> None:
583 # A holder paused past the stale threshold (GC pause, SIGSTOP, suspended VM) can have its marker evicted
584 # by a peer that then claims the writer slot. On release the holder must not unlink that peer's live
585 # marker; unlinking it would let a second writer through and break mutual exclusion.
586 lock = _make_lock(lock_file, heartbeat_interval=10, stale_threshold=40)
587 lock.acquire_write(timeout=2)
588 try:
589 write_marker = f"{lock_file}.write"
590 peer_marker = b"a" * 32 + b"\n1\npeerhost\n"
591 Path(write_marker).write_bytes(peer_marker)
592 lock.release()
593 assert Path(write_marker).read_bytes() == peer_marker
594 finally:
595 lock.close()
596
597
598 def test_writer_phase2_does_not_complete_on_a_peers_marker(lock_file: str, monkeypatch: pytest.MonkeyPatch) -> None:
599 # A writer paused past stale_threshold during phase 2 (waiting for readers to drain) can have its stale
600 # marker evicted by a peer that reclaims .write with its own token. Phase 2 must notice the foreign marker
601 # rather than keep touching it and completing the acquire as if we still held the slot, which would let two
602 # writers run at once. A live reader keeps phase 2 looping; on the first poll sleep we simulate the eviction
603 # by overwriting .write with a peer token and draining the reader.
604 reader = _make_lock(lock_file, heartbeat_interval=10, stale_threshold=40)
605 reader.acquire_read(timeout=2)
606 writer = _make_lock(lock_file, heartbeat_interval=10, stale_threshold=40)
607 write_marker = f"{lock_file}.write"
608 peer_marker = b"a" * 32 + b"\n1\npeerhost\n"
609 real_sleep = time.sleep
610 swapped = threading.Event()
611
612 # Only the writer's phase-2 poll loop calls the patched sleep (the reader's heartbeat waits on an Event), so the
613 # swap lands on the first poll and the second poll ends the wait. Driving the timeout from the hook instead of the
614 # wall clock keeps this deterministic: a loaded runner could otherwise blow the deadline during phase-2 setup and
615 # raise Timeout before the first sleep ever ran, leaving the swap uninjected.
616 def hook(seconds: float) -> None: # ruff:ignore[unused-function-argument] # replaces time.sleep; the duration is irrelevant to the swap
617 if swapped.is_set():
618 raise Timeout(lock_file)
619 swapped.set()
620 Path(write_marker).write_bytes(peer_marker)
621 reader.release()
622
623 monkeypatch.setattr(sync_mod.time, "sleep", hook)
624 try:
625 with pytest.raises(Timeout):
626 writer.acquire_write(timeout=30)
627 assert swapped.is_set()
628 # We never overwrote or refreshed the peer's live marker.
629 assert Path(write_marker).read_bytes() == peer_marker
630 finally:
631 monkeypatch.setattr(sync_mod.time, "sleep", real_sleep)
632 writer.close()
633 reader.close()
634
635
636 def test_heartbeat_survives_transient_touch_error(lock_file: str, monkeypatch: pytest.MonkeyPatch) -> None:
637 # On the NFS-style filesystems this lock targets, a transient ESTALE/EIO on the heartbeat touch is
638 # routine; it must not kill the heartbeat and drop the lease while we still believe we hold it.
639 def boom(name: str, *, fd: int | None = None) -> None: # ruff:ignore[unused-function-argument] # matches the patched touch signature and always raises
640 raise OSError(EIO, "Input/output error")
641
642 lock = _make_lock(lock_file, heartbeat_interval=0.02, stale_threshold=0.2)
643 lock.acquire_write(timeout=2)
644 try:
645 hold = lock._hold
646 assert hold is not None
647 monkeypatch.setattr(sync_mod, "touch", boom)
648 time.sleep(0.2) # ~10 ticks, every one failing the touch
649 assert hold.heartbeat_thread.is_alive()
650 assert not hold.heartbeat_stop.is_set()
651 finally:
652 lock.release(force=True)
653 lock.close()
654
655
656 @pytest.mark.parametrize(
657 "target", [pytest.param("_open_marker_fd", id="open"), pytest.param("_read_marker_fd", id="read")]
658 )
659 def test_heartbeat_survives_a_transient_marker_error(
660 lock_file: str, monkeypatch: pytest.MonkeyPatch, target: str
661 ) -> None:
662 # A transient ESTALE/EIO opening or reading the marker is routine on the NFS-style filesystems this lock targets.
663 # Unlike the marker actually vanishing, it must not stop the heartbeat and drop the lease.
664 def boom(*_args: object, **_kwargs: object) -> None:
665 raise OSError(EIO, "Input/output error")
666
667 lock = _make_lock(lock_file, heartbeat_interval=0.02, stale_threshold=0.2)
668 lock.acquire_write(timeout=2)
669 try:
670 hold = lock._hold
671 assert hold is not None
672 monkeypatch.setattr(sync_mod, target, boom)
673 time.sleep(0.2) # ~10 ticks, every one failing the open or read
674 assert hold.heartbeat_thread.is_alive()
675 assert not hold.heartbeat_stop.is_set()
676 finally:
677 lock.release(force=True)
678 lock.close()
679
680
681 def test_heartbeat_stops_when_marker_evicted(lock_file: str, monkeypatch: pytest.MonkeyPatch) -> None:
682 # An O_NOFOLLOW open failing with ENOENT means the marker we held is gone: a peer evicted us. Unlike a transient
683 # filesystem error, this is an unambiguous loss, so the heartbeat must stop rather than keep retrying.
684 def gone(name: str, *, dir_fd: int | None = None) -> int: # ruff:ignore[unused-function-argument] # matches the patched _open_marker_fd signature and always raises
685 raise FileNotFoundError(ENOENT, "No such file or directory")
686
687 lock = _make_lock(lock_file, heartbeat_interval=0.02, stale_threshold=0.2)
688 lock.acquire_write(timeout=2)
689 try:
690 hold = lock._hold
691 assert hold is not None
692 monkeypatch.setattr(sync_mod, "_open_marker_fd", gone)
693 assert hold.heartbeat_stop.wait(timeout=_PROCESS_DEADLINE)
694 hold.heartbeat_thread.join(timeout=_PROCESS_DEADLINE)
695 assert not hold.heartbeat_thread.is_alive()
696 finally:
697 lock.release(force=True)
698 lock.close()
699
700
701 @pytest.mark.parametrize("mode", [pytest.param("write", id="write"), pytest.param("read", id="read")])
702 def test_acquire_hands_back_the_slot_when_the_heartbeat_cannot_start(
703 lock_file: str, mocker: MockerFixture, mode: Literal["read", "write"]
704 ) -> None:
705 # A heartbeat thread the OS refuses (an rlimit reached) must not leave a hold behind: a peer would evict the
706 # unrefreshed marker and acquire while this instance still believed it held the lock, and release() would raise
707 # joining a thread that never started.
708 mocker.patch.object(sync_mod._HeartbeatThread, "start", side_effect=RuntimeError("can't start new thread"))
709 lock = _make_lock(lock_file)
710 acquire = lock.acquire_write if mode == "write" else lock.acquire_read
711 with pytest.raises(RuntimeError, match="can't start new thread"):
712 acquire(timeout=2)
713
714 assert lock._hold is None
715 assert not Path(lock._paths.write).exists()
716 assert not lock._any_readers()
717 lock.release(force=True) # a handed-back slot leaves nothing to release, so this must not raise
718 lock.close()
719
720
721 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
722 @pytest.mark.timeout(_PROCESS_DEADLINE * 3)
723 def test_live_heartbeat_keeps_lock_alive_past_stale_threshold(lock_file: str) -> None:
724 # Generous timing here so the test stays stable on slow Windows runners where the holder's
725 # multiprocessing.spawn startup, the heartbeat thread scheduling, and the parent's mtime resolution
726 # can all introduce sub-second jitter.
727 heartbeat, stale = 0.3, 1.5
728 held, release = Event(), Event()
729 holder = Process(
730 target=_worker,
731 args=(lock_file, "write", held, release, -1, True, heartbeat, stale, 0.05),
732 )
733 with cleanup_processes([holder]):
734 holder.start()
735 assert held.wait(timeout=_PROCESS_DEADLINE)
736 time.sleep(stale * 2)
737 lock = _make_lock(lock_file, heartbeat_interval=heartbeat, stale_threshold=stale)
738 try:
739 with pytest.raises(Timeout):
740 lock.acquire_write(timeout=0.5)
741 finally:
742 lock.close()
743 release.set()
744 holder.join(timeout=_PROCESS_DEADLINE)
745
746
747 @pytest.mark.parametrize(
748 "content",
749 [
750 pytest.param(b"deadbeefdeadbeefdeadbeefdeadbeef\nnotanumber\nhost\n", id="non-numeric-pid"),
751 pytest.param(b"deadbeefdeadbeefdeadbeefdeadbeef\n0\nhost\n", id="zero-pid"),
752 pytest.param(b"deadbeefdeadbeefdeadbeefdeadbeef\n9999999999\nhost\n", id="pid-too-large"),
753 pytest.param(b"bogus\n4711\nhost\n", id="wrong-length-token"),
754 pytest.param(b"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ\n4711\nhost\n", id="non-hex-token"),
755 pytest.param(b"deadbeefdeadbeefdeadbeefdeadbeef\n4711\nhost with space\n", id="hostname-space"),
756 pytest.param(b"deadbeefdeadbeefdeadbeefdeadbeef\n4711\nhost\n\n\n", id="trailing-blank-lines"),
757 pytest.param(b"only one line\n", id="too-few-lines"),
758 pytest.param(b"a\nb\nc\nd\n", id="too-many-lines"),
759 pytest.param(b"x" * 2048, id="oversized"),
760 pytest.param("ééé\n4711\nhost\n".encode(), id="non-ascii"),
761 ],
762 )
763 def test_stale_malformed_marker_is_evicted(lock_file: str, content: bytes) -> None:
764 _write_stale_marker(f"{lock_file}.write", content)
765 lock = _make_lock(lock_file)
766 try:
767 with lock.write_lock(timeout=2):
768 pass
769 finally:
770 lock.close()
771
772
773 @pytest.mark.parametrize("mode", [pytest.param("write", id="write"), pytest.param("read", id="read")])
774 @pytest.mark.parametrize(
775 "raw",
776 [pytest.param("host with space", id="space"), pytest.param("wörks", id="non-ascii")],
777 )
778 @pytest.mark.timeout(10)
779 def test_out_of_grammar_hostname_keeps_the_slot_held(
780 lock_file: str, mocker: MockerFixture, raw: str, mode: Literal["read", "write"]
781 ) -> None:
782 # A kernel hostname outside the marker grammar used to reach the marker verbatim, so a holder published a marker
783 # its own heartbeat read as malformed. A write slot then never claimed at all, and a read slot aged out under its
784 # live reader and fell to the next contender.
785 mocker.patch("filelock._identity.socket.gethostname", return_value=raw)
786 holder = _make_lock(lock_file)
787 acquire = holder.acquire_write if mode == "write" else holder.acquire_read
788 acquire(timeout=2)
789 try:
790 contender = _make_lock(lock_file)
791 try:
792 # longer than the stale threshold, so only a heartbeat that reads its own marker keeps the slot
793 with pytest.raises(Timeout):
794 contender.acquire_write(timeout=1)
795 finally:
796 contender.close()
797 finally:
798 holder.release()
799 holder.close()
800
801
802 def test_fifo_write_marker_does_not_block(lock_file: str) -> None: # pragma: needs fifo
803 if sys.platform == "win32" or not CAPABILITIES["fifo"]: # pragma: win32 cover
804 pytest.skip("os.mkfifo is unavailable") # the platform arm also narrows so ty resolves os.mkfifo below
805 marker = f"{lock_file}.write"
806 os.mkfifo(marker)
807 past = time.time() - 1000
808 os.utime(marker, (past, past))
809 # Without O_NONBLOCK this open blocks forever; the lock instead reads the FIFO as a stale marker and evicts it.
810 lock = _make_lock(lock_file)
811 try:
812 with lock.write_lock(timeout=2):
813 pass
814 finally:
815 lock.close()
816
817
818 def test_fifo_write_marker_with_writer_is_evicted(lock_file: str) -> None: # pragma: needs fifo
819 if sys.platform == "win32" or not CAPABILITIES["fifo"]: # pragma: win32 cover
820 pytest.skip("os.mkfifo is unavailable") # the platform arm also narrows so ty resolves os.mkfifo below
821 marker = f"{lock_file}.write"
822 os.mkfifo(marker)
823 past = time.time() - 1000
824 os.utime(marker, (past, past))
825 # A writer attached to the FIFO makes the non-blocking read raise EAGAIN on all platforms, matching a
826 # writerless FIFO on FreeBSD (#587). The lock must evict the stale marker by mtime without reading it, so
827 # the acquire completes instead of timing out.
828 reader_fd = os.open(marker, os.O_RDONLY | os.O_NONBLOCK)
829 writer_fd = os.open(marker, os.O_WRONLY)
830 lock = _make_lock(lock_file)
831 try:
832 with lock.write_lock(timeout=2):
833 pass
834 finally:
835 lock.close()
836 os.close(writer_fd)
837 os.close(reader_fd)
838
839
840 @pytest.mark.skipif(not hasattr(os, "O_NOFOLLOW"), reason="O_NOFOLLOW required")
841 def test_symlinked_write_marker_is_refused(lock_file: str, tmp_path: Path) -> None: # pragma: needs o-nofollow
842 victim = tmp_path / "victim"
843 victim.write_text("do-not-touch")
844 Path(f"{lock_file}.write").symlink_to(victim)
845 lock = _make_lock(lock_file)
846 try:
847 with pytest.raises((OSError, Timeout)):
848 lock.acquire_write(timeout=0.5)
849 finally:
850 lock.close()
851 assert victim.read_text() == "do-not-touch"
852
853
854 @pytest.mark.skipif(
855 os.utime not in os.supports_follow_symlinks, reason="os.utime cannot refuse symlinks on this platform"
856 )
857 def test_touch_does_not_follow_symlink(lock_file: str, tmp_path: Path) -> None: # pragma: needs utime-nofollow
858 # The phase-2 writer-drain touch refreshes the .write marker by path (no held fd); if a peer swaps a
859 # symlink in, the touch must land on the link itself, not the file it points at.
860 victim = tmp_path / "victim"
861 victim.write_text("do-not-touch")
862 past = time.time() - 1000
863 os.utime(victim, (past, past))
864 marker = Path(f"{lock_file}.write")
865 marker.symlink_to(victim)
866
867 util_mod.touch(str(marker))
868
869 assert victim.stat().st_mtime == pytest.approx(past) # a timestamp round-trip need not be bit-exact
870 assert victim.read_text() == "do-not-touch"
871
872
873 @pytest.mark.skipif(not util_mod._SUPPORTS_UTIME_FD, reason="os.utime cannot target an fd on this platform")
874 def test_refresh_touches_verified_fd_not_swapped_path( # pragma: needs utime-fd
875 lock_file: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
876 ) -> None:
877 # A peer can swap our marker for a symlink in the window after the heartbeat's O_NOFOLLOW open but before
878 # the touch; because the refresh touches the verified fd, the swapped symlink's target stays untouched.
879 victim = tmp_path / "victim"
880 victim.write_text("do-not-touch")
881 past = time.time() - 1000
882 os.utime(victim, (past, past))
883
884 lock = _make_lock(lock_file, heartbeat_interval=30, stale_threshold=90)
885 lock.acquire_write(timeout=2)
886 try:
887 marker = Path(f"{lock_file}.write")
888 real_open = sync_mod._open_marker
889
890 def swap_after_open(name: str, *, dir_fd: int | None = None) -> int | None:
891 fd = real_open(name, dir_fd=dir_fd)
892 if fd is not None and Path(name) == marker: # pragma: no branch # the refresh only opens the marker
893 marker.unlink()
894 marker.symlink_to(victim)
895 return fd
896
897 monkeypatch.setattr(sync_mod, "_open_marker", swap_after_open)
898 assert lock._refresh_marker() is True
899 assert victim.stat().st_mtime == pytest.approx(past) # a timestamp round-trip need not be bit-exact
900 assert victim.read_text() == "do-not-touch"
901 finally:
902 lock.release(force=True)
903 lock.close()
904
905
906 @pytest.mark.skipif(not CAPABILITIES["symlink"], reason="staging the readers directory as a symlink")
907 def test_symlinked_readers_directory_is_refused(lock_file: str, tmp_path: Path) -> None: # pragma: needs symlink
908 victim_dir = tmp_path / "victim_dir"
909 victim_dir.mkdir()
910 Path(f"{lock_file}.readers").symlink_to(victim_dir)
911 lock = _make_lock(lock_file)
912 try:
913 with pytest.raises(RuntimeError, match="not a directory or is a symlink"):
914 lock.acquire_read(timeout=0.5)
915 finally:
916 lock.close()
917 assert list(victim_dir.iterdir()) == []
918
919
920 def test_readers_path_as_regular_file_is_refused(lock_file: str) -> None:
921 Path(f"{lock_file}.readers").write_bytes(b"x")
922 lock = _make_lock(lock_file)
923 try:
924 with pytest.raises(RuntimeError, match="not a directory or is a symlink"):
925 lock.acquire_read(timeout=0.5)
926 finally:
927 lock.close()
928
929
930 @NEEDS_FILE_MODE
931 def test_write_marker_is_created_with_0600(lock_file: str) -> None: # pragma: needs file-mode
932 lock = _make_lock(lock_file)
933 try:
934 with lock.write_lock(timeout=2):
935 assert stat.S_IMODE(Path(f"{lock_file}.write").lstat().st_mode) == 0o600
936 finally:
937 lock.close()
938
939
940 @NEEDS_FILE_MODE
941 def test_readers_directory_is_created_with_0700(lock_file: str) -> None: # pragma: needs file-mode
942 lock = _make_lock(lock_file)
943 try:
944 with lock.read_lock(timeout=2):
945 assert stat.S_IMODE(Path(f"{lock_file}.readers").lstat().st_mode) == 0o700
946 finally:
947 lock.close()
948
949
950 def test_writer_ignores_housekeeping_files_in_readers_dir(lock_file: str) -> None:
951 # A writer's phase-2 drain scan must not mistake dotfiles or leftover .break.* files from aborted
952 # evictions for live readers.
953 readers = Path(f"{lock_file}.readers")
954 readers.mkdir(mode=0o700, exist_ok=True)
955 (readers / ".hidden").write_bytes(b"ignored")
956 (readers / "stale.break.12345.abcdef").write_bytes(b"also ignored")
957 lock = _make_lock(lock_file)
958 try:
959 with lock.write_lock(timeout=2):
960 pass
961 finally:
962 lock.close()
963
964
965 @NEEDS_FILE_MODE
966 def test_reader_file_is_created_with_0600(lock_file: str) -> None: # pragma: needs file-mode
967 lock = _make_lock(lock_file)
968 try:
969 with lock.read_lock(timeout=2):
970 entries = list(Path(f"{lock_file}.readers").iterdir())
971 assert len(entries) == 1
972 assert stat.S_IMODE(entries[0].lstat().st_mode) == 0o600
973 finally:
974 lock.close()
975
976
977 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
978 @NEEDS_FORK
979 @pytest.mark.timeout(_PROCESS_DEADLINE * 2)
980 def test_child_cannot_reuse_parents_lock_instance(tmp_path: Path) -> None: # pragma: needs fork
981 ctx = mp.get_context("spawn")
982 result, failure = ctx.Event(), ctx.Event()
983 proc = ctx.Process(target=_reuse_inherited_lock, args=(str(tmp_path / "foo.lock"), result, failure))
984 with cleanup_processes([proc]):
985 proc.start()
986 proc.join(timeout=_PROCESS_DEADLINE)
987 assert not failure.is_set()
988 assert result.is_set()
989
990
991 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
992 @NEEDS_FORK
993 @pytest.mark.timeout(_PROCESS_DEADLINE * 2)
994 def test_child_release_on_inherited_lock_is_silent(tmp_path: Path) -> None: # pragma: needs fork
995 ctx = mp.get_context("spawn")
996 result, failure = ctx.Event(), ctx.Event()
997 proc = ctx.Process(target=_release_inherited_lock, args=(str(tmp_path / "foo.lock"), result, failure))
998 with cleanup_processes([proc]):
999 proc.start()
1000 proc.join(timeout=_PROCESS_DEADLINE)
1001 assert not failure.is_set()
1002 assert result.is_set()
1003
1004
1005 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
1006 @NEEDS_FORK
1007 @pytest.mark.timeout(_PROCESS_DEADLINE * 2)
1008 def test_child_can_acquire_a_different_lock_after_fork(tmp_path: Path) -> None: # pragma: needs fork
1009 ctx = mp.get_context("spawn")
1010 result, failure = ctx.Event(), ctx.Event()
1011 proc = ctx.Process(
1012 target=_reacquire_fresh_lock_in_child,
1013 args=(str(tmp_path / "parent.lock"), str(tmp_path / "child.lock"), result, failure),
1014 )
1015 with cleanup_processes([proc]):
1016 proc.start()
1017 proc.join(timeout=_PROCESS_DEADLINE)
1018 assert not failure.is_set()
1019 assert result.is_set()
1020
1021
1022 @NEEDS_FORK
1023 @pytest.mark.timeout(_PROCESS_DEADLINE * 2)
1024 # Holding the write lock keeps the heartbeat thread alive, so this fork is necessarily from a multi-threaded
1025 # process and Python 3.15 warns that it may deadlock. That is the scenario under test, and it is already safe:
1026 # register_at_fork resets inherited state in the child (any child use raises "invalidated by fork()"). Expected.
1027 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
1028 @pytest.mark.filterwarnings("ignore:.*multi-threaded, use of fork.*:DeprecationWarning")
1029 def test_parent_retains_lock_across_fork(tmp_path: Path) -> None: # pragma: needs fork
1030 path = str(tmp_path / "foo.lock")
1031 lock = SoftReadWriteLock(path, heartbeat_interval=0.2, stale_threshold=1.0, poll_interval=0.02)
1032 lock.acquire_write(timeout=5)
1033 try:
1034 child = _fork_process(target=time.sleep, args=(0.05,))
1035 child.start()
1036 child.join(timeout=_PROCESS_DEADLINE)
1037 assert Path(f"{path}.write").exists()
1038 peer = SoftReadWriteLock(
1039 path,
1040 heartbeat_interval=0.2,
1041 stale_threshold=1.0,
1042 poll_interval=0.02,
1043 is_singleton=False,
1044 )
1045 try:
1046 with pytest.raises(Timeout):
1047 peer.acquire_write(timeout=0.3)
1048 finally:
1049 peer.close()
1050 finally:
1051 lock.release()
1052 lock.close()
1053 assert not Path(f"{path}.write").exists()
1054
1055
1056 def _make_lock(
1057 path: str,
1058 *,
1059 heartbeat_interval: float = 0.1,
1060 stale_threshold: float = 0.5,
1061 poll_interval: float = 0.02,
1062 is_singleton: bool = False,
1063 ) -> SoftReadWriteLock:
1064 return SoftReadWriteLock(
1065 path,
1066 heartbeat_interval=heartbeat_interval,
1067 stale_threshold=stale_threshold,
1068 poll_interval=poll_interval,
1069 is_singleton=is_singleton,
1070 )
1071
1072
1073 def _worker(
1074 lock_file: str,
1075 mode: Literal["read", "write"],
1076 acquired_event: EventType,
1077 release_event: EventType | None = None,
1078 timeout: float = -1,
1079 blocking: bool = True,
1080 heartbeat_interval: float = 0.1,
1081 stale_threshold: float = 1.0,
1082 poll_interval: float = 0.02,
1083 ) -> None:
1084 lock = SoftReadWriteLock(
1085 lock_file,
1086 timeout=timeout,
1087 blocking=blocking,
1088 is_singleton=False,
1089 heartbeat_interval=heartbeat_interval,
1090 stale_threshold=stale_threshold,
1091 poll_interval=poll_interval,
1092 )
1093 try:
1094 with lock.read_lock() if mode == "read" else lock.write_lock():
1095 acquired_event.set()
1096 if release_event is not None:
1097 release_event.wait(timeout=_PROCESS_DEADLINE)
1098 else:
1099 time.sleep(0.2)
1100 finally:
1101 lock.close()
1102
1103
1104 def _sigkill_worker( # pragma: forked child
1105 lock_file: str,
1106 mode: Literal["read", "write"],
1107 acquired_event: EventType,
1108 heartbeat_interval: float,
1109 stale_threshold: float,
1110 ) -> None:
1111 lock = SoftReadWriteLock(
1112 lock_file,
1113 is_singleton=False,
1114 heartbeat_interval=heartbeat_interval,
1115 stale_threshold=stale_threshold,
1116 poll_interval=0.05,
1117 )
1118 if mode == "read":
1119 lock.acquire_read()
1120 else:
1121 lock.acquire_write()
1122 acquired_event.set()
1123 time.sleep(60)
1124
1125
1126 def _write_stale_marker(path: str, content: bytes) -> None:
1127 Path(path).write_bytes(content)
1128 past = time.time() - 1000
1129 os.utime(path, (past, past))
1130
1131
1132 def _reuse_inherited_lock(lock_file: str, result: EventType, failure: EventType) -> None: # pragma: needs fork
1133 lock = SoftReadWriteLock(lock_file, heartbeat_interval=0.2, stale_threshold=1.0, poll_interval=0.02)
1134 lock.acquire_write(timeout=5)
1135 ok = _fork_event()
1136
1137 def child_entry() -> None:
1138 try:
1139 lock.acquire_read(timeout=1)
1140 except RuntimeError as exc:
1141 if "invalidated by fork" in str(exc): # pragma: no branch # the inherited lock raises nothing else
1142 ok.set()
1143
1144 child = _fork_process(target=child_entry)
1145 child.start()
1146 child.join(timeout=_PROCESS_DEADLINE)
1147 if ok.is_set():
1148 result.set()
1149 else: # pragma: no cover # reached only if the child fails to report the inherited lock, i.e. a regression
1150 failure.set()
1151 lock.release()
1152 lock.close()
1153
1154
1155 def _release_inherited_lock(lock_file: str, result: EventType, failure: EventType) -> None: # pragma: needs fork
1156 lock = SoftReadWriteLock(lock_file, heartbeat_interval=0.2, stale_threshold=1.0, poll_interval=0.02)
1157 lock.acquire_read(timeout=5)
1158 ok = _fork_event()
1159
1160 def child_entry() -> None:
1161 try:
1162 lock.release()
1163 except RuntimeError: # pragma: no cover # release on a fork-inherited lock is silent; guards a regression
1164 return
1165 ok.set()
1166
1167 child = _fork_process(target=child_entry)
1168 child.start()
1169 child.join(timeout=_PROCESS_DEADLINE)
1170 if ok.is_set():
1171 result.set()
1172 else: # pragma: no cover # reached only if the child's silent release regresses into raising
1173 failure.set()
1174 lock.release()
1175 lock.close()
1176
1177
1178 def _reacquire_fresh_lock_in_child( # pragma: needs fork
1179 lock_file: str, child_path: str, result: EventType, failure: EventType
1180 ) -> None:
1181 parent_lock = SoftReadWriteLock(lock_file, heartbeat_interval=0.2, stale_threshold=1.0, poll_interval=0.02)
1182 parent_lock.acquire_write(timeout=5)
1183 ok = _fork_event()
1184
1185 def child_entry() -> None:
1186 child_lock = SoftReadWriteLock(
1187 child_path,
1188 is_singleton=False,
1189 heartbeat_interval=0.2,
1190 stale_threshold=1.0,
1191 poll_interval=0.02,
1192 )
1193 try:
1194 with child_lock.read_lock(timeout=2):
1195 ok.set()
1196 finally:
1197 child_lock.close()
1198
1199 child = _fork_process(target=child_entry)
1200 child.start()
1201 child.join(timeout=_PROCESS_DEADLINE)
1202 if ok.is_set():
1203 result.set()
1204 else: # pragma: no cover # reached only if the child cannot acquire a fresh lock after the fork, i.e. a regression
1205 failure.set()
1206 parent_lock.release()
1207 parent_lock.close()
1208
1209
1210 def _fork_process( # pragma: needs fork
1211 target: Callable[..., object], args: tuple[object, ...] = ()
1212 ) -> mp.process.BaseProcess:
1213 if sys.platform == "win32": # pragma: win32 cover
1214 msg = "fork context is POSIX only"
1215 raise RuntimeError(msg)
1216 return mp.get_context("fork").Process(target=target, args=args)
1217
1218
1219 def _fork_event() -> EventType: # pragma: needs fork
1220 if sys.platform == "win32": # pragma: win32 cover
1221 msg = "fork context is POSIX only"
1222 raise RuntimeError(msg)
1223 return mp.get_context("fork").Event()
1224
1225
1226 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
1227 def test_cleanup_terminates_a_still_running_process() -> None:
1228 proc = Process(target=time.sleep, args=(30,))
1229 proc.start()
1230 started = time.monotonic()
1231
1232 with cleanup_processes([proc]):
1233 assert proc.is_alive()
1234
1235 # A helper that only joined would sit here for the child's whole sleep instead of signaling it first.
1236 assert time.monotonic() - started < 10
1237
1238
1239 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
1240 def test_cleanup_closes_the_process() -> None:
1241 proc = Process(target=time.sleep, args=(30,))
1242 proc.start()
1243
1244 with cleanup_processes([proc]):
1245 assert proc.is_alive()
1246
1247 with pytest.raises(ValueError, match="process object is closed"):
1248 proc.is_alive()
1249
1250
1251 def test_write_marker_zero_write_rolls_back(lock_file: str, mocker: MockerFixture) -> None:
1252 mocker.patch("filelock._util.os.write", return_value=0)
1253
1254 lock = SoftReadWriteLock(lock_file, is_singleton=False)
1255 with pytest.raises(OSError, match="0 bytes"):
1256 lock.acquire_write(timeout=1)
1257 assert not Path(f"{lock_file}.write").exists()
1258
1259
1260 def test_touch_writer_marker_returns_false_when_marker_missing(lock_file: str) -> None:
1261 lock = SoftReadWriteLock(lock_file, is_singleton=False)
1262 assert lock._touch_writer_marker_if_ours("0" * 32) is False
1263
1264
1265 def test_claim_writer_marker_returns_false_on_create_race(lock_file: str, mocker: MockerFixture) -> None:
1266 lock = SoftReadWriteLock(lock_file, is_singleton=False)
1267 mocker.patch.object(sync_mod, "_atomic_create_marker", side_effect=FileExistsError)
1268 with lock._locks.state:
1269 assert lock._claim_writer_marker("0" * 32) is False
1270
1271
1272 def test_atomic_create_marker_rolls_back_on_write_failure(tmp_path: Path, mocker: MockerFixture) -> None:
1273 marker = str(tmp_path / "marker")
1274 mocker.patch.object(sync_mod, "write_all", side_effect=OSError("write boom"))
1275 with pytest.raises(OSError, match="write boom"):
1276 sync_mod._atomic_create_marker(marker, "0" * 32)
1277 assert not Path(marker).exists()
1278
1279
1280 def test_same_file_true_for_matching_identity(tmp_path: Path) -> None:
1281 target = tmp_path / "present"
1282 target.write_bytes(b"x")
1283 st = os.lstat(target)
1284 assert sync_mod._same_file(str(target), (st.st_dev, st.st_ino), dir_fd=None) is True
1285
1286
1287 def test_same_file_false_when_stat_fails(tmp_path: Path) -> None:
1288 assert sync_mod._same_file(str(tmp_path / "absent"), (1, 2), dir_fd=None) is False
1289
1290
1291 def test_refresh_marker_stops_once_a_peer_owns_the_marker(lock_file: str) -> None:
1292 # A peer that evicted our marker and wrote its own owns the file now; refreshing it would keep a stranger's
1293 # marker alive, so the heartbeat has to stop instead.
1294 lock = _make_lock(lock_file)
1295 try:
1296 lock.acquire_write(timeout=2)
1297 foreign = f"{'0' * 32}\n{os.getpid()}\n{socket.gethostname()}\n".encode("ascii")
1298 Path(f"{lock_file}.write").write_bytes(foreign)
1299
1300 assert lock._refresh_marker() is False
1301 finally:
1302 lock.close()