Debian Codegraph @

tests/test_read_write.py

raw
1 from __future__ import annotations
2
3 import sys
4 import time
5 from multiprocessing import Event, Process, Value, set_start_method
6 from typing import TYPE_CHECKING, Final, Literal, cast
7
8 import pytest
9
10 pytest.importorskip("sqlite3")
11
12 import sqlite3
13
14 from filelock import ReadWriteLock, Timeout
15 from tests.capability_marks import SKIP_ON_UNRELIABLE_PROCESS_SYNC
16 from tests.process_helpers import cleanup_processes
17 from tests.read_write_helpers import assert_read_write_lock_state
18
19 # Bounds how long a spawned process may take to reach the lock, not how fast it must be: an interpreter that starts
20 # slowly under a loaded suite is not a locking failure. Only a genuine hang waits this out. Each test's own timeout
21 # has to outlast the waits it makes, so those are multiples of this rather than bare seconds.
22 _PROCESS_DEADLINE: Final[int] = 30
23 # Reaping a process that has already been signaled is not a startup wait, and it has to stay under the suite's own
24 # per-test timeout so the guard still reports the hang it was put there for.
25 _REAP_DEADLINE: Final[int] = 5
26
27 pytestmark = SKIP_ON_UNRELIABLE_PROCESS_SYNC
28
29 if sys.implementation.name == "pypy":
30 set_start_method(
31 "spawn", force=True
32 ) # pragma: no cover # exercised only under the pypy fork backend, which runs without coverage
33
34 if TYPE_CHECKING:
35 from multiprocessing.sharedctypes import Synchronized
36 from multiprocessing.synchronize import Event as EventType
37 from pathlib import Path
38
39 from pytest_mock import MockerFixture
40
41
42 @pytest.mark.timeout(_PROCESS_DEADLINE * 5)
43 def test_read_locks_are_shared(lock_file: str) -> None:
44 read1_acquired = Event()
45 read2_acquired = Event()
46
47 reader1 = Process(target=acquire_lock, args=(lock_file, "read", read1_acquired))
48 reader2 = Process(target=acquire_lock, args=(lock_file, "read", read2_acquired))
49
50 with cleanup_processes([reader1, reader2]):
51 reader1.start()
52 time.sleep(0.5) # let reader1 acquire before reader2 starts
53 reader2.start()
54
55 assert read1_acquired.wait(timeout=_PROCESS_DEADLINE), f"First read lock not acquired on {lock_file}"
56 assert read2_acquired.wait(timeout=_PROCESS_DEADLINE), f"Second read lock not acquired on {lock_file}"
57
58 reader1.join(timeout=_PROCESS_DEADLINE)
59 reader2.join(timeout=_PROCESS_DEADLINE)
60 assert not reader1.is_alive(), "Reader 1 did not exit cleanly"
61 assert not reader2.is_alive(), "Reader 2 did not exit cleanly"
62
63
64 @pytest.mark.timeout(_PROCESS_DEADLINE * 5)
65 def test_write_lock_excludes_other_write_locks(lock_file: str) -> None:
66 write1_acquired = Event()
67 release_write1 = Event()
68 write2_acquired = Event()
69
70 holder = Process(target=acquire_lock, args=(lock_file, "write", write1_acquired, release_write1))
71 contender = Process(target=acquire_lock, args=(lock_file, "write", write2_acquired, None, 0.5, True))
72
73 with cleanup_processes([holder]):
74 holder.start()
75 assert write1_acquired.wait(timeout=_PROCESS_DEADLINE), "First write lock not acquired"
76
77 with cleanup_processes([contender]):
78 contender.start()
79 assert not write2_acquired.wait(timeout=1), "Second write lock should not be acquired"
80
81 release_write1.set()
82 holder.join(timeout=_PROCESS_DEADLINE)
83 assert not holder.is_alive(), "Holder did not exit cleanly"
84
85 write2_acquired.clear()
86 successor = Process(target=acquire_lock, args=(lock_file, "write", write2_acquired))
87
88 with cleanup_processes([successor]):
89 successor.start()
90 assert write2_acquired.wait(timeout=_PROCESS_DEADLINE), (
91 "Second write lock not acquired after first released"
92 )
93 successor.join(timeout=_PROCESS_DEADLINE)
94 assert not successor.is_alive(), "Successor did not exit cleanly"
95
96
97 @pytest.mark.parametrize(
98 ("holder_mode", "contender_mode"),
99 [
100 pytest.param("write", "read", id="write-blocks-read"),
101 pytest.param("read", "write", id="read-blocks-write"),
102 ],
103 )
104 @pytest.mark.timeout(_PROCESS_DEADLINE * 5)
105 def test_lock_excludes_opposite_mode(
106 lock_file: str,
107 holder_mode: Literal["read", "write"],
108 contender_mode: Literal["read", "write"],
109 ) -> None:
110 holder_acquired = Event()
111 release_holder = Event()
112 contender_acquired = Event()
113 contender_started = Event()
114
115 holder = Process(target=acquire_lock, args=(lock_file, holder_mode, holder_acquired, release_holder))
116 contender = Process(
117 target=acquire_lock,
118 args=(lock_file, contender_mode, contender_acquired, None, -1, True, contender_started),
119 )
120
121 with cleanup_processes([holder, contender]):
122 holder.start()
123 assert holder_acquired.wait(timeout=_PROCESS_DEADLINE), f"{holder_mode} lock not acquired"
124
125 contender.start()
126 contender_started.set()
127
128 time.sleep(2) # confirm the contender stays blocked
129 assert not contender_acquired.is_set(), f"{contender_mode} lock should not be acquired while {holder_mode} held"
130
131 release_holder.set()
132 holder.join(timeout=_PROCESS_DEADLINE)
133
134 assert contender_acquired.wait(timeout=_PROCESS_DEADLINE), (
135 f"{contender_mode} lock not acquired after {holder_mode} released"
136 )
137
138 contender.join(timeout=_PROCESS_DEADLINE)
139 assert not contender.is_alive(), "Contender did not exit cleanly"
140
141
142 @pytest.mark.timeout(_PROCESS_DEADLINE * 8)
143 def test_write_non_starvation(lock_file: str) -> None:
144 """A writer that joins after the first reader must acquire before the reader chain drains.
145
146 Seven readers overlap in a chain and the writer contends mid-chain. It should win the lock while readers still
147 hold it, so it is not starved.
148 """
149 NUM_READERS: Final[int] = 7
150
151 chain_forward = [Event() for _ in range(NUM_READERS)]
152 chain_backward = [Event() for _ in range(NUM_READERS)]
153 writer_ready = Event()
154 writer_contending = Event()
155 writer_acquired = Event()
156
157 release_count = Value("i", 0)
158
159 readers = []
160 for idx in range(NUM_READERS):
161 next_reader = chain_forward[idx + 1] if idx < NUM_READERS - 1 else None
162 prev_or_writer = chain_backward[idx - 1] if idx > 0 else writer_ready
163 reader = Process(
164 target=chain_reader,
165 args=(idx, lock_file, release_count, chain_forward[idx], chain_backward[idx], next_reader, prev_or_writer),
166 )
167 readers.append(reader)
168
169 # The last reader holds until its own wait expires, since the test only releases the chain once the writer is in,
170 # so the writer has to outwait that hold rather than time out first.
171 writer = Process(
172 target=acquire_lock,
173 args=(lock_file, "write", writer_acquired, None, _PROCESS_DEADLINE * 2, True, writer_ready, writer_contending),
174 )
175
176 with cleanup_processes([*readers, writer]):
177 for reader in readers:
178 reader.start()
179
180 chain_forward[0].set()
181
182 assert writer_ready.wait(timeout=_PROCESS_DEADLINE), "First reader did not acquire lock"
183
184 # Count only the releases the writer actually waited through; a slow interpreter start is not starvation.
185 # The contending event says the writer process booted, not that its write intent reached the database, and
186 # only the intent bars new readers. The probe observes that boundary: a non-blocking read acquire times out
187 # exactly once the intent is registered, so the count starts there. Probing before the writer exists pins
188 # the still-pending arc, which the loop alone cannot promise: on a fast host the first in-loop probe
189 # already times out.
190 prober = ReadWriteLock(lock_file, is_singleton=False)
191 probe_deadline = time.monotonic() + _PROCESS_DEADLINE
192 assert _write_intent_pending(prober, probe_deadline)
193
194 writer.start()
195
196 assert writer_contending.wait(timeout=_PROCESS_DEADLINE), "Writer process did not reach the lock"
197 # pragma-no-branch: the loop never exhausts in a passing run, since the helper's deadline fires first
198 for _ in range(_PROCESS_DEADLINE * 20): # pragma: no branch
199 if not _write_intent_pending(prober, probe_deadline): # pragma: no branch # exits at the writer's speed
200 break
201 prober.close()
202 with release_count.get_lock():
203 releases_before_contending = release_count.value
204
205 assert writer_acquired.wait(timeout=_PROCESS_DEADLINE * 2), "Writer couldn't acquire lock - possible starvation"
206
207 with release_count.get_lock():
208 read_releases = release_count.value - releases_before_contending
209
210 assert read_releases < 3, f"Writer acquired after {read_releases} readers released - this indicates starvation"
211
212 writer.join(timeout=_PROCESS_DEADLINE)
213 assert not writer.is_alive(), "Writer did not exit cleanly"
214
215 for event in chain_backward:
216 event.set()
217
218 for idx, reader in enumerate(readers):
219 reader.join(timeout=_PROCESS_DEADLINE)
220 assert not reader.is_alive(), f"Reader {idx} did not exit cleanly"
221
222
223 @pytest.mark.parametrize(
224 "hold_mode",
225 [pytest.param("read", id="upgrade"), pytest.param("write", id="downgrade")],
226 )
227 @pytest.mark.timeout(_PROCESS_DEADLINE * 3)
228 def test_lock_mode_transition_prohibited(lock_file: str, hold_mode: Literal["read", "write"]) -> None:
229 result = Value("i", -1)
230
231 worker = Process(target=try_illegal_transition, args=(lock_file, hold_mode, result))
232
233 with cleanup_processes([worker]):
234 worker.start()
235 worker.join(timeout=_PROCESS_DEADLINE)
236 assert not worker.is_alive(), "Process did not exit cleanly"
237
238 assert result.value == 0, f"Illegal {hold_mode} transition was permitted"
239
240
241 @pytest.mark.timeout(_PROCESS_DEADLINE * 3)
242 def test_timeout_behavior(lock_file: str) -> None:
243 write_acquired = Event()
244 release_write = Event()
245 read_acquired = Event()
246
247 writer = Process(target=acquire_lock, args=(lock_file, "write", write_acquired, release_write))
248 reader = Process(target=acquire_lock, args=(lock_file, "read", read_acquired, None, 0.5, True))
249
250 with cleanup_processes([writer, reader]):
251 writer.start()
252 assert write_acquired.wait(timeout=_PROCESS_DEADLINE), "Write lock not acquired"
253
254 start_time = time.time()
255 reader.start()
256
257 assert not read_acquired.wait(timeout=1), "Read lock should not be acquired"
258 reader.join(timeout=_PROCESS_DEADLINE)
259
260 elapsed = time.time() - start_time
261 assert 0.4 <= elapsed <= 10.0, f"Timeout was not respected: {elapsed}s"
262
263 release_write.set()
264 writer.join(timeout=_PROCESS_DEADLINE)
265
266
267 @pytest.mark.timeout(_PROCESS_DEADLINE * 3)
268 def test_non_blocking_behavior(lock_file: str) -> None:
269 write_acquired = Event()
270 release_write = Event()
271
272 writer = Process(target=acquire_lock, args=(lock_file, "write", write_acquired, release_write))
273
274 with cleanup_processes([writer]):
275 writer.start()
276 assert write_acquired.wait(timeout=_PROCESS_DEADLINE), "Write lock not acquired"
277
278 start_time = time.time()
279
280 with pytest.raises(Timeout):
281 ReadWriteLock(lock_file).acquire_read(blocking=False)
282
283 elapsed = time.time() - start_time
284
285 assert elapsed < 0.1, f"Non-blocking took too long: {elapsed}s"
286
287 release_write.set()
288 writer.join(timeout=_PROCESS_DEADLINE)
289
290
291 @pytest.mark.parametrize(
292 "mode",
293 [pytest.param("read", id="read"), pytest.param("write", id="write")],
294 )
295 @pytest.mark.timeout(_PROCESS_DEADLINE * 3)
296 def test_recursive_lock_acquisition(lock_file: str, mode: Literal["read", "write"]) -> None:
297 success = Value("i", 0)
298 worker = Process(target=recursive_lock, args=(lock_file, mode, success))
299
300 with cleanup_processes([worker]):
301 worker.start()
302 worker.join(timeout=_PROCESS_DEADLINE)
303
304 assert success.value == 1, "Recursive lock acquisition failed"
305
306
307 @pytest.mark.parametrize(
308 "mode",
309 [pytest.param("read", id="read"), pytest.param("write", id="write")],
310 )
311 @pytest.mark.timeout(_PROCESS_DEADLINE * 4)
312 def test_lock_release_on_process_termination(lock_file: str, mode: Literal["read", "write"]) -> None:
313 lock_acquired = Event()
314
315 crashing = Process(target=acquire_lock_and_crash, args=(lock_file, mode, lock_acquired))
316 crashing.start()
317
318 assert lock_acquired.wait(timeout=_PROCESS_DEADLINE), "Lock not acquired by first process"
319
320 write_acquired = Event()
321 successor = Process(target=acquire_lock, args=(lock_file, "write", write_acquired))
322
323 with cleanup_processes([crashing, successor]):
324 time.sleep(0.5) # let the lock settle before killing the holder
325 crashing.terminate()
326 crashing.join(timeout=_REAP_DEADLINE)
327
328 successor.start()
329
330 assert write_acquired.wait(timeout=_PROCESS_DEADLINE), "Lock not acquired after process termination"
331
332 successor.join(timeout=_PROCESS_DEADLINE)
333 assert not successor.is_alive(), "Successor did not exit cleanly"
334
335
336 @pytest.mark.parametrize(
337 "mode",
338 [pytest.param("read", id="read"), pytest.param("write", id="write")],
339 )
340 @pytest.mark.timeout(15)
341 def test_single_lock_reentrant(lock_file: str, mode: Literal["read", "write"]) -> None:
342 lock = ReadWriteLock(lock_file)
343 acquire = lock.read_lock if mode == "read" else lock.write_lock
344
345 with acquire(), acquire():
346 pass
347
348 with acquire():
349 pass
350
351
352 @pytest.mark.parametrize(
353 ("first", "second"),
354 [
355 pytest.param("read", "write", id="read-then-write"),
356 pytest.param("write", "read", id="write-then-read"),
357 ],
358 )
359 @pytest.mark.timeout(15)
360 def test_sequential_lock_modes(
361 lock_file: str,
362 first: Literal["read", "write"],
363 second: Literal["read", "write"],
364 ) -> None:
365 lock = ReadWriteLock(lock_file)
366 for mode in (first, second):
367 acquire = lock.read_lock if mode == "read" else lock.write_lock
368 with acquire():
369 pass
370
371
372 @pytest.mark.parametrize(
373 "path_change",
374 [pytest.param("cwd", id="relative-cwd"), pytest.param("symlink", id="retargeted-symlink")],
375 )
376 def test_read_write_lock_keeps_constructed_database(
377 tmp_path: Path, monkeypatch: pytest.MonkeyPatch, path_change: Literal["cwd", "symlink"]
378 ) -> None:
379 first_directory = tmp_path / "first"
380 second_directory = tmp_path / "second"
381 first_directory.mkdir()
382 second_directory.mkdir()
383 first_database = first_directory / "lock.db"
384 second_database = second_directory / "lock.db"
385 if path_change == "cwd":
386 monkeypatch.chdir(first_directory)
387 lock = ReadWriteLock("lock.db", is_singleton=False)
388 monkeypatch.chdir(second_directory)
389 else:
390 lock_path = tmp_path / "lock.db"
391 try:
392 lock_path.symlink_to(first_database)
393 except OSError as error: # pragma: no cover - platform policy can deny symlink creation
394 pytest.skip(str(error))
395 lock = ReadWriteLock(lock_path, is_singleton=False)
396 lock_path.unlink()
397 lock_path.symlink_to(second_database)
398
399 with lock.read_lock():
400 assert_read_write_lock_state(str(first_database), "write", available=False)
401 assert_read_write_lock_state(str(second_database), "write", available=True)
402 lock.close()
403
404
405 @pytest.mark.parametrize(
406 ("held_mode", "probe_mode"),
407 [
408 pytest.param("read", "write", id="read"),
409 pytest.param("write", "read", id="write"),
410 ],
411 )
412 @pytest.mark.parametrize(
413 ("after_rollback", "available_after_failure"),
414 [
415 pytest.param(False, False, id="transaction-open"),
416 pytest.param(True, True, id="transaction-ended"),
417 ],
418 )
419 def test_release_rollback_failure_reconciles_lock_state(
420 lock_file: str,
421 mocker: MockerFixture,
422 held_mode: Literal["read", "write"],
423 probe_mode: Literal["read", "write"],
424 *,
425 after_rollback: bool,
426 available_after_failure: bool,
427 ) -> None:
428 rollback_error = _patch_rollback_failure(mocker, after_rollback=after_rollback)
429 lock = ReadWriteLock(lock_file, is_singleton=False)
430 (lock.acquire_read if held_mode == "read" else lock.acquire_write)()
431
432 with pytest.raises(sqlite3.OperationalError, match="rollback failed") as info:
433 lock.release()
434 assert info.value is rollback_error
435 assert_read_write_lock_state(lock_file, probe_mode, available=available_after_failure)
436
437 if available_after_failure:
438 with pytest.raises(RuntimeError, match="not held"):
439 lock.release()
440 else:
441 lock.release()
442 assert_read_write_lock_state(lock_file, probe_mode, available=True)
443 lock.close()
444
445
446 def _patch_rollback_failure(mocker: MockerFixture, *, after_rollback: bool) -> sqlite3.OperationalError:
447 real_connect = sqlite3.connect
448 rollback_error = sqlite3.OperationalError("rollback failed")
449 connection_count = 0
450
451 def connect(
452 database: str,
453 *,
454 factory: type[sqlite3.Connection],
455 timeout: float,
456 ) -> sqlite3.Connection:
457 nonlocal connection_count
458 connection_count += 1
459 real_connection = real_connect(
460 database,
461 check_same_thread=False,
462 factory=factory,
463 cached_statements=0,
464 timeout=timeout,
465 )
466 if connection_count != 2:
467 return real_connection
468
469 rollback_failed = False
470
471 def rollback() -> None:
472 nonlocal rollback_failed
473 if not rollback_failed:
474 rollback_failed = True
475 if after_rollback:
476 real_connection.rollback()
477 raise rollback_error
478 real_connection.rollback()
479
480 connection = mocker.MagicMock(
481 spec_set=type(real_connection),
482 wraps=real_connection,
483 **{"rollback.side_effect": rollback},
484 )
485 mocker.patch.object(
486 type(connection),
487 "in_transaction",
488 new_callable=mocker.PropertyMock,
489 create=True,
490 side_effect=lambda: real_connection.in_transaction,
491 )
492 return cast("sqlite3.Connection", connection)
493
494 mocker.patch("filelock._read_write._connect", side_effect=connect)
495 return rollback_error
496
497
498 @pytest.fixture
499 def lock_file(tmp_path: Path) -> str:
500 return str(tmp_path / "test_lock.db")
501
502
503 @pytest.mark.parametrize("mode", [pytest.param("read", id="read"), pytest.param("write", id="write")])
504 def test_acquire_proxy_releases_the_read_write_lock_on_exit(lock_file: str, mode: Literal["read", "write"]) -> None:
505 # acquire_read/acquire_write hand back the shared AcquireReturnProxy; a read/write lock is not a BaseFileLock, so
506 # exiting the proxy must route through the lock's own release() rather than a context-error policy.
507 lock = ReadWriteLock(lock_file, is_singleton=False)
508 acquire = lock.acquire_read if mode == "read" else lock.acquire_write
509
510 with acquire():
511 assert_read_write_lock_state(lock_file, "write", available=False)
512
513 assert_read_write_lock_state(lock_file, "write", available=True)
514
515
516 def acquire_lock(
517 lock_file: str,
518 mode: Literal["read", "write"],
519 acquired_event: EventType,
520 release_event: EventType | None = None,
521 timeout: float = -1,
522 blocking: bool = True,
523 ready_event: EventType | None = None,
524 contending_event: EventType | None = None,
525 ) -> None:
526 if ready_event:
527 ready_event.wait(timeout=_PROCESS_DEADLINE)
528
529 lock = ReadWriteLock(lock_file, timeout=timeout, blocking=blocking)
530 if contending_event:
531 contending_event.set() # interpreter start-up is over, so a caller can time the contention itself
532 with lock.read_lock() if mode == "read" else lock.write_lock():
533 acquired_event.set()
534 if release_event:
535 release_event.wait(timeout=_PROCESS_DEADLINE)
536 else:
537 time.sleep(0.5) # hold briefly to simulate work
538
539
540 def test_cleanup_reports_the_failure_that_escaped_before_a_start() -> None:
541 unstarted = Process(target=time.sleep, args=(0,))
542
543 def fail_before_start() -> None:
544 with cleanup_processes([unstarted]):
545 msg = "the real failure"
546 raise AssertionError(msg)
547
548 with pytest.raises(AssertionError, match="the real failure"):
549 fail_before_start()
550
551
552 def _write_intent_pending(prober: ReadWriteLock, deadline: float) -> bool:
553 try:
554 prober.acquire_read(blocking=False)
555 except Timeout:
556 return False
557 prober.release()
558 assert time.monotonic() < deadline, "Writer never registered its write intent"
559 time.sleep(0.05)
560 return True
561
562
563 def chain_reader(
564 reader_index: int,
565 lock_file: str,
566 release_count: Synchronized[int],
567 start_signal: EventType,
568 release_signal: EventType,
569 next_reader_signal: EventType | None,
570 writer_or_prev_signal: EventType,
571 ) -> None:
572 start_signal.wait(timeout=_PROCESS_DEADLINE)
573
574 lock = ReadWriteLock(lock_file)
575 with lock.read_lock():
576 if reader_index > 0:
577 time.sleep(2) # overlap with earlier readers so the writer contends mid-chain
578
579 if next_reader_signal is not None:
580 next_reader_signal.set()
581
582 if reader_index == 0:
583 time.sleep(1) # hold briefly before releasing the writer
584
585 writer_or_prev_signal.set()
586
587 release_signal.wait(timeout=_PROCESS_DEADLINE)
588
589 with release_count.get_lock():
590 release_count.value += 1
591
592
593 def try_illegal_transition(lock_file: str, hold_mode: Literal["read", "write"], result: Synchronized[int]) -> None:
594 lock = ReadWriteLock(lock_file)
595 with lock.read_lock() if hold_mode == "read" else lock.write_lock():
596 try:
597 if hold_mode == "read":
598 lock.acquire_write()
599 else:
600 lock.acquire_read()
601 except RuntimeError:
602 result.value = 0
603
604
605 def recursive_lock(lock_file: str, mode: Literal["read", "write"], success_flag: Synchronized[int]) -> None:
606 lock = ReadWriteLock(lock_file)
607 acquire = lock.read_lock if mode == "read" else lock.write_lock
608 with acquire():
609 assert lock._lock_level == 1
610 assert lock._current_mode == mode
611
612 with acquire():
613 assert lock._lock_level == 2
614 assert lock._current_mode == mode
615
616 with acquire():
617 assert lock._lock_level == 3
618 assert lock._current_mode == mode
619
620 assert lock._lock_level == 2
621 assert lock._current_mode == mode
622
623 assert lock._lock_level == 1
624 assert lock._current_mode == mode
625
626 assert lock._lock_level == 0
627 assert lock._current_mode is None
628
629 success_flag.value = 1
630
631
632 def acquire_lock_and_crash(lock_file: str, mode: Literal["read", "write"], acquired_event: EventType) -> None:
633 lock = ReadWriteLock(lock_file) # pragma: win32 no cover
634 with lock.read_lock() if mode == "read" else lock.write_lock(): # pragma: win32 no cover
635 acquired_event.set()
636 while True: # pragma: win32 no cover
637 time.sleep(0.1)