pytest-modal 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
File without changes
@@ -0,0 +1,107 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import configparser
5
+ import re
6
+ from pathlib import Path
7
+
8
+ MARK = "@@pytest-modal@@ "
9
+ BYE = MARK + '{"kind": "bye"}'
10
+ BOOT = "import sys; sys.path.insert(0, sys.argv.pop(1)); import pytest; sys.exit(pytest.main(sys.argv[1:]))"
11
+
12
+
13
+ def source(value: str) -> str:
14
+ if value in ("auto", "upload", "disk") or elsewhere(value):
15
+ return value
16
+ raise argparse.ArgumentTypeError("expected auto, upload, disk, a sandbox id (sb-...) or an image id (im-...)")
17
+
18
+
19
+ def elsewhere(source: str) -> bool:
20
+ """Whether the project is held by a sandbox or image this process names and has no files of."""
21
+ return source.startswith(("sb-", "im-"))
22
+
23
+
24
+ def project(root: Path) -> str:
25
+ """A name for the project at `root` that its other checkouts share and other projects do not: where its
26
+ repository was cloned from, without the scheme and any credentials, then the path to `root` inside it.
27
+ A directory outside a repository has only its own name."""
28
+ for folder in (root, *root.parents):
29
+ settings = configparser.ConfigParser(strict=False, interpolation=None)
30
+ try:
31
+ settings.read(folder / ".git" / "config")
32
+ url = settings['remote "origin"']["url"]
33
+ except (KeyError, OSError, configparser.Error):
34
+ continue
35
+ origin = re.sub(r"^\w+://([^@/]*@)?|^[^@/:]+@|(\.git)?/*$", "", url).replace(":", "/")
36
+ return "/".join([origin, *root.relative_to(folder).parts])
37
+ return root.name
38
+
39
+
40
+ def add_options(parser) -> None:
41
+ if getattr(parser, "_modal_options", False):
42
+ return
43
+ parser._modal_options = True
44
+ group = parser.getgroup("modal", "run tests in Modal sandboxes")
45
+ group.addoption("--modal", action="store_true", help="run the collected tests in Modal sandboxes")
46
+ group.addoption("--modal-shards", default="auto", metavar="N", help="number of sandboxes, or auto (default)")
47
+ group.addoption(
48
+ "--modal-max-shards",
49
+ type=int,
50
+ metavar="N",
51
+ help="upper bound for auto (default 1024 sandboxes, or 64 processes with --modal-backend=local)",
52
+ )
53
+ group.addoption("--modal-group-by", choices=("file", "test"), default="file", help="what stays in one sandbox")
54
+ group.addoption(
55
+ "--modal-collect",
56
+ choices=("local", "remote"),
57
+ default="local",
58
+ help="remote: collect in a sandbox; this process then imports no test code and loads no conftest.py "
59
+ "(always the case with --modal-from=ID)",
60
+ )
61
+ group.addoption(
62
+ "--modal-from",
63
+ type=source,
64
+ default="auto",
65
+ metavar="SOURCE",
66
+ help="upload: send the project; disk: snapshot this sandbox's disk (auto: disk inside a sandbox, else "
67
+ "upload); or the id of a sandbox (sb-...) to snapshot or of an image (im-...) that holds the project",
68
+ )
69
+ group.addoption("--modal-workdir", metavar="DIR", help="directory the shards run in, with --modal-from=ID")
70
+ group.addoption("--modal-retries", type=int, default=2, metavar="N", help="restarts of a shard that ran nothing")
71
+ group.addoption("--modal-args", default="", metavar="ARGS", help="extra pytest arguments for the shards only")
72
+ group.addoption(
73
+ "--modal-backend", choices=("modal", "local"), default="modal", help="local: one subprocess a shard"
74
+ )
75
+ group.addoption("--modal-app", default="pytest-modal", metavar="NAME", help="name of the Modal app for the run")
76
+ group.addoption("--modal-worker", choices=("run", "collect"), help=argparse.SUPPRESS)
77
+ parser.addini("modal_conf", "file with pytest-modal hooks, loaded only by the controller", default="modal_conf.py")
78
+ parser.addini(
79
+ "modal_isolate",
80
+ "each line: patterns for test files that run together in a sandbox of their own",
81
+ type="linelist",
82
+ default=[],
83
+ )
84
+ parser.addini("modal_python", "interpreter the shards run (default: python, or this one with a disk snapshot)")
85
+ parser.addini(
86
+ "modal_project",
87
+ "name the weights are kept under on Modal (default: where the repository was cloned from, else the "
88
+ "root directory's name)",
89
+ )
90
+ parser.addini("modal_timeout", "seconds a sandbox may live", default="3600")
91
+ parser.addini("modal_start_timeout", "seconds a shard may take to start before it is replaced", default="300")
92
+
93
+
94
+ def add_hooks(pluginmanager) -> None:
95
+ if getattr(pluginmanager, "_modal_hooks", False):
96
+ return
97
+ pluginmanager._modal_hooks = True
98
+ from . import hookspecs
99
+
100
+ pluginmanager.add_hookspecs(hookspecs)
101
+
102
+
103
+ def group_mark(item) -> str | None:
104
+ mark = item.get_closest_marker("xdist_group")
105
+ if mark is None:
106
+ return None
107
+ return "group:" + str(mark.args[0] if mark.args else mark.kwargs.get("name"))
@@ -0,0 +1,301 @@
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import importlib.metadata
5
+ import json
6
+ import os
7
+ import re
8
+ import shutil
9
+ import subprocess
10
+ import sys
11
+ import sysconfig
12
+ import tempfile
13
+ import threading
14
+ import time
15
+ from pathlib import Path
16
+ from urllib.parse import unquote, urlparse
17
+
18
+ import pytest
19
+
20
+ from ._common import BOOT, BYE
21
+
22
+ PACKAGE = Path(__file__).parent
23
+ REMOTE_LIB = "/opt/pytest-modal"
24
+ # The weights are left out because every run rewrites them and no shard reads them.
25
+ IGNORE = [".git", ".venv", "**/__pycache__", "**/*.pyc", "**/node_modules", "**/.pytest_cache/v/modal"]
26
+ SITE = "/usr/local/lib/python{}/site-packages"
27
+ NOT_MIRRORED = {"pytest-modal", "pip"}
28
+ STORE = "pytest-modal"
29
+ # Shards that may be starting at once. The Modal client does its work on one thread, which this many keep
30
+ # busy: past it every shard waited for all the others, 6 s at 1,024 and 19 s at 2,765 against 1.5 s.
31
+ STARTING = 128
32
+ CREDENTIALS = (
33
+ "MODAL_TOKEN_ID",
34
+ "MODAL_TOKEN_SECRET",
35
+ "MODAL_OAUTH_REFRESH_TOKEN",
36
+ "MODAL_OAUTH_CLIENT_ID",
37
+ "MODAL_OAUTH_CLIENT_SECRET",
38
+ "MODAL_OAUTH_JWT_KEY",
39
+ )
40
+ HOW_TO_SIGN_IN = (
41
+ "On your own machine: `modal token new`. In CI: set MODAL_TOKEN_ID and MODAL_TOKEN_SECRET, best those of a "
42
+ "service user that can write to one environment. Inside a Modal sandbox, which has no identity of its own: "
43
+ "give the two variables to this pytest command alone, or run pytest outside the sandbox with "
44
+ "--modal-from=<sandbox id>, which needs no token inside it."
45
+ )
46
+
47
+
48
+ def library() -> str:
49
+ """A directory holding this package and nothing else, for a shard's interpreter to import it from."""
50
+ folder = tempfile.mkdtemp(prefix="pytest-modal-")
51
+ shutil.copytree(PACKAGE, Path(folder, "pytest_modal"), ignore=shutil.ignore_patterns("__pycache__"))
52
+ return folder
53
+
54
+
55
+ def origin(source: str) -> str:
56
+ """Where the shards get the project, from the value of --modal-from: "upload", "disk" (a snapshot of this
57
+ machine's disk, which only a Modal sandbox can take), or the id of a sandbox or image that holds it."""
58
+ inside = "MODAL_SANDBOX_ID" in os.environ
59
+ if source == "disk" and not inside:
60
+ raise pytest.UsageError("--modal-from=disk only works inside a Modal sandbox")
61
+ if source == "auto":
62
+ return "disk" if inside else "upload"
63
+ return source
64
+
65
+
66
+ def sign_in() -> None:
67
+ """Open the Modal client, then take its credentials out of this process's environment: the client keeps
68
+ them, and project code imported here, or anything it starts, does not inherit them."""
69
+ import modal
70
+
71
+ try:
72
+ modal.Client.from_env()
73
+ except modal.exception.AuthError as error:
74
+ raise pytest.UsageError(f"pytest --modal could not sign in to Modal: {error}\n{HOW_TO_SIGN_IN}") from error
75
+ except modal.exception.Error as error:
76
+ raise pytest.UsageError(f"pytest --modal could not reach Modal: {error}") from error
77
+ for name in CREDENTIALS:
78
+ os.environ.pop(name, None)
79
+
80
+
81
+ def without_modal(env) -> dict[str, str]:
82
+ """The environment test code gets: this sandbox's identity and Modal credentials stay with the controller."""
83
+ return {key: value for key, value in env.items() if not key.startswith("MODAL_")}
84
+
85
+
86
+ class Local:
87
+ name = ""
88
+
89
+ def __init__(self, config, env=None):
90
+ self.library = library()
91
+ self.command = [config.getini("modal_python") or sys.executable, "-c", BOOT, self.library]
92
+ self.cwd = str(config.invocation_params.dir)
93
+ self.env = dict(os.environ) if env is None else env
94
+ self.processes = []
95
+
96
+ def run(self, lane, args, emit) -> int:
97
+ # Shards share this directory, where pytest-cov erases and combines every .coverage.* it finds: each
98
+ # keeps its data elsewhere, and only the controller writes here.
99
+ private = {"COVERAGE_FILE": os.path.join(self.library, f"coverage-{id(lane)}")}
100
+ process = subprocess.Popen(
101
+ [*self.command, *args],
102
+ cwd=self.cwd,
103
+ env={**self.env, **lane.env, **private},
104
+ text=True,
105
+ stdin=subprocess.PIPE,
106
+ stdout=subprocess.PIPE,
107
+ stderr=subprocess.STDOUT,
108
+ )
109
+ self.processes.append(process)
110
+ lane.stop = process.kill
111
+ lane.shard.where = f"pid {process.pid}"
112
+ process.stdin.write("\n".join(lane.shard.ids))
113
+ process.stdin.close()
114
+ for line in process.stdout:
115
+ emit(line)
116
+ return process.wait()
117
+
118
+ def full(self, outcome) -> bool:
119
+ return False
120
+
121
+ def weights(self, project) -> dict:
122
+ return {}
123
+
124
+ def keep(self, project, weights) -> None:
125
+ pass
126
+
127
+ def close(self):
128
+ for process in self.processes:
129
+ if process.poll() is None:
130
+ process.kill()
131
+ shutil.rmtree(self.library, ignore_errors=True)
132
+
133
+
134
+ class Modal:
135
+ def __init__(self, config):
136
+ import modal
137
+
138
+ self.modal = modal
139
+ # An ephemeral app: Modal stops it, and the sandboxes in it, when this process stops heartbeating.
140
+ self.app = modal.App(config.getoption("modal_app"))
141
+ self.options = {
142
+ "timeout": int(config.getini("modal_timeout")),
143
+ **(config.hook.pytest_modal_sandbox(config=config) or {}),
144
+ }
145
+ self.tags = {"pytest-modal": self.app.name, **self.options.pop("tags", {})}
146
+ self.snapshots = []
147
+ self.gate = threading.BoundedSemaphore(STARTING)
148
+ self.closed = False
149
+ # The app stops with this block if anything in it fails, and the snapshots go once it has.
150
+ with contextlib.ExitStack() as stack:
151
+ stack.callback(self.forget)
152
+ stack.enter_context(self.app.run())
153
+ self.name = f"app {self.app.app_id}"
154
+ self.prepare(config, origin(config.getoption("modal_from")), stack)
155
+ self.stack = stack.pop_all()
156
+
157
+ def snapshot(self, sandbox):
158
+ """The disk of a sandbox as an image. It is deleted when the run ends, or by Modal once no sandbox of
159
+ the run can still be alive, should this process not live to do it."""
160
+ image = self.modal.Sandbox.from_id(sandbox).snapshot_filesystem(timeout=300, ttl=self.options["timeout"])
161
+ self.snapshots.append(image.object_id)
162
+ return image
163
+
164
+ def forget(self):
165
+ for image in self.snapshots:
166
+ with contextlib.suppress(self.modal.exception.Error):
167
+ self.modal.experimental.image_delete(image)
168
+
169
+ def full(self, outcome) -> bool:
170
+ """Whether a shard ended this way because Modal has no room for another sandbox: a limit on how many
171
+ run at once, or on how fast they are created, which the client has by then waited on and retried."""
172
+ return isinstance(outcome, self.modal.exception.ResourceExhaustedError)
173
+
174
+ def weights(self, project) -> dict:
175
+ try:
176
+ return self.modal.Dict.from_name(STORE, create_if_missing=True).get(project, {})
177
+ except self.modal.exception.Error:
178
+ return {}
179
+
180
+ def keep(self, project, weights) -> None:
181
+ with contextlib.suppress(self.modal.exception.Error):
182
+ self.modal.Dict.from_name(STORE, create_if_missing=True).put(project, weights)
183
+
184
+ def prepare(self, config, source, stack):
185
+ modal = self.modal
186
+ root, here = config.rootpath, config.invocation_params.dir
187
+ if source == "disk":
188
+ folder = library()
189
+ stack.callback(shutil.rmtree, folder, ignore_errors=True)
190
+ self.command = [config.getini("modal_python") or sys.executable, "-c", BOOT, folder]
191
+ self.env = without_modal(os.environ)
192
+ self.cwd = str(here)
193
+ self.image = self.snapshot(os.environ["MODAL_SANDBOX_ID"])
194
+ return
195
+ self.command = [config.getini("modal_python") or "python", "-c", BOOT, REMOTE_LIB]
196
+ self.env = {}
197
+ if source == "upload":
198
+ image = config.hook.pytest_modal_image(config=config) or mirror(modal, root, stack)
199
+ image = image.add_local_dir(root, str(root), ignore=IGNORE)
200
+ self.cwd = str(here if here.is_relative_to(root) else root)
201
+ else:
202
+ if source.startswith("sb-"):
203
+ source = self.snapshot(source).object_id
204
+ # Looked up by id: the image object a snapshot returns takes no files on top.
205
+ image = modal.Image.from_id(source)
206
+ self.cwd = config.getoption("modal_workdir")
207
+ # Built here, once, so that a build that fails is one error and not one for each shard.
208
+ self.image = image.add_local_dir(PACKAGE, f"{REMOTE_LIB}/pytest_modal", ignore=["__pycache__"]).build(self.app)
209
+
210
+ def run(self, lane, args, emit) -> int:
211
+ tags = {**self.tags, "pytest-modal-shard": lane.gateway.id if lane.mode == "run" else lane.mode}
212
+ with self.gate:
213
+ if self.closed:
214
+ raise RuntimeError("the run ended before this shard's turn to start")
215
+ # The shard's clock starts with its turn, not with the wait for it.
216
+ lane.queued, lane.launched = time.monotonic() - lane.launched, time.monotonic()
217
+ box = self.modal.Sandbox.create(
218
+ "sleep", "infinity", app=self.app, image=self.image, tags=tags, **self.options
219
+ )
220
+ lane.stop = box.terminate
221
+ lane.shard.where = box.object_id
222
+ lane.created = time.monotonic() - lane.launched
223
+ process = box.exec(
224
+ "sh",
225
+ "-c",
226
+ 'exec "$@" 2>&1',
227
+ "sh",
228
+ *self.command,
229
+ *args,
230
+ workdir=self.cwd,
231
+ env={**self.env, **lane.env},
232
+ )
233
+ process.stdin.write("\n".join(lane.shard.ids))
234
+ process.stdin.write_eof()
235
+ process.stdin.drain()
236
+ code = None
237
+ for line in lines(process.stdout):
238
+ emit(line)
239
+ # After its goodbye a shard only has an interpreter to shut down, which nothing waits for.
240
+ if BYE in line:
241
+ code = 0
242
+ break
243
+ code = process.wait() if code is None else code
244
+ box.terminate()
245
+ return code
246
+
247
+ def close(self):
248
+ self.closed = True
249
+ self.stack.close()
250
+
251
+
252
+ def lines(pieces):
253
+ """The lines of text that arrives in pieces. Asked for a line at a time, the Modal client makes a trip to
254
+ its event loop for every line, which at a thousand shards is most of what the controller does."""
255
+ rest = ""
256
+ for piece in pieces:
257
+ *whole, rest = (rest + piece).split("\n")
258
+ yield from whole
259
+ if rest:
260
+ yield rest
261
+
262
+
263
+ def environment(folders=None):
264
+ """What an image needs to match this environment: a pin for each package an index has and, for each
265
+ package installed from a path, its files in site-packages and the source an editable install points at."""
266
+ pins, files, sources = {}, {}, []
267
+ folders = folders or sorted({sysconfig.get_path("purelib"), sysconfig.get_path("platlib")})
268
+ for dist in importlib.metadata.distributions(path=folders):
269
+ name = re.sub(r"[-_.]+", "-", dist.metadata["Name"] or "").lower()
270
+ if not name or name in NOT_MIRRORED or name in pins:
271
+ continue
272
+ origin = json.loads(dist.read_text("direct_url.json") or "null")
273
+ if origin is None:
274
+ pins[name] = f"{name}=={dist.version}"
275
+ continue
276
+ if origin.get("dir_info", {}).get("editable"):
277
+ sources.append(Path(unquote(urlparse(origin["url"]).path)))
278
+ for file in dist.files or []:
279
+ if ".." not in file.parts and "__pycache__" not in file.parts:
280
+ files[file.locate()] = file.as_posix()
281
+ return sorted(pins.values()), files, sources
282
+
283
+
284
+ def mirror(modal, root, stack):
285
+ """debian_slim with this Python minor version and the packages of this environment."""
286
+ version = "{}.{}".format(*sys.version_info)
287
+ pins, files, sources = environment()
288
+ image = modal.Image.debian_slim(python_version=version).uv_pip_install(*pins)
289
+ if files:
290
+ staged = Path(stack.enter_context(tempfile.TemporaryDirectory(prefix="pytest-modal-")))
291
+ for local, relative in files.items():
292
+ (staged / relative).parent.mkdir(parents=True, exist_ok=True)
293
+ shutil.copyfile(local, staged / relative)
294
+ image = image.add_local_dir(staged, SITE.format(version))
295
+ for source in sources:
296
+ if source.is_dir() and not source.is_relative_to(root):
297
+ image = image.add_local_dir(source, str(source), ignore=IGNORE)
298
+ return image
299
+
300
+
301
+ BACKENDS = {"local": Local, "modal": Modal}
@@ -0,0 +1,11 @@
1
+ import pytest
2
+
3
+
4
+ @pytest.hookspec(firstresult=True)
5
+ def pytest_modal_image(config):
6
+ """Return the modal.Image the tests run in when the project is uploaded. The project is added on top."""
7
+
8
+
9
+ @pytest.hookspec(firstresult=True)
10
+ def pytest_modal_sandbox(config):
11
+ """Return keyword arguments for modal.Sandbox.create, such as cpu, memory, gpu, secrets or volumes."""
pytest_modal/plan.py ADDED
@@ -0,0 +1,63 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from dataclasses import dataclass, field
5
+ from statistics import median
6
+
7
+
8
+ @dataclass
9
+ class Shard:
10
+ index: int
11
+ ids: list[str] = field(default_factory=list)
12
+ weight: float = 0.0
13
+ where: str = ""
14
+
15
+ @property
16
+ def paths(self) -> list[str]:
17
+ return sorted({nodeid.split("::")[0] for nodeid in self.ids})
18
+
19
+
20
+ def plan(
21
+ tests: list[tuple[str, str]],
22
+ shards: int | None,
23
+ durations: dict[str, float],
24
+ limit: int,
25
+ alone: frozenset[str] = frozenset(),
26
+ start: float = 0.0,
27
+ ) -> list[Shard]:
28
+ """Split (nodeid, group) pairs, given in collection order, into shards of similar expected time.
29
+
30
+ A group never spans two shards, and each group named in `alone` has a shard to itself. No number of
31
+ sandboxes finishes before the heaviest group does. With no shard count the plan fills shards to half
32
+ that group's weight, in at most `limit` shards: a shard also pays to start, and tests cost more in a
33
+ process that ran others. It fills them to no less than `start`, what a shard costs before its first test
34
+ and after its last, in the unit of the weights: lighter shards would spend most of their time starting.
35
+ A count that is given is not held to `limit`.
36
+ """
37
+ default = median(durations.values()) if durations else 1.0
38
+ members: dict[str, list[int]] = {}
39
+ weights: dict[str, float] = {}
40
+ for position, (nodeid, group) in enumerate(tests):
41
+ members.setdefault(group, []).append(position)
42
+ weights[group] = weights.get(group, 0.0) + durations.get(nodeid, default)
43
+ apart = [group for group in members if group in alone]
44
+ packed = sorted((group for group in members if group not in alone), key=lambda name: -weights[name])
45
+ if shards is None:
46
+ fill = max(weights[packed[0]] / 2, start) if packed else 0
47
+ wanted = math.ceil(sum(weights[group] for group in packed) / fill) if fill else 0
48
+ wanted = min(wanted, limit - len(apart))
49
+ else:
50
+ wanted = shards - len(apart)
51
+ shared = min(max(wanted, 1), len(packed))
52
+ bins = [Shard(index) for index in range(shared + len(apart))]
53
+ positions: list[list[int]] = [[] for _ in bins]
54
+ for shard, group in zip(bins[shared:], apart):
55
+ shard.weight = weights[group]
56
+ positions[shard.index] = members[group]
57
+ for group in packed:
58
+ lightest = min(bins[:shared], key=lambda shard: shard.weight)
59
+ lightest.weight += weights[group]
60
+ positions[lightest.index] += members[group]
61
+ for shard, held in zip(bins, positions):
62
+ shard.ids = [tests[position][0] for position in sorted(held)]
63
+ return bins