Debian Codegraph @

tests/test_async_filelock_acquire_cancellation.py

raw
1 from __future__ import annotations
2
3 import asyncio
4 import logging
5 import sys
6 import threading
7 from concurrent.futures import ThreadPoolExecutor
8 from errno import EIO
9 from typing import TYPE_CHECKING
10
11 import pytest
12
13 from filelock import (
14 AsyncFileLock,
15 BaseAsyncFileLock,
16 ContextErrorPolicy,
17 )
18 from tests.async_filelock_cancellation_helpers import assert_cancellation_message, assert_file_lock_state
19 from tests.capability_marks import NEEDS_FCNTL, XFAIL_WITHOUT_COROUTINE_CANCELLATION
20
21 if sys.version_info >= (3, 11): # pragma: no cover (py311+)
22 from builtins import BaseExceptionGroup, ExceptionGroup # pragma: >=3.11 cover
23 else: # pragma: no cover (<py311)
24 from exceptiongroup import BaseExceptionGroup, ExceptionGroup
25
26 if TYPE_CHECKING:
27 from pathlib import Path
28
29 from pytest_mock import MockerFixture
30
31
32 @pytest.mark.asyncio
33 async def test_backend_cancellation_after_acquire_rolls_back(tmp_path: Path) -> None:
34 backend_cancellation = asyncio.CancelledError("backend canceled")
35 released = False
36
37 class CancellingFileLock(BaseAsyncFileLock):
38 async def _acquire(self) -> None: # ty: ignore[invalid-method-override]
39 self._context.lock_file_fd = 1
40 raise backend_cancellation
41
42 async def _release(self) -> None: # ty: ignore[invalid-method-override]
43 nonlocal released
44 released = True
45 self._context.lock_file_fd = None
46
47 lock = CancellingFileLock(tmp_path / "a", run_in_executor=False)
48 with pytest.raises(asyncio.CancelledError, match="backend canceled"):
49 await lock.acquire()
50 assert (released, lock.is_locked, lock.lock_counter) == (True, False, 0)
51
52
53 @pytest.mark.parametrize("policy", [pytest.param("chain", id="chain"), pytest.param("group", id="group")])
54 @pytest.mark.asyncio
55 @XFAIL_WITHOUT_COROUTINE_CANCELLATION
56 async def test_backend_cancellation_rollback_failure_follows_policy(tmp_path: Path, policy: ContextErrorPolicy) -> None:
57 backend_cancellation = asyncio.CancelledError("backend canceled")
58 rollback_error = OSError(EIO, "rollback failed")
59 prior_leaf = LookupError("prior rollback failure")
60 prior_cause = RuntimeError("prior rollback cause")
61 prior_rollback_error = ExceptionGroup("prior rollback failures", (prior_leaf,))
62 prior_rollback_error.__cause__ = prior_cause
63 prior_cause.__context__ = prior_rollback_error
64 fail_rollback = True
65
66 class CancellingFileLock(BaseAsyncFileLock):
67 async def _acquire(self) -> None: # ty: ignore[invalid-method-override]
68 self._context.lock_file_fd = 1
69 raise backend_cancellation
70
71 async def _release(self) -> None: # ty: ignore[invalid-method-override]
72 if fail_rollback:
73 try:
74 raise prior_rollback_error
75 except ExceptionGroup:
76 raise rollback_error # ruff:ignore[raise-without-from-inside-except] # exercise implicit backend context preservation
77 self._context.lock_file_fd = None
78
79 lock = CancellingFileLock(tmp_path / "a", run_in_executor=False, context_error_policy=policy)
80 if policy == "chain":
81 with pytest.raises(OSError, match="rollback failed") as info:
82 await lock.acquire()
83 assert (info.value, rollback_error.__context__, backend_cancellation.__context__) == (
84 rollback_error,
85 backend_cancellation,
86 prior_rollback_error,
87 )
88 else:
89 with pytest.raises(BaseExceptionGroup) as info:
90 await lock.acquire()
91 assert (info.value.exceptions, rollback_error.__context__) == (
92 (backend_cancellation, rollback_error),
93 prior_rollback_error,
94 )
95 assert (lock.is_locked, lock.lock_counter) == (True, 1)
96
97 fail_rollback = False
98 await lock.release()
99 assert (lock.is_locked, lock.lock_counter) == (False, 0)
100
101
102 @pytest.mark.asyncio
103 async def test_caller_and_backend_cancellation_both_surface(tmp_path: Path) -> None:
104 acquire_started = asyncio.Event()
105 finish_acquire = asyncio.Event()
106 backend_cancellation = asyncio.CancelledError("backend canceled")
107
108 class CancellingFileLock(BaseAsyncFileLock):
109 async def _acquire(self) -> None: # ty: ignore[invalid-method-override]
110 self._context.lock_file_fd = 1
111 acquire_started.set()
112 await finish_acquire.wait()
113 raise backend_cancellation
114
115 async def _release(self) -> None: # ty: ignore[invalid-method-override]
116 self._context.lock_file_fd = None
117
118 lock = CancellingFileLock(tmp_path / "a", run_in_executor=False, context_error_policy="group")
119 task = asyncio.create_task(lock.acquire())
120 await acquire_started.wait()
121 task.cancel("caller canceled")
122 finish_acquire.set()
123 with pytest.raises(BaseExceptionGroup) as info:
124 await task
125
126 caller_cancellation, grouped_backend_cancellation = info.value.exceptions
127 assert isinstance(caller_cancellation, asyncio.CancelledError)
128 assert (caller_cancellation.args, grouped_backend_cancellation) == (("caller canceled",), backend_cancellation)
129 assert (lock.is_locked, lock.lock_counter) == (False, 0)
130
131
132 @pytest.mark.asyncio
133 async def test_acquire_cancellation_before_executor_start_rolls_back(tmp_path: Path) -> None:
134 executor_started = threading.Event()
135 release_executor = threading.Event()
136 acquired = threading.Event()
137 with ThreadPoolExecutor(max_workers=1) as executor:
138 blocker = executor.submit(_block_executor, executor_started, release_executor)
139 assert executor_started.wait(timeout=5)
140 lock = AsyncFileLock(tmp_path / "a", executor=executor, on_acquired=lambda _fd: acquired.set())
141 task = asyncio.create_task(lock.acquire())
142 await asyncio.sleep(0)
143 assert (lock.lock_counter, acquired.is_set()) == (1, False)
144 task.cancel()
145 release_executor.set()
146 with pytest.raises(asyncio.CancelledError):
147 await task
148 blocker.result(timeout=5)
149
150 assert acquired.is_set()
151 assert (lock.is_locked, lock.lock_counter) == (False, 0)
152 assert_file_lock_state(str(tmp_path / "a"), available=True)
153
154
155 @NEEDS_FCNTL
156 @pytest.mark.asyncio
157 async def test_acquire_cancellation_does_not_release_later_claim(tmp_path: Path) -> None: # pragma: needs fcntl
158 hook_started = asyncio.Event()
159 finish_hook = threading.Event()
160 loop = asyncio.get_running_loop()
161
162 def block_hook(_fd: int) -> None:
163 loop.call_soon_threadsafe(hook_started.set)
164 assert finish_hook.wait(timeout=5)
165
166 lock = AsyncFileLock(tmp_path / "a", on_acquired=block_hook)
167 first_acquire = asyncio.create_task(lock.acquire())
168 await hook_started.wait()
169 second_acquire = asyncio.create_task(lock.acquire())
170 first_acquire.cancel("cancel first acquire")
171 finish_hook.set()
172 with pytest.raises(asyncio.CancelledError) as info:
173 await first_acquire
174 assert_cancellation_message(info.value, "cancel first acquire")
175 await second_acquire
176
177 assert (lock.is_locked, lock.lock_counter) == (True, 1)
178 assert_file_lock_state(str(tmp_path / "a"), available=False)
179 await lock.release()
180 assert_file_lock_state(str(tmp_path / "a"), available=True)
181
182
183 @NEEDS_FCNTL
184 @pytest.mark.asyncio
185 @XFAIL_WITHOUT_COROUTINE_CANCELLATION
186 async def test_cancelled_queued_acquire_does_not_claim_transition(tmp_path: Path) -> None: # pragma: needs fcntl
187 hook_started = asyncio.Event()
188 finish_hook = threading.Event()
189 loop = asyncio.get_running_loop()
190
191 def block_hook(_fd: int) -> None:
192 loop.call_soon_threadsafe(hook_started.set)
193 assert finish_hook.wait(timeout=5)
194
195 lock = AsyncFileLock(tmp_path / "a", on_acquired=block_hook)
196 first_acquire = asyncio.create_task(lock.acquire())
197 await hook_started.wait()
198 queued_acquire = asyncio.create_task(lock.acquire())
199 await asyncio.sleep(0)
200 queued_acquire.cancel("cancel queued acquire")
201 with pytest.raises(asyncio.CancelledError) as info:
202 await queued_acquire
203 assert_cancellation_message(info.value, "cancel queued acquire")
204 assert lock.lock_counter == 1
205
206 finish_hook.set()
207 await first_acquire
208 await lock.acquire()
209 assert lock.lock_counter == 2
210 await lock.release()
211 await lock.release()
212 assert_file_lock_state(str(tmp_path / "a"), available=True)
213
214
215 @NEEDS_FCNTL
216 @pytest.mark.asyncio # pragma: needs fcntl
217 async def test_acquire_repeated_cancellation_waits_for_rollback(tmp_path: Path, mocker: MockerFixture) -> None:
218 hook_started = asyncio.Event()
219 finish_hook = threading.Event()
220 rollback_started = asyncio.Event()
221 finish_rollback = threading.Event()
222 loop = asyncio.get_running_loop()
223
224 def block_hook(_fd: int) -> None:
225 loop.call_soon_threadsafe(hook_started.set)
226 assert finish_hook.wait(timeout=5)
227
228 def block_rollback(_fd: int, _operation: int) -> None:
229 loop.call_soon_threadsafe(rollback_started.set)
230 assert finish_rollback.wait(timeout=5)
231
232 lock = AsyncFileLock(tmp_path / "a", on_acquired=block_hook)
233 task = asyncio.create_task(lock.acquire())
234 await hook_started.wait()
235 mocker.patch("filelock._unix.fcntl.flock", side_effect=block_rollback)
236 task.cancel("first cancellation")
237 finish_hook.set()
238 await rollback_started.wait()
239 task.cancel("second cancellation")
240 finish_rollback.set()
241 with pytest.raises(asyncio.CancelledError) as info:
242 await task
243
244 assert_cancellation_message(info.value, "first cancellation")
245 assert (lock.is_locked, lock.lock_counter) == (False, 0)
246 assert_file_lock_state(str(tmp_path / "a"), available=True)
247
248
249 @NEEDS_FCNTL
250 @pytest.mark.parametrize("policy", [pytest.param("chain", id="chain"), pytest.param("group", id="group")])
251 @pytest.mark.asyncio
252 @XFAIL_WITHOUT_COROUTINE_CANCELLATION
253 async def test_acquire_cancellation_surfaces_attempt_error_after_rollback( # pragma: needs fcntl
254 tmp_path: Path, policy: ContextErrorPolicy
255 ) -> None:
256 hook_started = asyncio.Event()
257 finish_hook = threading.Event()
258 loop = asyncio.get_running_loop()
259 callback_error = ValueError("hook failed")
260 prior_context = LookupError("prior callback failure")
261 callback_error.__context__ = prior_context
262
263 def fail_hook(_fd: int) -> None:
264 loop.call_soon_threadsafe(hook_started.set)
265 assert finish_hook.wait(timeout=5)
266 raise callback_error
267
268 lock = AsyncFileLock(tmp_path / "a", context_error_policy=policy, on_acquired=fail_hook)
269 task = asyncio.create_task(lock.acquire())
270 await hook_started.wait()
271 task.cancel("cancel acquire")
272 finish_hook.set()
273 if policy == "chain":
274 with pytest.raises(ValueError, match="hook failed") as info:
275 await task
276 cancellation = info.value.__context__
277 assert info.value is callback_error
278 else:
279 with pytest.raises(BaseExceptionGroup) as info:
280 await task
281 cancellation, grouped_callback_error = info.value.exceptions
282 assert grouped_callback_error is callback_error
283 assert (info.value.__cause__, info.value.__suppress_context__) == (None, True)
284 assert isinstance(cancellation, asyncio.CancelledError)
285 assert (cancellation.args, cancellation.__context__, callback_error.__cause__, callback_error.__context__) == (
286 ("cancel acquire",),
287 prior_context if policy == "chain" else None,
288 None,
289 cancellation if policy == "chain" else prior_context,
290 )
291 assert (lock.is_locked, lock.lock_counter) == (False, 0)
292 assert_file_lock_state(str(tmp_path / "a"), available=True)
293
294
295 @NEEDS_FCNTL
296 @pytest.mark.parametrize(
297 ("context_message", "preserved"),
298 [pytest.param("unrelated", True, id="distinct"), pytest.param("attempt", False, id="equivalent")],
299 )
300 @pytest.mark.asyncio
301 @XFAIL_WITHOUT_COROUTINE_CANCELLATION
302 async def test_acquire_cancellation_group_reconciles_attempt_context( # pragma: needs fcntl
303 tmp_path: Path, context_message: str, *, preserved: bool
304 ) -> None:
305 hook_started = asyncio.Event()
306 finish_hook = threading.Event()
307 loop = asyncio.get_running_loop()
308 nested_leaf = LookupError("nested")
309 callback_group = ExceptionGroup("attempt", (nested_leaf,))
310 prior_context = ExceptionGroup(context_message, (nested_leaf,))
311 callback_group.__context__ = prior_context
312
313 def fail_hook(_fd: int) -> None:
314 loop.call_soon_threadsafe(hook_started.set)
315 assert finish_hook.wait(timeout=5)
316 raise callback_group
317
318 lock = AsyncFileLock(tmp_path / "a", context_error_policy="group", on_acquired=fail_hook)
319 task = asyncio.create_task(lock.acquire())
320 await hook_started.wait()
321 task.cancel("cancel acquire")
322 finish_hook.set()
323 with pytest.raises(BaseExceptionGroup) as info:
324 await task
325
326 cancellation, grouped_callback_error = info.value.exceptions
327 assert isinstance(cancellation, asyncio.CancelledError)
328 assert isinstance(grouped_callback_error, ExceptionGroup)
329 assert grouped_callback_error is callback_group
330 assert (
331 type(grouped_callback_error),
332 grouped_callback_error.message,
333 grouped_callback_error.exceptions,
334 grouped_callback_error.__context__,
335 callback_group.__context__,
336 ) == (
337 ExceptionGroup,
338 "attempt",
339 (nested_leaf,),
340 prior_context if preserved else None,
341 prior_context if preserved else None,
342 )
343 assert (lock.is_locked, lock.lock_counter) == (False, 0)
344 assert_file_lock_state(str(tmp_path / "a"), available=True)
345
346
347 @NEEDS_FCNTL
348 @pytest.mark.parametrize("policy", [pytest.param("chain", id="chain"), pytest.param("group", id="group")])
349 @pytest.mark.asyncio
350 @XFAIL_WITHOUT_COROUTINE_CANCELLATION
351 async def test_acquire_cancellation_surfaces_rollback_error( # pragma: needs fcntl
352 tmp_path: Path,
353 mocker: MockerFixture,
354 caplog: pytest.LogCaptureFixture,
355 policy: ContextErrorPolicy,
356 ) -> None:
357 hook_started = asyncio.Event()
358 finish_hook = threading.Event()
359 loop = asyncio.get_running_loop()
360
361 def block_hook(_fd: int) -> None:
362 loop.call_soon_threadsafe(hook_started.set)
363 assert finish_hook.wait(timeout=5)
364
365 rollback_error = OSError(EIO, "rollback failed")
366 lock = AsyncFileLock(tmp_path / "a", context_error_policy=policy, on_acquired=block_hook)
367 task = asyncio.create_task(lock.acquire())
368 await hook_started.wait()
369 mocker.patch("filelock._unix.fcntl.flock", side_effect=[rollback_error, None])
370 task.cancel("cancel acquire")
371 finish_hook.set()
372 if policy == "chain":
373 with pytest.raises(OSError, match="rollback failed") as info:
374 await task
375 cancellation = info.value.__context__
376 assert info.value is rollback_error
377 else:
378 with pytest.raises(BaseExceptionGroup) as info:
379 await task
380 cancellation, grouped_rollback_error = info.value.exceptions
381 assert grouped_rollback_error is rollback_error
382 assert (info.value.__cause__, info.value.__suppress_context__) == (None, True)
383 assert isinstance(cancellation, asyncio.CancelledError)
384 assert (cancellation.args, rollback_error.__cause__, rollback_error.__context__) == (
385 ("cancel acquire",),
386 None,
387 cancellation if policy == "chain" else None,
388 )
389 assert (cancellation.__traceback__ is not None, rollback_error.__traceback__ is not None) == (True, True)
390 assert not any(record.name == "asyncio" and record.levelno >= logging.ERROR for record in caplog.records)
391 assert (lock.is_locked, lock.lock_counter) == (True, 1)
392 assert_file_lock_state(str(tmp_path / "a"), available=False)
393 await lock.release()
394
395
396 @NEEDS_FCNTL
397 @pytest.mark.parametrize("policy", [pytest.param("chain", id="chain"), pytest.param("group", id="group")])
398 @pytest.mark.asyncio
399 @XFAIL_WITHOUT_COROUTINE_CANCELLATION
400 async def test_acquire_cancellation_surfaces_attempt_and_rollback_errors( # pragma: needs fcntl
401 tmp_path: Path, mocker: MockerFixture, policy: ContextErrorPolicy
402 ) -> None:
403 hook_started = asyncio.Event()
404 finish_hook = threading.Event()
405 loop = asyncio.get_running_loop()
406 callback_error = ValueError("hook failed")
407
408 def fail_hook(_fd: int) -> None:
409 loop.call_soon_threadsafe(hook_started.set)
410 assert finish_hook.wait(timeout=5)
411 raise callback_error
412
413 first_rollback_error = OSError(EIO, "hook rollback failed")
414 second_rollback_error = OSError(EIO, "cancellation rollback failed")
415 lock = AsyncFileLock(tmp_path / "a", context_error_policy=policy, on_acquired=fail_hook)
416 task = asyncio.create_task(lock.acquire())
417 await hook_started.wait()
418 mocker.patch(
419 "filelock._unix.fcntl.flock",
420 side_effect=[first_rollback_error, second_rollback_error, None],
421 )
422 task.cancel("cancel acquire")
423 finish_hook.set()
424 if policy == "chain":
425 with pytest.raises(OSError, match="cancellation rollback failed") as info:
426 await task
427 attempt_error = info.value.__context__
428 cancellation = attempt_error.__context__ if attempt_error is not None else None
429 assert info.value is second_rollback_error
430 else:
431 with pytest.raises(BaseExceptionGroup) as info:
432 await task
433 cancellation, attempt_error, grouped_rollback_error = info.value.exceptions
434 assert grouped_rollback_error is second_rollback_error
435 assert (info.value.__cause__, info.value.__suppress_context__) == (None, True)
436 assert isinstance(attempt_error, BaseExceptionGroup)
437 assert (attempt_error.exceptions[0], attempt_error.exceptions[1]) == (callback_error, first_rollback_error)
438 assert isinstance(cancellation, asyncio.CancelledError)
439 assert (
440 cancellation.args,
441 attempt_error.__cause__,
442 attempt_error.__context__,
443 second_rollback_error.__cause__,
444 second_rollback_error.__context__,
445 ) == (
446 ("cancel acquire",),
447 None,
448 cancellation if policy == "chain" else None,
449 None,
450 attempt_error if policy == "chain" else None,
451 )
452 assert (callback_error.__context__, first_rollback_error.__context__) == (None, None)
453 assert (
454 cancellation.__traceback__ is not None,
455 callback_error.__traceback__ is not None,
456 first_rollback_error.__traceback__ is not None,
457 attempt_error.__traceback__ is not None,
458 second_rollback_error.__traceback__ is not None,
459 ) == (True, True, True, True, True)
460 assert (lock.is_locked, lock.lock_counter) == (True, 1)
461 assert_file_lock_state(str(tmp_path / "a"), available=False)
462 await lock.release()
463
464
465 @pytest.mark.asyncio
466 async def test_non_executor_immediate_acquire_precedes_scheduled_callback(tmp_path: Path) -> None:
467 callbacks: list[str] = []
468 asyncio.get_running_loop().call_soon(callbacks.append, "callback")
469 lock = AsyncFileLock(tmp_path / "a", run_in_executor=False)
470
471 await lock.acquire()
472
473 assert callbacks == []
474 await lock.release()
475 await asyncio.sleep(0)
476 assert callbacks == ["callback"]
477
478
479 def _block_executor(executor_started: threading.Event, release_executor: threading.Event) -> None:
480 executor_started.set()
481 assert release_executor.wait(timeout=5)