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 stat
7 import sys
8 import threading
9 import time
10 from contextlib import closing, suppress
11 from errno import EIO
12 from multiprocessing import Event, Process
13 from pathlib import Path
14 from typing import TYPE_CHECKING, Final, Literal
15
16 import pytest
17 from capabilities import CAPABILITIES
18
19 from filelock import AsyncSoftReadWriteLock, SoftFileLockProtocolError, Timeout
20 from filelock._lease import LeaseCompromise
21 from filelock._soft_rw import SoftReadWriteLock
22 from filelock._soft_rw import _storage as storage_mod
23 from filelock._soft_rw import _sync as sync_mod
24 from filelock._soft_rw._protocol import GenerationLog, Snapshot, encode_holder, new_token
25 from filelock._soft_rw._storage import OsFiles
26 from tests.capability_marks import NEEDS_FILE_MODE, NEEDS_FORK, NEEDS_POSIX_SIGNALS, SKIP_ON_UNRELIABLE_PROCESS_SYNC
27 from tests.process_helpers import cleanup_processes
28
29 if TYPE_CHECKING:
30 from collections.abc import Callable, Generator
31 from multiprocessing.synchronize import Event as EventType
32
33 from pytest_mock import MockerFixture
34
35 pytestmark = pytest.mark.requires_hard_links
36
37
38 # Bounds how long a spawned process or thread may take to reach the lock, not how fast it must be: an interpreter
39 # that starts slowly under a loaded suite is not a locking failure. The short negative waits below are deliberate,
40 # since those assert a contender stays blocked and have to stay brief.
41 _PROCESS_DEADLINE: Final[int] = 30
42
43
44 @pytest.fixture(autouse=True)
45 def _clear_singletons() -> Generator[None]:
46 SoftReadWriteLock._instances.clear()
47 yield
48 for lock in filter(None, (ref() for ref in list(SoftReadWriteLock._instances.valuerefs()))):
49 lock.close()
50 SoftReadWriteLock._instances.clear()
51
52
53 @pytest.fixture
54 def lock_file(tmp_path: Path) -> str:
55 return str(tmp_path / "test.lock")
56
57
58 @pytest.fixture
59 def lock(lock_file: str) -> Generator[SoftReadWriteLock]:
60 instance = _make_lock(lock_file)
61 try:
62 yield instance
63 finally:
64 instance.close()
65
66
67 def _state(lock_file: str) -> Snapshot:
68 return GenerationLog(OsFiles(lock_file), lock_file, f"{lock_file}.rw").latest()
69
70
71 def _holders(lock_file: str) -> list[str]:
72 holders = Path(f"{lock_file}.rw", "holders")
73 return sorted(entry.name for entry in holders.iterdir()) if holders.is_dir() else []
74
75
76 def _generations(lock_file: str) -> list[str]:
77 return sorted(entry.name for entry in Path(f"{lock_file}.rw", "gen").iterdir() if not entry.name.startswith("."))
78
79
80 def _plant_holder(lock_file: str, *, mode: Literal["read", "write"], host: str = "terminated-pod") -> str:
81 # What a process on another host leaves behind when it dies holding the lock: its record and the snapshot naming it.
82 files = OsFiles(lock_file)
83 root = f"{lock_file}.rw"
84 files.prepare(root)
85 token = new_token()
86 record = encode_holder(token, new_token()).replace(b"host=", f"host={host}?".encode("ascii"), 1)
87 files.create(str(Path(root, "holders", token)), record)
88 log = GenerationLog(files, lock_file, root)
89 latest = log.latest()
90 writer, readers = (token, latest.readers) if mode == "write" else (latest.writer, latest.readers | {token})
91 assert log.commit(Snapshot(generation=latest.generation + 1, writer=writer, readers=readers))
92 return token
93
94
95 @pytest.mark.parametrize(
96 "lock_type",
97 [pytest.param(SoftReadWriteLock, id="sync"), pytest.param(AsyncSoftReadWriteLock, id="async")],
98 )
99 @pytest.mark.parametrize("cached", [pytest.param(False, id="new"), pytest.param(True, id="cached")])
100 @pytest.mark.parametrize(
101 ("settings", "message"),
102 [
103 pytest.param({name: value}, name, id=f"{name}-{label}")
104 for name in ("heartbeat_interval", "stale_threshold", "poll_interval")
105 for label, value in (("nan", float("nan")), ("infinity", float("inf")), ("negative-infinity", float("-inf")))
106 ]
107 + [
108 pytest.param({"heartbeat_interval": sys.float_info.max}, "stale_threshold", id="default-overflow"),
109 ],
110 )
111 def test_rejects_invalid_intervals(
112 tmp_path: Path,
113 lock_type: type[SoftReadWriteLock | AsyncSoftReadWriteLock],
114 cached: bool,
115 settings: dict[str, float],
116 message: str,
117 ) -> None:
118 path: Final = tmp_path / "timing.lock"
119 # Keep the weakly cached instance alive through the second construction.
120 existing: Final = SoftReadWriteLock(path) if cached else None
121 try:
122 with pytest.raises(ValueError, match=rf"{message} must .*finite"):
123 lock_type(
124 path,
125 heartbeat_interval=settings.get("heartbeat_interval", 30),
126 stale_threshold=settings.get("stale_threshold"),
127 poll_interval=settings.get("poll_interval", 0.25),
128 )
129 finally:
130 if existing is not None:
131 existing.close()
132
133
134 @pytest.mark.parametrize(
135 ("heartbeat_interval", "stale_threshold", "poll_interval", "match"),
136 [
137 pytest.param(0, None, 0.25, "heartbeat_interval must be positive", id="heartbeat-non-positive"),
138 pytest.param(10, 5, 0.25, "stale_threshold must exceed", id="stale-not-greater"),
139 pytest.param(30, None, 0, "poll_interval must be positive", id="poll-non-positive"),
140 pytest.param(1, 3, 3, "poll_interval must be below", id="poll-not-below-stale"),
141 ],
142 )
143 def test_rejects_invalid_interval_relationship(
144 lock_file: str, heartbeat_interval: float, stale_threshold: float | None, poll_interval: float, match: str
145 ) -> None:
146 with pytest.raises(ValueError, match=match):
147 SoftReadWriteLock(
148 lock_file,
149 is_singleton=False,
150 heartbeat_interval=heartbeat_interval,
151 stale_threshold=stale_threshold,
152 poll_interval=poll_interval,
153 )
154
155
156 def test_public_attributes(lock_file: str) -> None:
157 lock = SoftReadWriteLock(
158 lock_file,
159 timeout=5,
160 blocking=False,
161 heartbeat_interval=10,
162 stale_threshold=45,
163 poll_interval=0.5,
164 is_singleton=False,
165 )
166 try:
167 assert lock.lock_file == lock_file
168 assert lock.timeout == 5
169 assert lock.blocking is False
170 assert lock.heartbeat_interval == 10
171 assert lock.stale_threshold == 45
172 assert lock.poll_interval == pytest.approx(0.5)
173 finally:
174 lock.close()
175
176
177 def test_default_stale_threshold_is_triple_heartbeat(lock_file: str) -> None:
178 lock = SoftReadWriteLock(lock_file, heartbeat_interval=12, is_singleton=False)
179 try:
180 assert lock.stale_threshold == 36
181 finally:
182 lock.close()
183
184
185 def test_singleton_returns_same_instance(lock_file: str) -> None:
186 first = SoftReadWriteLock(lock_file)
187 second = SoftReadWriteLock(lock_file)
188 try:
189 assert first is second
190 finally:
191 first.close()
192
193
194 def test_non_singleton_returns_distinct_instances(lock_file: str) -> None:
195 first = SoftReadWriteLock(lock_file, is_singleton=False)
196 second = SoftReadWriteLock(lock_file, is_singleton=False)
197 try:
198 assert first is not second
199 finally:
200 first.close()
201 second.close()
202
203
204 def test_singleton_mismatch_raises(lock_file: str) -> None:
205 first = SoftReadWriteLock(lock_file, timeout=5)
206 try:
207 with pytest.raises(ValueError, match="cannot be changed"):
208 SoftReadWriteLock(lock_file, timeout=10)
209 finally:
210 first.close()
211
212
213 def test_get_lock_returns_singleton(lock_file: str) -> None:
214 first = SoftReadWriteLock.get_lock(lock_file)
215 second = SoftReadWriteLock.get_lock(lock_file)
216 try:
217 assert first is second
218 finally:
219 first.close()
220
221
222 def test_leaked_acquired_singleton_is_closed_on_teardown(lock_file: str) -> None:
223 # A live heartbeat thread keeps the singleton reachable, so the autouse teardown finds and closes it.
224 lock = SoftReadWriteLock(lock_file, heartbeat_interval=0.5)
225 lock.acquire_write(timeout=2)
226 assert _state(lock_file).writer is not None
227
228
229 def test_reentrant_read_holds_and_releases(lock: SoftReadWriteLock) -> None:
230 with lock.read_lock(timeout=2), lock.read_lock(timeout=2):
231 pass
232 with lock.read_lock(timeout=2):
233 pass
234
235
236 def test_reentrant_write_holds_and_releases(lock_file: str, lock: SoftReadWriteLock) -> None:
237 with lock.write_lock(timeout=2), lock.write_lock(timeout=2):
238 assert _state(lock_file).writer is not None
239 assert _state(lock_file).writer is None
240
241
242 @pytest.mark.parametrize(
243 ("first_mode", "second_mode", "direction"),
244 [
245 pytest.param("read", "write", "upgrade", id="upgrade"),
246 pytest.param("write", "read", "downgrade", id="downgrade"),
247 ],
248 )
249 def test_change_of_mode_while_held_raises(
250 lock: SoftReadWriteLock, first_mode: Literal["read", "write"], second_mode: Literal["read", "write"], direction: str
251 ) -> None:
252 first_lock = lock.read_lock if first_mode == "read" else lock.write_lock
253 second_acquire = lock.acquire_read if second_mode == "read" else lock.acquire_write
254 with first_lock(timeout=2), pytest.raises(RuntimeError, match=f"{direction} not allowed"):
255 second_acquire(timeout=1)
256
257
258 def test_write_lock_is_thread_pinned(lock: SoftReadWriteLock) -> None:
259 errors: list[BaseException] = []
260 lock.acquire_write(timeout=2)
261
262 def other() -> None:
263 try:
264 lock.acquire_write(timeout=1, blocking=False)
265 except BaseException as exc:
266 errors.append(exc)
267
268 thread = threading.Thread(target=other)
269 thread.start()
270 thread.join()
271 lock.release()
272 assert len(errors) == 1
273 assert isinstance(errors[0], (RuntimeError, Timeout))
274
275
276 def test_blocking_acquire_without_timeout_waits_for_release(lock_file: str) -> None:
277 # Without a deadline the poll loop sleeps a full interval each round rather than clamping to a budget.
278 holder = _make_lock(lock_file)
279 holder.acquire_write(timeout=2)
280 acquired = threading.Event()
281
282 def waiter() -> None:
283 contender = _make_lock(lock_file)
284 try:
285 contender.acquire_read(timeout=-1)
286 acquired.set()
287 contender.release()
288 finally:
289 contender.close()
290
291 thread = threading.Thread(target=waiter)
292 thread.start()
293 try:
294 assert not acquired.wait(timeout=0.2)
295 holder.release()
296 assert acquired.wait(timeout=_PROCESS_DEADLINE)
297 finally:
298 thread.join(timeout=_PROCESS_DEADLINE)
299 holder.close()
300
301
302 def test_release_without_hold_raises(lock_file: str) -> None:
303 lock = SoftReadWriteLock(lock_file)
304 try:
305 with pytest.raises(RuntimeError, match="not held"):
306 lock.release()
307 finally:
308 lock.close()
309
310
311 def test_release_force_without_hold_is_noop(lock_file: str) -> None:
312 lock = SoftReadWriteLock(lock_file)
313 try:
314 lock.release(force=True)
315 finally:
316 lock.close()
317
318
319 def test_release_force_on_reentrant_lock_drops_all(lock: SoftReadWriteLock) -> None:
320 lock.acquire_read(timeout=2)
321 lock.acquire_read(timeout=2)
322 lock.release(force=True)
323 with lock.write_lock(timeout=2):
324 pass
325
326
327 def test_close_is_idempotent(lock_file: str) -> None:
328 lock = SoftReadWriteLock(lock_file)
329 lock.close()
330 lock.close()
331
332
333 def test_acquire_on_closed_raises(lock_file: str) -> None:
334 lock = SoftReadWriteLock(lock_file)
335 lock.close()
336 with pytest.raises(RuntimeError, match="has been closed"):
337 lock.acquire_read(timeout=1)
338 with pytest.raises(RuntimeError, match="has been closed"):
339 lock.acquire_write(timeout=1)
340
341
342 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
343 @pytest.mark.timeout(_PROCESS_DEADLINE * 5)
344 def test_multiple_readers_can_hold_simultaneously(lock_file: str) -> None:
345 r1, r2, release = Event(), Event(), Event()
346 p1 = Process(target=_worker, args=(lock_file, "read", r1, release))
347 p2 = Process(target=_worker, args=(lock_file, "read", r2, release))
348 with cleanup_processes([p1, p2]):
349 p1.start()
350 p2.start()
351 assert r1.wait(timeout=_PROCESS_DEADLINE)
352 assert r2.wait(timeout=_PROCESS_DEADLINE)
353 release.set()
354 p1.join(timeout=_PROCESS_DEADLINE)
355 p2.join(timeout=_PROCESS_DEADLINE)
356
357
358 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
359 @pytest.mark.timeout(_PROCESS_DEADLINE * 4)
360 @pytest.mark.parametrize("contender_mode", [pytest.param("write", id="writer"), pytest.param("read", id="reader")])
361 def test_write_lock_excludes_contender(lock_file: str, contender_mode: Literal["read", "write"]) -> None:
362 held, release = Event(), Event()
363 contender_acquired = Event()
364 writer = Process(target=_worker, args=(lock_file, "write", held, release))
365 contender = Process(target=_worker, args=(lock_file, contender_mode, contender_acquired, None, 0.3, True))
366 with cleanup_processes([writer, contender]):
367 writer.start()
368 assert held.wait(timeout=_PROCESS_DEADLINE)
369 contender.start()
370 assert not contender_acquired.wait(timeout=0.5)
371 release.set()
372 writer.join(timeout=_PROCESS_DEADLINE)
373 contender.join(timeout=_PROCESS_DEADLINE)
374
375
376 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
377 @pytest.mark.timeout(_PROCESS_DEADLINE * 5)
378 def test_writer_drains_existing_readers(lock_file: str) -> None:
379 r_held, r_release = Event(), Event()
380 w_held = Event()
381 reader = Process(target=_worker, args=(lock_file, "read", r_held, r_release))
382 writer = Process(target=_worker, args=(lock_file, "write", w_held))
383 with cleanup_processes([reader, writer]):
384 reader.start()
385 assert r_held.wait(timeout=_PROCESS_DEADLINE)
386 writer.start()
387 assert not w_held.wait(timeout=0.5)
388 r_release.set()
389 reader.join(timeout=_PROCESS_DEADLINE)
390 assert w_held.wait(timeout=_PROCESS_DEADLINE)
391 writer.join(timeout=_PROCESS_DEADLINE)
392
393
394 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
395 @pytest.mark.timeout(_PROCESS_DEADLINE * 7)
396 def test_writer_preference_blocks_new_readers(lock_file: str) -> None:
397 r1_held, r1_release = Event(), Event()
398 w_held, w_release = Event(), Event()
399 r2_held = Event()
400 reader1 = Process(target=_worker, args=(lock_file, "read", r1_held, r1_release))
401 writer = Process(target=_worker, args=(lock_file, "write", w_held, w_release))
402 reader2 = Process(target=_worker, args=(lock_file, "read", r2_held, None, 10, True))
403 with cleanup_processes([reader1, writer, reader2]):
404 reader1.start()
405 assert r1_held.wait(timeout=_PROCESS_DEADLINE)
406 writer.start()
407 # Start reader2 only once the writer is named in the latest snapshot: a fixed sleep undershoots on a Windows
408 # runner still spawning the writer's interpreter, and reader2 then slips in ahead of the writer's intent.
409 deadline = time.monotonic() + _PROCESS_DEADLINE
410 while _state(lock_file).writer is None:
411 assert time.monotonic() < deadline
412 time.sleep(0.01)
413 reader2.start()
414 assert not r2_held.wait(timeout=0.5)
415 r1_release.set()
416 assert w_held.wait(timeout=_PROCESS_DEADLINE)
417 assert not r2_held.wait(timeout=0.3)
418 w_release.set()
419 assert r2_held.wait(timeout=_PROCESS_DEADLINE)
420 reader1.join(timeout=_PROCESS_DEADLINE)
421 writer.join(timeout=_PROCESS_DEADLINE)
422 reader2.join(timeout=_PROCESS_DEADLINE)
423
424
425 @pytest.mark.timeout(_PROCESS_DEADLINE * 4)
426 def test_transaction_lock_timeout_across_threads(lock_file: str) -> None:
427 # Two threads share one lock instance. Thread A holds the transaction lock while spinning on a peer
428 # writer; thread B times out on the transaction lock, exercising the in-process Timeout path rather
429 # than cross-process contention.
430 # Staleness is not under test: a peer heartbeat that stalls past a short threshold on a loaded runner would let
431 # thread A evict the peer and take the lock, turning thread B's Timeout into a same-instance ownership error.
432 peer = SoftReadWriteLock(
433 lock_file,
434 is_singleton=False,
435 heartbeat_interval=0.1,
436 stale_threshold=_PROCESS_DEADLINE,
437 poll_interval=0.02,
438 )
439 peer.acquire_write(timeout=2)
440 try:
441 lock = SoftReadWriteLock(
442 lock_file,
443 is_singleton=False,
444 heartbeat_interval=0.1,
445 stale_threshold=_PROCESS_DEADLINE,
446 poll_interval=0.02,
447 )
448 try:
449 thread_ready = threading.Event()
450 release_thread = threading.Event()
451
452 def target_a() -> None:
453 thread_ready.set()
454 with suppress(Timeout):
455 lock.acquire_write(timeout=2)
456 release_thread.wait(timeout=_PROCESS_DEADLINE)
457
458 thread_a = threading.Thread(target=target_a)
459 thread_a.start()
460 try:
461 thread_ready.wait(timeout=_PROCESS_DEADLINE)
462 time.sleep(0.05)
463 with pytest.raises(Timeout):
464 lock.acquire_write(timeout=0.1)
465 finally:
466 release_thread.set()
467 thread_a.join(timeout=_PROCESS_DEADLINE)
468 finally:
469 lock.close()
470 finally:
471 peer.release()
472 peer.close()
473
474
475 @pytest.mark.timeout(_PROCESS_DEADLINE * 3)
476 def test_two_readers_in_same_process_share_slot(lock_file: str) -> None:
477 # Many threads take a read lock on one instance; one hits the inner reentrant branch (lock level
478 # above 0 after waiting on the transaction lock).
479 lock = SoftReadWriteLock(
480 lock_file,
481 is_singleton=False,
482 heartbeat_interval=0.1,
483 stale_threshold=0.5,
484 poll_interval=0.02,
485 )
486 try:
487 barrier = threading.Barrier(8)
488
489 def target() -> None:
490 barrier.wait(timeout=_PROCESS_DEADLINE)
491 with lock.read_lock(timeout=5):
492 time.sleep(0.05)
493
494 threads = [threading.Thread(target=target) for _ in range(8)]
495 for thread in threads:
496 thread.start()
497 for thread in threads:
498 thread.join(timeout=_PROCESS_DEADLINE)
499 finally:
500 lock.close()
501
502
503 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
504 @pytest.mark.timeout(_PROCESS_DEADLINE * 3)
505 def test_timeout_raises(lock_file: str, lock: SoftReadWriteLock) -> None:
506 held, release = Event(), Event()
507 holder = Process(target=_worker, args=(lock_file, "write", held, release))
508 with cleanup_processes([holder]):
509 holder.start()
510 assert held.wait(timeout=_PROCESS_DEADLINE)
511 with pytest.raises(Timeout):
512 lock.acquire_write(timeout=0.3)
513 release.set()
514 holder.join(timeout=_PROCESS_DEADLINE)
515
516
517 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
518 @pytest.mark.timeout(_PROCESS_DEADLINE * 3)
519 def test_non_blocking_writer_contended_raises(lock_file: str, lock: SoftReadWriteLock) -> None:
520 held, release = Event(), Event()
521 holder = Process(target=_worker, args=(lock_file, "write", held, release))
522 with cleanup_processes([holder]):
523 holder.start()
524 assert held.wait(timeout=_PROCESS_DEADLINE)
525 with pytest.raises(Timeout):
526 lock.acquire_write(timeout=1, blocking=False)
527 with pytest.raises(Timeout):
528 lock.acquire_read(timeout=1, blocking=False)
529 release.set()
530 holder.join(timeout=_PROCESS_DEADLINE)
531
532
533 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
534 @NEEDS_POSIX_SIGNALS
535 @pytest.mark.timeout(_PROCESS_DEADLINE * 3)
536 @pytest.mark.parametrize(
537 ("dead_mode", "contender_mode"),
538 [pytest.param("write", "read", id="dead-writer"), pytest.param("read", "write", id="dead-reader")],
539 )
540 def test_dead_holder_evicted_by_contender(
541 lock_file: str,
542 lock: SoftReadWriteLock,
543 dead_mode: Literal["read", "write"],
544 contender_mode: Literal["read", "write"],
545 ) -> None: # pragma: needs posix-signals
546 held = Event()
547 holder = Process(target=_sigkill_worker, args=(lock_file, dead_mode, held, 0.1, 0.5))
548 with cleanup_processes([holder]):
549 holder.start()
550 assert held.wait(timeout=_PROCESS_DEADLINE)
551 pid = holder.pid
552 assert pid is not None
553 os.kill(pid, getattr(signal, "SIGKILL")) # ruff:ignore[get-attr-with-constant] - signal.SIGKILL is POSIX-only
554 holder.join(timeout=_PROCESS_DEADLINE)
555 time.sleep(0.8)
556 contender = lock.read_lock if contender_mode == "read" else lock.write_lock
557 with contender(timeout=5):
558 pass
559 if contender_mode == "read":
560 # A write lock's success already proves no live reader or writer remained; a read lock's does not.
561 assert _state(lock_file).writer is None
562
563
564 def test_heartbeat_reports_eviction_and_stops(lock_file: str) -> None:
565 # A peer that waited out the stale threshold commits a snapshot without this holder. The next heartbeat sees the
566 # snapshot no longer naming it, records the loss, and stops refreshing a claim that no longer exists.
567 seen: list[LeaseCompromise] = []
568 lock = _make_lock(lock_file, heartbeat_interval=0.05, stale_threshold=0.2, on_compromise=seen.append)
569 lock.acquire_write(timeout=2)
570 try:
571 hold = lock._hold
572 assert hold is not None
573 log = GenerationLog(OsFiles(lock_file), lock_file, f"{lock_file}.rw")
574 latest = log.latest()
575 assert log.commit(Snapshot(generation=latest.generation + 1, writer=None, readers=frozenset()))
576 assert hold.heartbeat_stop.wait(timeout=_PROCESS_DEADLINE)
577 assert lock.compromise == LeaseCompromise(lock_file=lock_file, token=hold.participant.token, reason="evicted")
578 assert seen == [lock.compromise]
579 finally:
580 lock.release(force=True)
581 lock.close()
582 peer = _make_lock(lock_file, heartbeat_interval=0.05, stale_threshold=0.2)
583 try:
584 with peer.write_lock(timeout=1):
585 pass
586 finally:
587 peer.close()
588
589
590 def test_heartbeat_reports_a_removed_holder_record(lock_file: str) -> None:
591 lock = _make_lock(lock_file, heartbeat_interval=0.05, stale_threshold=0.2)
592 lock.acquire_read(timeout=2)
593 try:
594 hold = lock._hold
595 assert hold is not None
596 Path(f"{lock_file}.rw", "holders", hold.participant.token).unlink()
597 assert hold.heartbeat_stop.wait(timeout=_PROCESS_DEADLINE)
598 assert lock.compromise is not None
599 assert lock.compromise.reason == "evicted"
600 finally:
601 lock.release(force=True)
602 lock.close()
603
604
605 def test_release_leaves_a_peers_claim_alone(lock_file: str) -> None:
606 # A holder paused past the stale threshold (GC pause, SIGSTOP, suspended VM) can be evicted, after which a peer
607 # holds the writer slot. Releasing commits this holder out and leaves the peer's claim alone.
608 lock = _make_lock(lock_file, heartbeat_interval=10, stale_threshold=40)
609 lock.acquire_write(timeout=2)
610 try:
611 peer = _plant_holder(lock_file, mode="write")
612 lock.release()
613 assert _state(lock_file).writer == peer
614 assert _holders(lock_file) == [peer]
615 finally:
616 lock.close()
617
618
619 def test_writer_evicted_while_draining_queues_behind_its_evictor(
620 lock_file: str, monkeypatch: pytest.MonkeyPatch
621 ) -> None:
622 # A writer paused past stale_threshold while waiting for readers can be evicted; a peer then names itself writer.
623 # The resumed writer must not finish its acquire as if it still held the slot. Instead it queues again.
624 reader = _make_lock(lock_file, heartbeat_interval=10, stale_threshold=40)
625 reader.acquire_read(timeout=2)
626 writer = _make_lock(lock_file, heartbeat_interval=10, stale_threshold=40)
627 real_sleep = time.sleep
628 swapped = threading.Event()
629 peer: list[str] = []
630
631 def hook(seconds: float) -> None: # ruff:ignore[unused-function-argument] # replaces time.sleep; the duration is irrelevant to the swap
632 if swapped.is_set():
633 raise Timeout(lock_file)
634 swapped.set()
635 # The peer evicts the draining writer and takes the slot; the reader leaves so only the slot blocks the writer.
636 files = OsFiles(lock_file)
637 log = GenerationLog(files, lock_file, f"{lock_file}.rw")
638 latest = log.latest()
639 peer.append(_plant_holder(lock_file, mode="read"))
640 latest = log.latest()
641 assert log.commit(Snapshot(generation=latest.generation + 1, writer=peer[0], readers=frozenset()))
642 reader.release()
643
644 monkeypatch.setattr(sync_mod.time, "sleep", hook)
645 try:
646 with pytest.raises(Timeout):
647 writer.acquire_write(timeout=30)
648 assert swapped.is_set()
649 assert _state(lock_file).writer == peer[0]
650 finally:
651 monkeypatch.setattr(sync_mod.time, "sleep", real_sleep)
652 writer.close()
653 reader.close()
654
655
656 def test_heartbeat_survives_a_transient_refresh_error(lock_file: str, mocker: MockerFixture) -> None:
657 # On the NFS-style filesystems this lock targets, a transient ESTALE/EIO on the heartbeat is routine; it must not
658 # kill the heartbeat and drop the claim while we still believe we hold it.
659 lock = _make_lock(lock_file, heartbeat_interval=0.02, stale_threshold=0.5)
660 lock.acquire_write(timeout=2)
661 try:
662 hold = lock._hold
663 assert hold is not None
664 mocker.patch.object(storage_mod.OsFiles, "overwrite", side_effect=OSError(EIO, "Input/output error"))
665 time.sleep(0.2) # ~10 ticks, every one failing the refresh
666 assert hold.heartbeat_thread.is_alive()
667 assert not hold.heartbeat_stop.is_set()
668 assert lock.compromise is None
669 finally:
670 mocker.stopall()
671 lock.release(force=True)
672 lock.close()
673
674
675 def test_heartbeat_reports_refresh_failures_that_outlast_the_margin(lock_file: str, mocker: MockerFixture) -> None:
676 # Failures that run long enough for a peer to evict the record before the next success could land are a loss the
677 # holder must hear about, a margin before the record ages out.
678 seen: list[LeaseCompromise] = []
679 lock = _make_lock(lock_file, heartbeat_interval=0.02, stale_threshold=0.1, on_compromise=seen.append)
680 lock.acquire_write(timeout=2)
681 try:
682 hold = lock._hold
683 assert hold is not None
684 mocker.patch.object(storage_mod.OsFiles, "overwrite", side_effect=OSError(EIO, "Input/output error"))
685 assert hold.heartbeat_stop.wait(timeout=_PROCESS_DEADLINE)
686 assert [compromise.reason for compromise in seen] == ["refresh-failed"]
687 finally:
688 mocker.stopall()
689 lock.release(force=True)
690 lock.close()
691
692
693 @pytest.mark.parametrize("mode", [pytest.param("write", id="write"), pytest.param("read", id="read")])
694 def test_acquire_hands_back_the_slot_when_the_heartbeat_cannot_start(
695 lock_file: str, lock: SoftReadWriteLock, mocker: MockerFixture, mode: Literal["read", "write"]
696 ) -> None:
697 # A heartbeat thread the OS refuses (an rlimit reached) must not leave a hold behind: a peer would evict the
698 # unrefreshed record and acquire while this instance still believed it held the lock, and release() would raise
699 # joining a thread that never started.
700 mocker.patch.object(sync_mod._HeartbeatThread, "start", side_effect=RuntimeError("can't start new thread"))
701 acquire = lock.acquire_write if mode == "write" else lock.acquire_read
702 with pytest.raises(RuntimeError, match="can't start new thread"):
703 acquire(timeout=2)
704
705 assert lock._hold is None
706 assert _state(lock_file).members == frozenset()
707 assert _holders(lock_file) == []
708 lock.release(force=True) # a handed-back slot leaves nothing to release, so this must not raise
709
710
711 def test_short_attempts_still_evict_a_dead_holder(lock_file: str) -> None:
712 # How long a peer's record has stayed unchanged is knowledge the lock keeps across attempts: a caller whose every
713 # attempt is shorter than the stale threshold (a retry loop, blocking=False) must still get past a crashed holder.
714 _plant_holder(lock_file, mode="write")
715 lock = _make_lock(lock_file, heartbeat_interval=0.1, stale_threshold=0.3)
716 try:
717
718 def attempt() -> bool:
719 try:
720 lock.acquire_read(blocking=False)
721 except Timeout:
722 return False
723 return True
724
725 deadline = time.monotonic() + 5
726 while not attempt():
727 assert time.monotonic() < deadline
728 time.sleep(0.02)
729 lock.release()
730 finally:
731 lock.close()
732
733
734 def test_singleton_rejects_a_different_on_compromise(lock_file: str) -> None:
735 seen: list[LeaseCompromise] = []
736 first = SoftReadWriteLock(lock_file, on_compromise=seen.append)
737 try:
738 assert SoftReadWriteLock(lock_file) is first
739 assert SoftReadWriteLock(lock_file, on_compromise=seen.append) is first
740 with pytest.raises(ValueError, match="different on_compromise"):
741 SoftReadWriteLock(lock_file, on_compromise=seen.remove)
742 finally:
743 first.close()
744
745
746 def test_release_from_on_compromise_leaves_cleanly(lock_file: str) -> None:
747 # The callback runs on the heartbeat thread; a release there has no thread to join and must still leave.
748 lock = SoftReadWriteLock(
749 lock_file,
750 is_singleton=False,
751 heartbeat_interval=0.05,
752 stale_threshold=0.2,
753 poll_interval=0.02,
754 on_compromise=lambda _compromise: lock.release(force=True),
755 )
756 lock.acquire_write(timeout=2)
757 hold = lock._hold
758 assert hold is not None
759 try:
760 log = GenerationLog(OsFiles(lock_file), lock_file, f"{lock_file}.rw")
761 latest = log.latest()
762 assert log.commit(Snapshot(generation=latest.generation + 1, writer=None, readers=frozenset()))
763 assert hold.heartbeat_stop.wait(timeout=_PROCESS_DEADLINE)
764 hold.heartbeat_thread.join(timeout=_PROCESS_DEADLINE)
765 assert lock._hold is None
766 assert _holders(lock_file) == []
767 finally:
768 lock.close()
769
770
771 def test_lock_file_in_a_missing_directory_is_created(tmp_path: Path) -> None:
772 lock = _make_lock(str(tmp_path / "nested" / "deeper" / "x.lock"))
773 try:
774 with lock.write_lock(timeout=1):
775 pass
776 finally:
777 lock.close()
778
779
780 def test_late_heartbeat_tick_does_not_stamp_a_later_hold(lock_file: str) -> None:
781 # A tick that outlived its release's join reports on the hold it served, not on a hold acquired since.
782 lock = _make_lock(lock_file, heartbeat_interval=10, stale_threshold=40)
783 lock.acquire_write(timeout=2)
784 old = lock._hold
785 assert old is not None
786 lock.release()
787 lock.acquire_write(timeout=2)
788 try:
789 lock._report_compromise(old, "evicted", None)
790 assert lock.compromise is None
791 finally:
792 lock.release()
793 lock.close()
794
795
796 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
797 @pytest.mark.timeout(_PROCESS_DEADLINE * 3)
798 def test_live_heartbeat_keeps_lock_alive_past_stale_threshold(lock_file: str) -> None:
799 # Generous timing here so the test stays stable on slow Windows runners where the holder's
800 # multiprocessing.spawn startup, the heartbeat thread scheduling, and the parent's clock resolution
801 # can all introduce sub-second jitter.
802 heartbeat, stale = 0.3, 1.5
803 held, release = Event(), Event()
804 holder = Process(
805 target=_worker,
806 args=(lock_file, "write", held, release, -1, True, heartbeat, stale, 0.05),
807 )
808 with cleanup_processes([holder]):
809 holder.start()
810 assert held.wait(timeout=_PROCESS_DEADLINE)
811 time.sleep(stale * 2)
812 lock = _make_lock(lock_file, heartbeat_interval=heartbeat, stale_threshold=stale)
813 try:
814 with pytest.raises(Timeout):
815 lock.acquire_write(timeout=stale * 2)
816 finally:
817 lock.close()
818 release.set()
819 holder.join(timeout=_PROCESS_DEADLINE)
820
821
822 def test_generation_is_a_fencing_token(lock_file: str) -> None:
823 first = _make_lock(lock_file)
824 second = _make_lock(lock_file)
825 try:
826 assert first.generation is None
827 with first.write_lock(timeout=2):
828 granted = first.generation
829 assert granted is not None
830 with second.write_lock(timeout=2):
831 later = second.generation
832 assert later is not None
833 assert later > granted
834 assert second.generation is None
835 finally:
836 first.close()
837 second.close()
838
839
840 def test_foreign_host_holder_is_evicted_after_the_stale_threshold(lock_file: str) -> None:
841 # The report behind #725: a pod dies on another host holding the lock, and a replacement pod under a different
842 # hostname must still get in. Liveness is a nonce that stopped changing, so the hostname plays no part in it.
843 _plant_holder(lock_file, mode="write")
844 lock = _make_lock(lock_file, heartbeat_interval=0.1, stale_threshold=0.3)
845 try:
846 started = time.monotonic()
847 with pytest.raises(Timeout):
848 lock.acquire_read(timeout=0.1)
849 # The first attempt already started watching the record, so the wait spans both attempts.
850 with lock.read_lock(timeout=5):
851 assert time.monotonic() - started >= 0.3 - 0.05
852 assert _holders(lock_file) == []
853 finally:
854 lock.close()
855
856
857 def test_release_never_blocks_on_an_abandoned_claim(lock_file: str) -> None:
858 # The other half of #725: a writer holding the lock could not let go while a foreign host's record sat in the way.
859 # Leaving is one commit of the holder's own token, so nothing a dead peer left can block it.
860 lock = _make_lock(lock_file, heartbeat_interval=10, stale_threshold=40)
861 lock.acquire_write(timeout=2)
862 _plant_holder(lock_file, mode="read")
863 started = time.monotonic()
864 lock.release()
865 assert time.monotonic() - started < 1
866 assert _state(lock_file).writer is None
867 lock.close()
868
869
870 def test_malformed_generation_record_fails_closed(lock_file: str, lock: SoftReadWriteLock) -> None:
871 with lock.write_lock(timeout=2):
872 pass
873 latest = _generations(lock_file)[-1]
874 Path(f"{lock_file}.rw", "gen", f"{int(latest) + 1:020d}").write_bytes(b"garbage\n")
875 with pytest.raises(SoftFileLockProtocolError, match="malformed generation record"):
876 lock.acquire_write(timeout=1)
877
878
879 def test_malformed_holder_record_is_evicted(lock_file: str) -> None:
880 # A record that cannot be parsed still identifies nobody who refreshes it, so it ages out like any other.
881 token = _plant_holder(lock_file, mode="write")
882 Path(f"{lock_file}.rw", "holders", token).write_bytes(b"\x00garbage")
883 lock = _make_lock(lock_file, heartbeat_interval=0.1, stale_threshold=0.3)
884 try:
885 with lock.write_lock(timeout=5):
886 pass
887 finally:
888 lock.close()
889
890
891 def test_temporary_commit_files_are_swept(lock_file: str) -> None:
892 orphan = Path(f"{lock_file}.rw", "gen", ".commit-abandoned")
893 lock = _make_lock(lock_file, heartbeat_interval=0.05, stale_threshold=0.2)
894 try:
895 with lock.write_lock(timeout=2):
896 pass
897 orphan.write_bytes(b"left by a crash between create and link")
898 with lock.write_lock(timeout=2):
899 time.sleep(0.6)
900 assert not orphan.exists()
901 finally:
902 lock.close()
903
904
905 def test_generations_are_compacted(lock_file: str, lock: SoftReadWriteLock) -> None:
906 for _ in range(80):
907 with lock.write_lock(timeout=2):
908 pass
909 assert len(_generations(lock_file)) <= 66
910
911
912 def test_a_participant_behind_a_compacted_generation_rescans(lock_file: str) -> None:
913 lock = _make_lock(lock_file)
914 peer = _make_lock(lock_file)
915 try:
916 with lock.write_lock(timeout=2):
917 pass
918 stale_log = GenerationLog(OsFiles(lock_file), lock_file, f"{lock_file}.rw")
919 remembered = stale_log.latest()
920 for _ in range(40):
921 with peer.write_lock(timeout=2):
922 pass
923 assert not Path(f"{lock_file}.rw", "gen", f"{remembered.generation:020d}").exists()
924 assert stale_log.latest().generation == _state(lock_file).generation
925 finally:
926 lock.close()
927 peer.close()
928
929
930 @pytest.mark.skipif(not CAPABILITIES["symlink"], reason="staging the protocol directory as a symlink")
931 def test_symlinked_protocol_directory_is_refused(
932 lock_file: str, tmp_path: Path, lock: SoftReadWriteLock
933 ) -> None: # pragma: needs symlink
934 victim_dir = tmp_path / "victim_dir"
935 victim_dir.mkdir()
936 Path(f"{lock_file}.rw").symlink_to(victim_dir)
937 with pytest.raises(RuntimeError, match="not a directory or is a symlink"):
938 lock.acquire_read(timeout=0.5)
939 assert list(victim_dir.iterdir()) == []
940
941
942 def test_protocol_path_as_regular_file_is_refused(lock_file: str, lock: SoftReadWriteLock) -> None:
943 Path(f"{lock_file}.rw").write_bytes(b"x")
944 with pytest.raises(RuntimeError, match="not a directory or is a symlink"):
945 lock.acquire_read(timeout=0.5)
946
947
948 @NEEDS_FILE_MODE
949 def test_records_are_owner_only(lock_file: str, lock: SoftReadWriteLock) -> None: # pragma: needs file-mode
950 with lock.write_lock(timeout=2):
951 root = Path(f"{lock_file}.rw")
952 for directory in (root, root / "gen", root / "holders"):
953 assert stat.S_IMODE(directory.lstat().st_mode) == 0o700
954 generation = root / "gen" / _generations(lock_file)[-1]
955 assert stat.S_IMODE(generation.lstat().st_mode) == 0o600
956 (holder,) = _holders(lock_file)
957 assert stat.S_IMODE((root / "holders" / holder).lstat().st_mode) == 0o600
958
959
960 def test_stray_files_in_the_protocol_directories_are_ignored(lock_file: str, lock: SoftReadWriteLock) -> None:
961 root = Path(f"{lock_file}.rw")
962 (root / "gen").mkdir(parents=True)
963 (root / "holders").mkdir()
964 (root / "gen" / ".hidden").write_bytes(b"ignored")
965 (root / "gen" / "not-a-generation").write_bytes(b"ignored")
966 (root / "holders" / "not-a-token").write_bytes(b"ignored")
967 with lock.write_lock(timeout=2):
968 pass
969
970
971 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
972 @NEEDS_FORK
973 @pytest.mark.timeout(_PROCESS_DEADLINE * 2)
974 @pytest.mark.parametrize(
975 ("scenario", "names"),
976 [
977 pytest.param("reuse-raises", ("foo.lock",), id="reuse-raises"),
978 pytest.param("release-is-silent", ("foo.lock",), id="release-is-silent"),
979 pytest.param("fresh-lock-after-fork", ("parent.lock", "child.lock"), id="fresh-lock-after-fork"),
980 ],
981 )
982 def test_child_fork_lock_behavior(tmp_path: Path, scenario: str, names: tuple[str, ...]) -> None: # pragma: needs fork
983 # Resolved by name, not passed as the parametrize value: the targets are defined later in this module, and a
984 # decorator evaluates its arguments at import time, before those definitions exist.
985 target = {
986 "reuse-raises": _reuse_inherited_lock,
987 "release-is-silent": _release_inherited_lock,
988 "fresh-lock-after-fork": _reacquire_fresh_lock_in_child,
989 }[scenario]
990 ctx = mp.get_context("spawn")
991 result, failure = ctx.Event(), ctx.Event()
992 proc = ctx.Process(target=target, args=(*(str(tmp_path / name) for name in names), result, failure))
993 with cleanup_processes([proc]):
994 proc.start()
995 proc.join(timeout=_PROCESS_DEADLINE)
996 assert not failure.is_set()
997 assert result.is_set()
998
999
1000 @NEEDS_FORK
1001 @pytest.mark.timeout(_PROCESS_DEADLINE * 2)
1002 # Holding the write lock keeps the heartbeat thread alive, so this fork is necessarily from a multi-threaded
1003 # process and Python 3.15 warns that it may deadlock. That is the scenario under test, and it is already safe:
1004 # register_at_fork resets inherited state in the child (any child use raises "invalidated by fork()"). Expected.
1005 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
1006 @pytest.mark.filterwarnings("ignore:.*multi-threaded, use of fork.*:DeprecationWarning")
1007 def test_parent_retains_lock_across_fork(tmp_path: Path) -> None: # pragma: needs fork
1008 path = str(tmp_path / "foo.lock")
1009 lock = SoftReadWriteLock(path, heartbeat_interval=0.2, stale_threshold=1.0, poll_interval=0.02)
1010 lock.acquire_write(timeout=5)
1011 try:
1012 child = _fork_process(target=time.sleep, args=(0.05,))
1013 child.start()
1014 child.join(timeout=_PROCESS_DEADLINE)
1015 assert _state(path).writer is not None
1016 peer = SoftReadWriteLock(
1017 path,
1018 heartbeat_interval=0.2,
1019 stale_threshold=1.0,
1020 poll_interval=0.02,
1021 is_singleton=False,
1022 )
1023 try:
1024 with pytest.raises(Timeout):
1025 peer.acquire_write(timeout=0.3)
1026 finally:
1027 peer.close()
1028 finally:
1029 lock.release()
1030 lock.close()
1031 assert _state(path).writer is None
1032
1033
1034 def _make_lock(
1035 path: str,
1036 *,
1037 heartbeat_interval: float = 0.1,
1038 stale_threshold: float = 0.5,
1039 poll_interval: float = 0.02,
1040 is_singleton: bool = False,
1041 on_compromise: Callable[[LeaseCompromise], None] | None = None,
1042 ) -> SoftReadWriteLock:
1043 return SoftReadWriteLock(
1044 path,
1045 heartbeat_interval=heartbeat_interval,
1046 stale_threshold=stale_threshold,
1047 poll_interval=poll_interval,
1048 is_singleton=is_singleton,
1049 on_compromise=on_compromise,
1050 )
1051
1052
1053 def _worker(
1054 lock_file: str,
1055 mode: Literal["read", "write"],
1056 acquired_event: EventType,
1057 release_event: EventType | None = None,
1058 timeout: float = -1,
1059 blocking: bool = True,
1060 heartbeat_interval: float = 0.1,
1061 stale_threshold: float = 1.0,
1062 poll_interval: float = 0.02,
1063 ) -> None:
1064 lock = SoftReadWriteLock(
1065 lock_file,
1066 timeout=timeout,
1067 blocking=blocking,
1068 is_singleton=False,
1069 heartbeat_interval=heartbeat_interval,
1070 stale_threshold=stale_threshold,
1071 poll_interval=poll_interval,
1072 )
1073 try:
1074 with lock.read_lock() if mode == "read" else lock.write_lock():
1075 acquired_event.set()
1076 if release_event is not None:
1077 release_event.wait(timeout=_PROCESS_DEADLINE)
1078 else:
1079 time.sleep(0.2)
1080 finally:
1081 lock.close()
1082
1083
1084 def _sigkill_worker( # pragma: forked child
1085 lock_file: str,
1086 mode: Literal["read", "write"],
1087 acquired_event: EventType,
1088 heartbeat_interval: float,
1089 stale_threshold: float,
1090 ) -> None:
1091 lock = SoftReadWriteLock(
1092 lock_file,
1093 is_singleton=False,
1094 heartbeat_interval=heartbeat_interval,
1095 stale_threshold=stale_threshold,
1096 poll_interval=0.05,
1097 )
1098 if mode == "read":
1099 lock.acquire_read()
1100 else:
1101 lock.acquire_write()
1102 acquired_event.set()
1103 time.sleep(60)
1104
1105
1106 def _reuse_inherited_lock(lock_file: str, result: EventType, failure: EventType) -> None: # pragma: needs fork
1107 lock = SoftReadWriteLock(lock_file, heartbeat_interval=0.2, stale_threshold=1.0, poll_interval=0.02)
1108 lock.acquire_write(timeout=5)
1109 ok = _fork_event()
1110
1111 def child_entry() -> None:
1112 try:
1113 lock.acquire_read(timeout=1)
1114 except RuntimeError as exc:
1115 if "invalidated by fork" in str(exc): # pragma: no branch # the inherited lock raises nothing else
1116 ok.set()
1117
1118 child = _fork_process(target=child_entry)
1119 child.start()
1120 child.join(timeout=_PROCESS_DEADLINE)
1121 if ok.is_set():
1122 result.set()
1123 else: # pragma: no cover # reached only if the child fails to report the inherited lock, i.e. a regression
1124 failure.set()
1125 lock.release()
1126 lock.close()
1127
1128
1129 def _release_inherited_lock(lock_file: str, result: EventType, failure: EventType) -> None: # pragma: needs fork
1130 lock = SoftReadWriteLock(lock_file, heartbeat_interval=0.2, stale_threshold=1.0, poll_interval=0.02)
1131 lock.acquire_read(timeout=5)
1132 ok = _fork_event()
1133
1134 def child_entry() -> None:
1135 try:
1136 lock.release()
1137 except RuntimeError: # pragma: no cover # release on a fork-inherited lock is silent; guards a regression
1138 return
1139 ok.set()
1140
1141 child = _fork_process(target=child_entry)
1142 child.start()
1143 child.join(timeout=_PROCESS_DEADLINE)
1144 if ok.is_set():
1145 result.set()
1146 else: # pragma: no cover # reached only if the child's silent release regresses into raising
1147 failure.set()
1148 lock.release()
1149 lock.close()
1150
1151
1152 def _reacquire_fresh_lock_in_child( # pragma: needs fork
1153 lock_file: str, child_path: str, result: EventType, failure: EventType
1154 ) -> None:
1155 parent_lock = SoftReadWriteLock(lock_file, heartbeat_interval=0.2, stale_threshold=1.0, poll_interval=0.02)
1156 parent_lock.acquire_write(timeout=5)
1157 ok = _fork_event()
1158
1159 def child_entry() -> None:
1160 child_lock = SoftReadWriteLock(
1161 child_path,
1162 is_singleton=False,
1163 heartbeat_interval=0.2,
1164 stale_threshold=1.0,
1165 poll_interval=0.02,
1166 )
1167 try:
1168 with child_lock.read_lock(timeout=2):
1169 ok.set()
1170 finally:
1171 child_lock.close()
1172
1173 child = _fork_process(target=child_entry)
1174 child.start()
1175 child.join(timeout=_PROCESS_DEADLINE)
1176 if ok.is_set():
1177 result.set()
1178 else: # pragma: no cover # reached only if the child cannot acquire a fresh lock after the fork, i.e. a regression
1179 failure.set()
1180 parent_lock.release()
1181 parent_lock.close()
1182
1183
1184 def _fork_process( # pragma: needs fork
1185 target: Callable[..., object], args: tuple[object, ...] = ()
1186 ) -> mp.process.BaseProcess:
1187 if sys.platform == "win32": # pragma: win32 cover
1188 msg = "fork context is POSIX only"
1189 raise RuntimeError(msg)
1190 return mp.get_context("fork").Process(target=target, args=args)
1191
1192
1193 def _fork_event() -> EventType: # pragma: needs fork
1194 if sys.platform == "win32": # pragma: win32 cover
1195 msg = "fork context is POSIX only"
1196 raise RuntimeError(msg)
1197 return mp.get_context("fork").Event()
1198
1199
1200 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
1201 def test_cleanup_terminates_a_still_running_process() -> None:
1202 proc = Process(target=time.sleep, args=(30,))
1203 proc.start()
1204 started = time.monotonic()
1205
1206 with cleanup_processes([proc]):
1207 assert proc.is_alive()
1208
1209 # A helper that only joined would sit here for the child's whole sleep instead of signaling it first.
1210 assert time.monotonic() - started < 10
1211
1212
1213 @SKIP_ON_UNRELIABLE_PROCESS_SYNC
1214 def test_cleanup_closes_the_process() -> None:
1215 proc = Process(target=time.sleep, args=(30,))
1216 proc.start()
1217
1218 with cleanup_processes([proc]):
1219 assert proc.is_alive()
1220
1221 with pytest.raises(ValueError, match="process object is closed"):
1222 proc.is_alive()
1223
1224
1225 def test_record_zero_write_rolls_back(lock_file: str, mocker: MockerFixture) -> None:
1226 mocker.patch("filelock._util.os.write", return_value=0)
1227
1228 lock = SoftReadWriteLock(lock_file, is_singleton=False)
1229 with pytest.raises(OSError, match="0 bytes"):
1230 lock.acquire_write(timeout=1)
1231 assert _holders(lock_file) == []
1232
1233
1234 @pytest.mark.parametrize("mode", [pytest.param("read", id="read"), pytest.param("write", id="write")])
1235 @pytest.mark.parametrize(
1236 ("timeout", "blocking"),
1237 [
1238 pytest.param(0.02, True, id="deadline"),
1239 pytest.param(0, True, id="zero-timeout"),
1240 pytest.param(-1, False, id="nonblocking-unbounded"),
1241 pytest.param(10, False, id="nonblocking-finite"),
1242 ],
1243 )
1244 def test_contention_obeys_acquisition_policy(
1245 lock_file: str, mocker: MockerFixture, mode: Literal["read", "write"], timeout: float, *, blocking: bool
1246 ) -> None:
1247 _plant_holder(lock_file, mode="write")
1248 real_sleep: Final = time.sleep
1249
1250 def sleep(seconds: float) -> None:
1251 assert blocking
1252 assert 0 < seconds <= timeout
1253 real_sleep(seconds)
1254
1255 mocker.patch("time.sleep", autospec=True, side_effect=sleep)
1256 with closing(SoftReadWriteLock(lock_file, timeout=timeout, blocking=blocking, poll_interval=10)) as lock:
1257 acquire: Final = lock.acquire_read if mode == "read" else lock.acquire_write
1258 with pytest.raises(Timeout) as caught:
1259 acquire()
1260 assert caught.value.lock_file == lock_file
1261 assert _state(lock_file).readers == frozenset()
1262
1263
1264 @pytest.mark.asyncio
1265 @pytest.mark.parametrize("mode", [pytest.param("read", id="read"), pytest.param("write", id="write")])
1266 async def test_async_contention_reports_public_path(lock_file: str, mode: Literal["read", "write"]) -> None:
1267 _plant_holder(lock_file, mode="write")
1268 lock: Final = AsyncSoftReadWriteLock(lock_file, timeout=0.02)
1269 try:
1270 acquire: Final = lock.acquire_read if mode == "read" else lock.acquire_write
1271 with pytest.raises(Timeout) as caught:
1272 await acquire()
1273 assert caught.value.lock_file == lock_file
1274 finally:
1275 await lock.close()
1276
1277
1278 def test_writer_timeout_commits_itself_out(lock_file: str) -> None:
1279 # A writer that gives up while draining must not stay named: it would block every reader until a peer waited out
1280 # the stale threshold. Its own token is all it removes, both from the snapshot and from the holder registry, so
1281 # the reader it waited on keeps its hold.
1282 reader = _make_lock(lock_file, heartbeat_interval=10, stale_threshold=40)
1283 writer = _make_lock(lock_file, heartbeat_interval=10, stale_threshold=40, poll_interval=0.01)
1284 try:
1285 reader.acquire_read()
1286 with pytest.raises(Timeout):
1287 writer.acquire_write(timeout=0.05)
1288 state = _state(lock_file)
1289 assert state.writer is None
1290 assert len(state.readers) == 1
1291 assert len(_holders(lock_file)) == 1
1292 finally:
1293 writer.close()
1294 reader.close()