Debian Codegraph @

tests/test_fork_backends.py

raw
1 from __future__ import annotations
2
3 import asyncio
4 import os
5 import subprocess # ruff:ignore[suspicious-subprocess-import] # isolated interpreter controls child callback registration order
6 import sys
7 from errno import EBADF
8 from typing import TYPE_CHECKING, NoReturn, cast
9
10 import pytest
11
12 from filelock import BaseAsyncFileLock, BaseFileLock
13 from tests.capability_marks import NEEDS_FORK, NEEDS_GENERATOR_EXCEPTION_CONTEXT
14 from tests.fork_helpers import exit_child, fork_process
15
16 if sys.version_info >= (3, 11):
17 from builtins import BaseExceptionGroup # pragma: >=3.11 cover
18 else: # pragma: <3.11 cover
19 from exceptiongroup import BaseExceptionGroup
20
21 if TYPE_CHECKING:
22 from collections.abc import Callable
23 from pathlib import Path
24
25 from pytest_mock import MockerFixture
26
27
28 class _DescriptorLock(BaseFileLock):
29 acquire_error: BaseException | None = None
30 descriptor: int | None = None
31 fail_release: bool = False
32
33 def _acquire(self) -> None: # pragma: needs fork
34 self.descriptor = self._context.lock_file_fd = os.open(self.lock_file, os.O_CREAT | os.O_RDWR, 0o600)
35 if self.acquire_error is not None:
36 raise self.acquire_error
37
38 def _release(self) -> None: # pragma: needs fork
39 if self.fail_release:
40 msg = "unlock failed"
41 raise RuntimeError(msg)
42 os.close(cast("int", self._context.lock_file_fd))
43 self._context.lock_file_fd = None
44
45
46 class _CoroutineDescriptorLock(BaseAsyncFileLock):
47 acquire_error: BaseException | None = None
48 acquire_error_before_descriptor: BaseException | None = None
49 descriptor: int | None = None
50 release_error: BaseException | None = None
51 release_error_before_close: BaseException | None = None
52
53 async def _acquire(self) -> None: # ty: ignore[invalid-method-override] # coroutine backends are supported
54 if self.acquire_error_before_descriptor is not None:
55 raise self.acquire_error_before_descriptor
56 self.descriptor = self._context.lock_file_fd = os.open(self.lock_file, os.O_CREAT | os.O_RDWR, 0o600)
57 if self.acquire_error is not None: # pragma: needs fork
58 raise self.acquire_error
59
60 async def _release(self) -> None: # ty: ignore[invalid-method-override] # coroutine backends are supported
61 if self.release_error_before_close is not None: # pragma: needs fork
62 raise self.release_error_before_close
63 os.close(cast("int", self._context.lock_file_fd))
64 self._context.lock_file_fd = None
65 if self.release_error is not None:
66 raise self.release_error
67
68
69 @NEEDS_FORK # pragma: needs fork
70 def test_third_party_descriptor_is_closed_in_child(tmp_path: Path) -> None:
71 descriptors: list[int] = []
72 lock = _DescriptorLock(str(tmp_path / "third-party.lock"), is_singleton=False, on_acquired=descriptors.append)
73 lock.acquire()
74
75 child_pid = _fork_descriptor_probe(descriptors[0], os.fstat)
76 _, status = os.waitpid(child_pid, 0)
77 lock.release()
78
79 assert os.waitstatus_to_exitcode(status) == 0
80
81
82 @NEEDS_FORK # pragma: needs fork
83 def test_unlock_failure_keeps_descriptor_registered(tmp_path: Path) -> None:
84 descriptors: list[int] = []
85 lock = _DescriptorLock(str(tmp_path / "retry.lock"), is_singleton=False, on_acquired=descriptors.append)
86 lock.acquire()
87 lock.fail_release = True
88 with pytest.raises(RuntimeError, match="unlock failed"):
89 lock.release()
90
91 child_pid = _fork_descriptor_probe(descriptors[0], os.fstat)
92 _, status = os.waitpid(child_pid, 0)
93 lock.fail_release = False
94 lock.release()
95
96 assert os.waitstatus_to_exitcode(status) == 0
97
98
99 @NEEDS_FORK # pragma: needs fork
100 def test_acquisition_failure_keeps_descriptor_registered_until_rollback(tmp_path: Path) -> None:
101 lock = _DescriptorLock(str(tmp_path / "partial.lock"), is_singleton=False)
102 lock.acquire_error = RuntimeError("acquire failed")
103 lock.fail_release = True
104 with pytest.raises(BaseExceptionGroup) as info:
105 lock.acquire(timeout=0)
106 child_pid = _fork_descriptor_probe(cast("int", lock.descriptor), os.fstat)
107 _, status = os.waitpid(child_pid, 0)
108 lock.acquire_error = None
109 lock.fail_release = False
110 lock.release()
111
112 assert (
113 _error_details(info.value),
114 os.waitstatus_to_exitcode(status),
115 ) == (
116 [(RuntimeError, "acquire failed"), (RuntimeError, "unlock failed")],
117 0,
118 )
119
120
121 @pytest.mark.parametrize(
122 ("fail_release", "expected"),
123 [
124 pytest.param(
125 False,
126 [(RuntimeError, "acquire failed"), (OSError, "registration failed")],
127 id="rollback-succeeds",
128 ),
129 pytest.param(
130 True,
131 [
132 (RuntimeError, "acquire failed"),
133 (OSError, "registration failed"),
134 (RuntimeError, "unlock failed"),
135 ],
136 id="rollback-fails",
137 ),
138 ],
139 )
140 @NEEDS_FORK # pragma: needs fork
141 def test_acquisition_and_registration_errors_are_grouped(
142 tmp_path: Path,
143 mocker: MockerFixture,
144 *,
145 fail_release: bool,
146 expected: list[tuple[type[BaseException], str]],
147 ) -> None:
148 lock = _DescriptorLock(str(tmp_path / "registration.lock"), is_singleton=False)
149 lock.acquire_error = RuntimeError("acquire failed")
150 lock.fail_release = fail_release
151 real_fstat = os.fstat
152
153 def fail_registration(fd: int) -> os.stat_result:
154 assert fd == lock.descriptor
155 msg = "registration failed"
156 raise OSError(msg)
157
158 fstat_mock = mocker.patch("os.fstat", side_effect=fail_registration)
159 with pytest.raises(BaseExceptionGroup) as info:
160 lock.acquire(timeout=0)
161 descriptor = cast("int", lock.descriptor)
162 mocker.stop(fstat_mock)
163
164 child_pid = _fork_descriptor_probe(descriptor, real_fstat)
165 _, status = os.waitpid(child_pid, 0)
166 lock.acquire_error = None
167 lock.fail_release = False
168 lock.release(force=True)
169
170 with pytest.raises(OSError, match=rf"\[Errno {EBADF}\]"):
171 real_fstat(descriptor)
172 assert (_error_details(info.value), os.waitstatus_to_exitcode(status)) == (expected, 0)
173
174
175 @NEEDS_FORK # pragma: needs fork
176 def test_registration_failure_tracks_descriptor_when_rollback_fails(tmp_path: Path, mocker: MockerFixture) -> None:
177 lock = _DescriptorLock(str(tmp_path / "group.lock"), is_singleton=False)
178 lock.fail_release = True
179 real_fstat = os.fstat
180
181 def fail_registration(fd: int) -> os.stat_result:
182 assert fd == lock.descriptor
183 msg = "registration failed"
184 raise OSError(msg)
185
186 fstat_mock = mocker.patch("os.fstat", side_effect=fail_registration)
187 with pytest.raises(BaseExceptionGroup) as info:
188 lock.acquire(timeout=0)
189 descriptor = cast("int", lock.descriptor)
190 mocker.stop(fstat_mock)
191
192 child_pid = _fork_descriptor_probe(descriptor, real_fstat)
193 _, status = os.waitpid(child_pid, 0)
194 lock.fail_release = False
195 lock.release()
196
197 with pytest.raises(OSError, match=rf"\[Errno {EBADF}\]"):
198 real_fstat(descriptor)
199 assert (_error_details(info.value), os.waitstatus_to_exitcode(status)) == (
200 [(OSError, "registration failed"), (RuntimeError, "unlock failed")],
201 0,
202 )
203
204
205 @NEEDS_FORK # pragma: needs fork
206 def test_unverified_descriptor_does_not_close_reused_child_fd(tmp_path: Path) -> None:
207 script = """
208 from __future__ import annotations
209
210 import os
211 import sys
212
213 if sys.version_info >= (3, 11):
214 from builtins import BaseExceptionGroup # pragma: >=3.11 cover
215 else:
216 from exceptiongroup import BaseExceptionGroup
217
218 descriptor = -1
219 replacement_descriptor = -1
220 real_fstat = os.fstat
221
222 def replace_descriptor_in_child() -> None:
223 global replacement_descriptor
224 os.close(descriptor)
225 replacement_descriptor = os.open(sys.argv[2], os.O_CREAT | os.O_RDWR, 0o600)
226
227 os.register_at_fork(after_in_child=replace_descriptor_in_child)
228
229 from filelock import BaseFileLock
230
231 class FailingRollbackLock(BaseFileLock):
232 fail_release = True
233
234 def _acquire(self) -> None:
235 global descriptor
236 descriptor = self._context.lock_file_fd = os.open(self.lock_file, os.O_CREAT | os.O_RDWR, 0o600)
237
238 def _release(self) -> None:
239 if self.fail_release:
240 raise RuntimeError("rollback failed")
241 os.close(self._context.lock_file_fd if self._context.lock_file_fd is not None else -1)
242 self._context.lock_file_fd = None
243
244 def fail_descriptor_probe(fd: int) -> os.stat_result:
245 if fd == descriptor:
246 raise OSError("registration failed")
247 return real_fstat(fd)
248
249 os.fstat = fail_descriptor_probe
250 lock = FailingRollbackLock(sys.argv[1], is_singleton=False)
251 try:
252 lock.acquire(timeout=0)
253 except BaseExceptionGroup:
254 pass
255 else:
256 raise SystemExit(2)
257
258 child_pid = os.fork()
259 if child_pid == 0:
260 try:
261 real_fstat(replacement_descriptor)
262 except OSError:
263 os._exit(1)
264 os._exit(0 if replacement_descriptor == descriptor else 2)
265
266 _, status = os.waitpid(child_pid, 0)
267 os.fstat = real_fstat
268 lock.fail_release = False
269 lock.release()
270 raise SystemExit(os.waitstatus_to_exitcode(status))
271 """
272 result = subprocess.run(
273 [
274 sys.executable,
275 "-c",
276 script,
277 str(tmp_path / "lock"),
278 str(tmp_path / "replacement"),
279 ],
280 check=False,
281 capture_output=True,
282 text=True,
283 timeout=10,
284 )
285
286 assert (result.returncode, result.stderr) == (0, "")
287
288
289 @NEEDS_FORK # pragma: needs fork
290 def test_control_flow_registration_error_rolls_back_descriptor(tmp_path: Path, mocker: MockerFixture) -> None:
291 descriptors: list[int] = []
292
293 class StopAcquire(BaseException):
294 pass
295
296 class CapturingLock(_DescriptorLock):
297 def _acquire(self) -> None:
298 super()._acquire()
299 descriptors.append(cast("int", self._context.lock_file_fd))
300
301 real_fstat = os.fstat
302
303 def interrupt_registration(fd: int) -> os.stat_result:
304 assert fd == descriptors[0]
305 raise StopAcquire
306
307 mocker.patch("os.fstat", side_effect=interrupt_registration)
308 with pytest.raises(StopAcquire):
309 CapturingLock(str(tmp_path / "interrupt.lock"), is_singleton=False).acquire(timeout=0)
310
311 with pytest.raises(OSError, match=rf"\[Errno {EBADF}\]"):
312 real_fstat(descriptors[0])
313
314
315 @pytest.mark.asyncio
316 @NEEDS_FORK # pragma: needs fork
317 async def test_coroutine_registration_error_rolls_back_descriptor(tmp_path: Path, mocker: MockerFixture) -> None:
318 descriptors: list[int] = []
319 real_fstat = os.fstat
320
321 def fail_registration(fd: int) -> os.stat_result:
322 descriptors.append(fd)
323 msg = "registration failed"
324 raise OSError(msg)
325
326 mocker.patch("os.fstat", side_effect=fail_registration)
327 with pytest.raises(OSError, match="registration failed"):
328 await _CoroutineDescriptorLock(str(tmp_path / "coroutine.lock"), is_singleton=False).acquire(timeout=0)
329
330 with pytest.raises(OSError, match=rf"\[Errno {EBADF}\]"):
331 real_fstat(descriptors[0])
332
333
334 @pytest.mark.asyncio
335 async def test_coroutine_acquisition_failure_before_descriptor_propagates(tmp_path: Path) -> None:
336 acquisition_error = RuntimeError("acquire failed")
337 lock = _CoroutineDescriptorLock(str(tmp_path / "coroutine-empty.lock"), is_singleton=False)
338 lock.acquire_error_before_descriptor = acquisition_error
339
340 with pytest.raises(RuntimeError, match="acquire failed") as info:
341 await lock.acquire(timeout=0)
342
343 assert (info.value is acquisition_error, lock.is_locked) == (True, False)
344
345
346 @NEEDS_FORK # pragma: needs fork
347 @pytest.mark.asyncio
348 async def test_coroutine_acquisition_failure_keeps_descriptor_registered_until_rollback(tmp_path: Path) -> None:
349 lock = _CoroutineDescriptorLock(
350 str(tmp_path / "coroutine-partial.lock"), is_singleton=False, context_error_policy="group"
351 )
352 lock.acquire_error = RuntimeError("acquire failed")
353 lock.release_error = RuntimeError("release failed")
354 with pytest.raises(BaseExceptionGroup) as info:
355 await lock.acquire(timeout=0)
356 descriptor = cast("int", lock.descriptor)
357
358 child_pid = _fork_descriptor_probe(descriptor, os.fstat)
359 _, status = await asyncio.to_thread(os.waitpid, child_pid, 0)
360 lock.acquire_error = None
361 lock.release_error = None
362 await lock.release()
363
364 assert (_error_details(info.value), os.waitstatus_to_exitcode(status)) == (
365 [(RuntimeError, "acquire failed"), (RuntimeError, "release failed")],
366 0,
367 )
368
369
370 @pytest.mark.parametrize(
371 ("release_error", "expected"),
372 [
373 pytest.param(
374 None,
375 [(RuntimeError, "acquire failed"), (OSError, "registration failed")],
376 id="rollback-succeeds",
377 ),
378 pytest.param(
379 RuntimeError("release failed"),
380 [
381 (RuntimeError, "acquire failed"),
382 (OSError, "registration failed"),
383 (RuntimeError, "release failed"),
384 ],
385 id="rollback-fails",
386 ),
387 ],
388 )
389 @NEEDS_FORK # pragma: needs fork
390 @pytest.mark.asyncio
391 async def test_coroutine_acquisition_and_registration_errors_are_grouped(
392 tmp_path: Path,
393 mocker: MockerFixture,
394 release_error: BaseException | None,
395 expected: list[tuple[type[BaseException], str]],
396 ) -> None:
397 lock = _CoroutineDescriptorLock(str(tmp_path / "coroutine-registration.lock"), is_singleton=False)
398 lock.acquire_error = RuntimeError("acquire failed")
399 lock.release_error = release_error
400 real_fstat = os.fstat
401
402 def fail_registration(fd: int) -> os.stat_result:
403 assert fd == lock.descriptor
404 msg = "registration failed"
405 raise OSError(msg)
406
407 fstat_mock = mocker.patch("os.fstat", side_effect=fail_registration)
408 with pytest.raises(BaseExceptionGroup) as info:
409 await lock.acquire(timeout=0)
410 descriptor = cast("int", lock.descriptor)
411 mocker.stop(fstat_mock)
412
413 # Probe the closed descriptor before the fork and waitpid below, whose own opens could reclaim its freed number.
414 with pytest.raises(OSError, match=rf"\[Errno {EBADF}\]"):
415 real_fstat(descriptor)
416
417 child_pid = _fork_descriptor_probe(descriptor, real_fstat)
418 _, status = await asyncio.to_thread(os.waitpid, child_pid, 0)
419 lock.acquire_error = None
420 lock.release_error = None
421 await lock.release(force=True)
422
423 assert (_error_details(info.value), os.waitstatus_to_exitcode(status)) == (expected, 0)
424
425
426 @NEEDS_FORK # pragma: needs fork
427 @pytest.mark.asyncio
428 async def test_coroutine_registration_failure_tracks_descriptor_when_rollback_fails(
429 tmp_path: Path, mocker: MockerFixture
430 ) -> None:
431 lock = _CoroutineDescriptorLock(str(tmp_path / "coroutine-group.lock"), is_singleton=False)
432 lock.release_error_before_close = RuntimeError("rollback failed")
433 real_fstat = os.fstat
434
435 def fail_registration(fd: int) -> os.stat_result:
436 assert fd == lock.descriptor
437 msg = "registration failed"
438 raise OSError(msg)
439
440 fstat_mock = mocker.patch("os.fstat", side_effect=fail_registration)
441 with pytest.raises(BaseExceptionGroup) as info:
442 await lock.acquire(timeout=0)
443 descriptor = cast("int", lock.descriptor)
444 mocker.stop(fstat_mock)
445
446 child_pid = _fork_descriptor_probe(descriptor, real_fstat)
447 _, status = await asyncio.to_thread(os.waitpid, child_pid, 0)
448 lock.release_error_before_close = None
449 await lock.release()
450
451 with pytest.raises(OSError, match=rf"\[Errno {EBADF}\]"):
452 real_fstat(descriptor)
453 assert (_error_details(info.value), os.waitstatus_to_exitcode(status)) == (
454 [(OSError, "registration failed"), (RuntimeError, "rollback failed")],
455 0,
456 )
457
458
459 @NEEDS_GENERATOR_EXCEPTION_CONTEXT
460 @pytest.mark.asyncio
461 async def test_coroutine_on_acquired_error_preserves_context(tmp_path: Path) -> None:
462 callback_error = RuntimeError("hook failed")
463 prior_context = LookupError("prior callback failure")
464 callback_error.__context__ = prior_context
465
466 def fail_callback(_fd: int) -> None:
467 raise callback_error
468
469 lock = _CoroutineDescriptorLock(
470 str(tmp_path / "coroutine-hook-context.lock"), is_singleton=False, on_acquired=fail_callback
471 )
472 with pytest.raises(RuntimeError, match="hook failed") as info:
473 await lock.acquire(timeout=0)
474
475 assert (info.value is callback_error, callback_error.__context__, lock.is_locked) == (True, prior_context, False)
476
477
478 @pytest.mark.asyncio
479 async def test_coroutine_on_acquired_and_rollback_errors_are_grouped(tmp_path: Path) -> None:
480 callback_error = RuntimeError("hook failed")
481
482 def fail_callback(_fd: int) -> None:
483 raise callback_error
484
485 lock = _CoroutineDescriptorLock(
486 str(tmp_path / "coroutine-hook.lock"), is_singleton=False, on_acquired=fail_callback
487 )
488 lock.release_error = RuntimeError("release failed")
489 with pytest.raises(BaseExceptionGroup) as info:
490 await lock.acquire(timeout=0)
491
492 assert _error_details(info.value) == [
493 (RuntimeError, "hook failed"),
494 (RuntimeError, "release failed"),
495 ]
496
497
498 def _error_details(group: BaseExceptionGroup) -> list[tuple[type[BaseException], str]]:
499 return [(type(error), str(error)) for error in group.exceptions]
500
501
502 def _fork_descriptor_probe( # pragma: needs fork
503 descriptor: int, stat_descriptor: Callable[[int], os.stat_result]
504 ) -> int:
505 def probe_child() -> NoReturn:
506 with pytest.raises(OSError, match=rf"\[Errno {EBADF}\]"):
507 stat_descriptor(descriptor)
508 exit_child(0)
509
510 return fork_process(probe_child)