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