Repository navigation
Expand file tree
/
Copy pathtest_wheel.py
More file actions
444 lines (363 loc) · 17.1 KB
/
Copy pathtest_wheel.py
File metadata and controls
444 lines (363 loc) · 17.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
"""The one artifact VisionSet ships, checked as an artifact.
Everything else in this suite tests a source checkout. What a user gets is a
wheel, and three things can be wrong with it that no source test can see: **the
compiled UI is not inside it**, **the version metadata disagrees with `VERSION`**,
and **something enormous came along for the ride**. Each of those installs
cleanly, starts cleanly, and is wrong.
The first is the one worth naming. `uv build` copies `src/visionset/_static/` as
package data *at the moment it runs*, and a fresh checkout's `_static/` holds two
placeholder files — so a wheel built before `pnpm bundle:static` contains no app
at all. It installs. `visionset server` starts. `/app/` answers a 404 naming a script
the user cannot run, because they do not have the repository. There is no error
and no traceback anywhere in that sequence.
**This directory is ``tests/packaging/`` and not ``tests/dist/``**, which is not
taste: pytest's default ``norecursedirs`` includes ``dist``, so a directory by
that name is silently never collected — no error, no warning, and a suite that
reports every other test passing. Overriding ``norecursedirs`` would have fixed
it and would also have started collecting real build output; renaming costs
nothing.
**Opt-in locally, required in CI**, a variation on the optional-binary rule. These
install into a fresh virtual environment and start a server, which is about a
minute — so they skip unless `VISIONSET_REQUIRE_WHEEL=1` says a wheel exists and
must be tested, or `VISIONSET_WHEEL` names one. CI's `wheel` job sets the first
after running `scripts/build_dist.sh`, so a build step that silently produced
nothing goes red rather than quietly shrinking the suite.
"""
from __future__ import annotations
import json
import re
import socket
import subprocess
import time
import zipfile
from pathlib import Path
from urllib.error import URLError
from urllib.request import urlopen
import pytest
from tests.packaging._wheel import VERSION, clean_env, console_script, wheel_path
#: The ceiling the counted part of a wheel may not cross, a guard rather than a
#: budget. Everything but `ORT_PREFIX` is counted — see `MAX_ORT_BYTES`.
#:
#: That counted part is ~2.5 MB compressed today (the curated checkpoint manifests and
#: their licence evidence are about 0.15 MB of it), so the headroom is about 1.04x —
#: the UI and the format plugins have grown into most of it, and the next person
#: to read this is likelier to be raising the number than reassured by it.
#: It still fails loudly the day `node_modules/`, a fixture video or a `.venv`
#: gets swept in, which is the failure this exists for and the one that is
#: invisible in a directory listing.
MAX_WHEEL_BYTES = 2688 * 1024
#: The one deliberately enormous thing inside, measured separately so the guard
#: above keeps its teeth.
#:
#: `_static/ort/` is ONNX Runtime's WebAssembly runtime, ~25 MB uncompressed and
#: ~6.4 MB deflated, and it has to be in the wheel: browser inference runs the
#: model on the user's machine, and the wheel is the only thing that serves the
#: app. Folding it into `MAX_WHEEL_BYTES` would have meant raising that ceiling
#: past 8 MB, which is the same as deleting it — the accidents it exists to catch
#: are megabyte-sized. So the rest of the wheel is still held to 2.5 MB and this
#: payload is bounded on its own, where a version bump that doubles it is a
#: sentence about ONNX Runtime rather than a mystery about the wheel.
ORT_PREFIX = "visionset/_static/ort/"
MAX_ORT_BYTES = 10 * 1024 * 1024
#: Nothing matching these may be inside. Each is something that has ended up in
#: somebody's wheel: a dependency tree, a test corpus, a virtualenv, a workspace.
FORBIDDEN = (
"node_modules/",
".venv/",
"workspace-data/",
"visionset.db",
".git/",
".env",
"/tests/",
"/e2e/",
)
#: Media suffixes. `_static/` legitimately holds none today — the app ships as
#: HTML, CSS, JavaScript and one WebAssembly runtime — so any of these is
#: something nobody meant to ship.
FORBIDDEN_SUFFIXES = (
".pem",
".key",
".p12",
".pfx",
".mp4",
".mov",
".avi",
".jpg",
".jpeg",
".tiff",
".bmp",
# Browser model weights belong to the explicit CDN/cache acquisition flow.
# ONNX Runtime's own `.wasm` payload remains the deliberately packaged exception.
".onnx",
".pt",
)
#: How long the freshly installed server gets to bind a socket.
#:
#: Generous, because a cold import of fastapi, pydantic and sqlalchemy on a shared
#: CI runner is seconds rather than milliseconds, and this is the one place in the
#: suite where a wall-clock number decides a pass. It is a *ceiling*, not a
#: sleep — the loop returns the moment `/health` answers.
STARTUP_TIMEOUT_SECONDS = 60.0
WHEEL = wheel_path()
@pytest.fixture(scope="module")
def names() -> list[str]:
with zipfile.ZipFile(WHEEL) as archive:
return archive.namelist()
# --- what is inside -----------------------------------------------------------
def test_the_compiled_app_travels_inside_the_wheel(names: list[str]) -> None:
"""The delivery thesis, and the failure that has no error message.
A wheel built before `pnpm bundle:static` carries `_static/README.md` and
`_static/.gitkeep` and nothing else. It installs, it starts, and `/app/`
answers a 404 naming a script its user does not have.
"""
assert "visionset/_static/index.html" in names
assert any(name.startswith("visionset/_static/assets/") for name in names)
assert any(name.endswith(".js") for name in names)
assert any(name.endswith(".css") for name in names)
def test_the_browser_inference_runtime_travels_inside_the_wheel(names: list[str]) -> None:
"""The same failure as above, one directory over and with no 404 to read.
ONNX Runtime's WebAssembly runtime is fetched by the inference worker at the
moment a user first asks this device for a suggestion — not at page load — so a
wheel without it serves an app that looks entirely healthy until that click,
and then fails inside a worker where the SPA fallback has already answered the
404 with HTML. `frontend/app/vite.config.ts` copies the directory out of
`@visionset/browser-inference`'s build output for exactly this reason, and
nothing else in the suite would notice if that plugin were removed.
"""
assert any(name.startswith(ORT_PREFIX) for name in names)
assert any(name.endswith(".wasm") for name in names)
def test_the_bundle_was_built_for_the_ui_prefix(names: list[str]) -> None:
"""The bundle-base trap, and it is invisible once the wheel is built.
A bundle built with the dev base references `/assets/…`, which the SPA
fallback answers with `index.html` at **200** — so the page loads blank
rather than failing, and the browser console is the only place it shows.
"""
with zipfile.ZipFile(WHEEL) as archive:
index = archive.read("visionset/_static/index.html").decode("utf-8")
assert "/app/assets/" in index
assert re.search(r'src=["\']/assets/', index) is None
def test_the_package_itself_is_all_there(names: list[str]) -> None:
for expected in (
"visionset/__init__.py",
"visionset/cli/main.py",
"visionset/server/main.py",
"visionset/mcp/main.py",
"visionset/kernel/services/workspace_service.py",
"visionset/formats/ultralytics/__init__.py",
"visionset/formats/yolov5_yaml/__init__.py",
"visionset/formats/darknet/__init__.py",
"visionset/formats/coco/__init__.py",
"visionset/formats/voc/__init__.py",
"visionset/formats/verification.json",
):
assert expected in names, expected
def test_the_entry_points_ship_so_the_command_and_the_plugins_exist(
names: list[str],
) -> None:
"""Without this file there is no `visionset` command and no exporter at all.
Format discovery is `importlib.metadata` over the `visionset.formats` group,
which reads *installed* metadata — so a wheel whose entry points did not make
it is one where `visionset format list` is empty and nothing says why.
"""
(entry_points,) = [name for name in names if name.endswith("entry_points.txt")]
with zipfile.ZipFile(WHEEL) as archive:
declared = archive.read(entry_points).decode("utf-8")
assert "visionset = visionset.cli.main:app" in declared
assert "[visionset.formats]" in declared
for plugin in ("ultralytics", "yolov5-yaml", "darknet", "coco", "voc"):
assert f"{plugin} = visionset.formats." in declared
assert "dummy" not in declared
assert "[visionset.preprocessing]" in declared
for plugin in ("pillow-resize", "pillow-augment"):
assert f"{plugin} = visionset.preprocessing.pillow:" in declared
# --- what is not -------------------------------------------------------------
def test_nothing_enormous_came_along_for_the_ride(names: list[str]) -> None:
for name in names:
assert not any(part in name for part in FORBIDDEN), name
assert not name.endswith(FORBIDDEN_SUFFIXES), name
def test_the_wheel_stays_under_its_ceiling() -> None:
"""A guard, not a budget. See `MAX_WHEEL_BYTES`.
Everything but the ORT runtime, which has its own ceiling — see `MAX_ORT_BYTES`
for why the two are counted apart.
"""
with zipfile.ZipFile(WHEEL) as archive:
size = sum(
entry.compress_size
for entry in archive.infolist()
if not entry.filename.startswith(ORT_PREFIX)
)
assert size < MAX_WHEEL_BYTES, f"{WHEEL.name} is {size} bytes without the ORT runtime"
def test_the_ort_runtime_stays_under_its_own_ceiling() -> None:
"""See `MAX_ORT_BYTES`."""
with zipfile.ZipFile(WHEEL) as archive:
size = sum(
entry.compress_size
for entry in archive.infolist()
if entry.filename.startswith(ORT_PREFIX)
)
assert size < MAX_ORT_BYTES, f"{ORT_PREFIX} is {size} bytes"
def test_no_source_maps_ship(names: list[str]) -> None:
"""They would roughly double the wheel and are useless without the sources."""
assert not [name for name in names if name.endswith(".map")]
# --- what it says it is -------------------------------------------------------
def test_the_wheel_metadata_agrees_with_the_version_file(names: list[str]) -> None:
"""One source of truth, checked at the far end of the pipeline.
`VERSION` is read by hatch at build time, by `__init__` at runtime through
installed metadata, and by `pnpm version:sync` for the frontend. This is the
place they can silently disagree: a stale `dist/` from before a version bump
looks exactly like a fresh one.
"""
assert WHEEL.name.startswith(f"visionset-{VERSION}-")
(metadata,) = [name for name in names if name.endswith(".dist-info/METADATA")]
with zipfile.ZipFile(WHEEL) as archive:
declared = archive.read(metadata).decode("utf-8")
assert f"Version: {VERSION}\n" in declared
assert f"visionset-{VERSION}.dist-info/" in metadata
# --- installing it ------------------------------------------------------------
def _command(venv: Path, *arguments: str) -> subprocess.CompletedProcess[str]:
return subprocess.run(
[str(console_script(venv)), *arguments],
capture_output=True,
text=True,
check=False,
env=clean_env(),
)
def test_the_installed_command_reports_the_version_the_wheel_claims(
installed: Path,
) -> None:
result = _command(installed, "--version")
assert result.returncode == 0, result.stderr
assert result.stdout.strip() == VERSION
def test_the_installed_command_finds_every_exporter(installed: Path) -> None:
"""Entry-point discovery, from the *installed* metadata rather than the source tree."""
result = _command(installed, "format", "list", "--json")
assert result.returncode == 0, result.stderr
names = [item["name"] for item in json.loads(result.stdout)["items"]]
assert names == [
"bdd100k-lane",
"classification",
"classification-dir",
"coco",
"coco-panoptic",
"createml",
"culane",
"curvelanes",
"cvat-images",
"cvat-video",
"darknet",
"dota",
"kitti",
"labelme",
"mot",
"open-images",
"openlane-2d",
"segmentation-png",
"tfrecord",
"tusimple",
"ultralytics",
"voc",
"yolo-obb",
"yolov5-yaml",
]
def test_the_installed_command_reads_the_shipped_verification_descriptor(installed: Path) -> None:
"""The descriptor is package data; a wheel without it would call every built-in unproven."""
result = _command(installed, "format", "matrix", "--json")
assert result.returncode == 0, result.stderr
document = json.loads(result.stdout)
assert document["descriptor_version"] >= 1
assert {row["status"] for row in document["items"]} == {"validated"}
def test_the_installed_server_serves_the_real_app(installed: Path, tmp_path: Path) -> None:
"""The acceptance criterion, end to end: pip, then a browser could use it.
Asserts the *bundle* came back rather than merely a 200 — the SPA fallback
answers `index.html` for anything under `/app/` that looks like a browser
request, so a status code alone proves almost nothing.
"""
workspace = tmp_path / "ws"
result = _command(installed, "init", str(workspace))
assert result.returncode == 0, result.stderr
foreign_cwd = tmp_path / "elsewhere"
foreign_cwd.mkdir()
with _serving(installed, workspace, _free_port(), foreign_cwd) as base:
index = _get(f"{base}/app/")
assert "/app/assets/" in index
# `/` is a redirect to `/app/`, which urllib follows, so this proves the
# front door works and not merely the mount.
assert _get(base) == index
# …and the API is still at the root, which is why the app is not.
assert '"status"' in _get(f"{base}/health")
def _free_port() -> int:
"""A port nothing is listening on, chosen by the kernel.
Not a constant: a hard-coded port collides with a previous run that outlived
its test, and the failure is a **404 from somebody else's server** rather
than a refused connection — which reads as a bug in the wheel. There is a
race between closing this socket and the server binding it, and it is the
right trade: the alternative is a number that is wrong on somebody's machine
forever.
"""
with socket.socket() as probe:
probe.bind(("127.0.0.1", 0))
return int(probe.getsockname()[1])
def _serving(venv: Path, workspace: Path, port: int, cwd: Path) -> _Server:
return _Server(venv, workspace, port, cwd)
class _Server:
"""`visionset server` for the duration of a `with`, or say why it never came up."""
def __init__(self, venv: Path, workspace: Path, port: int, cwd: Path) -> None:
self._cwd = cwd
self._venv = venv
self._workspace = workspace
self._port = port
self._process: subprocess.Popen[str] | None = None
def __enter__(self) -> str:
try:
return self._start()
except BaseException:
# **`__exit__` is not called when `__enter__` raises**, so a server
# that came up but never answered would outlive the test and hold its
# port — which the next run meets as a 404 from a stranger rather than
# as a refused connection.
self.__exit__()
raise
def _start(self) -> str:
self._process = subprocess.Popen(
[
str(console_script(self._venv)),
"server",
"--workspace",
str(self._workspace),
"--port",
str(self._port),
],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
env=clean_env(),
cwd=self._cwd,
)
base = f"http://127.0.0.1:{self._port}"
# Polled against a deadline rather than a fixed number of tries: a
# refused connection comes back instantly, so a bare loop would spend its
# whole budget in milliseconds and report a timeout that never happened.
deadline = time.monotonic() + STARTUP_TIMEOUT_SECONDS
while time.monotonic() < deadline:
if self._process.poll() is not None:
output = self._process.communicate()[0]
raise AssertionError(f"the server exited before answering:\n{output}")
try:
urlopen(f"{base}/health", timeout=1).read()
except (URLError, OSError):
time.sleep(0.1)
continue
return base
raise AssertionError(f"the server never answered /health within {STARTUP_TIMEOUT_SECONDS}s")
def __exit__(self, *_: object) -> None:
if self._process is None:
return
self._process.terminate()
try:
self._process.wait(timeout=20)
except subprocess.TimeoutExpired: # pragma: no cover - a hung server
self._process.kill()
self._process.wait(timeout=20)
def _get(url: str) -> str:
with urlopen(url, timeout=10) as response:
return response.read().decode("utf-8")