Debian Codegraph @

tests/test_async_read_write_cancellation.py

raw
1 from __future__ import annotations
2
3 import asyncio
4 import functools
5 import multiprocessing
6 import sqlite3
7 import sys
8 import threading
9 from concurrent.futures import ThreadPoolExecutor
10 from typing import TYPE_CHECKING, Literal, cast
11
12 import pytest
13
14 from filelock import AsyncReadWriteLock, ReadWriteLock
15 from tests.async_filelock_cancellation_helpers import assert_cancellation_message
16 from tests.capability_marks import XFAIL_WITHOUT_COROUTINE_CANCELLATION
17 from tests.read_write_helpers import assert_read_write_lock_state
18
19 if TYPE_CHECKING:
20 from collections.abc import Callable
21 from multiprocessing.sharedctypes import Synchronized
22 from multiprocessing.synchronize import Event as EventType
23 from pathlib import Path
24
25 from pytest_mock import MockerFixture
26
27
28 @pytest.fixture
29 def lock_file(tmp_path: Path) -> str:
30 return str(tmp_path / "test_lock.db")
31
32
33 @pytest.mark.parametrize("mode", [pytest.param("read", id="read"), pytest.param("write", id="write")])
34 @pytest.mark.asyncio
35 async def test_acquire_cancellation_before_executor_start_rolls_back(
36 lock_file: str, mocker: MockerFixture, mode: Literal["read", "write"]
37 ) -> None:
38 executor_started = threading.Event()
39 release_executor = threading.Event()
40 rollback_started = asyncio.Event()
41 finish_rollback = threading.Event()
42 loop = asyncio.get_running_loop()
43 _patch_async_rollback(mocker, loop, rollback_started, finish_rollback)
44
45 with ThreadPoolExecutor(max_workers=1) as executor:
46 blocker = executor.submit(_block_executor, executor_started, release_executor)
47 assert executor_started.wait(timeout=5)
48 lock = AsyncReadWriteLock(lock_file, is_singleton=False, executor=executor)
49 acquire = lock.acquire_read if mode == "read" else lock.acquire_write
50 task = asyncio.create_task(acquire())
51 await asyncio.sleep(0)
52 task.cancel("first cancellation")
53 release_executor.set()
54 await rollback_started.wait()
55 assert_read_write_lock_state(lock_file, "write" if mode == "read" else "read", available=False)
56 task.cancel("second cancellation")
57 finish_rollback.set()
58 with pytest.raises(asyncio.CancelledError) as info:
59 await task
60 blocker.result(timeout=5)
61 assert_cancellation_message(info.value, "first cancellation")
62 assert_read_write_lock_state(lock_file, "write" if mode == "read" else "read", available=True)
63 with pytest.raises(RuntimeError, match="not held"):
64 await lock.release()
65 await lock.close()
66
67
68 @pytest.mark.parametrize(
69 "cancel_caller",
70 [pytest.param(False, id="executor"), pytest.param(True, id="caller-and-executor")],
71 )
72 @XFAIL_WITHOUT_COROUTINE_CANCELLATION
73 def test_executor_cancels_queued_acquire_without_compensation(lock_file: str, *, cancel_caller: bool) -> None:
74 context = multiprocessing.get_context("spawn")
75 canceled = context.Value("b", False)
76 process = context.Process(target=_cancel_queued_read_write_acquire, args=(lock_file, cancel_caller, canceled))
77 process.start()
78 try:
79 process.join(timeout=10)
80 assert (process.exitcode, canceled.value) == (0, True)
81 finally:
82 if process.is_alive(): # pragma: no cover - cleanup for a hung child after the assertion fails
83 process.terminate()
84 process.join(timeout=5)
85 process.close()
86
87
88 @pytest.mark.asyncio
89 @XFAIL_WITHOUT_COROUTINE_CANCELLATION
90 async def test_caller_cancellation_preserves_cancelled_executor_acquire(lock_file: str) -> None:
91 executor_started = threading.Event()
92 release_executor = threading.Event()
93 executor = ThreadPoolExecutor(max_workers=1)
94 blocker = executor.submit(_block_executor, executor_started, release_executor)
95 assert executor_started.wait(timeout=5)
96 lock = AsyncReadWriteLock(lock_file, executor=executor)
97 try:
98 task = asyncio.create_task(lock.acquire_write())
99 await asyncio.sleep(0)
100 task.cancel("caller canceled")
101 await asyncio.sleep(0)
102 executor.shutdown(wait=False, cancel_futures=True)
103 release_executor.set()
104 blocker.result(timeout=5)
105
106 with pytest.raises(asyncio.CancelledError) as info:
107 await task
108 assert isinstance(info.value.__context__, asyncio.CancelledError)
109 assert_cancellation_message(info.value.__context__, "caller canceled")
110 contender = ReadWriteLock(lock_file, is_singleton=False)
111 try:
112 with contender.write_lock(blocking=False):
113 pass
114 finally:
115 contender.close()
116 finally:
117 release_executor.set()
118 executor.shutdown(wait=True, cancel_futures=True)
119 ReadWriteLock(lock_file).close()
120
121
122 @pytest.mark.asyncio
123 @XFAIL_WITHOUT_COROUTINE_CANCELLATION
124 async def test_acquire_cancellation_surfaces_compensation_failure(lock_file: str, mocker: MockerFixture) -> None:
125 executor_started = threading.Event()
126 release_executor = threading.Event()
127 rollback_started = asyncio.Event()
128 finish_rollback = threading.Event()
129 rollback_error = _patch_async_rollback_failure(
130 mocker, asyncio.get_running_loop(), rollback_started, finish_rollback
131 )
132
133 with ThreadPoolExecutor(max_workers=1) as executor:
134 blocker = executor.submit(_block_executor, executor_started, release_executor)
135 assert executor_started.wait(timeout=5)
136 lock = AsyncReadWriteLock(lock_file, is_singleton=False, executor=executor)
137 task = asyncio.create_task(lock.acquire_write())
138 await asyncio.sleep(0)
139 task.cancel("cancel acquire")
140 release_executor.set()
141 await rollback_started.wait()
142 finish_rollback.set()
143 with pytest.raises(sqlite3.OperationalError, match="rollback failed") as info:
144 await task
145 blocker.result(timeout=5)
146 assert info.value is rollback_error
147 cancellation = rollback_error.__context__
148 assert isinstance(cancellation, asyncio.CancelledError)
149 assert cancellation.args == ("cancel acquire",)
150 assert_read_write_lock_state(lock_file, "read", available=False)
151
152 await lock.release()
153 assert_read_write_lock_state(lock_file, "read", available=True)
154 await lock.close()
155
156
157 @pytest.mark.parametrize("mode", [pytest.param("read", id="read"), pytest.param("write", id="write")])
158 @pytest.mark.asyncio
159 async def test_acquire_cancellation_while_sqlite_waits_rolls_back(
160 lock_file: str, mocker: MockerFixture, mode: Literal["read", "write"]
161 ) -> None:
162 context = multiprocessing.get_context("spawn")
163 holder_acquired = context.Event()
164 release_holder = context.Event()
165 holder = context.Process(
166 target=_hold_read_write_lock,
167 args=(lock_file, "write" if mode == "read" else "read", holder_acquired, release_holder),
168 )
169 holder.start()
170 try:
171 assert holder_acquired.wait(timeout=5), "read-write lock holder did not acquire"
172 execute_started = asyncio.Event()
173 _patch_async_execute_signal(mocker, asyncio.get_running_loop(), execute_started)
174 lock = AsyncReadWriteLock(lock_file, is_singleton=False)
175 task = asyncio.create_task((lock.acquire_read if mode == "read" else lock.acquire_write)())
176 await execute_started.wait()
177 task.cancel("cancel blocked acquire")
178 release_holder.set()
179 with pytest.raises(asyncio.CancelledError) as info:
180 await task
181 assert_cancellation_message(info.value, "cancel blocked acquire")
182 holder.join(timeout=5)
183 assert not holder.is_alive(), "read-write lock holder did not exit"
184 assert_read_write_lock_state(lock_file, "write" if mode == "read" else "read", available=True)
185 with pytest.raises(RuntimeError, match="not held"):
186 await lock.release()
187 await lock.close()
188 finally:
189 release_holder.set()
190 if holder.is_alive(): # pragma: no cover - cleanup for a hung child after the assertion fails
191 holder.terminate()
192 holder.join(timeout=5)
193
194
195 @pytest.mark.parametrize("mode", [pytest.param("read", id="read"), pytest.param("write", id="write")])
196 @pytest.mark.asyncio
197 @XFAIL_WITHOUT_COROUTINE_CANCELLATION
198 async def test_acquire_cancellation_surfaces_acquire_and_rollback_errors(
199 lock_file: str, mocker: MockerFixture, mode: Literal["read", "write"]
200 ) -> None:
201 acquire_started = asyncio.Event()
202 finish_acquire = threading.Event()
203 loop = asyncio.get_running_loop()
204 acquire_error, rollback_error, prior_rollback_error = _patch_async_acquire_and_rollback_failure(
205 mocker, loop, acquire_started, finish_acquire, mode
206 )
207 lock = AsyncReadWriteLock(lock_file, is_singleton=False)
208 task = asyncio.create_task((lock.acquire_read if mode == "read" else lock.acquire_write)())
209 await acquire_started.wait()
210 task.cancel("cancel acquire")
211 finish_acquire.set()
212
213 with pytest.raises(sqlite3.OperationalError, match="rollback failed") as info:
214 await task
215 assert info.value is rollback_error
216 cancellation = rollback_error.__context__
217 assert isinstance(cancellation, asyncio.CancelledError)
218 assert (cancellation.args, cancellation.__context__, acquire_error.__context__) == (
219 ("cancel acquire",),
220 acquire_error,
221 prior_rollback_error,
222 )
223 assert_read_write_lock_state(lock_file, "write" if mode == "read" else "read", available=False)
224
225 await (lock.acquire_read if mode == "read" else lock.acquire_write)()
226 assert_read_write_lock_state(lock_file, "write" if mode == "read" else "read", available=False)
227 await lock.release()
228 assert_read_write_lock_state(lock_file, "write" if mode == "read" else "read", available=True)
229 await lock.close()
230
231
232 @pytest.mark.parametrize("supplied", [pytest.param(False, id="owned"), pytest.param(True, id="supplied")])
233 @pytest.mark.asyncio
234 async def test_close_cancellation_shuts_down_only_an_owned_executor(
235 lock_file: str, mocker: MockerFixture, supplied: bool
236 ) -> None:
237 rollback_started = asyncio.Event()
238 finish_rollback = threading.Event()
239 _patch_async_rollback(mocker, asyncio.get_running_loop(), rollback_started, finish_rollback)
240 lock = AsyncReadWriteLock(
241 lock_file, is_singleton=False, executor=ThreadPoolExecutor(max_workers=1) if supplied else None
242 )
243 await lock.acquire_write()
244 executor = lock.executor
245 task = asyncio.create_task(lock.close())
246 await rollback_started.wait()
247 task.cancel("cancel close")
248 finish_rollback.set()
249
250 with pytest.raises(asyncio.CancelledError) as info:
251 await task
252 assert_cancellation_message(info.value, "cancel close")
253 assert_read_write_lock_state(lock_file, "read", available=True)
254 if supplied:
255 assert executor.submit(int).result(timeout=5) == 0
256 executor.shutdown(wait=True)
257 else:
258 with pytest.raises(RuntimeError):
259 executor.submit(int)
260
261
262 @pytest.mark.parametrize("operation", [pytest.param("release", id="release"), pytest.param("close", id="close")])
263 @pytest.mark.asyncio
264 @XFAIL_WITHOUT_COROUTINE_CANCELLATION
265 async def test_cancellation_surfaces_rollback_error(
266 lock_file: str, mocker: MockerFixture, operation: Literal["release", "close"]
267 ) -> None:
268 rollback_started = asyncio.Event()
269 finish_rollback = threading.Event()
270 rollback_error = _patch_async_rollback_failure(
271 mocker, asyncio.get_running_loop(), rollback_started, finish_rollback
272 )
273 lock = AsyncReadWriteLock(lock_file, is_singleton=False)
274 await lock.acquire_write()
275 executor = lock.executor
276 task = asyncio.create_task(lock.release() if operation == "release" else lock.close())
277 await rollback_started.wait()
278 task.cancel(f"cancel {operation}")
279 finish_rollback.set()
280
281 with pytest.raises(sqlite3.OperationalError, match="rollback failed") as info:
282 await task
283 assert info.value is rollback_error
284 cancellation = rollback_error.__context__
285 assert isinstance(cancellation, asyncio.CancelledError)
286 assert cancellation.args == (f"cancel {operation}",)
287 assert_read_write_lock_state(lock_file, "read", available=False)
288 assert executor.submit(int).result(timeout=5) == 0
289
290 if operation == "release":
291 await lock.release()
292 await lock.close()
293 assert_read_write_lock_state(lock_file, "read", available=True)
294 with pytest.raises(RuntimeError):
295 executor.submit(int)
296
297
298 @pytest.mark.parametrize("mode", [pytest.param("read", id="read"), pytest.param("write", id="write")])
299 @pytest.mark.asyncio
300 @XFAIL_WITHOUT_COROUTINE_CANCELLATION
301 async def test_context_cancellation_preserves_body_and_rollback_contexts(
302 lock_file: str, mocker: MockerFixture, mode: Literal["read", "write"]
303 ) -> None:
304 rollback_started = asyncio.Event()
305 finish_rollback = threading.Event()
306 body_error = ValueError("body failed")
307 prior_error = LookupError("prior rollback failure")
308 rollback_error = _patch_async_rollback_failure(
309 mocker,
310 asyncio.get_running_loop(),
311 rollback_started,
312 finish_rollback,
313 prior_context=prior_error,
314 )
315 lock = AsyncReadWriteLock(lock_file, is_singleton=False)
316
317 async def fail_in_context() -> None:
318 async with lock.read_lock() if mode == "read" else lock.write_lock():
319 raise body_error
320
321 task = asyncio.create_task(fail_in_context())
322 await rollback_started.wait()
323 task.cancel("cancel release")
324 finish_rollback.set()
325
326 with pytest.raises(sqlite3.OperationalError, match="rollback failed") as info:
327 await task
328 cancellation = rollback_error.__context__
329 assert isinstance(cancellation, asyncio.CancelledError)
330 assert (info.value, cancellation.args, cancellation.__context__, prior_error.__context__) == (
331 rollback_error,
332 ("cancel release",),
333 prior_error,
334 body_error,
335 )
336 probe_mode: Literal["read", "write"] = "write" if mode == "read" else "read"
337 assert_read_write_lock_state(lock_file, probe_mode, available=False)
338
339 await lock.release()
340 await lock.close()
341 assert_read_write_lock_state(lock_file, probe_mode, available=True)
342
343
344 def _patch_async_rollback(
345 mocker: MockerFixture,
346 loop: asyncio.AbstractEventLoop,
347 rollback_started: asyncio.Event,
348 finish_rollback: threading.Event,
349 ) -> None:
350 def rollback(real_connection: sqlite3.Connection) -> None:
351 loop.call_soon_threadsafe(rollback_started.set)
352 assert finish_rollback.wait(timeout=5)
353 real_connection.rollback()
354
355 _patch_async_connection(mocker, rollback=rollback)
356
357
358 def _cancel_queued_read_write_acquire(lock_file: str, cancel_caller: bool, canceled: Synchronized[bool]) -> None:
359 async def cancel_queued_acquire() -> None:
360 executor_started = threading.Event()
361 release_executor = threading.Event()
362 executor = ThreadPoolExecutor(max_workers=1)
363 blocker = executor.submit(_block_executor, executor_started, release_executor)
364 assert executor_started.wait(timeout=5)
365 lock = AsyncReadWriteLock(lock_file, is_singleton=False, executor=executor)
366 task = asyncio.create_task(lock.acquire_write())
367 await asyncio.sleep(0)
368 if cancel_caller:
369 task.cancel("caller canceled")
370 await asyncio.sleep(0)
371 executor.shutdown(wait=False, cancel_futures=True)
372 release_executor.set()
373 blocker.result(timeout=5)
374 try:
375 await task
376 except asyncio.CancelledError as error:
377 context = error.__context__
378 if cancel_caller and sys.version_info >= (3, 11): # pragma: >=3.11 cover
379 canceled.value = isinstance(context, asyncio.CancelledError) and context.args == ("caller canceled",)
380 else:
381 canceled.value = True
382 contender = ReadWriteLock(lock_file, is_singleton=False)
383 with contender.write_lock(blocking=False):
384 pass
385 contender.close()
386
387 asyncio.run(cancel_queued_acquire())
388
389
390 def _patch_async_execute_signal(
391 mocker: MockerFixture,
392 loop: asyncio.AbstractEventLoop,
393 execute_started: asyncio.Event,
394 ) -> None:
395 def executescript(real_connection: sqlite3.Connection, statement: str) -> sqlite3.Cursor:
396 if "PRAGMA journal_mode" in statement:
397 loop.call_soon_threadsafe(execute_started.set)
398 return real_connection.executescript(statement)
399
400 _patch_async_connection(mocker, executescript=executescript)
401
402
403 def _patch_async_rollback_failure(
404 mocker: MockerFixture,
405 loop: asyncio.AbstractEventLoop,
406 rollback_started: asyncio.Event,
407 finish_rollback: threading.Event,
408 *,
409 prior_context: BaseException | None = None,
410 ) -> sqlite3.OperationalError:
411 rollback_error = sqlite3.OperationalError("rollback failed")
412 rollback_error.__context__ = prior_context
413 rollback_failed = False
414
415 def rollback(real_connection: sqlite3.Connection) -> None:
416 nonlocal rollback_failed
417 if rollback_failed:
418 real_connection.rollback()
419 return
420 rollback_failed = True
421 loop.call_soon_threadsafe(rollback_started.set)
422 assert finish_rollback.wait(timeout=5)
423 raise rollback_error
424
425 _patch_async_connection(mocker, rollback=rollback)
426 return rollback_error
427
428
429 def _patch_async_acquire_and_rollback_failure(
430 mocker: MockerFixture,
431 loop: asyncio.AbstractEventLoop,
432 acquire_started: asyncio.Event,
433 finish_acquire: threading.Event,
434 mode: Literal["read", "write"],
435 ) -> tuple[sqlite3.OperationalError, sqlite3.OperationalError, LookupError]:
436 acquire_error = sqlite3.OperationalError("acquire failed")
437 rollback_error = sqlite3.OperationalError("rollback failed")
438 prior_rollback_error = LookupError("prior rollback failure")
439 rollback_error.__context__ = prior_rollback_error
440 acquire_failed = False
441 rollback_failed = False
442
443 def executescript(real_connection: sqlite3.Connection, statement: str) -> sqlite3.Cursor:
444 nonlocal acquire_failed
445 cursor = real_connection.executescript(statement)
446 target = "SELECT name" in statement if mode == "read" else "BEGIN EXCLUSIVE" in statement
447 if target and not acquire_failed:
448 acquire_failed = True
449 loop.call_soon_threadsafe(acquire_started.set)
450 assert finish_acquire.wait(timeout=5)
451 cursor.close()
452 raise acquire_error
453 return cursor
454
455 def rollback(real_connection: sqlite3.Connection) -> None:
456 nonlocal rollback_failed
457 if not rollback_failed:
458 rollback_failed = True
459 try:
460 raise prior_rollback_error
461 except LookupError:
462 raise rollback_error # ruff:ignore[raise-without-from-inside-except] # exercise implicit backend context preservation
463 real_connection.rollback()
464
465 _patch_async_connection(mocker, executescript=executescript, rollback=rollback)
466 return acquire_error, rollback_error, prior_rollback_error
467
468
469 def _patch_async_connection(
470 mocker: MockerFixture,
471 *,
472 executescript: Callable[[sqlite3.Connection, str], sqlite3.Cursor] | None = None,
473 rollback: Callable[[sqlite3.Connection], None] | None = None,
474 ) -> None:
475 real_connect = sqlite3.connect
476 connection_count = 0
477
478 def connect(
479 database: str,
480 *,
481 factory: type[sqlite3.Connection],
482 timeout: float,
483 ) -> sqlite3.Connection:
484 nonlocal connection_count
485 real_connection = real_connect(
486 database,
487 check_same_thread=False,
488 factory=factory,
489 cached_statements=0,
490 timeout=timeout,
491 )
492 connection_count += 1
493 if connection_count != 2:
494 return real_connection
495 configuration: dict[str, Callable[[str], sqlite3.Cursor] | Callable[[], None]] = {}
496 if executescript is not None:
497 configuration["executescript.side_effect"] = functools.partial(executescript, real_connection)
498 if rollback is not None:
499 configuration["rollback.side_effect"] = functools.partial(rollback, real_connection)
500 connection = mocker.MagicMock(spec_set=type(real_connection), wraps=real_connection, **configuration)
501 mocker.patch.object(
502 type(connection),
503 "in_transaction",
504 new_callable=mocker.PropertyMock,
505 create=True,
506 side_effect=lambda: real_connection.in_transaction,
507 )
508 return cast("sqlite3.Connection", connection)
509
510 mocker.patch("filelock._read_write._connect", side_effect=connect)
511
512
513 def _block_executor(executor_started: threading.Event, release_executor: threading.Event) -> None:
514 executor_started.set()
515 assert release_executor.wait(timeout=5)
516
517
518 def _hold_read_write_lock(
519 lock_file: str,
520 mode: Literal["read", "write"],
521 acquired: EventType,
522 release: EventType,
523 ) -> None:
524 lock = ReadWriteLock(lock_file, is_singleton=False)
525 (lock.acquire_read if mode == "read" else lock.acquire_write)()
526 acquired.set()
527 try:
528 assert release.wait(timeout=10)
529 finally:
530 lock.release()
531 lock.close()