|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import os |
| 4 | +import subprocess |
| 5 | +import sys |
| 6 | +import sysconfig |
| 7 | +from textwrap import dedent |
| 8 | +from typing import TYPE_CHECKING |
| 9 | + |
| 10 | +import pytest |
| 11 | + |
| 12 | +if TYPE_CHECKING: |
| 13 | + from pathlib import Path |
| 14 | + |
| 15 | +# The driver fills its import cache on first use, and the cache cannot be reset within a |
| 16 | +# process, so every attempt runs in a fresh interpreter. Only a free-threaded build with the GIL |
| 17 | +# disabled can expose a race; on other builds this is a smoke test. |
| 18 | +FREE_THREADED = bool(sysconfig.get_config_var("Py_GIL_DISABLED")) |
| 19 | + |
| 20 | + |
| 21 | +@pytest.mark.parametrize("attempt", range(10 if FREE_THREADED else 1)) |
| 22 | +def test_concurrent_first_use_of_the_import_cache( |
| 23 | + attempt: int, build_dir: Path |
| 24 | +) -> None: |
| 25 | + code = dedent(f""" |
| 26 | + import sys |
| 27 | + import threading |
| 28 | +
|
| 29 | + sys.path.append(r"{build_dir!s}") |
| 30 | +
|
| 31 | + import ladybug as lb |
| 32 | +
|
| 33 | + db = lb.Database(":memory:") |
| 34 | + conns = [lb.Connection(db) for _ in range(16)] |
| 35 | + start = threading.Barrier(len(conns)) |
| 36 | + errors = [] |
| 37 | +
|
| 38 | + def run(conn, n): |
| 39 | + start.wait() |
| 40 | + try: |
| 41 | + assert conn.execute("RETURN $n", {{"n": n}}).get_next() == [n] |
| 42 | + except BaseException as e: |
| 43 | + errors.append(e) |
| 44 | +
|
| 45 | + threads = [threading.Thread(target=run, args=(c, i)) for i, c in enumerate(conns)] |
| 46 | + for t in threads: |
| 47 | + t.start() |
| 48 | + for t in threads: |
| 49 | + t.join() |
| 50 | + assert not errors, errors |
| 51 | + """) |
| 52 | + env = {**os.environ, "PYTHON_GIL": "0"} if FREE_THREADED else None |
| 53 | + result = subprocess.run( |
| 54 | + [sys.executable, "-c", code], |
| 55 | + env=env, |
| 56 | + capture_output=True, |
| 57 | + text=True, |
| 58 | + check=False, |
| 59 | + ) |
| 60 | + assert result.returncode == 0, (result.returncode, result.stderr) |
0 commit comments