Debian Codegraph @

tasks/capabilities.py

raw
1 """What the runtime this suite is running on can actually do.
2
3 Probed rather than inferred from a platform or interpreter name: a name answers who is running, and every question
4 here is about what the runtime can do. The coverage pragmas and the tests' skipif gates both read these, so a test
5 cannot skip while coverage still demands its lines.
6
7 Kept apart from the pragma plugin so reading a capability never requires coverage to be installed.
8 """
9
10 from __future__ import annotations
11
12 import gc
13 import os
14 import signal
15 import socket
16 import sys
17 import tempfile
18 import weakref
19 from asyncio import CancelledError
20 from contextlib import asynccontextmanager, contextmanager
21 from importlib import import_module
22 from importlib.util import find_spec
23 from pathlib import Path
24 from typing import TYPE_CHECKING, Final
25
26 if TYPE_CHECKING:
27 from collections.abc import AsyncIterator, Generator, Iterator
28
29
30 def _supports_symlink() -> bool:
31 # Windows grants this per privilege, not per platform, so ask the filesystem.
32 with tempfile.TemporaryDirectory() as directory:
33 target = Path(directory, "target")
34 target.touch()
35 try:
36 Path(directory, "link").symlink_to(target)
37 except (OSError, NotImplementedError, AttributeError):
38 return False
39 return True
40
41
42 def _supports_unlinking_an_open_file() -> bool:
43 # Where this is refused, a peer can never take a live holder's marker.
44 with tempfile.TemporaryDirectory() as directory:
45 victim = Path(directory, "victim")
46 victim.touch()
47 with victim.open("rb"):
48 try:
49 victim.unlink()
50 except OSError:
51 return False
52 return True
53
54
55 def _honors_link_follow_symlinks() -> bool:
56 # PyPy advertises the option then rejects it with EINVAL, so trust a real link over os.supports_follow_symlinks.
57 if not hasattr(os, "link"):
58 return False
59 with tempfile.TemporaryDirectory() as directory:
60 source = Path(directory, "source")
61 source.touch()
62 try:
63 os.link(source, Path(directory, "link"), follow_symlinks=False)
64 except (OSError, NotImplementedError, ValueError):
65 return False
66 return True
67
68
69 def _finalizes_on_last_reference() -> bool:
70 # Only a refcounting collector runs __del__ the moment the last reference goes; a tracing one defers it.
71 finalized: list[bool] = []
72
73 class Probe:
74 def __del__(self) -> None:
75 finalized.append(True)
76
77 Probe()
78 return bool(finalized)
79
80
81 def _finalizes_on_collection() -> bool:
82 # GraalPy queues finalizers on the host collector, so even a forced collection does not run __del__.
83 finalized: list[bool] = []
84
85 class Probe:
86 def __del__(self) -> None:
87 finalized.append(True)
88
89 Probe()
90 gc.collect()
91 return bool(finalized)
92
93
94 def _collects_classes() -> bool:
95 # A dynamically built lock subclass must not outlive its last reference, or the registries keyed on it leak.
96 def build() -> type:
97 class Probe:
98 pass
99
100 return Probe
101
102 reference = weakref.ref(build())
103 gc.collect()
104 return reference() is None
105
106
107 def _preserves_context_thrown_into_a_generator() -> bool:
108 # GraalPy resets __context__ when contextlib throws into the suspended generator, losing the chained cause.
109 @contextmanager
110 def probe() -> Iterator[None]:
111 yield
112
113 error = KeyError("thrown")
114 error.__context__ = ValueError("context")
115 try:
116 with probe():
117 raise error
118 except KeyError as caught:
119 return caught.__context__ is not None
120 return False # pragma: no cover # the raise above always propagates
121
122
123 class _Suspend:
124 """An awaitable that parks its coroutine once, so a probe can throw into a suspended frame without a loop."""
125
126 def __await__(self) -> Generator[None, None, None]:
127 yield
128
129
130 def _propagates_a_cancellation_thrown_into_a_coroutine() -> bool:
131 # Driven by hand so the probe needs no event loop: GraalPy answers athrow with RuntimeError instead of the
132 # CancelledError, so every cancellation crossing an async context manager surfaces as the wrong exception.
133 @asynccontextmanager
134 async def gate() -> AsyncIterator[None]:
135 await _Suspend()
136 yield
137
138 async def body() -> None:
139 async with gate():
140 pass
141
142 coroutine = body()
143 coroutine.send(None)
144 try:
145 coroutine.throw(CancelledError())
146 except CancelledError:
147 return True
148 except BaseException: # ruff:ignore[blind-except] # whatever else a runtime substitutes counts as the deviation
149 return False
150 return False # pragma: no cover # throwing into the suspended coroutine always raises
151
152
153 _AUDIT_PROBE_EVENT: Final[str] = "filelock.capability-probe"
154
155
156 def _delivers_audit_events() -> bool:
157 # GraalPy accepts a hook and never calls it. The hook is a permanent no-op; tests install their own anyway.
158 delivered: list[bool] = []
159 sys.addaudithook(lambda event, _args: delivered.append(True) if event == _AUDIT_PROBE_EVENT else None)
160 sys.audit(_AUDIT_PROBE_EVENT)
161 return bool(delivered)
162
163
164 def _refuses_to_open_a_symlink() -> bool:
165 # GraalPy accepts O_NOFOLLOW then follows the link anyway, so ask for the refusal rather than the constant.
166 if not hasattr(os, "O_NOFOLLOW"):
167 return False
168 if not _supports_symlink():
169 # Nothing to point the probe at, so keep the constant's answer rather than reporting a gap we cannot see.
170 return True
171 with tempfile.TemporaryDirectory() as directory:
172 target = Path(directory, "target")
173 target.touch()
174 link = Path(directory, "link")
175 link.symlink_to(target)
176 try:
177 descriptor = os.open(link, os.O_RDONLY | os.O_NOFOLLOW)
178 except OSError:
179 return True
180 os.close(descriptor)
181 return False
182
183
184 def _reports_object_tracebacks() -> bool:
185 # pytest's thread and unraisable exception hooks ask tracemalloc where the offending object was allocated. GraalPy
186 # raises NotImplementedError from that lookup; CPython answers None while not tracing, and PyPy, which ships no
187 # tracemalloc, is never asked.
188 try:
189 get_object_traceback = import_module("tracemalloc").get_object_traceback
190 except ImportError:
191 return True
192 try:
193 get_object_traceback(object())
194 except NotImplementedError:
195 return False
196 return True
197
198
199 def _enforces_file_mode() -> bool:
200 # Without POSIX permission bits a chmod does not read back.
201 with tempfile.TemporaryDirectory() as directory:
202 probe = Path(directory, "probe")
203 probe.touch()
204 probe.chmod(_OWNER_READ_WRITE)
205 return probe.stat().st_mode & 0o777 == _OWNER_READ_WRITE
206
207
208 _OWNER_READ_WRITE: Final[int] = 0o600
209
210 #: Capability -> whether this runtime provides it. Tests gate their skipif on this same mapping.
211 CAPABILITIES: Final[dict[str, bool]] = {
212 "fork": hasattr(os, "fork") and hasattr(os, "register_at_fork"),
213 # Narrower than "fork": GraalPy registers fork handlers but cannot fork.
214 "register-at-fork": hasattr(os, "register_at_fork"),
215 "dir-fd": os.open in os.supports_dir_fd,
216 # Narrower than "dir-fd": GraalPy takes os.open relative to a directory descriptor but not os.link.
217 "link-dir-fd": hasattr(os, "link") and os.link in os.supports_dir_fd,
218 "fork1": hasattr(os, "fork1"),
219 "hard-link": hasattr(os, "link"),
220 "symlink": _supports_symlink(),
221 "fcntl": find_spec("fcntl") is not None,
222 "unlink-open-file": _supports_unlinking_an_open_file(),
223 "posix-signals": hasattr(signal, "SIGKILL"),
224 "file-mode": _enforces_file_mode(),
225 "prompt-finalization": _finalizes_on_last_reference(),
226 "collected-finalization": _finalizes_on_collection(),
227 "class-collection": _collects_classes(),
228 "generator-exception-context": _preserves_context_thrown_into_a_generator(),
229 "coroutine-cancellation": _propagates_a_cancellation_thrown_into_a_coroutine(),
230 "audit-events": _delivers_audit_events(),
231 "fd-directory": any(Path(view).is_dir() for view in ("/dev/fd", "/proc/self/fd")),
232 "fifo": hasattr(os, "mkfifo"),
233 "af-unix": hasattr(socket, "AF_UNIX"),
234 # Distinct from "symlink": a runtime can create them yet still not refuse to follow one.
235 "o-nofollow": _refuses_to_open_a_symlink(),
236 "utime-nofollow": os.utime in os.supports_follow_symlinks,
237 "utime-fd": os.utime in os.supports_fd,
238 "sqlite3": find_spec("sqlite3") is not None,
239 # A source consumer may run the suite unmeasured, and a forked child then has nothing to flush.
240 "coverage": find_spec("coverage") is not None,
241 "link-follow-symlinks": _honors_link_follow_symlinks(),
242 "tracemalloc-object-traceback": _reports_object_tracebacks(),
243 # Only the tox env that installs a released filelock sets this.
244 "old-client": bool(os.environ.get("FILELOCK_OLD_CLIENT_PATH")),
245 }
246
247
248 __all__ = [
249 "CAPABILITIES",
250 ]