Debian Codegraph @

tests/test_strict_soft_stress.py

raw
1 from __future__ import annotations
2
3 import os
4 import signal
5 import subprocess # ruff:ignore[suspicious-subprocess-import] # isolated interpreters exercise cross-process exclusion
6 import sys
7 import time
8 from typing import TYPE_CHECKING, Final
9
10 import pytest
11
12 if TYPE_CHECKING:
13 from pathlib import Path
14
15 _PROCESS_COUNT: Final[int] = 8
16 _ACQUISITIONS_PER_PROCESS: Final[int] = 500
17 # A guard against a deadlock, not a throughput assertion: overlap fails immediately through the markers below, so this
18 # budget only bounds a hang. The four thousand contended acquisitions cost CPython about three seconds and GraalPy about
19 # twenty-eight on a ten-core machine, and the CI runners have far fewer, so it is sized for the slowest interpreter on
20 # the smallest runner rather than for the fastest, which is what a seventy-five second guard encoded.
21 _WORKER_DEADLINE: Final[int] = 300
22 # Catch overlap two independent ways. An occupancy marker fails immediately the instant a second holder enters the
23 # critical section, and a counter read-modify-write fails afterwards when two holders read the same value and one
24 # increment vanishes. Both beat an O_EXCL create/unlink pair, which tripped over Windows' delete-pending lag where the
25 # previous holder's unlink had not finished before the next holder's create ran. The check lives in the worker's exit
26 # status, not in its stderr: interpreters are free to print to stderr (PyPy warns when it cannot size the CPU cache),
27 # so demanding empty stderr flakes without proving anything about exclusion.
28 _WORKER: Final[str] = """
29 import sys
30 import time
31 from pathlib import Path
32
33 from filelock import StrictSoftFileLock
34
35 lock_path, start_path, counter_path, occupied_path = map(Path, sys.argv[1:5])
36 while not start_path.exists():
37 time.sleep(0.001)
38 for _ in range(int(sys.argv[5])):
39 with StrictSoftFileLock(lock_path, timeout=30, poll_interval=0.0005):
40 if occupied_path.exists():
41 raise SystemExit("two holders entered the critical section at once")
42 occupied_path.write_text("held")
43 count = int(counter_path.read_text()) if counter_path.exists() else 0
44 counter_path.write_text(str(count + 1))
45 occupied_path.unlink()
46 """
47
48
49 pytestmark = pytest.mark.requires_hard_links
50
51
52 @pytest.mark.timeout(_WORKER_DEADLINE + 60)
53 def test_strict_soft_eight_process_contention_has_no_overlap(tmp_path: Path) -> None:
54 lock_path = tmp_path / "resource.lock"
55 start_path = tmp_path / "start"
56 counter_path = tmp_path / "counter"
57 occupied_path = tmp_path / "occupied"
58 processes = [
59 subprocess.Popen(
60 [
61 sys.executable,
62 "-c",
63 _WORKER,
64 str(lock_path),
65 str(start_path),
66 str(counter_path),
67 str(occupied_path),
68 str(_ACQUISITIONS_PER_PROCESS),
69 ],
70 stdout=subprocess.PIPE,
71 stderr=subprocess.PIPE,
72 text=True,
73 start_new_session=sys.platform != "win32",
74 creationflags=subprocess.CREATE_NEW_PROCESS_GROUP if sys.platform == "win32" else 0,
75 )
76 for _ in range(_PROCESS_COUNT)
77 ]
78 start_path.touch()
79 deadline = time.monotonic() + _WORKER_DEADLINE
80 outputs: list[tuple[str, str]] = []
81 try:
82 outputs.extend(process.communicate(timeout=max(0.1, deadline - time.monotonic())) for process in processes)
83 except subprocess.TimeoutExpired: # pragma: no cover - test failure cleanup
84 _kill_processes(processes)
85 pytest.fail(f"strict soft-lock stress workers exceeded {_WORKER_DEADLINE} seconds")
86
87 recorded = int(counter_path.read_text()) if counter_path.exists() else 0
88 assert ([process.returncode for process in processes], recorded) == (
89 [0] * _PROCESS_COUNT,
90 _PROCESS_COUNT * _ACQUISITIONS_PER_PROCESS,
91 ), outputs
92
93
94 def _kill_processes(processes: list[subprocess.Popen[str]]) -> None: # pragma: no cover - test failure cleanup
95 for process in processes:
96 if process.poll() is None:
97 if sys.platform == "win32":
98 process.kill()
99 else:
100 os.killpg(process.pid, signal.SIGKILL)
101 for process in processes:
102 process.communicate()