~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
build: enforce lean package artifacts (#6086)
LearningCircuit3acf5ab2a27f
diff --git a/.github/scripts/package_artifact_policy.py b/.github/scripts/package_artifact_policy.pynew file mode 100644index 0000000000..48eee9d4f6--- /dev/null+++ b/.github/scripts/package_artifact_policy.py@@ -0,0 +1,491 @@+#!/usr/bin/env python3+"""Fail closed when a release artifact is unexpectedly large or opaque.++The repository intentionally contains a large development test suite and+several dependency lockfiles. They are useful in Git, but are not runtime+package data. This gate inspects the wheel and source distribution immediately+after PDM builds them, before either artifact can be uploaded or published.+"""++from __future__ import annotations++import argparse+import stat+import sys+import tarfile+import zipfile+from pathlib import Path, PurePosixPath+++MIB = 1024 * 1024+MAX_ARTIFACT_BYTES = {"wheel": 7 * MIB, "sdist": 7 * MIB}+MAX_UNPACKED_BYTES = 32 * MIB+MAX_MEMBER_BYTES = 8 * MIB+MAX_FILE_MEMBERS = 2_000++FORBIDDEN_COMPONENTS = {+ ".git",+ ".mypy_cache",+ ".pytest_cache",+ ".ruff_cache",+ "__pycache__",+ "node_modules",+ "tests",+}+FORBIDDEN_BASENAMES = {+ ".coverage",+ ".ds_store",+ "npm-shrinkwrap.json",+ "package-lock.json",+ "pdm.lock",+ "pipfile.lock",+ "pnpm-lock.yaml",+ "poetry.lock",+ "uv.lock",+ "yarn.lock",+}+FORBIDDEN_SUFFIXES = {".pyc", ".pyo"}++MAGIC_SIGNATURES = (+ (b"\x7fELF", "ELF executable/object"),+ (b"MZ", "PE executable"),+ (b"\xca\xfe\xba\xbe", "Java class/Mach-O binary"),+ (b"\xfe\xed\xfa\xce", "Mach-O binary"),+ (b"\xfe\xed\xfa\xcf", "Mach-O binary"),+ (b"\xce\xfa\xed\xfe", "Mach-O binary"),+ (b"\xcf\xfa\xed\xfe", "Mach-O binary"),+ (b"\x89PNG\r\n\x1a\n", "PNG image"),+ (b"\xff\xd8\xff", "JPEG image"),+ (b"GIF87a", "GIF image"),+ (b"GIF89a", "GIF image"),+ (b"%PDF-", "PDF document"),+ (b"PK\x03\x04", "ZIP/container"),+ (b"PK\x05\x06", "empty ZIP/container"),+ (b"\x1f\x8b", "gzip data"),+ (b"BZh", "bzip2 data"),+ (b"\xfd7zXZ\x00", "xz data"),+ (b"7z\xbc\xaf\x27\x1c", "7z archive"),+ (b"Rar!\x1a\x07", "RAR archive"),+ (b"SQLite format 3\x00", "SQLite database"),+ (b"\x00asm", "WebAssembly"),+ (b"OggS", "Ogg media"),+ (b"fLaC", "FLAC audio"),+)+++def artifact_kind(path: Path) -> str | None:+ if path.name.endswith(".whl"):+ return "wheel"+ if path.name.endswith(".tar.gz"):+ return "sdist"+ return None+++def _safe_parts(name: str) -> tuple[str, ...] | None:+ if (+ not name+ or "\\" in name+ or any(+ ord(character) < 32 or ord(character) == 127 for character in name+ )+ ):+ return None+ path = PurePosixPath(name)+ if (+ not path.parts+ or path.is_absolute()+ or any(part in {"", ".", ".."} or ":" in part for part in path.parts)+ ):+ return None+ return path.parts+++def _logical_path(name: str, *, sdist_root: str | None) -> PurePosixPath | None:+ parts = _safe_parts(name)+ if parts is None:+ return None+ if sdist_root is not None:+ if not parts or parts[0] != sdist_root or len(parts) == 1:+ return None+ parts = parts[1:]+ return PurePosixPath(*parts)+++def _path_policy_error(path: PurePosixPath) -> str | None:+ lowered = tuple(part.lower() for part in path.parts)+ forbidden = sorted(FORBIDDEN_COMPONENTS.intersection(lowered))+ if forbidden:+ return f"forbidden directory component(s): {', '.join(forbidden)}"+ if path.name.lower() in FORBIDDEN_BASENAMES:+ return f"forbidden lock/cache file: {path.name}"+ if path.suffix.lower() in FORBIDDEN_SUFFIXES:+ return f"forbidden generated bytecode: {path.suffix}"+ return None+++def _package_path(path: PurePosixPath) -> PurePosixPath:+ if path.parts and path.parts[0] == "src":+ return PurePosixPath(*path.parts[1:])+ return path+++def _expected_binary_error(+ path: PurePosixPath, data: bytes+) -> tuple[bool, str | None]:+ package_path = _package_path(path)+ rendered = package_path.as_posix()++ if rendered == "local_deep_research/web/static/favicon.png":+ valid = data.startswith(b"\x89PNG\r\n\x1a\n")+ return (+ True,+ None if valid else "approved PNG path has an invalid signature",+ )++ if rendered in {+ "local_deep_research/web/static/sounds/error.mp3",+ "local_deep_research/web/static/sounds/success.mp3",+ }:+ valid = data.startswith(b"ID3") or (+ len(data) >= 2 and data[0] == 0xFF and data[1] & 0xE0 == 0xE0+ )+ return (+ True,+ None if valid else "approved MP3 path has an invalid signature",+ )++ font_prefix = ("local_deep_research", "web", "static", "dist", "fonts")+ if package_path.parts[: len(font_prefix)] == font_prefix:+ suffix = package_path.suffix.lower()+ # Only font formats with a fixed, checkable magic are accepted here.+ # `.svg` fonts are plain text (no binary signature to verify) and+ # `.eot` starts with a size header instead of a fixed magic, so+ # neither can be added to this map without weakening the check+ # this gate exists to provide. If a frontend dependency bump ever+ # routes `.svg`/`.eot` output into dist/fonts/, the release build+ # will block here until this map is deliberately extended.+ signatures = {+ ".ttf": (b"\x00\x01\x00\x00", b"OTTO"),+ ".woff": (b"wOFF",),+ ".woff2": (b"wOF2",),+ }+ expected = signatures.get(suffix)+ if expected is None:+ return (+ True,+ f"unsupported generated font type: {suffix or '<none>'}",+ )+ valid = any(data.startswith(signature) for signature in expected)+ return True, None if valid else f"invalid {suffix} font signature"++ return False, None+++def _unexpected_binary_reason(data: bytes) -> str | None:+ for signature, description in MAGIC_SIGNATURES:+ if data.startswith(signature):+ return description+ if data.startswith(b"RIFF") and data[8:12] in {b"AVI ", b"WAVE", b"WEBP"}:+ return "RIFF binary"+ if len(data) >= 12 and data[4:8] == b"ftyp":+ return "ISO media container"+ if b"\x00" in data:+ return "NUL byte"+ try:+ data.decode("utf-8")+ except UnicodeDecodeError:+ return "non-UTF-8 content"+ controls = sum(+ 1+ for byte in data+ if (byte < 32 and byte not in {9, 10, 12, 13}) or byte == 127+ )+ if controls >= 8 and controls / max(len(data), 1) >= 0.01:+ return "dense binary control bytes"+ return None+++def _content_policy_error(path: PurePosixPath, data: bytes) -> str | None:+ expected_binary, error = _expected_binary_error(path, data)+ if expected_binary:+ return error+ reason = _unexpected_binary_reason(data)+ if reason is not None:+ return f"unexpected binary content ({reason})"+ return None+++def _resource_errors(file_count: int, unpacked_bytes: int) -> list[str]:+ errors = []+ if file_count > MAX_FILE_MEMBERS:+ errors.append(+ f"contains {file_count:,} files; limit is {MAX_FILE_MEMBERS:,}"+ )+ if unpacked_bytes > MAX_UNPACKED_BYTES:+ errors.append(+ f"unpacks to {unpacked_bytes:,} bytes; limit is "+ f"{MAX_UNPACKED_BYTES:,}"+ )+ return errors+++def _inspect_wheel(path: Path) -> tuple[int, int, list[str]]:+ errors: list[str] = []+ with zipfile.ZipFile(path) as archive:+ members = archive.infolist()+ files = [member for member in members if not member.is_dir()]+ unpacked = sum(member.file_size for member in files)+ errors.extend(_resource_errors(len(files), unpacked))+ if errors:+ return len(files), unpacked, errors++ seen: set[PurePosixPath] = set()+ for member in members:+ logical = _logical_path(member.filename, sdist_root=None)+ if logical is None:+ errors.append(f"unsafe wheel member path: {member.filename!r}")+ continue+ mode = member.external_attr >> 16+ if mode and stat.S_ISLNK(mode):+ errors.append(f"symbolic link is not permitted: {logical}")+ continue+ if member.is_dir():+ error = _path_policy_error(logical)+ if error is None and member.file_size:+ error = "directory entry carries data"+ if error is not None:+ errors.append(f"{logical}: {error}")+ continue+ if logical in seen:+ errors.append(f"duplicate wheel member: {logical}")+ continue+ seen.add(logical)+ if member.flag_bits & 0x1:+ errors.append(+ f"encrypted wheel member is not permitted: {logical}"+ )+ continue+ if member.file_size > MAX_MEMBER_BYTES:+ errors.append(+ f"{logical}: {member.file_size:,} bytes exceeds the per-file "+ f"limit of {MAX_MEMBER_BYTES:,}"+ )+ continue++ error = _path_policy_error(logical)+ if error is not None:+ errors.append(f"{logical}: {error}")+ continue+ try:+ data = archive.read(member)+ except (OSError, RuntimeError) as exc:+ errors.append(f"{logical}: unable to read member: {exc}")+ continue+ error = _content_policy_error(logical, data)+ if error is not None:+ errors.append(f"{logical}: {error}")++ return len(files), unpacked, errors+++def _inspect_sdist(path: Path) -> tuple[int, int, list[str]]:+ errors: list[str] = []+ with tarfile.open(path, mode="r:gz") as archive:+ members = archive.getmembers()+ roots = {+ parts[0]+ for member in members+ if (parts := _safe_parts(member.name)) is not None+ }+ if len(roots) != 1:+ errors.append(+ "source distribution must have exactly one safe root directory; "+ f"found {sorted(roots)!r}"+ )+ return 0, 0, errors+ root = next(iter(roots))++ files = [member for member in members if member.isfile()]+ unpacked = sum(member.size for member in files)+ errors.extend(_resource_errors(len(files), unpacked))+ if errors:+ return len(files), unpacked, errors++ seen: set[PurePosixPath] = set()+ for member in members:+ # The archive's own root is a valid directory entry. Every other+ # directory still needs path validation before it can be ignored.+ if member.isdir() and _safe_parts(member.name) == (root,):+ continue+ logical = _logical_path(member.name, sdist_root=root)+ if logical is None:+ errors.append(f"unsafe sdist member path: {member.name!r}")+ continue+ if member.isdir():+ error = _path_policy_error(logical)+ if error is None and member.size:+ error = "directory entry carries data"+ if error is not None:+ errors.append(f"{logical}: {error}")+ continue+ if not member.isfile():+ errors.append(+ f"non-regular archive member is not permitted: {logical}"+ )+ continue+ if logical in seen:+ errors.append(f"duplicate sdist member: {logical}")+ continue+ seen.add(logical)+ if member.size > MAX_MEMBER_BYTES:+ errors.append(+ f"{logical}: {member.size:,} bytes exceeds the per-file limit "+ f"of {MAX_MEMBER_BYTES:,}"+ )+ continue++ error = _path_policy_error(logical)+ if error is not None:+ errors.append(f"{logical}: {error}")+ continue+ extracted = archive.extractfile(member)+ if extracted is None:+ errors.append(f"{logical}: unable to read regular member")+ continue+ data = extracted.read()+ error = _content_policy_error(logical, data)+ if error is not None:+ errors.append(f"{logical}: {error}")++ return len(files), unpacked, errors+++def _largest_members(path: Path, kind: str) -> list[tuple[str, int]]:+ """Return up to 5 largest regular-file members, largest first.++ Best-effort diagnostics only: an artifact this is called for has+ already failed the overall size limit, so if it also can't be parsed+ (e.g. it's corrupt), this returns an empty list rather than raising.+ """+ try:+ if kind == "wheel":+ with zipfile.ZipFile(path) as archive:+ sized = [+ (member.filename, member.file_size)+ for member in archive.infolist()+ if not member.is_dir()+ ]+ else:+ with tarfile.open(path, mode="r:gz") as archive:+ sized = [+ (member.name, member.size)+ for member in archive.getmembers()+ if member.isfile()+ ]+ except (OSError, tarfile.TarError, zipfile.BadZipFile):+ return []+ sized.sort(key=lambda item: item[1], reverse=True)+ return sized[:5]+++def inspect_artifact(path: Path) -> tuple[dict[str, int | str], list[str]]:+ kind = artifact_kind(path)+ summary: dict[str, int | str] = {+ "kind": kind or "unknown",+ "size": 0,+ "files": 0,+ "unpacked": 0,+ }+ if kind is None:+ return summary, [f"unsupported artifact type: {path}"]+ try:+ size = path.stat().st_size+ except OSError as exc:+ return summary, [f"unable to stat {path}: {exc}"]+ summary["size"] = size+ if size > MAX_ARTIFACT_BYTES[kind]:+ error = (+ f"{kind} is {size:,} bytes; limit is {MAX_ARTIFACT_BYTES[kind]:,}"+ )+ largest = _largest_members(path, kind)+ if largest:+ details = ", ".join(+ f"{name} ({member_size:,} bytes)"+ for name, member_size in largest+ )+ error = f"{error}; largest members: {details}"+ return summary, [error]++ try:+ if kind == "wheel":+ files, unpacked, errors = _inspect_wheel(path)+ else:+ files, unpacked, errors = _inspect_sdist(path)+ except (OSError, tarfile.TarError, zipfile.BadZipFile) as exc:+ return summary, [f"cannot inspect {kind}: {exc}"]+ summary["files"] = files+ summary["unpacked"] = unpacked+ return summary, errors+++def _discover(inputs: list[Path]) -> tuple[list[Path], list[str]]:+ if len(inputs) != 1 or not inputs[0].is_dir():+ return inputs, []++ directory = inputs[0]+ children = sorted(directory.iterdir())+ artifacts = [+ path+ for path in children+ if path.is_file() and artifact_kind(path) is not None+ ]+ unexpected = [+ path.name+ for path in children+ if not (path.is_file() and artifact_kind(path) is not None)+ ]+ errors = []+ if unexpected:+ errors.append(f"unexpected files in {directory}: {unexpected!r}")+ for kind in ("wheel", "sdist"):+ matches = [path for path in artifacts if artifact_kind(path) == kind]+ if len(matches) != 1:+ errors.append(+ f"expected exactly one {kind} in {directory}; found {len(matches)}"+ )+ return artifacts, errors+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "artifacts",+ nargs="+",+ type=Path,+ help="artifact files, or one directory containing one wheel and one sdist",+ )+ args = parser.parse_args(argv)++ artifacts, errors = _discover(args.artifacts)+ summaries = []+ for artifact in artifacts:+ summary, artifact_errors = inspect_artifact(artifact)+ summaries.append((artifact, summary))+ errors.extend(f"{artifact}: {error}" for error in artifact_errors)++ if errors:+ print("Package artifact policy failed:", file=sys.stderr)+ for error in errors:+ print(f" - {error}", file=sys.stderr)+ return 1++ for artifact, summary in summaries:+ print(+ f"OK {artifact}: {summary['kind']}, {summary['size']:,} bytes, "+ f"{summary['files']:,} files, {summary['unpacked']:,} unpacked bytes"+ )+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.ymlindex e2b8608018..b115db235f 100644--- a/.github/workflows/publish.yml+++ b/.github/workflows/publish.yml@@ -370,6 +370,9 @@ jobs:echo "Package sizes:"du -h dist/*+ - name: Enforce package artifact policy+ run: python .github/scripts/package_artifact_policy.py dist/+- name: Upload packageuses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1with:diff --git a/.github/workflows/release-gate.yml b/.github/workflows/release-gate.ymlindex cec31b5b84..29f7a7a76e 100644--- a/.github/workflows/release-gate.yml+++ b/.github/workflows/release-gate.yml@@ -378,8 +378,11 @@ jobs:npm cinpm run build- - name: Build wheel with PDM- run: pdm build --no-sdist+ - name: Build wheel and source distribution with PDM+ run: pdm build++ - name: Enforce package artifact policy+ run: python .github/scripts/package_artifact_policy.py dist/- name: Verify pip install in clean environmentrun: |diff --git a/changelog.d/6086.misc.md b/changelog.d/6086.misc.mdnew file mode 100644index 0000000000..1418f7d2f1--- /dev/null+++ b/changelog.d/6086.misc.md@@ -0,0 +1 @@+Published source distributions (`.tar.gz`) no longer bundle the repository's `tests/` tree; it stays in Git and CI. Both the wheel and the sdist are now inspected against a size and content policy before upload, rejecting unexpected binaries, development-only files, and unsafe archive entries.diff --git a/pyproject.toml b/pyproject.tomlindex 4f6cad564a..a87457f960 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -239,6 +239,13 @@ include-package-data = true[tool.pdm]distribution = trueversion = { source = "file", path = "src/local_deep_research/__version__.py" }++[tool.pdm.build]+# PDM includes tests/ in source distributions by default. The complete test+# suite is maintained in Git and CI, but is not needed to build or install the+# package; shipping it made the v1.10.7 sdist roughly twice the necessary size.+excludes = ["tests/"]+[[tool.pdm.source]]url = "https://download.pytorch.org/whl/cpu"name = "torch"diff --git a/tests/ci/test_package_artifact_policy.py b/tests/ci/test_package_artifact_policy.pynew file mode 100644index 0000000000..cd8628707b--- /dev/null+++ b/tests/ci/test_package_artifact_policy.py@@ -0,0 +1,430 @@+"""Regression tests for the release artifact size and content gate."""++# allow: no-sut-import — this test invokes the release gate script as a+# subprocess (it runs standalone in CI before the package is installed),+# so it never imports local_deep_research directly.++from __future__ import annotations++import io+import stat+import subprocess+import sys+import tarfile+import tomllib+import zipfile+from pathlib import Path++import pytest+import yaml+++REPO_ROOT = Path(__file__).resolve().parents[2]+POLICY = REPO_ROOT / ".github" / "scripts" / "package_artifact_policy.py"+PYPROJECT = REPO_ROOT / "pyproject.toml"+PUBLISH_WORKFLOW = REPO_ROOT / ".github" / "workflows" / "publish.yml"+RELEASE_GATE = REPO_ROOT / ".github" / "workflows" / "release-gate.yml"++MIB = 1024 * 1024+++def _write_wheel(+ path: Path,+ members: dict[str, bytes],+ compression: int = zipfile.ZIP_DEFLATED,+) -> None:+ with zipfile.ZipFile(path, mode="w", compression=compression) as archive:+ for name, data in members.items():+ archive.writestr(name, data)+++def _write_sdist(path: Path, members: dict[str, bytes]) -> None:+ with tarfile.open(path, mode="w:gz") as archive:+ for name, data in members.items():+ info = tarfile.TarInfo(f"local_deep_research-1.0.0/{name}")+ info.size = len(data)+ archive.addfile(info, io.BytesIO(data))+++def _run_policy(*paths: Path) -> subprocess.CompletedProcess[str]:+ return subprocess.run(+ [sys.executable, str(POLICY), *map(str, paths)],+ cwd=REPO_ROOT,+ check=False,+ capture_output=True,+ text=True,+ timeout=30,+ )+++def _minimal_wheel(path: Path) -> None:+ _write_wheel(+ path,+ {+ "local_deep_research/__init__.py": b'__version__ = "1.0.0"\n',+ "local_deep_research-1.0.0.dist-info/METADATA": (+ b"Metadata-Version: 2.4\nName: local-deep-research\n"+ ),+ },+ )+++def _minimal_sdist(path: Path) -> None:+ _write_sdist(+ path,+ {+ "pyproject.toml": b"[build-system]\nrequires = []\n",+ "src/local_deep_research/__init__.py": b"# package\n",+ },+ )+++def test_clean_wheel_and_sdist_pass_as_a_complete_dist_directory(tmp_path):+ _minimal_wheel(tmp_path / "local_deep_research-1.0.0-py3-none-any.whl")+ _minimal_sdist(tmp_path / "local_deep_research-1.0.0.tar.gz")++ result = _run_policy(tmp_path)++ assert result.returncode == 0, result.stdout + result.stderr+ assert result.stdout.count("OK ") == 2+++ "member",+ [+ "tests/test_runtime.py",+ "pdm.lock",+ "src/package-lock.json",+ "src/local_deep_research/__pycache__/module.pyc",+ "src/local_deep_research/.pytest_cache/state",+ ],+)+def test_sdist_rejects_development_only_content(tmp_path, member):+ artifact = tmp_path / "local_deep_research-1.0.0.tar.gz"+ _write_sdist(artifact, {member: b"development-only\n"})++ result = _run_policy(artifact)++ assert result.returncode == 1+ assert member in result.stderr+++def test_disguised_binary_content_is_rejected(tmp_path):+ artifact = tmp_path / "local_deep_research-1.0.0-py3-none-any.whl"+ _write_wheel(+ artifact,+ {"local_deep_research/reviewable.py": b"PK\x03\x04not-python"},+ )++ result = _run_policy(artifact)++ assert result.returncode == 1+ assert "unexpected binary content (ZIP/container)" in result.stderr+++def test_only_expected_runtime_binary_locations_pass(tmp_path):+ artifact = tmp_path / "local_deep_research-1.0.0-py3-none-any.whl"+ _write_wheel(+ artifact,+ {+ "local_deep_research/web/static/favicon.png": (+ b"\x89PNG\r\n\x1a\nfixture"+ ),+ "local_deep_research/web/static/sounds/error.mp3": (+ b"\xff\xfb\x90\xc4fixture"+ ),+ "local_deep_research/web/static/sounds/success.mp3": (+ b"ID3fixture"+ ),+ "local_deep_research/web/static/dist/fonts/math.hash.woff": (+ b"wOFFfixture"+ ),+ "local_deep_research/web/static/dist/fonts/math.hash.woff2": (+ b"wOF2fixture"+ ),+ "local_deep_research/web/static/dist/fonts/math.hash.ttf": (+ b"\x00\x01\x00\x00fixture"+ ),+ },+ )++ result = _run_policy(artifact)++ assert result.returncode == 0, result.stdout + result.stderr+++def test_expected_binary_path_with_wrong_signature_fails(tmp_path):+ artifact = tmp_path / "local_deep_research-1.0.0-py3-none-any.whl"+ _write_wheel(+ artifact,+ {"local_deep_research/web/static/favicon.png": b"not a PNG\n"},+ )++ result = _run_policy(artifact)++ assert result.returncode == 1+ assert "approved PNG path has an invalid signature" in result.stderr+++ "member",+ [+ "../outside.py",+ "/outside.py",+ "C:/outside.py",+ "bad\\name.py",+ "bad\nname.py",+ ],+)+def test_unsafe_archive_member_path_fails(tmp_path, member):+ artifact = tmp_path / "local_deep_research-1.0.0-py3-none-any.whl"+ _write_wheel(artifact, {member: b"payload\n"})++ result = _run_policy(artifact)++ assert result.returncode == 1+ assert "unsafe wheel member path" in result.stderr+++def test_oversized_artifact_fails_before_archive_parsing(tmp_path):+ artifact = tmp_path / "oversized-py3-none-any.whl"+ with artifact.open("wb") as stream:+ stream.truncate(7 * 1024 * 1024 + 1)++ result = _run_policy(artifact)++ assert result.returncode == 1+ assert "limit is 7,340,032" in result.stderr+++def test_dist_directory_rejects_extra_or_missing_artifacts(tmp_path):+ _minimal_wheel(tmp_path / "local_deep_research-1.0.0-py3-none-any.whl")+ (tmp_path / "unexpected.zip").write_bytes(b"PK\x03\x04")++ result = _run_policy(tmp_path)++ assert result.returncode == 1+ assert "unexpected files" in result.stderr+ assert "expected exactly one sdist" in result.stderr+++def test_pdm_build_excludes_the_full_test_tree_from_sdists():+ config = tomllib.loads(PYPROJECT.read_text(encoding="utf-8"))++ assert config["tool"]["pdm"]["build"]["excludes"] == ["tests/"]+++ ("workflow_path", "job_name"),+ [+ (PUBLISH_WORKFLOW, "build-package"),+ (RELEASE_GATE, "pip-install-check"),+ ],+)+def test_real_release_builds_enforce_the_artifact_policy(+ workflow_path, job_name+):+ workflow = yaml.safe_load(workflow_path.read_text(encoding="utf-8"))+ steps = workflow["jobs"][job_name]["steps"]+ runs = [step.get("run", "") for step in steps]+ commands = [line.strip() for run in runs for line in run.splitlines()]++ assert "pdm build" in commands+ assert "pdm build --no-sdist" not in commands+ assert "python .github/scripts/package_artifact_policy.py dist/" in commands++[email protected]("kind", ["wheel", "sdist"])+ "name", ["../outside/", "/outside/", "bad\\name/", "./"]+)+def test_unsafe_directory_entries_fail(tmp_path, kind, name):+ artifact = tmp_path / ("sample.whl" if kind == "wheel" else "sample.tar.gz")+ if kind == "wheel":+ _minimal_wheel(artifact)+ with zipfile.ZipFile(artifact, "a") as archive:+ archive.writestr(name, b"")+ else:+ with tarfile.open(artifact, "w:gz") as archive:+ regular = tarfile.TarInfo("package/pyproject.toml")+ regular.size = 1+ archive.addfile(regular, io.BytesIO(b"#"))+ directory = tarfile.TarInfo(name)+ directory.type = tarfile.DIRTYPE+ archive.addfile(directory)++ result = _run_policy(artifact)++ assert result.returncode == 1+ assert f"unsafe {kind} member path" in result.stderr+++def test_wheel_rejects_symlink_mode_with_directory_name(tmp_path):+ artifact = tmp_path / "sample.whl"+ _minimal_wheel(artifact)+ with zipfile.ZipFile(artifact, "a") as archive:+ link = zipfile.ZipInfo("local_deep_research/link/")+ link.create_system = 3+ link.external_attr = (stat.S_IFLNK | 0o777) << 16+ archive.writestr(link, b"../target")++ result = _run_policy(artifact)++ assert result.returncode == 1+ assert "symbolic link is not permitted" in result.stderr++[email protected]("kind", ["wheel", "sdist"])+def test_ordinary_directory_entries_remain_supported(tmp_path, kind):+ artifact = tmp_path / ("sample.whl" if kind == "wheel" else "sample.tar.gz")+ if kind == "wheel":+ _minimal_wheel(artifact)+ with zipfile.ZipFile(artifact, "a") as archive:+ archive.writestr("local_deep_research/nested/", b"")+ else:+ with tarfile.open(artifact, "w:gz") as archive:+ for name in ["package", "package/src", "package/src/nested"]:+ directory = tarfile.TarInfo(name)+ directory.type = tarfile.DIRTYPE+ archive.addfile(directory)+ regular = tarfile.TarInfo("package/src/nested/module.py")+ regular.size = 1+ archive.addfile(regular, io.BytesIO(b"#"))++ result = _run_policy(artifact)++ assert result.returncode == 0, result.stderr++[email protected]("kind", ["wheel", "sdist"])+def test_directory_entry_carrying_data_is_rejected(tmp_path, kind):+ artifact = tmp_path / ("sample.whl" if kind == "wheel" else "sample.tar.gz")+ if kind == "wheel":+ _minimal_wheel(artifact)+ with zipfile.ZipFile(artifact, "a") as archive:+ archive.writestr(+ "local_deep_research/payload.so/", b"\x7fELF" + b"\x00" * 204+ )+ else:+ with tarfile.open(artifact, "w:gz") as archive:+ regular = tarfile.TarInfo("package/pyproject.toml")+ regular.size = 1+ archive.addfile(regular, io.BytesIO(b"#"))+ payload = b"\x7fELF" + b"\x00" * 204+ directory = tarfile.TarInfo("package/payload.so")+ directory.type = tarfile.DIRTYPE+ directory.size = len(payload)+ archive.addfile(directory, io.BytesIO(payload))++ result = _run_policy(artifact)++ assert result.returncode == 1+ assert "payload.so: directory entry carries data" in result.stderr+++def test_wheel_file_count_limit_is_enforced(tmp_path):+ artifact = tmp_path / "local_deep_research-1.0.0-py3-none-any.whl"+ members = {f"local_deep_research/f{i}.txt": b"" for i in range(2001)}+ _write_wheel(artifact, members)++ result = _run_policy(artifact)++ assert result.returncode == 1+ assert "contains 2,001 files; limit is 2,000" in result.stderr+++def test_wheel_member_size_limit_is_enforced(tmp_path):+ # Deflate-compressible zero bytes keep the on-disk artifact under the+ # 7 MiB artifact-size limit while the member's *uncompressed* size+ # (what MAX_MEMBER_BYTES checks) is one byte over 8 MiB, so it is the+ # per-file limit that fires rather than the whole-artifact limit.+ artifact = tmp_path / "local_deep_research-1.0.0-py3-none-any.whl"+ _write_wheel(+ artifact,+ {"local_deep_research/big.bin": b"\x00" * (8 * MIB + 1)},+ )++ result = _run_policy(artifact)++ assert result.returncode == 1+ assert "limit of 8,388,608" in result.stderr+++def test_sdist_unpacked_size_limit_is_enforced(tmp_path):+ artifact = tmp_path / "local_deep_research-1.0.0.tar.gz"+ _write_sdist(+ artifact,+ {"local_deep_research/big.bin": b"\x00" * (32 * MIB + 1)},+ )++ result = _run_policy(artifact)++ assert result.returncode == 1+ assert "limit is 33,554,432" in result.stderr+++def test_pyc_suffix_outside_pycache_fires_the_suffix_rule(tmp_path):+ artifact = tmp_path / "local_deep_research-1.0.0.tar.gz"+ _write_sdist(artifact, {"local_deep_research/mod.pyc": b"bytecode\n"})++ result = _run_policy(artifact)++ assert result.returncode == 1+ assert "forbidden generated bytecode: .pyc" in result.stderr+ assert "__pycache__" not in result.stderr+++def test_wheel_rejects_forbidden_path(tmp_path):+ artifact = tmp_path / "local_deep_research-1.0.0-py3-none-any.whl"+ _write_wheel(artifact, {"tests/x.py": b"content\n"})++ result = _run_policy(artifact)++ assert result.returncode == 1+ assert "forbidden directory component(s): tests" in result.stderr+++def test_sdist_rejects_forbidden_content(tmp_path):+ artifact = tmp_path / "local_deep_research-1.0.0.tar.gz"+ _write_sdist(+ artifact, {"local_deep_research/native.so": b"\x7fELFnot-real"}+ )++ result = _run_policy(artifact)++ assert result.returncode == 1+ assert "unexpected binary content (ELF executable/object)" in result.stderr+++def test_oversized_artifact_message_lists_largest_members(tmp_path):+ artifact = tmp_path / "oversized-py3-none-any.whl"+ # Stored, not deflated: zero-filled members compress to almost nothing,+ # and the on-disk size is what the artifact limit measures.+ _write_wheel(+ artifact,+ {+ "local_deep_research/big.bin": b"\x00" * (5 * MIB),+ "local_deep_research/medium.bin": b"\x00" * (2 * MIB),+ "local_deep_research/small.bin": b"\x00" * 1024,+ },+ compression=zipfile.ZIP_STORED,+ )++ result = _run_policy(artifact)++ assert result.returncode == 1+ assert "limit is 7,340,032" in result.stderr+ assert "local_deep_research/big.bin (5,242,880 bytes)" in result.stderr+ assert "local_deep_research/medium.bin (2,097,152 bytes)" in result.stderr+++def test_dist_directory_rejects_non_file_children(tmp_path):+ _minimal_wheel(tmp_path / "local_deep_research-1.0.0-py3-none-any.whl")+ _minimal_sdist(tmp_path / "local_deep_research-1.0.0.tar.gz")+ (tmp_path / "extra").mkdir()++ result = _run_policy(tmp_path)++ assert result.returncode == 1+ assert "unexpected files" in result.stderr+ assert "'extra'" in result.stderrdiff --git a/tests/web/test_vite_asset_pipeline.py b/tests/web/test_vite_asset_pipeline.pyindex 79971e08b8..94a609e565 100644--- a/tests/web/test_vite_asset_pipeline.py+++ b/tests/web/test_vite_asset_pipeline.py@@ -316,7 +316,7 @@ class TestReleasedInstallGetsDist:"""text = RELEASE_GATE_WF.read_text(encoding="utf-8")- assert "npm run build" in text and "pdm build --no-sdist" in text, (+ assert "npm run build" in text and "pdm build" in text, ("release-gate no longer builds a wheel from built frontend ""assets; this test's premise is gone")