Personal AI, On Personal Devices
Python
fix(packaging): shrink PyPI archives and validate release artifacts (#953)
Elliot Sluskya7c233c3575f
diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.ymlindex 3fa7ed2e..509c8127 100644--- a/.github/workflows/pypi-publish.yml+++ b/.github/workflows/pypi-publish.yml@@ -98,6 +98,36 @@ jobs:- name: Build packagerun: uv build+ - name: Validate release artifacts+ run: |+ set -euo pipefail+ # Keep this check in the workflow: the target tag may predate it.+ uv run --no-project python - <<'PY'+ from pathlib import Path++ max_artifact_bytes = 20 * 1024 * 1024+ wheels = sorted(Path("dist").glob("*.whl"))+ sdists = sorted(Path("dist").glob("*.tar.gz"))+ if not wheels or not sdists:+ raise SystemExit(+ "Expected at least one wheel and one .tar.gz source archive"+ )++ oversized = []+ for artifact in [*wheels, *sdists]:+ size = artifact.stat().st_size+ print(f"{artifact.name}: {size:,} bytes ({size / 1024**2:.2f} MiB)")+ if size > max_artifact_bytes:+ oversized.append(artifact.name)+ if oversized:+ raise SystemExit(+ "Archive exceeds the 20 MiB upload budget: "+ + ", ".join(oversized)+ + ". Check for bundled build outputs or native binaries."+ )+ PY+ uvx twine check --strict dist/*+- name: Publish to TestPyPI (dry run)if: ${{ inputs.dry_run }}env:@@ -106,7 +136,7 @@ jobs:set -euo pipefailif [[ -z "${UV_PUBLISH_TOKEN:-}" ]]; thenecho "::warning::TEST_PYPI_API_TOKEN is not set — skipping the TestPyPI upload."- echo "Build + twine check passed, which validated version derivation and packaging end to end."+ echo "Build, archive size checks, and strict twine validation passed."echo "To exercise a real upload, add a TEST_PYPI_API_TOKEN secret (or a TestPyPI trusted publisher)."exit 0fidiff --git a/pyproject.toml b/pyproject.tomlindex d0d04407..c9cc1e2c 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -231,8 +231,20 @@ fallback_version = "0.0.0+unknown"[tool.uv.sources]openjarvis-rust = { path = "rust/crates/openjarvis-python" }+[tool.hatch.build.targets.sdist]+# Tauri release bundles carry these executables; Python source distributions+# must not duplicate platform binaries on every PyPI release.+exclude = [+ "/desktop/src-tauri/binaries",+ "/frontend/src-tauri/binaries",+]+# The publishing workflow builds this UI before packaging. Keep its generated+# files even though the directory is intentionally ignored by Git.+artifacts = ["/src/openjarvis/server/static/**"]+[tool.hatch.build.targets.wheel]packages = ["src/openjarvis"]+artifacts = ["/src/openjarvis/server/static/**"]exclude = ["/src/openjarvis/agents/claude_code_runner",]diff --git a/tests/deployment/test_packaging.py b/tests/deployment/test_packaging.pyindex 47b6bae6..5dbc3806 100644--- a/tests/deployment/test_packaging.py+++ b/tests/deployment/test_packaging.py@@ -10,8 +10,14 @@ which the desktop app installs from source viafrom __future__ import annotations+import os+import shutil+import subprocess+import tarfile+import zipfilefrom pathlib import Path+import pytestimport tomllibROOT = Path(__file__).resolve().parent.parent.parent@@ -100,3 +106,95 @@ def test_claude_runner_wheel_maps_only_runtime_files() -> None:)assert (CLAUDE_RUNNER / filename).is_file()assert f"/{source}" in wheel["exclude"]+++def test_sdist_omits_desktop_binaries_and_rebuilds_runtime_wheel(tmp_path) -> None:+ uv = shutil.which("uv")+ if uv is None:+ pytest.skip("uv is required for archive-content validation")++ project = tmp_path / "project"+ project.mkdir()+ runtime_sources = (+ "src/openjarvis/__init__.py",+ "src/openjarvis/templates/data/assistant.toml",+ )+ force_include = _pyproject()["tool"]["hatch"]["build"]["targets"]["wheel"][+ "force-include"+ ]+ for relative in (+ "pyproject.toml",+ ".gitignore",+ "README.md",+ "LICENSE",+ *runtime_sources,+ ):+ destination = project / relative+ destination.parent.mkdir(parents=True, exist_ok=True)+ shutil.copy2(ROOT / relative, destination)+ for relative in force_include:+ source, destination = ROOT / relative, project / relative+ destination.parent.mkdir(parents=True, exist_ok=True)+ if source.is_dir():+ shutil.copytree(+ source,+ destination,+ ignore=shutil.ignore_patterns("node_modules", "__pycache__"),+ )+ else:+ shutil.copy2(source, destination)++ binary_dirs = ("desktop/src-tauri/binaries", "frontend/src-tauri/binaries")+ for relative in binary_dirs:+ directory = project / relative+ directory.mkdir(parents=True)+ (directory / "bundled-native-executable").write_bytes(b"native binary")+ # Keep buildable desktop source; only prebuilt executables are excluded.+ desktop_source = "frontend/src-tauri/src/lib.rs"+ (project / desktop_source).parent.mkdir(parents=True)+ (project / desktop_source).write_text("// desktop source\n")+ generated_assets = {+ "src/openjarvis/server/static/index.html": (+ '<script src="assets/app.js"></script>'+ ),+ "src/openjarvis/server/static/assets/app.js": "// generated frontend\n",+ }+ for relative, contents in generated_assets.items():+ asset = project / relative+ asset.parent.mkdir(parents=True, exist_ok=True)+ asset.write_text(contents)++ dist = tmp_path / "dist"+ # uv's default build creates the wheel from the newly built sdist.+ subprocess.run(+ [uv, "build", "--out-dir", str(dist)],+ cwd=project,+ env=os.environ | {"SETUPTOOLS_SCM_PRETEND_VERSION": "1.0.0"},+ check=True,+ capture_output=True,+ text=True,+ timeout=90,+ )+ with tarfile.open(next(dist.glob("*.tar.gz"))) as archive:+ source_files = {member.name.split("/", 1)[1] for member in archive.getmembers()}+ assert not any(+ name.startswith(f"{directory}/")+ for name in source_files+ for directory in binary_dirs+ )+ assert desktop_source in source_files+ assert set(runtime_sources) <= source_files+ assert set(generated_assets) <= source_files+ with zipfile.ZipFile(next(dist.glob("*.whl"))) as archive:+ wheel_files = set(archive.namelist())+ assert {source.removeprefix("src/") for source in runtime_sources} <= wheel_files+ assert {source.removeprefix("src/") for source in generated_assets} <= wheel_files+ for source, destination in force_include.items():+ if (project / source).is_file():+ assert destination in wheel_files+ else:+ for path in (project / source).rglob("*"):+ if path.is_file():+ assert f"{destination}/{path.relative_to(project / source)}" in (+ wheel_files+ )diff --git a/tests/deployment/test_release_artifact_validation.py b/tests/deployment/test_release_artifact_validation.pynew file mode 100644index 00000000..bde53a17--- /dev/null+++ b/tests/deployment/test_release_artifact_validation.py@@ -0,0 +1,110 @@+"""Release archives must fit the upload budget before publication."""++from __future__ import annotations++import subprocess+import sys+from pathlib import Path++import pytest+import yaml++ROOT = Path(__file__).resolve().parents[2]+MAX_ARTIFACT_BYTES = 20 * 1024 * 1024+++def workflow_steps():+ workflow = yaml.safe_load((ROOT / ".github/workflows/pypi-publish.yml").read_text())+ return workflow["jobs"]["publish"]["steps"]+++def validation_command():+ return next(+ step["run"]+ for step in workflow_steps()+ if step.get("name") == "Validate release artifacts"+ )+++def run_validation(tmp_path):+ # A tag checkout may have no validation helper; only dist exists here.+ source = validation_command().split("<<'PY'\n", 1)[1].split("\nPY\n", 1)[0]+ return subprocess.run(+ [sys.executable, "-"],+ input=source,+ cwd=tmp_path,+ capture_output=True,+ text=True,+ check=False,+ )+++def distributions(tmp_path: Path) -> tuple[Path, Path]:+ dist = tmp_path / "dist"+ dist.mkdir()+ wheel = dist / "openjarvis-1.0.4-py3-none-any.whl"+ sdist = dist / "openjarvis-1.0.4.tar.gz"+ wheel.write_bytes(b"wheel")+ sdist.write_bytes(b"sdist")+ return wheel, sdist+++def test_reports_both_artifacts_without_checkout_helpers(tmp_path):+ wheel, sdist = distributions(tmp_path)+ result = run_validation(tmp_path)+ assert result.returncode == 0, result.stderr+ output = result.stdout+ assert wheel.name in output and sdist.name in output+ assert "5 bytes" in output+ assert "MiB" in output++[email protected]("artifact_index", [0, 1])+def test_rejects_oversized_wheel_or_sdist(tmp_path, artifact_index):+ archives = distributions(tmp_path)+ oversized = archives[artifact_index]+ with oversized.open("wb") as archive:+ archive.truncate(MAX_ARTIFACT_BYTES + 1)+ result = run_validation(tmp_path)+ assert result.returncode != 0+ assert oversized.name in result.stderr+ assert "exceeds the 20 MiB upload budget" in result.stderr+ assert all(artifact.name in result.stdout for artifact in archives)+++def test_exact_budget_is_allowed(tmp_path):+ wheel, _ = distributions(tmp_path)+ with wheel.open("wb") as archive:+ archive.truncate(MAX_ARTIFACT_BYTES)+ result = run_validation(tmp_path)+ assert result.returncode == 0, result.stderr++[email protected]("missing", ["wheel", "sdist", "both"])+def test_missing_distribution_is_an_error(tmp_path, missing):+ wheel, sdist = distributions(tmp_path)+ if missing in {"wheel", "both"}:+ wheel.unlink()+ if missing in {"sdist", "both"}:+ sdist.unlink()+ result = run_validation(tmp_path)+ assert result.returncode != 0+ assert "Expected at least one wheel and one" in result.stderr+++def test_metadata_and_size_validation_precede_both_upload_paths():+ steps = workflow_steps()+ validation = next(+ index+ for index, step in enumerate(steps)+ if "uvx twine check --strict" in step.get("run", "")+ )+ command = steps[validation]["run"]+ assert "set -euo pipefail" in command+ assert command.index("<<'PY'") < command.index("uvx twine check --strict")+ assert "if" not in steps[validation]+ uploads = [+ index for index, step in enumerate(steps) if "uv publish" in step.get("run", "")+ ]+ assert len(uploads) == 2+ assert all(validation < index for index in uploads)