| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import contextlib |
| 4 |
import os |
| 5 |
import signal |
| 6 |
import subprocess # ruff:ignore[suspicious-subprocess-import] # isolates process-global audit hooks and fork exits |
| 7 |
import sys |
| 8 |
import textwrap |
| 9 |
from typing import TYPE_CHECKING, Final, Literal |
| 10 |
|
| 11 |
import pytest |
| 12 |
from capabilities import CAPABILITIES |
| 13 |
|
| 14 |
from filelock import ReadWriteLock |
| 15 |
from tests.capability_marks import ( |
| 16 |
NEEDS_AUDIT_EVENTS, |
| 17 |
NEEDS_COLLECTED_FINALIZATION, |
| 18 |
NEEDS_FORK, |
| 19 |
NEEDS_FORK1, |
| 20 |
) |
| 21 |
|
| 22 |
if TYPE_CHECKING: |
| 23 |
from pathlib import Path |
| 24 |
|
| 25 |
from _typeshed import StrOrBytesPath |
| 26 |
|
| 27 |
_NEEDS_FD_DIRECTORY: Final[pytest.MarkDecorator] = pytest.mark.skipif( |
| 28 |
not CAPABILITIES["fd-directory"], reason="counting open descriptors needs a /dev/fd or /proc/self/fd view" |
| 29 |
) |
| 30 |
|
| 31 |
|
| 32 |
@NEEDS_AUDIT_EVENTS |
| 33 |
def test_read_write_lock_closes_idle_connections(tmp_path: Path) -> None: |
| 34 |
lock_path = tmp_path / "idle.db" |
| 35 |
connection_events = 0 |
| 36 |
|
| 37 |
# Typed for the sqlite3.connect payload the hook reads; every other event returns before touching args. |
| 38 |
def audit_hook( # pragma: no cover - interpreter audit hooks run with tracing disabled |
| 39 |
event: str, args: tuple[StrOrBytesPath, ...] |
| 40 |
) -> None: |
| 41 |
nonlocal connection_events |
| 42 |
if event != "sqlite3.connect": |
| 43 |
return |
| 44 |
database = args[0] |
| 45 |
if isinstance(database, (str, bytes)) and os.fsdecode(database) == str(lock_path): |
| 46 |
connection_events += 1 |
| 47 |
|
| 48 |
sys.addaudithook(audit_hook) |
| 49 |
lock = ReadWriteLock(lock_path, is_singleton=False) |
| 50 |
lock.acquire_read() |
| 51 |
lock.acquire_read() |
| 52 |
lock.release() |
| 53 |
lock.release() |
| 54 |
lock.acquire_write() |
| 55 |
lock.release() |
| 56 |
lock_path.unlink() |
| 57 |
|
| 58 |
assert connection_events == 3 |
| 59 |
|
| 60 |
|
| 61 |
@_NEEDS_FD_DIRECTORY |
| 62 |
@NEEDS_COLLECTED_FINALIZATION |
| 63 |
def test_read_write_lock_dropped_instances_leave_no_descriptors(tmp_path: Path) -> None: # pragma: needs fd-directory |
| 64 |
result = _run_fork_script(_dropped_instances_script(), [str(tmp_path)], timeout=10) |
| 65 |
|
| 66 |
assert result == (0, "", "") |
| 67 |
|
| 68 |
|
| 69 |
@NEEDS_FORK # pragma: needs fork |
| 70 |
@NEEDS_COLLECTED_FINALIZATION |
| 71 |
def test_async_read_write_lock_allows_finalizer_reentry(tmp_path: Path) -> None: |
| 72 |
result = _run_fork_script( |
| 73 |
_reentrant_finalizer_script(), |
| 74 |
[str(tmp_path / "async.db"), str(tmp_path / "finalizer.db")], |
| 75 |
timeout=10, |
| 76 |
) |
| 77 |
|
| 78 |
assert result == (0, "", "") |
| 79 |
|
| 80 |
|
| 81 |
def test_read_write_lock_subclass_has_independent_singletons(tmp_path: Path) -> None: |
| 82 |
class DerivedReadWriteLock(ReadWriteLock): |
| 83 |
pass |
| 84 |
|
| 85 |
lock_path = tmp_path / "subclass.db" |
| 86 |
base_lock = ReadWriteLock(lock_path) |
| 87 |
derived_lock = DerivedReadWriteLock(lock_path) |
| 88 |
|
| 89 |
assert (derived_lock is DerivedReadWriteLock(lock_path), derived_lock is not base_lock) == (True, True) |
| 90 |
|
| 91 |
|
| 92 |
@pytest.mark.parametrize( |
| 93 |
"audit_event", |
| 94 |
[ |
| 95 |
pytest.param("sqlite3.connect", marks=NEEDS_AUDIT_EVENTS, id="sqlite-connect"), |
| 96 |
pytest.param( |
| 97 |
"ctypes.dlsym", |
| 98 |
marks=pytest.mark.skipif( |
| 99 |
sys.implementation.name != "cpython" or sys.version_info >= (3, 12) or sys.platform == "win32", |
| 100 |
reason="connection escrow uses this audit event only on POSIX CPython before 3.12", |
| 101 |
), |
| 102 |
id="ctypes-dlsym", |
| 103 |
), |
| 104 |
], |
| 105 |
) |
| 106 |
def test_read_write_lock_rejects_recursive_singleton_construction(tmp_path: Path, audit_event: str) -> None: |
| 107 |
result = subprocess.run( # executes this test's fixed interpreter and source |
| 108 |
[sys.executable, "-c", _recursive_construction_script(), str(tmp_path / "construction.db"), audit_event], |
| 109 |
capture_output=True, |
| 110 |
check=False, |
| 111 |
text=True, |
| 112 |
timeout=10, |
| 113 |
) |
| 114 |
|
| 115 |
assert (result.returncode, result.stderr) == (0, "") |
| 116 |
|
| 117 |
|
| 118 |
@pytest.mark.skipif( |
| 119 |
sys.implementation.name != "cpython" or sys.version_info >= (3, 12), |
| 120 |
reason="connection escrow uses CPython reference functions before 3.12", |
| 121 |
) |
| 122 |
def test_read_write_lock_escrow_ignores_shared_ctypes_signatures(tmp_path: Path) -> None: # pragma: <3.12 cover |
| 123 |
result = subprocess.run( # executes this test's fixed interpreter and source |
| 124 |
[sys.executable, "-c", _ctypes_signature_script(), str(tmp_path / "ctypes.db")], |
| 125 |
capture_output=True, |
| 126 |
check=False, |
| 127 |
text=True, |
| 128 |
timeout=10, |
| 129 |
) |
| 130 |
|
| 131 |
assert (result.returncode, result.stderr) == (0, "") |
| 132 |
|
| 133 |
|
| 134 |
@pytest.mark.parametrize( |
| 135 |
"operation", |
| 136 |
[ |
| 137 |
pytest.param("acquire", id="acquire"), |
| 138 |
pytest.param("release", id="release"), |
| 139 |
pytest.param("close", id="close"), |
| 140 |
], |
| 141 |
) |
| 142 |
@NEEDS_AUDIT_EVENTS |
| 143 |
def test_read_write_lock_rejects_same_thread_operation_during_acquisition( |
| 144 |
tmp_path: Path, operation: Literal["acquire", "release", "close"] |
| 145 |
) -> None: |
| 146 |
result = subprocess.run( # executes this test's fixed interpreter and source |
| 147 |
[sys.executable, "-c", _recursive_acquisition_script(), str(tmp_path / "acquisition.db"), operation], |
| 148 |
capture_output=True, |
| 149 |
check=False, |
| 150 |
text=True, |
| 151 |
timeout=10, |
| 152 |
) |
| 153 |
|
| 154 |
assert (result.returncode, result.stderr) == (0, "") |
| 155 |
|
| 156 |
|
| 157 |
@pytest.mark.parametrize( |
| 158 |
"operation", |
| 159 |
[ |
| 160 |
pytest.param("release", id="release"), |
| 161 |
pytest.param("close", id="close"), |
| 162 |
], |
| 163 |
) |
| 164 |
@NEEDS_AUDIT_EVENTS |
| 165 |
def test_read_write_lock_serializes_other_thread_operation_during_acquisition( |
| 166 |
tmp_path: Path, operation: Literal["release", "close"] |
| 167 |
) -> None: |
| 168 |
result = subprocess.run( # executes this test's fixed interpreter and source |
| 169 |
[sys.executable, "-c", _concurrent_operation_script(), str(tmp_path / "concurrent.db"), operation], |
| 170 |
capture_output=True, |
| 171 |
check=False, |
| 172 |
text=True, |
| 173 |
timeout=10, |
| 174 |
) |
| 175 |
|
| 176 |
assert (result.returncode, result.stderr) == (0, "") |
| 177 |
|
| 178 |
|
| 179 |
@NEEDS_FORK # pragma: needs fork |
| 180 |
@pytest.mark.parametrize( |
| 181 |
("mode", "fork_name", "reject_audit_hook"), |
| 182 |
[ |
| 183 |
pytest.param("read", "fork", False, id="read-fork"), |
| 184 |
pytest.param("write", "fork", False, id="write-fork"), |
| 185 |
pytest.param("write", "fork", True, id="write-fork-rejected-audit-hook"), |
| 186 |
pytest.param( |
| 187 |
"read", |
| 188 |
"fork1", |
| 189 |
False, |
| 190 |
marks=NEEDS_FORK1, |
| 191 |
id="read-fork1", |
| 192 |
), |
| 193 |
pytest.param( |
| 194 |
"write", |
| 195 |
"fork1", |
| 196 |
False, |
| 197 |
marks=NEEDS_FORK1, |
| 198 |
id="write-fork1", |
| 199 |
), |
| 200 |
], |
| 201 |
) |
| 202 |
def test_read_write_lock_survives_normal_fork_child_exit( |
| 203 |
tmp_path: Path, |
| 204 |
mode: Literal["read", "write"], |
| 205 |
fork_name: Literal["fork", "fork1"], |
| 206 |
reject_audit_hook: bool, |
| 207 |
) -> None: |
| 208 |
result = _run_fork_script( |
| 209 |
_fork_script(), |
| 210 |
[ |
| 211 |
str(tmp_path / "fork.db"), |
| 212 |
mode, |
| 213 |
fork_name, |
| 214 |
"reject" if reject_audit_hook else "allow", |
| 215 |
], |
| 216 |
timeout=15, |
| 217 |
) |
| 218 |
|
| 219 |
assert result == (0, "", "") |
| 220 |
|
| 221 |
|
| 222 |
@NEEDS_FORK # pragma: needs fork |
| 223 |
def test_read_write_lock_fork_waits_for_sqlite_operation(tmp_path: Path) -> None: |
| 224 |
result = _run_fork_script(_fork_during_sqlite_script(), [str(tmp_path / "fork-gate.db")], timeout=15) |
| 225 |
|
| 226 |
assert result == (0, "", "") |
| 227 |
|
| 228 |
|
| 229 |
@pytest.mark.skipif( |
| 230 |
sys.implementation.name != "cpython" or not hasattr(os, "fork"), |
| 231 |
reason="requires CPython profile events and os.fork", |
| 232 |
) |
| 233 |
@pytest.mark.parametrize( |
| 234 |
"boundary", |
| 235 |
[ |
| 236 |
pytest.param("executescript", id="execute"), |
| 237 |
pytest.param("rollback", id="rollback"), |
| 238 |
pytest.param("close", id="close"), |
| 239 |
pytest.param("connection-return", id="connection-return"), |
| 240 |
], |
| 241 |
) |
| 242 |
def test_read_write_lock_fork_at_sqlite_boundary_exits_child( # pragma: needs fork |
| 243 |
tmp_path: Path, boundary: Literal["executescript", "rollback", "close", "connection-return"] |
| 244 |
) -> None: |
| 245 |
result = _run_fork_script( |
| 246 |
_fork_at_sqlite_boundary_script(), |
| 247 |
[str(tmp_path / "fork-boundary.db"), boundary], |
| 248 |
timeout=10, |
| 249 |
) |
| 250 |
|
| 251 |
assert result == (0, "", "") |
| 252 |
|
| 253 |
|
| 254 |
@NEEDS_FORK # pragma: needs fork |
| 255 |
def test_read_write_lock_idle_fork_handles_fresh_child_lock(tmp_path: Path) -> None: |
| 256 |
result = _run_fork_script(_idle_fork_script(), [str(tmp_path / "idle-fork.db")], timeout=10) |
| 257 |
|
| 258 |
assert result == (0, "", "") |
| 259 |
|
| 260 |
|
| 261 |
@pytest.mark.skipif(sys.implementation.name != "pypy" or not hasattr(os, "fork"), reason="requires fork on PyPy") |
| 262 |
def test_read_write_lock_pypy_child_allows_without_known_sqlite_use(tmp_path: Path) -> None: # pragma: pypy cover |
| 263 |
result = _run_fork_script( |
| 264 |
_pypy_fork_script(), |
| 265 |
[str(tmp_path / "child.db")], |
| 266 |
timeout=10, |
| 267 |
) |
| 268 |
|
| 269 |
assert result == (0, "", "") |
| 270 |
|
| 271 |
|
| 272 |
@pytest.mark.skipif(sys.implementation.name != "pypy" or not hasattr(os, "fork"), reason="requires fork on PyPy") |
| 273 |
def test_read_write_lock_pypy_child_rejects_after_external_sqlite_use(tmp_path: Path) -> None: # pragma: pypy cover |
| 274 |
result = _run_fork_script( |
| 275 |
_pypy_external_sqlite_script(), |
| 276 |
[str(tmp_path / "external.db"), str(tmp_path / "child.db")], |
| 277 |
timeout=10, |
| 278 |
) |
| 279 |
|
| 280 |
assert result == (0, "", "") |
| 281 |
|
| 282 |
|
| 283 |
def test_fork_script_terminates_timed_out_process_group() -> None: |
| 284 |
with pytest.raises(AssertionError, match="fork script exceeded"): |
| 285 |
_run_fork_script("import time; time.sleep(10)", [], timeout=0.01) |
| 286 |
|
| 287 |
|
| 288 |
@NEEDS_FORK # pragma: needs fork |
| 289 |
def test_read_write_lock_subclass_cache_resets_after_fork(tmp_path: Path) -> None: |
| 290 |
result = _run_fork_script(_subclass_fork_script(), [str(tmp_path / "subclass-fork.db")], timeout=10) |
| 291 |
|
| 292 |
assert result == (0, "", "") |
| 293 |
|
| 294 |
|
| 295 |
@NEEDS_FORK # pragma: needs fork |
| 296 |
@pytest.mark.parametrize("held", [pytest.param(False, id="idle"), pytest.param(True, id="held")]) |
| 297 |
def test_async_read_write_lock_fork_behavior(tmp_path: Path, held: bool) -> None: |
| 298 |
result = _run_fork_script( |
| 299 |
_async_fork_script(), |
| 300 |
[str(tmp_path / "async-fork.db"), "held" if held else "idle"], |
| 301 |
timeout=15, |
| 302 |
) |
| 303 |
|
| 304 |
assert result == (0, "", "") |
| 305 |
|
| 306 |
|
| 307 |
def _run_fork_script(script: str, arguments: list[str], *, timeout: float) -> tuple[int, str, str]: |
| 308 |
process = subprocess.Popen( # executes this test's fixed interpreter and source |
| 309 |
[sys.executable, "-c", script, *arguments], |
| 310 |
start_new_session=True, |
| 311 |
stderr=subprocess.PIPE, |
| 312 |
stdout=subprocess.PIPE, |
| 313 |
text=True, |
| 314 |
) |
| 315 |
try: |
| 316 |
process_output, process_error = process.communicate(timeout=timeout) |
| 317 |
except subprocess.TimeoutExpired as error: |
| 318 |
with contextlib.suppress(ProcessLookupError): |
| 319 |
if sys.platform == "win32": # pragma: win32 cover |
| 320 |
process.kill() |
| 321 |
else: # pragma: win32 no cover |
| 322 |
os.killpg(process.pid, signal.SIGKILL) |
| 323 |
process_output, process_error = process.communicate() |
| 324 |
msg = f"fork script exceeded {timeout} seconds: stdout={process_output!r}, stderr={process_error!r}" |
| 325 |
raise AssertionError(msg) from error |
| 326 |
assert process.returncode is not None # pragma: needs fork |
| 327 |
return process.returncode, process_output, process_error # pragma: needs fork |
| 328 |
|
| 329 |
|
| 330 |
def _dropped_instances_script() -> str: # pragma: needs fd-directory |
| 331 |
return textwrap.dedent( |
| 332 |
""" |
| 333 |
from __future__ import annotations |
| 334 |
|
| 335 |
import gc |
| 336 |
import sys |
| 337 |
from pathlib import Path |
| 338 |
|
| 339 |
from filelock import ReadWriteLock |
| 340 |
|
| 341 |
root = Path(sys.argv[1]) |
| 342 |
descriptor_path = Path("/dev/fd") if Path("/dev/fd").is_dir() else Path("/proc/self/fd") |
| 343 |
gc.collect() |
| 344 |
initial_count = sum(1 for _ in descriptor_path.iterdir()) |
| 345 |
for index in range(100): |
| 346 |
lock = ReadWriteLock(root / f"dropped-{index}.db", is_singleton=False) |
| 347 |
lock.acquire_write() |
| 348 |
del lock |
| 349 |
gc.collect() |
| 350 |
|
| 351 |
assert sum(1 for _ in descriptor_path.iterdir()) == initial_count |
| 352 |
with ReadWriteLock(root / "dropped-0.db", is_singleton=False).read_lock(): |
| 353 |
pass |
| 354 |
""" |
| 355 |
) |
| 356 |
|
| 357 |
|
| 358 |
def _reentrant_finalizer_script() -> str: # pragma: needs fork |
| 359 |
return textwrap.dedent( |
| 360 |
""" |
| 361 |
from __future__ import annotations |
| 362 |
|
| 363 |
import asyncio |
| 364 |
import gc |
| 365 |
import sys |
| 366 |
import weakref |
| 367 |
from threading import Condition, Event |
| 368 |
from types import CodeType, FrameType |
| 369 |
from typing import Final |
| 370 |
|
| 371 |
from filelock import AsyncReadWriteLock, ReadWriteLock |
| 372 |
|
| 373 |
class _FinalizerTarget: |
| 374 |
cycle: _FinalizerTarget |
| 375 |
|
| 376 |
_FINALIZED: Final[Event] = Event() |
| 377 |
|
| 378 |
def _close_lock() -> None: |
| 379 |
ReadWriteLock(sys.argv[2], is_singleton=False).close() |
| 380 |
_FINALIZED.set() |
| 381 |
|
| 382 |
_TARGET = _FinalizerTarget() |
| 383 |
_TARGET.cycle = _TARGET |
| 384 |
weakref.finalize(_TARGET, _close_lock) |
| 385 |
del _TARGET |
| 386 |
|
| 387 |
_NOTIFY_CODE: Final[CodeType] = Condition.notify_all.__code__ |
| 388 |
|
| 389 |
def _collect_at_notify(frame: FrameType, _event: str, _argument: None) -> None: |
| 390 |
if frame.f_code is _NOTIFY_CODE: |
| 391 |
sys.settrace(None) |
| 392 |
gc.collect() |
| 393 |
|
| 394 |
sys.settrace(_collect_at_notify) |
| 395 |
_LOCK: Final[AsyncReadWriteLock] = AsyncReadWriteLock(sys.argv[1], is_singleton=False) |
| 396 |
sys.settrace(None) |
| 397 |
|
| 398 |
assert _FINALIZED.is_set() |
| 399 |
asyncio.run(_LOCK.close()) |
| 400 |
""" |
| 401 |
) |
| 402 |
|
| 403 |
|
| 404 |
def _recursive_construction_script() -> str: |
| 405 |
return textwrap.dedent( |
| 406 |
""" |
| 407 |
from __future__ import annotations |
| 408 |
|
| 409 |
import sys |
| 410 |
|
| 411 |
from filelock import ReadWriteLock |
| 412 |
|
| 413 |
lock_path, audit_event = sys.argv[1:] |
| 414 |
armed = True |
| 415 |
|
| 416 |
from typing import TYPE_CHECKING |
| 417 |
|
| 418 |
if TYPE_CHECKING: |
| 419 |
from _typeshed import Unused |
| 420 |
|
| 421 |
def audit_hook(event: str, _args: Unused) -> None: |
| 422 |
if armed and event == audit_event: |
| 423 |
ReadWriteLock(lock_path) |
| 424 |
|
| 425 |
sys.addaudithook(audit_hook) |
| 426 |
try: |
| 427 |
ReadWriteLock(lock_path) |
| 428 |
except RuntimeError as error: |
| 429 |
assert str(error) == f"Singleton lock construction is already active for {lock_path}" |
| 430 |
else: |
| 431 |
raise AssertionError("recursive singleton construction succeeded") |
| 432 |
|
| 433 |
armed = False |
| 434 |
with ReadWriteLock(lock_path).read_lock(): |
| 435 |
pass |
| 436 |
""" |
| 437 |
) |
| 438 |
|
| 439 |
|
| 440 |
def _recursive_acquisition_script() -> str: |
| 441 |
return textwrap.dedent( |
| 442 |
""" |
| 443 |
from __future__ import annotations |
| 444 |
|
| 445 |
import sys |
| 446 |
|
| 447 |
from filelock import ReadWriteLock |
| 448 |
|
| 449 |
lock_path, operation = sys.argv[1:] |
| 450 |
lock = ReadWriteLock(lock_path) |
| 451 |
armed = True |
| 452 |
|
| 453 |
from typing import TYPE_CHECKING |
| 454 |
|
| 455 |
if TYPE_CHECKING: |
| 456 |
from _typeshed import Unused |
| 457 |
|
| 458 |
def audit_hook(event: str, _args: Unused) -> None: |
| 459 |
if armed and event == "sqlite3.connect": |
| 460 |
if operation == "acquire": |
| 461 |
lock.acquire_read() |
| 462 |
elif operation == "release": |
| 463 |
lock.release() |
| 464 |
else: |
| 465 |
lock.close() |
| 466 |
|
| 467 |
sys.addaudithook(audit_hook) |
| 468 |
try: |
| 469 |
lock.acquire_read() |
| 470 |
except RuntimeError as error: |
| 471 |
assert str(error) == ( |
| 472 |
f"Cannot {operation} ReadWriteLock on {lock_path} while acquisition is active in this thread" |
| 473 |
) |
| 474 |
else: |
| 475 |
raise AssertionError(f"recursive {operation} succeeded") |
| 476 |
|
| 477 |
armed = False |
| 478 |
with lock.read_lock(): |
| 479 |
pass |
| 480 |
""" |
| 481 |
) |
| 482 |
|
| 483 |
|
| 484 |
def _ctypes_signature_script() -> str: # pragma: <3.12 cover |
| 485 |
return textwrap.dedent( |
| 486 |
""" |
| 487 |
from __future__ import annotations |
| 488 |
|
| 489 |
import ctypes |
| 490 |
import sys |
| 491 |
|
| 492 |
ctypes.pythonapi.Py_IncRef.argtypes = (ctypes.c_void_p,) |
| 493 |
from filelock import ReadWriteLock |
| 494 |
|
| 495 |
lock = ReadWriteLock(sys.argv[1], is_singleton=False) |
| 496 |
lock.acquire_read() |
| 497 |
ctypes.pythonapi.Py_DecRef.argtypes = (ctypes.c_void_p,) |
| 498 |
lock.release() |
| 499 |
with ReadWriteLock(sys.argv[1], is_singleton=False).write_lock(): |
| 500 |
pass |
| 501 |
""" |
| 502 |
) |
| 503 |
|
| 504 |
|
| 505 |
def _concurrent_operation_script() -> str: |
| 506 |
return textwrap.dedent( |
| 507 |
""" |
| 508 |
from __future__ import annotations |
| 509 |
|
| 510 |
import queue |
| 511 |
import sqlite3 |
| 512 |
import sys |
| 513 |
import threading |
| 514 |
|
| 515 |
from filelock import ReadWriteLock |
| 516 |
|
| 517 |
lock_path, operation = sys.argv[1:] |
| 518 |
lock = ReadWriteLock(lock_path) |
| 519 |
acquisition_inside_connect = threading.Event() |
| 520 |
continue_acquisition = threading.Event() |
| 521 |
acquire_errors: queue.SimpleQueue[BaseException] = queue.SimpleQueue() |
| 522 |
operation_errors: queue.SimpleQueue[BaseException] = queue.SimpleQueue() |
| 523 |
armed = True |
| 524 |
|
| 525 |
from typing import TYPE_CHECKING |
| 526 |
|
| 527 |
if TYPE_CHECKING: |
| 528 |
from _typeshed import Unused |
| 529 |
|
| 530 |
def audit_hook(event: str, _args: Unused) -> None: |
| 531 |
if armed and event == "sqlite3.connect": |
| 532 |
acquisition_inside_connect.set() |
| 533 |
assert continue_acquisition.wait(5) |
| 534 |
|
| 535 |
def acquire() -> None: |
| 536 |
try: |
| 537 |
lock.acquire_write() |
| 538 |
except BaseException as error: |
| 539 |
acquire_errors.put(error) |
| 540 |
|
| 541 |
def operate() -> None: |
| 542 |
try: |
| 543 |
getattr(lock, operation)() |
| 544 |
except BaseException as error: |
| 545 |
operation_errors.put(error) |
| 546 |
|
| 547 |
sys.addaudithook(audit_hook) |
| 548 |
acquire_thread = threading.Thread(target=acquire) |
| 549 |
acquire_thread.start() |
| 550 |
assert acquisition_inside_connect.wait(5) |
| 551 |
operation_thread = threading.Thread(target=operate) |
| 552 |
operation_thread.start() |
| 553 |
operation_thread.join(0.1) |
| 554 |
assert operation_thread.is_alive() |
| 555 |
armed = False |
| 556 |
continue_acquisition.set() |
| 557 |
acquire_thread.join(5) |
| 558 |
operation_thread.join(5) |
| 559 |
assert not acquire_thread.is_alive() |
| 560 |
assert not operation_thread.is_alive() |
| 561 |
assert acquire_errors.empty() |
| 562 |
assert operation_errors.empty() |
| 563 |
if operation == "release": |
| 564 |
with lock.write_lock(): |
| 565 |
pass |
| 566 |
else: |
| 567 |
try: |
| 568 |
lock.acquire_read() |
| 569 |
except sqlite3.ProgrammingError as error: |
| 570 |
assert str(error) == "Cannot operate on a closed database." |
| 571 |
else: |
| 572 |
raise AssertionError("concurrent acquisition reopened a closed lock") |
| 573 |
""" |
| 574 |
) |
| 575 |
|
| 576 |
|
| 577 |
def _fork_script() -> str: |
| 578 |
return textwrap.dedent( |
| 579 |
""" |
| 580 |
from __future__ import annotations |
| 581 |
|
| 582 |
import gc |
| 583 |
import os |
| 584 |
import sqlite3 |
| 585 |
import sys |
| 586 |
from typing import TYPE_CHECKING |
| 587 |
|
| 588 |
if TYPE_CHECKING: |
| 589 |
from _typeshed import Unused |
| 590 |
|
| 591 |
lock_path, mode, fork_name, audit_hook_mode = sys.argv[1:] |
| 592 |
if audit_hook_mode == "reject": |
| 593 |
def reject_filelock_audit_hook(event: str, _args: Unused) -> None: |
| 594 |
if event == "sys.addaudithook": |
| 595 |
raise RuntimeError("audit hook registration rejected") |
| 596 |
|
| 597 |
sys.addaudithook(reject_filelock_audit_hook) |
| 598 |
|
| 599 |
from filelock import ReadWriteLock, Timeout |
| 600 |
|
| 601 |
lock = ReadWriteLock(lock_path, is_singleton=False) |
| 602 |
acquire = lock.acquire_read if mode == "read" else lock.acquire_write |
| 603 |
proxy = acquire() |
| 604 |
parent_to_child_read, parent_to_child_write = os.pipe() |
| 605 |
child_to_parent_read, child_to_parent_write = os.pipe() |
| 606 |
|
| 607 |
child_pid = getattr(os, fork_name)() |
| 608 |
if child_pid == 0: |
| 609 |
os.close(parent_to_child_write) |
| 610 |
os.close(child_to_parent_read) |
| 611 |
try: |
| 612 |
with proxy: |
| 613 |
pass |
| 614 |
try: |
| 615 |
lock.acquire_read() |
| 616 |
except RuntimeError as error: |
| 617 |
assert "was invalidated by fork()" in str(error) |
| 618 |
else: |
| 619 |
raise AssertionError("inherited acquisition succeeded") |
| 620 |
lock.release() |
| 621 |
lock.close() |
| 622 |
del proxy |
| 623 |
del lock |
| 624 |
gc.collect() |
| 625 |
sqlite_connects = 0 |
| 626 |
|
| 627 |
def count_sqlite_connects(event: str, _args: Unused) -> None: |
| 628 |
global sqlite_connects |
| 629 |
if event == "sqlite3.connect": |
| 630 |
sqlite_connects += 1 |
| 631 |
|
| 632 |
sys.addaudithook(count_sqlite_connects) |
| 633 |
try: |
| 634 |
ReadWriteLock(lock_path, is_singleton=False) |
| 635 |
except RuntimeError as error: |
| 636 |
expected = ( |
| 637 |
"ReadWriteLock is unavailable in a PyPy fork child" |
| 638 |
if sys.implementation.name == "pypy" |
| 639 |
else "was active across fork(); exec or exit" |
| 640 |
) |
| 641 |
assert expected in str(error) |
| 642 |
else: |
| 643 |
raise AssertionError("child reopened a database active during fork") |
| 644 |
assert sqlite_connects == 0 |
| 645 |
os.write(child_to_parent_write, b"1") |
| 646 |
assert os.read(parent_to_child_read, 1) == b"1" |
| 647 |
except BaseException: |
| 648 |
import traceback |
| 649 |
|
| 650 |
traceback.print_exc() |
| 651 |
sys.exit(1) |
| 652 |
sys.exit(0) |
| 653 |
|
| 654 |
os.close(parent_to_child_read) |
| 655 |
os.close(child_to_parent_write) |
| 656 |
assert os.read(child_to_parent_read, 1) == b"1" |
| 657 |
contender = ReadWriteLock(lock_path, is_singleton=False) |
| 658 |
conflicting_acquire = contender.acquire_write if mode == "read" else contender.acquire_read |
| 659 |
try: |
| 660 |
conflicting_acquire(blocking=False) |
| 661 |
except Timeout: |
| 662 |
pass |
| 663 |
else: |
| 664 |
raise AssertionError("child exit released the parent's lock") |
| 665 |
lock.release() |
| 666 |
os.write(parent_to_child_write, b"1") |
| 667 |
_, status = os.waitpid(child_pid, 0) |
| 668 |
assert os.waitstatus_to_exitcode(status) == 0 |
| 669 |
with sqlite3.connect(lock_path) as connection: |
| 670 |
assert connection.execute("PRAGMA integrity_check").fetchone() == ("ok",) |
| 671 |
""" |
| 672 |
) |
| 673 |
|
| 674 |
|
| 675 |
def _fork_during_sqlite_script() -> str: # pragma: needs fork |
| 676 |
return textwrap.dedent( |
| 677 |
r""" |
| 678 |
from __future__ import annotations |
| 679 |
|
| 680 |
import os |
| 681 |
import queue |
| 682 |
import sqlite3 |
| 683 |
import sys |
| 684 |
import threading |
| 685 |
import time |
| 686 |
import warnings |
| 687 |
from typing import TYPE_CHECKING |
| 688 |
|
| 689 |
if TYPE_CHECKING: |
| 690 |
from _typeshed import StrOrBytesPath |
| 691 |
|
| 692 |
from filelock import ReadWriteLock |
| 693 |
|
| 694 |
warnings.filterwarnings("ignore", category=DeprecationWarning, message=r".*fork\(\).*") |
| 695 |
|
| 696 |
lock_path = sys.argv[1] |
| 697 |
waiter = ReadWriteLock(lock_path, is_singleton=False) |
| 698 |
holder = sqlite3.connect(lock_path, check_same_thread=False) |
| 699 |
holder.executescript("PRAGMA journal_mode=MEMORY; BEGIN EXCLUSIVE TRANSACTION;").close() |
| 700 |
waiter_inside_connect = threading.Event() |
| 701 |
continue_connect = threading.Event() |
| 702 |
acquisition_errors: queue.SimpleQueue[BaseException] = queue.SimpleQueue() |
| 703 |
armed = True |
| 704 |
|
| 705 |
# Typed for the sqlite3.connect payload the hook reads; every other event returns before touching args. |
| 706 |
def audit_hook(event: str, args: tuple[StrOrBytesPath, ...]) -> None: |
| 707 |
if not armed or event != "sqlite3.connect": |
| 708 |
return |
| 709 |
database = args[0] |
| 710 |
if ( |
| 711 |
isinstance(database, (str, bytes)) |
| 712 |
and os.fsdecode(database) == lock_path |
| 713 |
): |
| 714 |
waiter_inside_connect.set() |
| 715 |
assert continue_connect.wait(5) |
| 716 |
|
| 717 |
def acquire() -> None: |
| 718 |
try: |
| 719 |
with waiter.read_lock(timeout=5): |
| 720 |
pass |
| 721 |
except BaseException as error: |
| 722 |
acquisition_errors.put(error) |
| 723 |
|
| 724 |
def release_holder() -> None: |
| 725 |
threading.Event().wait(0.2) |
| 726 |
continue_connect.set() |
| 727 |
holder.rollback() |
| 728 |
holder.close() |
| 729 |
|
| 730 |
sys.addaudithook(audit_hook) |
| 731 |
waiter_thread = threading.Thread(target=acquire) |
| 732 |
waiter_thread.start() |
| 733 |
assert waiter_inside_connect.wait(5) |
| 734 |
release_thread = threading.Thread(target=release_holder) |
| 735 |
release_thread.start() |
| 736 |
start = time.monotonic() |
| 737 |
child_pid = os.fork() |
| 738 |
elapsed = time.monotonic() - start |
| 739 |
if child_pid == 0: |
| 740 |
sys.exit(0) |
| 741 |
armed = False |
| 742 |
_, status = os.waitpid(child_pid, 0) |
| 743 |
waiter_thread.join(5) |
| 744 |
release_thread.join(5) |
| 745 |
assert os.waitstatus_to_exitcode(status) == 0 |
| 746 |
assert elapsed >= 0.1 |
| 747 |
assert not waiter_thread.is_alive() |
| 748 |
assert not release_thread.is_alive() |
| 749 |
if not acquisition_errors.empty(): |
| 750 |
raise acquisition_errors.get() |
| 751 |
""" |
| 752 |
) |
| 753 |
|
| 754 |
|
| 755 |
def _fork_at_sqlite_boundary_script() -> str: |
| 756 |
return textwrap.dedent( |
| 757 |
""" |
| 758 |
from __future__ import annotations |
| 759 |
|
| 760 |
import os |
| 761 |
import sqlite3 |
| 762 |
import sys |
| 763 |
from types import FrameType |
| 764 |
from typing import TYPE_CHECKING, Protocol |
| 765 |
|
| 766 |
if TYPE_CHECKING: |
| 767 |
from _typeshed import Unused |
| 768 |
|
| 769 |
class ProfiledCall(Protocol): |
| 770 |
@property |
| 771 |
def __name__(self) -> str: ... |
| 772 |
|
| 773 |
def reject_filelock_audit_hook(event: str, _args: Unused) -> None: |
| 774 |
if event == "sys.addaudithook": |
| 775 |
raise RuntimeError("audit hook registration rejected") |
| 776 |
|
| 777 |
sys.addaudithook(reject_filelock_audit_hook) |
| 778 |
|
| 779 |
from filelock import ReadWriteLock |
| 780 |
|
| 781 |
lock_path, boundary = sys.argv[1:] |
| 782 |
child_pids: list[int] = [] |
| 783 |
armed = True |
| 784 |
|
| 785 |
def profile( |
| 786 |
_frame: FrameType, |
| 787 |
event: str, |
| 788 |
value: ProfiledCall | sqlite3.Connection | None, |
| 789 |
) -> None: |
| 790 |
global armed |
| 791 |
connection_returned = boundary == "connection-return" and event == "return" and isinstance( |
| 792 |
value, sqlite3.Connection |
| 793 |
) |
| 794 |
sqlite_called = ( |
| 795 |
boundary != "connection-return" |
| 796 |
and event == "c_call" |
| 797 |
and value is not None |
| 798 |
and value.__name__ == boundary |
| 799 |
) |
| 800 |
if armed and (connection_returned or sqlite_called): |
| 801 |
armed = False |
| 802 |
child_pids.append(os.fork()) |
| 803 |
|
| 804 |
sys.setprofile(profile) |
| 805 |
with ReadWriteLock(lock_path, is_singleton=False).write_lock(): |
| 806 |
pass |
| 807 |
sys.setprofile(None) |
| 808 |
|
| 809 |
assert len(child_pids) == 1 |
| 810 |
_, status = os.waitpid(child_pids[0], 0) |
| 811 |
assert os.waitstatus_to_exitcode(status) == 70 |
| 812 |
""" |
| 813 |
) |
| 814 |
|
| 815 |
|
| 816 |
def _idle_fork_script() -> str: |
| 817 |
return textwrap.dedent( |
| 818 |
""" |
| 819 |
from __future__ import annotations |
| 820 |
|
| 821 |
import os |
| 822 |
import sys |
| 823 |
|
| 824 |
from filelock import ReadWriteLock |
| 825 |
|
| 826 |
lock_path = sys.argv[1] |
| 827 |
inherited_lock = ReadWriteLock(lock_path, is_singleton=False) |
| 828 |
child_pid = os.fork() |
| 829 |
if child_pid == 0: |
| 830 |
try: |
| 831 |
inherited_lock.acquire_read() |
| 832 |
except RuntimeError as error: |
| 833 |
assert "was invalidated by fork()" in str(error) |
| 834 |
else: |
| 835 |
raise AssertionError("inherited idle lock acquired") |
| 836 |
if sys.implementation.name == "pypy": |
| 837 |
try: |
| 838 |
ReadWriteLock(lock_path, is_singleton=False) |
| 839 |
except RuntimeError as error: |
| 840 |
assert str(error) == ( |
| 841 |
"ReadWriteLock is unavailable in a PyPy fork child; exec or exit before using it" |
| 842 |
) |
| 843 |
else: |
| 844 |
raise AssertionError("PyPy child opened SQLite after fork") |
| 845 |
else: |
| 846 |
with ReadWriteLock(lock_path, is_singleton=False).write_lock(): |
| 847 |
pass |
| 848 |
sys.exit(0) |
| 849 |
_, status = os.waitpid(child_pid, 0) |
| 850 |
assert os.waitstatus_to_exitcode(status) == 0 |
| 851 |
""" |
| 852 |
) |
| 853 |
|
| 854 |
|
| 855 |
def _pypy_fork_script() -> str: # pragma: pypy cover |
| 856 |
return textwrap.dedent( |
| 857 |
""" |
| 858 |
from __future__ import annotations |
| 859 |
|
| 860 |
import os |
| 861 |
import sys |
| 862 |
|
| 863 |
from filelock import ReadWriteLock |
| 864 |
|
| 865 |
child_path = sys.argv[1] |
| 866 |
child_pid = os.fork() |
| 867 |
if child_pid == 0: |
| 868 |
with ReadWriteLock(child_path, is_singleton=False).read_lock(): |
| 869 |
pass |
| 870 |
sys.exit(0) |
| 871 |
_, status = os.waitpid(child_pid, 0) |
| 872 |
assert os.waitstatus_to_exitcode(status) == 0 |
| 873 |
""" |
| 874 |
) |
| 875 |
|
| 876 |
|
| 877 |
def _pypy_external_sqlite_script() -> str: # pragma: pypy cover |
| 878 |
return textwrap.dedent( |
| 879 |
""" |
| 880 |
from __future__ import annotations |
| 881 |
|
| 882 |
import os |
| 883 |
import sqlite3 |
| 884 |
import sys |
| 885 |
|
| 886 |
from filelock import ReadWriteLock |
| 887 |
|
| 888 |
external_path, child_path = sys.argv[1:] |
| 889 |
sqlite3.connect(external_path).close() |
| 890 |
child_pid = os.fork() |
| 891 |
if child_pid == 0: |
| 892 |
try: |
| 893 |
ReadWriteLock(child_path, is_singleton=False) |
| 894 |
except RuntimeError as error: |
| 895 |
assert str(error) == ( |
| 896 |
"ReadWriteLock is unavailable in a PyPy fork child; exec or exit before using it" |
| 897 |
) |
| 898 |
else: |
| 899 |
raise AssertionError("PyPy child opened SQLite after parent use") |
| 900 |
sys.exit(0) |
| 901 |
_, status = os.waitpid(child_pid, 0) |
| 902 |
assert os.waitstatus_to_exitcode(status) == 0 |
| 903 |
""" |
| 904 |
) |
| 905 |
|
| 906 |
|
| 907 |
def _subclass_fork_script() -> str: |
| 908 |
return textwrap.dedent( |
| 909 |
""" |
| 910 |
from __future__ import annotations |
| 911 |
|
| 912 |
import os |
| 913 |
import sys |
| 914 |
|
| 915 |
from filelock import ReadWriteLock |
| 916 |
|
| 917 |
class DerivedReadWriteLock(ReadWriteLock): |
| 918 |
pass |
| 919 |
|
| 920 |
lock_path = sys.argv[1] |
| 921 |
inherited_lock = DerivedReadWriteLock(lock_path) |
| 922 |
child_pid = os.fork() |
| 923 |
if child_pid == 0: |
| 924 |
if sys.implementation.name == "pypy": |
| 925 |
try: |
| 926 |
DerivedReadWriteLock(lock_path) |
| 927 |
except RuntimeError as error: |
| 928 |
assert str(error) == ( |
| 929 |
"ReadWriteLock is unavailable in a PyPy fork child; exec or exit before using it" |
| 930 |
) |
| 931 |
else: |
| 932 |
raise AssertionError("PyPy child constructed a lock after fork") |
| 933 |
else: |
| 934 |
child_lock = DerivedReadWriteLock(lock_path) |
| 935 |
assert child_lock is not inherited_lock |
| 936 |
with child_lock.read_lock(): |
| 937 |
pass |
| 938 |
sys.exit(0) |
| 939 |
_, status = os.waitpid(child_pid, 0) |
| 940 |
assert os.waitstatus_to_exitcode(status) == 0 |
| 941 |
""" |
| 942 |
) |
| 943 |
|
| 944 |
|
| 945 |
def _async_fork_script() -> str: |
| 946 |
return textwrap.dedent( |
| 947 |
r""" |
| 948 |
from __future__ import annotations |
| 949 |
|
| 950 |
import asyncio |
| 951 |
import gc |
| 952 |
import os |
| 953 |
import sqlite3 |
| 954 |
import sys |
| 955 |
import warnings |
| 956 |
|
| 957 |
from filelock import AsyncAcquireReadWriteReturnProxy, AsyncReadWriteLock, ReadWriteLock, Timeout |
| 958 |
|
| 959 |
warnings.filterwarnings("ignore", category=DeprecationWarning, message=r".*fork\(\).*") |
| 960 |
lock_path, state = sys.argv[1:] |
| 961 |
|
| 962 |
async def set_up_parent() -> tuple[AsyncReadWriteLock, AsyncAcquireReadWriteReturnProxy | None]: |
| 963 |
parent_lock = AsyncReadWriteLock(lock_path, is_singleton=False) |
| 964 |
parent_proxy = await parent_lock.acquire_write() if state == "held" else None |
| 965 |
return parent_lock, parent_proxy |
| 966 |
|
| 967 |
lock, proxy = asyncio.run(set_up_parent()) |
| 968 |
child_pid = os.fork() |
| 969 |
if child_pid == 0: |
| 970 |
async def check_child() -> None: |
| 971 |
if proxy is not None: |
| 972 |
async with proxy: |
| 973 |
pass |
| 974 |
try: |
| 975 |
await lock.acquire_read() |
| 976 |
except RuntimeError as error: |
| 977 |
assert "was invalidated by fork()" in str(error) |
| 978 |
else: |
| 979 |
raise AssertionError("inherited async lock acquired") |
| 980 |
await lock.release() |
| 981 |
await lock.close() |
| 982 |
if sys.implementation.name == "pypy": |
| 983 |
try: |
| 984 |
AsyncReadWriteLock(lock_path, is_singleton=False) |
| 985 |
except RuntimeError as error: |
| 986 |
assert str(error) == ( |
| 987 |
"ReadWriteLock is unavailable in a PyPy fork child; exec or exit before using it" |
| 988 |
) |
| 989 |
else: |
| 990 |
raise AssertionError("PyPy child constructed an async lock after fork") |
| 991 |
elif state == "idle": |
| 992 |
fresh_lock = AsyncReadWriteLock(lock_path, is_singleton=False) |
| 993 |
async with fresh_lock.write_lock(): |
| 994 |
pass |
| 995 |
await fresh_lock.close() |
| 996 |
else: |
| 997 |
try: |
| 998 |
ReadWriteLock(lock_path, is_singleton=False) |
| 999 |
except RuntimeError as error: |
| 1000 |
expected = ( |
| 1001 |
"ReadWriteLock is unavailable in a PyPy fork child" |
| 1002 |
if sys.implementation.name == "pypy" |
| 1003 |
else "was active across fork(); exec or exit" |
| 1004 |
) |
| 1005 |
assert expected in str(error) |
| 1006 |
else: |
| 1007 |
raise AssertionError("active async database reopened in child") |
| 1008 |
|
| 1009 |
asyncio.run(check_child()) |
| 1010 |
del lock |
| 1011 |
gc.collect() |
| 1012 |
sys.exit(0) |
| 1013 |
|
| 1014 |
_, status = os.waitpid(child_pid, 0) |
| 1015 |
assert os.waitstatus_to_exitcode(status) == 0 |
| 1016 |
if state == "held": |
| 1017 |
contender = ReadWriteLock(lock_path, is_singleton=False) |
| 1018 |
try: |
| 1019 |
contender.acquire_read(blocking=False) |
| 1020 |
except Timeout: |
| 1021 |
pass |
| 1022 |
else: |
| 1023 |
raise AssertionError("async child cleanup released the parent's lock") |
| 1024 |
asyncio.run(lock.release()) |
| 1025 |
asyncio.run(lock.close()) |
| 1026 |
with sqlite3.connect(lock_path) as connection: |
| 1027 |
assert connection.execute("PRAGMA integrity_check").fetchone() == ("ok",) |
| 1028 |
""" |
| 1029 |
) |