Official Inference Code of EAGLE-4
ci(pkg): publish the qualified release files to PyPI
Seyfal Sultanov974ac803bb99
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.ymlindex 762e69a..06b840f 100644--- a/.github/workflows/publish.yml+++ b/.github/workflows/publish.yml@@ -1,8 +1,9 @@-# Public eagle-harness: upload a release to PyPI. Publishing a GitHub release vX.Y.Z on this repo builds the files with-# wheels.yml and uploads them with PyPI trusted publishing (no API token) once a maintainer approves the `pypi`-# environment. The files go to PyPI only: the GitHub release carries the engine wheels (tools/engine_release.py). In the-# private source repo this workflow is skipped: releases there come from release-please, and the upload happens on this-# repo after the export.+# Public eagle-harness: upload a release to PyPI. Publishing a GitHub release vX.Y.Z on this repo uploads the release's+# qualified harness files (the sdist, the binary wheel and the pure wheel, staged on the draft release with their+# harness-SHA256SUMS by tools/release_files.py) to PyPI with trusted publishing (no API token). These are the exact+# files the release images and the release benchmarks installed, so the job verifies and uploads them instead of+# rebuilding. Once PyPI serves the same SHA256s, `tools/release_files.py remove` takes them off the release page, which+# keeps only the engine wheels (tools/engine_release.py). In the private source repo this workflow is skipped.name: publishon:@@ -13,25 +14,32 @@ permissions:contents: readjobs:- wheels:- if: github.repository == 'eagle-hq/EAGLE-4'- uses: ./.github/workflows/wheels.yml- with:- ref: ${{ github.event.release.tag_name }}-publish:- needs: wheels+ if: github.repository == 'eagle-hq/EAGLE-4'runs-on: ubuntu-24.04+ timeout-minutes: 30environment:name: pypiurl: https://pypi.org/project/eagle-harness/permissions:+ contents: readid-token: write # PyPI trusted publishingsteps:- - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1with:- name: dist- path: dist+ ref: ${{ github.event.release.tag_name }}+ persist-credentials: false+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: "3.12"+ - run: python -m pip install twine+ - name: The release's harness files, each checked against harness-SHA256SUMS+ env:+ GH_TOKEN: ${{ github.token }}+ TAG: ${{ github.event.release.tag_name }}+ run: python tools/release_files.py fetch "$TAG" dist+ - run: python -m twine check --strict dist/*.tar.gz dist/*.whl dist/pure/*.whl+ - run: python tools/check_dist.py dist- name: The upload set (sdist, binary wheel, pure wheel) carries the tag's versionenv:TAG: ${{ github.event.release.tag_name }}diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.ymlindex 822a834..7b76d81 100644--- a/.github/workflows/wheels.yml+++ b/.github/workflows/wheels.yml@@ -1,6 +1,7 @@# Build the sdist, the binary wheel and the pure wheel with tools/build_wheel.sh, then check them (twine check and# tools/check_dist.py: name, version, extras, entry points, contents, license state). Nothing is uploaded here: the-# files are a workflow artifact; publish.yml and the source repo's release workflow call this workflow.+# files are a workflow artifact. A release's files are built here before the release, qualified, staged on the draft+# release (tools/release_files.py stage) and uploaded to PyPI unchanged by publish.yml.## The binary wheel carries the native candidate-head library prebuilt for CUDA 12.9 and 13.0# (eagle_harness/kernels/build.py), so `pip install` needs no nvcc; the sdist and the pure wheel build it on first use.diff --git a/tests/test_release_files.py b/tests/test_release_files.pynew file mode 100644index 0000000..476e159--- /dev/null+++ b/tests/test_release_files.py@@ -0,0 +1,130 @@+# Copyright 2026 Eagle AI Corp.+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available++"""tools/release_files.py against a file-backed gh fake: stage, fetch, remove."""++import importlib.util+import json+import os+from pathlib import Path+import sys++import pytest++REPO = Path(__file__).resolve().parents[1]+spec = importlib.util.spec_from_file_location("release_files", REPO / "tools/release_files.py")+release_files = importlib.util.module_from_spec(spec)+spec.loader.exec_module(release_files)++TAG = "v0.1.1"+NAMES = ("eagle_harness-0.1.1.tar.gz", "eagle_harness-0.1.1-py3-none-manylinux_2_34_x86_64.whl",+ "eagle_harness-0.1.1-py3-none-any.whl")+GH = """+import json, os, shutil, sys+from pathlib import Path+args = sys.argv[1:]+assert args[-2:] == ["--repo", "eagle-hq/EAGLE-4"], args+args = args[:-2]+remote = Path(os.environ["GH_TEST_REMOTE"])+with open(os.environ["GH_TEST_LOG"], "a") as log:+ log.write(json.dumps(args) + "\\n")+assert args[0] == "release" and args[2] == "v0.1.1", args+if args[1] == "view":+ print(json.dumps({"tagName": "v0.1.1", "isDraft": os.environ.get("GH_TEST_DRAFT") == "true",+ "assets": [{"name": p.name} for p in remote.iterdir()]}))+elif args[1] == "upload":+ assert len(args) == 4, args+ target = remote / Path(args[3]).name+ assert not target.exists(), "no clobber"+ shutil.copyfile(args[3], target)+elif args[1] == "download":+ name = args[args.index("--pattern") + 1]+ target = Path(args[args.index("--output") + 1])+ shutil.copyfile(remote / name, target)+ if os.environ.get("GH_TEST_CORRUPT") == name:+ target.write_bytes(b"corrupted transfer")+elif args[1] == "delete-asset":+ assert args[4:] == ["--yes"], args+ (remote / args[3]).unlink()+else:+ raise AssertionError(args)+"""+++def release(tmp_path, monkeypatch):+ remote = tmp_path / "remote"+ remote.mkdir()+ fake = tmp_path / "bin/gh"+ fake.parent.mkdir()+ fake.write_text(f"#!{sys.executable}\n{GH}")+ fake.chmod(0o755)+ monkeypatch.setenv("PATH", f"{fake.parent}{os.pathsep}{os.environ['PATH']}")+ monkeypatch.setenv("GH_TEST_REMOTE", str(remote))+ monkeypatch.setenv("GH_TEST_LOG", str(tmp_path / "gh.jsonl"))+ monkeypatch.setenv("GH_TEST_DRAFT", "true")+ return remote, tmp_path / "gh.jsonl"+++def dist(tmp_path):+ root = tmp_path / "dist"+ (root / "pure").mkdir(parents=True, exist_ok=True)+ for name in NAMES:+ (root / "pure" / name if name.endswith("-any.whl") else root / name).write_bytes(name.encode() * 3)+ (root / "SHA256SUMS").write_text("ignored\n")+ (root / "build.txt").write_text("ignored\n")+ return root+++def uploads(log):+ return [Path(json.loads(line)[3]).name for line in log.read_text().splitlines() if json.loads(line)[1] == "upload"]+++def test_stage_fetch_round_trip(tmp_path, release):+ remote, log = release+ staged = release_files.stage(TAG, dist(tmp_path))+ assert sorted(staged) == sorted(NAMES)+ assert uploads(log)[-1] == release_files.MANIFEST # the manifest goes last+ assert release_files.stage(TAG, dist(tmp_path)) == staged # a rerun verifies and uploads nothing+ assert len(uploads(log)) == 4+ out = tmp_path / "out"+ assert release_files.fetch(TAG, out) == staged+ assert (out / "pure" / NAMES[2]).read_bytes() == NAMES[2].encode() * 3+ assert {p.name for p in out.iterdir()} == {NAMES[0], NAMES[1], "pure", "SHA256SUMS"}+++def test_stage_refuses_a_published_release_and_a_different_existing_file(tmp_path, release, monkeypatch):+ remote, _ = release+ monkeypatch.setenv("GH_TEST_DRAFT", "false")+ with pytest.raises(ValueError, match="published"):+ release_files.stage(TAG, dist(tmp_path))+ monkeypatch.setenv("GH_TEST_DRAFT", "true")+ (remote / NAMES[0]).write_bytes(b"other bytes")+ with pytest.raises(ValueError, match="refusing to replace"):+ release_files.stage(TAG, dist(tmp_path))+ assert {p.name for p in remote.iterdir()} == {NAMES[0]}+++def test_fetch_fails_on_a_corrupt_file(tmp_path, release, monkeypatch):+ release_files.stage(TAG, dist(tmp_path))+ monkeypatch.setenv("GH_TEST_CORRUPT", NAMES[1])+ with pytest.raises(ValueError, match="SHA256 mismatch"):+ release_files.fetch(TAG, tmp_path / "out")++[email protected]("names", [NAMES[:2], (*NAMES, "eagle_harness-0.1.1-cp312-cp312-win_amd64.whl"),+ ("eagle_harness-0.1.0.tar.gz", *NAMES[1:])])+def test_classify_wants_exactly_the_three_files_of_the_version(names):+ with pytest.raises(ValueError):+ release_files.classify(list(names), "0.1.1")+++def test_remove_waits_for_pypi_digests(tmp_path, release):+ remote, _ = release+ staged = release_files.stage(TAG, dist(tmp_path))+ with pytest.raises(ValueError, match="PyPI does not serve"):+ release_files.remove(TAG, published={**staged, NAMES[1]: "0" * 64})+ assert len(list(remote.iterdir())) == 4+ removed = release_files.remove(TAG, published=staged)+ assert removed == [*sorted(NAMES), release_files.MANIFEST]+ assert not list(remote.iterdir())diff --git a/tools/release_files.py b/tools/release_files.pynew file mode 100644index 0000000..28bfcde--- /dev/null+++ b/tools/release_files.py@@ -0,0 +1,203 @@+#!/usr/bin/env python3+# Copyright 2026 Eagle AI Corp.+# SPDX-License-Identifier: LicenseRef-Eagle-4-Source-Available++"""Carry the qualified eagle-harness files to PyPI through the GitHub release.++ release_files.py stage <tag> <dist dir> upload the sdist, the binary wheel and the pure wheel to the DRAFT+ release, then harness-SHA256SUMS; read every file back+ release_files.py fetch <tag> <out dir> download them, verify every SHA256, lay them out as build_wheel.sh does+ release_files.py remove <tag> once PyPI serves the same SHA256s, delete them from the release++The release files are built and GPU-qualified before the release (the release images install the same wheel), so PyPI+receives exactly those files rather than a rebuild. ``publish.yml`` runs ``fetch``. Standard library and ``gh`` only.+"""++from __future__ import annotations++import argparse+import hashlib+import json+from pathlib import Path+import re+import subprocess+import sys+import tempfile+import urllib.request++REPOSITORY = "eagle-hq/EAGLE-4"+MANIFEST = "harness-SHA256SUMS"+PYPI_SIMPLE = "https://pypi.org/simple/eagle-harness/"+++def patterns(version: str) -> dict[str, re.Pattern]:+ v = re.escape(version)+ return {"sdist": re.compile(rf"eagle_harness-{v}\.tar\.gz"),+ "binary": re.compile(rf"eagle_harness-{v}-py3-none-manylinux_\d+_\d+_x86_64\.whl"),+ "pure": re.compile(rf"eagle_harness-{v}-py3-none-any\.whl")}+++def version_of(tag: str) -> str:+ if not re.fullmatch(r"v\d+\.\d+\.\d+", tag):+ raise ValueError("release tag must have the form vX.Y.Z")+ return tag[1:]+++def sha256(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as stream:+ for block in iter(lambda: stream.read(1 << 20), b""):+ digest.update(block)+ return digest.hexdigest()+++def classify(names: list[str], version: str) -> dict[str, str]:+ """Exactly one sdist, one manylinux x86_64 wheel and one pure wheel of ``version``; nothing else."""+ found: dict[str, str] = {}+ for name in names:+ kinds = [kind for kind, pattern in patterns(version).items() if pattern.fullmatch(name)]+ if len(kinds) != 1 or kinds[0] in found:+ raise ValueError(f"unexpected or duplicate release file for {version}: {name}")+ found[kinds[0]] = name+ missing = patterns(version).keys() - found.keys()+ if missing:+ raise ValueError(f"missing release files for {version}: {', '.join(sorted(missing))}")+ return found+++def read_manifest(text: str, version: str) -> dict[str, str]:+ entries = {}+ for line in text.splitlines():+ match = re.fullmatch(r"([a-f0-9]{64}) (\S+)", line)+ if not match or match[2] in entries:+ raise ValueError(f"invalid or duplicate {MANIFEST} line: {line!r}")+ entries[match[2]] = match[1]+ classify(list(entries), version)+ return entries+++def gh(*args: str, repository: str) -> str:+ return subprocess.check_output(["gh", *args, "--repo", repository], text=True)+++def release_state(tag: str, repository: str) -> dict:+ release = json.loads(gh("release", "view", tag, "--json", "tagName,isDraft,assets", repository=repository))+ if release["tagName"] != tag:+ raise ValueError(f"release {tag} not found")+ return release+++def download(tag: str, name: str, target: Path, repository: str) -> None:+ gh("release", "download", tag, "--pattern", name, "--output", str(target), repository=repository)+++def local_files(dist: Path, version: str) -> dict[str, Path]:+ paths = [p for p in [*dist.glob("eagle_harness-*"), *(dist / "pure").glob("eagle_harness-*")] if p.is_file()]+ found = classify([p.name for p in paths], version)+ by_name = {p.name: p for p in paths}+ return {kind: by_name[name] for kind, name in found.items()}+++def stage(tag: str, dist: Path, repository: str = REPOSITORY) -> dict[str, str]:+ version = version_of(tag)+ files = local_files(dist, version)+ checksums = {p.name: sha256(p) for p in sorted(files.values(), key=lambda p: p.name)}+ release = release_state(tag, repository)+ if not release["isDraft"]:+ raise ValueError(f"{tag} is published; stage the files on the draft release before publishing it")+ existing = {asset["name"] for asset in release["assets"]}+ with tempfile.TemporaryDirectory(prefix="harness-stage-") as temporary:+ work = Path(temporary)+ manifest = work / MANIFEST+ manifest.write_text("".join(f"{digest} {name}\n" for name, digest in checksums.items()))+ uploads = [*sorted(files.values(), key=lambda p: p.name), manifest]+ expected = {**checksums, MANIFEST: sha256(manifest)}+ # Preflight: a file already on the release must be byte-identical; nothing is ever replaced.+ for path in uploads:+ if path.name in existing:+ download(tag, path.name, work / f"existing-{path.name}", repository)+ if sha256(work / f"existing-{path.name}") != expected[path.name]:+ raise ValueError(f"{tag} already carries a different {path.name}; refusing to replace it")+ for path in uploads: # the manifest last: its presence means every file is there+ if path.name not in existing:+ gh("release", "upload", tag, str(path), repository=repository)+ download(tag, path.name, work / f"after-{path.name}", repository)+ if sha256(work / f"after-{path.name}") != expected[path.name]:+ raise ValueError(f"read-back of {tag}/{path.name} does not match")+ print(f"staged {tag}/{path.name} sha256={expected[path.name]}")+ return checksums+++def fetch(tag: str, out: Path, repository: str = REPOSITORY) -> dict[str, str]:+ version = version_of(tag)+ if out.exists() and any(out.iterdir()):+ raise ValueError(f"output directory is not empty: {out}")+ (out / "pure").mkdir(parents=True, exist_ok=True)+ download(tag, MANIFEST, out / MANIFEST, repository)+ entries = read_manifest((out / MANIFEST).read_text(), version)+ kinds = classify(list(entries), version)+ for kind, name in kinds.items():+ target = out / "pure" / name if kind == "pure" else out / name+ download(tag, name, target, repository)+ if sha256(target) != entries[name]:+ raise ValueError(f"SHA256 mismatch for {name}: the release file differs from {MANIFEST}")+ print(f"verified {name} sha256={entries[name]}")+ (out / MANIFEST).replace(out / "SHA256SUMS")+ return entries+++def pypi_digests(url: str = PYPI_SIMPLE) -> dict[str, str]:+ request = urllib.request.Request(url, headers={"Accept": "application/vnd.pypi.simple.v1+json"})+ with urllib.request.urlopen(request, timeout=60) as response:+ files = json.load(response)["files"]+ return {f["filename"]: f["hashes"].get("sha256", "") for f in files}+++def remove(tag: str, repository: str = REPOSITORY, published: dict[str, str] | None = None) -> list[str]:+ version = version_of(tag)+ with tempfile.TemporaryDirectory(prefix="harness-remove-") as temporary:+ manifest = Path(temporary) / MANIFEST+ download(tag, MANIFEST, manifest, repository)+ entries = read_manifest(manifest.read_text(), version)+ published = pypi_digests() if published is None else published+ differing = [name for name, digest in entries.items() if published.get(name) != digest]+ if differing:+ raise ValueError(f"PyPI does not serve these files with the release SHA256 yet: {', '.join(differing)}")+ present = {asset["name"] for asset in release_state(tag, repository)["assets"]}+ removed = []+ for name in [*sorted(entries), MANIFEST]:+ if name in present:+ gh("release", "delete-asset", tag, name, "--yes", repository=repository)+ removed.append(name)+ return removed+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--repository", default=REPOSITORY)+ commands = parser.add_subparsers(dest="command", required=True)+ stage_parser = commands.add_parser("stage")+ stage_parser.add_argument("tag")+ stage_parser.add_argument("dist", type=Path)+ fetch_parser = commands.add_parser("fetch")+ fetch_parser.add_argument("tag")+ fetch_parser.add_argument("out", type=Path)+ remove_parser = commands.add_parser("remove")+ remove_parser.add_argument("tag")+ args = parser.parse_args(argv)+ try:+ if args.command == "stage":+ stage(args.tag, args.dist, args.repository)+ elif args.command == "fetch":+ fetch(args.tag, args.out, args.repository)+ else:+ for name in remove(args.tag, args.repository):+ print(f"removed {args.tag}/{name} (PyPI serves the same SHA256)")+ except (ValueError, subprocess.CalledProcessError, OSError) as error:+ print(f"release_files: {error}", file=sys.stderr)+ return 1+ return 0+++if __name__ == "__main__":+ sys.exit(main())