From 47d30c0b0aae8d14d10d14e428a41a95919bea61 Mon Sep 17 00:00:00 2001 From: Gavin Ying Date: Sat, 14 Nov 2026 12:44:37 +0800 Subject: [PATCH] ci: one release guard for all three packages .github/scripts/release.py replaces modpoll's and modsim's preview-release.py, their version checks and modpoll-wot's inline check. Every release now proves the tag matches the package metadata, the commit is on v2 and each required check succeeded on it, found by name; modpoll-wot now requires its CI too, and all three require the integration suite. Its tests run in a new release tooling workflow and also prove that every required check is a job and that job names are unique across the workflows. The unused release_image_tags.py copies and the old scripts' tests are removed. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/release.py | 311 ++++++++++++++++++ .github/scripts/test_release.py | 205 ++++++++++++ .github/workflows/modpoll-release.yml | 18 +- .github/workflows/modpoll-wot-release.yml | 19 +- .github/workflows/modpoll.yml | 2 +- .github/workflows/modsim-release.yml | 15 +- .github/workflows/modsim.yml | 2 +- .github/workflows/release-tooling.yml | 38 +++ .../.github/scripts/check_release_version.py | 34 -- .../.github/scripts/preview-release.py | 188 ----------- .../.github/scripts/release_image_tags.py | 85 ----- .../modpoll/tests/test_preview_release.py | 180 ---------- .../modpoll/tests/test_release_image_tags.py | 122 ------- .../.github/scripts/check-release-version.py | 43 --- .../.github/scripts/check_release_version.py | 34 -- .../modsim/.github/scripts/preview-release.py | 189 ----------- .../.github/scripts/release_image_tags.py | 82 ----- packages/modsim/tests/test_modsim.py | 17 - packages/modsim/tests/test_preview_guard.py | 156 --------- .../modsim/tests/test_release_image_tags.py | 122 ------- 20 files changed, 584 insertions(+), 1278 deletions(-) create mode 100644 .github/scripts/release.py create mode 100644 .github/scripts/test_release.py create mode 100644 .github/workflows/release-tooling.yml delete mode 100644 packages/modpoll/.github/scripts/check_release_version.py delete mode 100644 packages/modpoll/.github/scripts/preview-release.py delete mode 100644 packages/modpoll/.github/scripts/release_image_tags.py delete mode 100644 packages/modpoll/tests/test_preview_release.py delete mode 100644 packages/modpoll/tests/test_release_image_tags.py delete mode 100644 packages/modsim/.github/scripts/check-release-version.py delete mode 100644 packages/modsim/.github/scripts/check_release_version.py delete mode 100644 packages/modsim/.github/scripts/preview-release.py delete mode 100644 packages/modsim/.github/scripts/release_image_tags.py delete mode 100644 packages/modsim/tests/test_preview_guard.py delete mode 100644 packages/modsim/tests/test_release_image_tags.py diff --git a/.github/scripts/release.py b/.github/scripts/release.py new file mode 100644 index 0000000..86b5f7d --- /dev/null +++ b/.github/scripts/release.py @@ -0,0 +1,311 @@ +"""Release checks for the three packages of this repository (standard library only). + +Every command takes the release tag, `-v` (for example `modsim-v2.0.0a14`): + + release.py version TAG [--root DIR] the tag matches the package metadata + release.py guard TAG version, commit on v2 and every required CI check succeeded + release.py pypi TAG PyPI has no files for the version yet, or exactly these files + release.py download TAG --directory DIR wait for the published wheel and verify its digest + +The commands work from any directory: package paths are relative to the repository root. +""" + +import argparse +from dataclasses import dataclass +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import time +import urllib.error +import urllib.request + +try: + import tomllib +except ModuleNotFoundError: # Python 3.10 + import tomli as tomllib + +ROOT = Path(__file__).resolve().parents[2] +PREVIEW = r"2\.[0-9]+\.[0-9]+(?:a|b|rc)[0-9]+" +ANY = r"[0-9]+\.[0-9]+\.[0-9]+(?:(?:a|b|rc)[0-9]+)?" +INTEGRATION = "integration conformance" + + +@dataclass(frozen=True) +class Package: + directory: str + versions: str + # The check runs that must have succeeded on the release commit, by name. Job names are unique + # across the repository's workflows; test_release.py proves each one is a job that exists. + checks: frozenset + module: str | None = None + + def path(self, root=ROOT): + return Path(root) / self.directory + + +PACKAGES = { + "modpoll": Package( + "packages/modpoll", + PREVIEW, + frozenset( + { + "quality-check", + "tox (3.10)", + "tox (3.14)", + "docs", + "modsim-equivalence", + INTEGRATION, + } + ), + ), + "modsim": Package( + "packages/modsim", + PREVIEW, + frozenset( + { + "modsim quality", + "modsim docs", + "modsim tox (3.10)", + "modsim tox (3.14)", + "modpoll snapshot replay", + "catalog-interop", + "single-device (ubuntu-latest)", + "single-device (macos-latest)", + "single-device (windows-latest)", + INTEGRATION, + } + ), + module="modsim/__init__.py", + ), + "modpoll-wot": Package( + "packages/modpoll-wot", + ANY, + frozenset( + { + "modpoll-wot test (3.10)", + "modpoll-wot test (3.14)", + "modpoll-wot package", + "consumer (modpoll)", + "consumer (modsim)", + INTEGRATION, + } + ), + ), +} + + +def parse_tag(tag): + """Return the package name, its definition and the version a release tag names.""" + for name in sorted(PACKAGES, key=len, reverse=True): + prefix = f"{name}-v" + if tag.startswith(prefix): + version = tag[len(prefix) :] + if re.fullmatch(PACKAGES[name].versions, version): + return name, PACKAGES[name], version + raise ValueError( + f"{tag}: {version} is not a version {name} releases from v2" + ) + raise ValueError( + f"{tag}: expected -v for one of {sorted(PACKAGES)}" + ) + + +def check_version(tag, root=ROOT): + """The tag must name the version in pyproject.toml and, where there is one, the module.""" + name, package, version = parse_tag(tag) + directory = package.path(root) + metadata = tomllib.loads((directory / "pyproject.toml").read_text(encoding="utf-8")) + declared = metadata.get("project", {}).get("version") + if declared != version: + raise ValueError(f"{tag}: {name} declares version {declared}") + if package.module: + text = (directory / package.module).read_text(encoding="utf-8") + found = re.search(r'^__version__ = "([^"]+)"', text, re.M) + if not found or found.group(1) != version: + raise ValueError(f"{tag}: {package.module} declares another version") + return name, package, version + + +def require_checks(package, runs, sha): + """Use the newest run of each name, so a rerun can neither hide nor repair the wrong commit.""" + latest = {} + for run in runs: + if run["name"] not in latest or run["id"] > latest[run["name"]]["id"]: + latest[run["name"]] = run + missing = sorted( + name + for name in package.checks + if latest.get(name, {}).get("head_sha") != sha + or latest[name].get("conclusion") != "success" + ) + if missing: + raise ValueError( + "release commit lacks successful checks: " + ", ".join(missing) + ) + + +def get_json(url, token=None): + headers = {"Accept": "application/json"} + if token: + headers["Authorization"] = "Bearer " + token + request = urllib.request.Request(url, headers=headers) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def check_runs(sha): + api = os.environ.get("GITHUB_API_URL", "https://api.github.com") + repository = os.environ["GITHUB_REPOSITORY"] + token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN") + runs, page = [], 1 + while True: + data = get_json( + f"{api}/repos/{repository}/commits/{sha}/check-runs?per_page=100&page={page}", + token, + ) + runs += data["check_runs"] + if len(runs) >= data["total_count"] or not data["check_runs"]: + return runs + page += 1 + + +def guard(tag): + name, package, version = check_version(tag) + sha = ( + os.environ.get("GITHUB_SHA") + or subprocess.check_output( + ["git", "rev-parse", "HEAD"], text=True, cwd=ROOT + ).strip() + ) + subprocess.run( + ["git", "merge-base", "--is-ancestor", sha, "origin/v2"], check=True, cwd=ROOT + ) + require_checks(package, check_runs(sha), sha) + print(f"Accepted {name} {version} at {sha}") + + +def local_artifacts(directory): + artifacts = { + path.name: hashlib.sha256(path.read_bytes()).hexdigest() + for path in Path(directory).iterdir() + if path.is_file() + and (path.name.endswith(".whl") or path.name.endswith(".tar.gz")) + } + if len(artifacts) != 2 or sum(name.endswith(".whl") for name in artifacts) != 1: + raise ValueError("exactly one wheel and one sdist are required") + return artifacts + + +def pypi_state(name, version, artifacts, fetch=get_json): + """`absent` when PyPI has no such version, `identical` when it holds exactly these files.""" + try: + data = fetch( + f"https://pypi.org/pypi/{name}/{version}/json?cache_bust={time.time_ns()}" + ) + except urllib.error.HTTPError as exc: + if exc.code == 404: + return "absent" + raise + published = {item["filename"]: item["digests"]["sha256"] for item in data["urls"]} + if published != artifacts: + raise ValueError( + f"PyPI already holds {name} {version} with other files; " + "publish the original artifacts or a new version" + ) + return "identical" + + +def wait_for(fetch, label, deadline, sleep=time.sleep, clock=time.monotonic): + """Retry a resource PyPI may not serve yet, without masking any other failure.""" + attempts = 0 + while True: + attempts += 1 + try: + value = fetch() + except urllib.error.HTTPError as exc: + if exc.code != 404: + raise + value = None + if value is not None: + return value + remaining = deadline - clock() + if remaining <= 0: + raise TimeoutError( + f"PyPI {label} still unavailable after {attempts} attempts" + ) + delay = min(20, remaining) + print( + f"PyPI {label} not available yet; retrying in {delay:.0f}s", + file=sys.stderr, + flush=True, + ) + sleep(delay) + + +def download_wheel(name, version, directory, fetch=get_json, read=None): + """Wait up to ten minutes for the published wheel and verify its digest.""" + deadline = time.monotonic() + 600 + + def find_wheel(): + data = fetch( + f"https://pypi.org/pypi/{name}/{version}/json?cache_bust={time.time_ns()}" + ) + wheels = [item for item in data["urls"] if item["filename"].endswith(".whl")] + if len(wheels) > 1: + raise ValueError("expected exactly one published wheel") + return wheels[0] if wheels else None + + item = wait_for(find_wheel, "wheel metadata", deadline) + + def fetch_wheel(): + separator = "&" if "?" in item["url"] else "?" + with urllib.request.urlopen( + f"{item['url']}{separator}cache_bust={time.time_ns()}", timeout=60 + ) as response: + return response.read() + + content = wait_for(read or fetch_wheel, "wheel file", deadline) + if hashlib.sha256(content).hexdigest() != item["digests"]["sha256"]: + raise ValueError("downloaded wheel does not match PyPI's SHA-256") + destination = Path(directory) / item["filename"] + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(content) + return destination + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("command", choices=("version", "guard", "pypi", "download")) + parser.add_argument("tag") + parser.add_argument( + "--root", type=Path, default=ROOT, help="checkout to read (version)" + ) + parser.add_argument( + "--directory", type=Path, help="where to save the wheel (download)" + ) + args = parser.parse_args(argv) + if args.command == "version": + name, _, version = check_version(args.tag, args.root) + print(f"{name} {version}") + elif args.command == "guard": + guard(args.tag) + elif args.command == "pypi": + name, package, version = check_version(args.tag) + state = pypi_state(name, version, local_artifacts(package.path() / "dist")) + if "GITHUB_OUTPUT" in os.environ: + with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output: + output.write(f"state={state}\n") + print(f"PyPI {name} {version}: {state}") + else: + if not args.directory: + parser.error("download requires --directory") + name, _, version = parse_tag(args.tag) + print(download_wheel(name, version, args.directory)) + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/test_release.py b/.github/scripts/test_release.py new file mode 100644 index 0000000..755f7da --- /dev/null +++ b/.github/scripts/test_release.py @@ -0,0 +1,205 @@ +"""The release checks every package's release workflow runs (.github/scripts/release.py).""" + +import hashlib +import importlib.util +import io +import itertools +from pathlib import Path +import shutil +import urllib.error + +import pytest +import yaml + +spec = importlib.util.spec_from_file_location( + "release", Path(__file__).with_name("release.py") +) +release = importlib.util.module_from_spec(spec) +spec.loader.exec_module(release) + +WORKFLOWS = release.ROOT / ".github/workflows" + + +def job_names(): + """Every check name the repository's workflows produce, with matrix values expanded.""" + names = [] + for path in sorted(WORKFLOWS.glob("*.yml")): + for key, job in yaml.safe_load(path.read_text())["jobs"].items(): + name = job.get("name", key) + matrix = job.get("strategy", {}).get("matrix", {}) + rows = ( + matrix.get("include") + or [ + dict(zip(matrix, values)) + for values in itertools.product( + *(v for v in matrix.values() if isinstance(v, list)) + ) + ] + or [{}] + ) + for row in rows: + expanded = name + for field, value in row.items(): + expanded = expanded.replace("${{ matrix.%s }}" % field, str(value)) + names.append((expanded, path.name)) + return names + + +def test_job_names_are_unique_across_workflows(): + # The guard finds checks by name; a second job with the same name could stand in for it. + seen = {} + for name, workflow in job_names(): + assert name not in seen, f"{name!r} in both {seen.get(name)} and {workflow}" + seen[name] = workflow + + +@pytest.mark.parametrize("package", sorted(release.PACKAGES)) +def test_every_required_check_is_a_job(package): + names = {name for name, _ in job_names()} + assert release.PACKAGES[package].checks <= names + assert "${{" not in " ".join(release.PACKAGES[package].checks) + + +def test_tags_name_their_package_and_a_version_it_releases(): + assert release.parse_tag("modpoll-v2.0.0a12")[::2] == ("modpoll", "2.0.0a12") + assert release.parse_tag("modsim-v2.0.0a14")[::2] == ("modsim", "2.0.0a14") + # The longest package name wins: this is modpoll-wot, not modpoll. + assert release.parse_tag("modpoll-wot-v0.7.0a1")[::2] == ("modpoll-wot", "0.7.0a1") + assert release.parse_tag("modpoll-wot-v1.0.0")[::2] == ("modpoll-wot", "1.0.0") + for tag in ( + "v2.0.0a12", + "modpoll-v1.6.2", + "modsim-v2.0.0", + "modsim-v2.0.0a1-extra", + "other-v1.0.0", + ): + with pytest.raises(ValueError): + release.parse_tag(tag) + + +def test_the_tag_must_match_the_package_metadata(): + for name, package in release.PACKAGES.items(): + version = release.tomllib.loads( + (package.path() / "pyproject.toml").read_text() + )["project"]["version"] + assert release.check_version(f"{name}-v{version}")[::2] == (name, version) + with pytest.raises(ValueError, match="declares version"): + release.check_version("modsim-v2.9.9a1") + + +def test_modsim_must_also_declare_the_version_in_its_module(tmp_path): + package = release.PACKAGES["modsim"] + target = package.path(tmp_path) + (target / "modsim").mkdir(parents=True) + shutil.copy(package.path() / "pyproject.toml", target) + version = release.tomllib.loads((target / "pyproject.toml").read_text())["project"][ + "version" + ] + (target / package.module).write_text('__version__ = "2.0.0a1"\n') + with pytest.raises(ValueError, match="modsim/__init__.py"): + release.check_version(f"modsim-v{version}", tmp_path) + (target / package.module).write_text(f'__version__ = "{version}"\n') + release.check_version(f"modsim-v{version}", tmp_path) + + +def run(name, run_id, conclusion="success", sha="abc"): + return {"name": name, "id": run_id, "conclusion": conclusion, "head_sha": sha} + + +def test_every_required_check_must_have_succeeded_on_the_commit(): + package = release.PACKAGES["modpoll-wot"] + passing = [run(name, index) for index, name in enumerate(sorted(package.checks))] + release.require_checks(package, passing, "abc") + with pytest.raises(ValueError, match="consumer \\(modsim\\)"): + release.require_checks( + package, [r for r in passing if r["name"] != "consumer (modsim)"], "abc" + ) + with pytest.raises(ValueError, match="lacks successful checks"): + release.require_checks(package, passing, "other") + # The newest run of a name decides: a later failure is not hidden by an earlier success, + # and a later success after a failure is accepted. + with pytest.raises(ValueError, match="modpoll-wot package"): + release.require_checks( + package, passing + [run("modpoll-wot package", 99, "failure")], "abc" + ) + retried = passing[:-1] + [ + run(passing[-1]["name"], 50, "failure"), + run(passing[-1]["name"], 51), + ] + release.require_checks(package, retried, "abc") + + +def not_found(): + return urllib.error.HTTPError( + "https://pypi.org", 404, "Not Found", {}, io.BytesIO() + ) + + +def test_pypi_holds_nothing_or_exactly_the_built_files(tmp_path): + (tmp_path / "pkg-1.0-py3-none-any.whl").write_bytes(b"wheel") + (tmp_path / "pkg-1.0.tar.gz").write_bytes(b"sdist") + local = release.local_artifacts(tmp_path) + + def missing(url): + raise not_found() + + assert release.pypi_state("pkg", "1.0", local, fetch=missing) == "absent" + published = { + "urls": [{"filename": n, "digests": {"sha256": d}} for n, d in local.items()] + } + assert ( + release.pypi_state("pkg", "1.0", local, fetch=lambda url: published) + == "identical" + ) + other = {"urls": [{"filename": "pkg-1.0.tar.gz", "digests": {"sha256": "0" * 64}}]} + with pytest.raises(ValueError, match="other files"): + release.pypi_state("pkg", "1.0", local, fetch=lambda url: other) + (tmp_path / "pkg-1.0-py3-none-any.whl").unlink() + with pytest.raises(ValueError, match="one wheel and one sdist"): + release.local_artifacts(tmp_path) + + +def test_waiting_retries_only_what_pypi_does_not_serve_yet(): + answers = iter([None, not_found(), "ready"]) + + def fetch(): + answer = next(answers) + if isinstance(answer, Exception): + raise answer + return answer + + clock = itertools.count() + assert ( + release.wait_for( + fetch, "x", 100, sleep=lambda s: None, clock=lambda: next(clock) + ) + == "ready" + ) + + def refused(): + raise urllib.error.HTTPError( + "https://pypi.org", 403, "Forbidden", {}, io.BytesIO() + ) + + with pytest.raises(urllib.error.HTTPError, match="403"): + release.wait_for(refused, "x", 100, sleep=lambda s: None) + with pytest.raises(TimeoutError): + release.wait_for(lambda: None, "x", 0, sleep=lambda s: None, clock=lambda: 1) + + +def test_a_downloaded_wheel_must_match_pypis_digest(tmp_path): + content = b"the wheel" + item = { + "filename": "pkg-1.0-py3-none-any.whl", + "url": "https://files.example/pkg.whl", + "digests": {"sha256": hashlib.sha256(content).hexdigest()}, + } + data = {"urls": [item]} + saved = release.download_wheel( + "pkg", "1.0", tmp_path, fetch=lambda url: data, read=lambda: content + ) + assert saved.read_bytes() == content + with pytest.raises(ValueError, match="SHA-256"): + release.download_wheel( + "pkg", "1.0", tmp_path, fetch=lambda url: data, read=lambda: b"tampered" + ) diff --git a/.github/workflows/modpoll-release.yml b/.github/workflows/modpoll-release.yml index 4d1e350..5b539ae 100644 --- a/.github/workflows/modpoll-release.yml +++ b/.github/workflows/modpoll-release.yml @@ -55,6 +55,7 @@ jobs: permissions: contents: write id-token: write + checks: read steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: @@ -66,10 +67,8 @@ jobs: - name: Require an accepted v2 preview candidate env: GH_TOKEN: ${{ github.token }} - TAG: ${{ needs.candidate.outputs.tag }} - run: | - git merge-base --is-ancestor "$GITHUB_SHA" origin/v2 - python .github/scripts/preview-release.py guard "$TAG" + GIT_TAG: ${{ needs.candidate.outputs.git-tag }} + run: python "$GITHUB_WORKSPACE/.github/scripts/release.py" guard "$GIT_TAG" - name: Build portable distributions run: uv build --no-sources --out-dir dist - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 @@ -86,8 +85,8 @@ jobs: - name: Check immutable version id: pypi env: - TAG: ${{ needs.candidate.outputs.tag }} - run: python .github/scripts/preview-release.py pypi "$TAG" + GIT_TAG: ${{ needs.candidate.outputs.git-tag }} + run: python "$GITHUB_WORKSPACE/.github/scripts/release.py" pypi "$GIT_TAG" - name: Publish application to PyPI if: steps.pypi.outputs.state == 'absent' # Trusted Publishing: PyPI accepts this workflow's OIDC identity; no token is stored. @@ -125,9 +124,10 @@ jobs: REGISTRY: ${{ vars.DOCKER_REGISTRY }} OWNER: ${{ vars.DOCKER_USERNAME }} TAG: ${{ needs.candidate.outputs.tag }} + GIT_TAG: ${{ needs.candidate.outputs.git-tag }} IMAGE_VERSION: ${{ needs.candidate.outputs.image-version }} run: | - python .github/scripts/check_release_version.py "$TAG" + python "$GITHUB_WORKSPACE/.github/scripts/release.py" version "$GIT_TAG" image="$REGISTRY/$OWNER/modpoll:$IMAGE_VERSION" # The image installs from the workspace lock, so it builds from the repository root. if docker buildx imagetools inspect "$image" >/dev/null 2>&1; then @@ -204,9 +204,9 @@ jobs: path: packages/modpoll/.interop/modsim - name: Download published application and install isolated fixtures env: - TAG: ${{ needs.candidate.outputs.tag }} + GIT_TAG: ${{ needs.candidate.outputs.git-tag }} run: | - python .github/scripts/preview-release.py download "$TAG" --directory "$RUNNER_TEMP/acceptance/distributions" + python "$GITHUB_WORKSPACE/.github/scripts/release.py" download "$GIT_TAG" --directory "$RUNNER_TEMP/acceptance/distributions" cp -r tests tools examples "$RUNNER_TEMP/acceptance/" uv venv "$RUNNER_TEMP/acceptance/.venv" uv pip install --python "$RUNNER_TEMP/acceptance/.venv/bin/python" "$RUNNER_TEMP"/acceptance/distributions/*.whl pytest pyserial==3.5 diff --git a/.github/workflows/modpoll-wot-release.yml b/.github/workflows/modpoll-wot-release.yml index 6d2d324..c52a3ac 100644 --- a/.github/workflows/modpoll-wot-release.yml +++ b/.github/workflows/modpoll-wot-release.yml @@ -22,24 +22,29 @@ jobs: permissions: contents: write id-token: write + checks: read steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 - - name: Require a tag on v2 that matches the package version + - name: Require an accepted v2 candidate + env: + GH_TOKEN: ${{ github.token }} run: | - git merge-base --is-ancestor "$GITHUB_SHA" origin/v2 - version=$(python3 -c 'import tomllib; print(tomllib.load(open("pyproject.toml", "rb"))["project"]["version"])') - test "$GITHUB_REF_NAME" = "modpoll-wot-v$version" - echo "VERSION=$version" >> "$GITHUB_ENV" + python "$GITHUB_WORKSPACE/.github/scripts/release.py" guard "$GITHUB_REF_NAME" + echo "VERSION=${GITHUB_REF_NAME#modpoll-wot-v}" >> "$GITHUB_ENV" - uses: jdx/mise-action@5228313ee0372e111a38da051671ca30fc5a96db # v3.6.3 with: version: '2026.10.1' working_directory: packages/modpoll-wot - run: mise run check - - name: Publish to PyPI without replacing existing files + - name: Check immutable version + id: pypi + run: python "$GITHUB_WORKSPACE/.github/scripts/release.py" pypi "$GITHUB_REF_NAME" + - name: Publish to PyPI + if: steps.pypi.outputs.state == 'absent' # Trusted Publishing: PyPI accepts this workflow's OIDC identity; no token is stored. - run: uv publish --no-progress --trusted-publishing always --check-url https://pypi.org/simple/ dist/* + run: uv publish --no-progress --trusted-publishing always dist/* - name: Verify the registry installation timeout-minutes: 15 run: | diff --git a/.github/workflows/modpoll.yml b/.github/workflows/modpoll.yml index f35d5a7..d2264ba 100644 --- a/.github/workflows/modpoll.yml +++ b/.github/workflows/modpoll.yml @@ -26,7 +26,7 @@ defaults: run: working-directory: packages/modpoll -# Job names are the check names the release guard requires (packages/modpoll/.github/scripts/preview-release.py). +# Job names are the check names the release guard requires (.github/scripts/release.py). jobs: quality-check: runs-on: ubuntu-latest diff --git a/.github/workflows/modsim-release.yml b/.github/workflows/modsim-release.yml index 24c156a..7e0a6a0 100644 --- a/.github/workflows/modsim-release.yml +++ b/.github/workflows/modsim-release.yml @@ -32,7 +32,7 @@ jobs: permissions: contents: write id-token: write - actions: read + checks: read steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: @@ -45,7 +45,7 @@ jobs: env: GH_TOKEN: ${{ github.token }} GIT_TAG: ${{ github.ref_name }} - run: python .github/scripts/preview-release.py guard "${GIT_TAG#modsim-}" + run: python "$GITHUB_WORKSPACE/.github/scripts/release.py" guard "$GIT_TAG" - run: uv build --no-sources --clear --out-dir dist - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: @@ -61,9 +61,9 @@ jobs: id: registry env: GIT_TAG: ${{ github.ref_name }} - run: python .github/scripts/preview-release.py immutable "${GIT_TAG#modsim-v}" + run: python "$GITHUB_WORKSPACE/.github/scripts/release.py" pypi "$GIT_TAG" - name: Publish PyPI package - if: steps.registry.outputs.exists == 'false' + if: steps.registry.outputs.state == 'absent' # Trusted Publishing: PyPI accepts this workflow's OIDC identity; no token is stored. run: uv publish --no-progress --trusted-publishing always dist/* - name: Publish GitHub prerelease @@ -136,15 +136,14 @@ jobs: env: GIT_TAG: ${{ inputs.tag || github.ref_name }} run: | - cd "$GITHUB_WORKSPACE/release/packages/modsim" - python .github/scripts/check_release_version.py "${GIT_TAG#modsim-}" - git rev-parse HEAD + python "$GITHUB_WORKSPACE/.github/scripts/release.py" version "$GIT_TAG" --root "$GITHUB_WORKSPACE/release" + git -C "$GITHUB_WORKSPACE/release" rev-parse HEAD - name: Install published wheel and test dependencies timeout-minutes: 15 env: GIT_TAG: ${{ inputs.tag || github.ref_name }} run: | - python .github/scripts/preview-release.py download "${GIT_TAG#modsim-v}" "$RUNNER_TEMP/distributions" + python "$GITHUB_WORKSPACE/.github/scripts/release.py" download "$GIT_TAG" --directory "$RUNNER_TEMP/distributions" - name: Test without application source run: | release="$GITHUB_WORKSPACE/release/packages/modsim" diff --git a/.github/workflows/modsim.yml b/.github/workflows/modsim.yml index d3929db..4e398ce 100644 --- a/.github/workflows/modsim.yml +++ b/.github/workflows/modsim.yml @@ -29,7 +29,7 @@ defaults: working-directory: packages/modsim # Job names are prefixed so they never share a check name with modpoll's; the release guard -# (packages/modsim/.github/scripts/preview-release.py) requires exactly these jobs. +# (.github/scripts/release.py) requires these checks. jobs: quality: name: modsim quality diff --git a/.github/workflows/release-tooling.yml b/.github/workflows/release-tooling.yml new file mode 100644 index 0000000..e46ffef --- /dev/null +++ b/.github/workflows/release-tooling.yml @@ -0,0 +1,38 @@ +name: release tooling +# The release checks every package's release workflow runs (.github/scripts/release.py), and the +# property they rely on: job names are unique across the repository's workflows. + +on: + push: + branches: [v2] + paths: + - .github/** + - packages/*/pyproject.toml + - packages/modsim/modsim/__init__.py + pull_request: + paths: + - .github/** + - packages/*/pyproject.toml + - packages/modsim/modsim/__init__.py + +permissions: + contents: read + +jobs: + tests: + name: release tooling tests + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: astral-sh/setup-uv@d0cc045d04ccac9d8b7881df0226f9e82c39688e # v6 + with: + version: 0.11.19 + python-version: '3.12' + enable-cache: true + cache-dependency-glob: uv.lock + - name: Install the workspace + run: uv sync --locked --all-packages --all-groups + - name: Lint the release checks + run: uv run --locked --no-sync ruff check .github/scripts + - name: Test the release checks + run: uv run --locked --no-sync pytest -q .github/scripts diff --git a/packages/modpoll/.github/scripts/check_release_version.py b/packages/modpoll/.github/scripts/check_release_version.py deleted file mode 100644 index fc5cd31..0000000 --- a/packages/modpoll/.github/scripts/check_release_version.py +++ /dev/null @@ -1,34 +0,0 @@ -"""Reject a release if its tag and checked-out package metadata differ.""" - -import sys -from pathlib import Path - -try: - import tomllib -except ModuleNotFoundError: - import tomli as tomllib - - -def package_version(): - metadata = tomllib.loads(Path("pyproject.toml").read_text(encoding="utf-8")) - try: - return metadata["project"]["version"] - except KeyError as exc: - raise ValueError("project version is missing from pyproject.toml") from exc - - -def main(): - tag = sys.argv[1] - expected = tag[1:] if tag.startswith("v") else tag - actual = package_version() - if actual != expected: - print( - "Project version %s does not match release tag %s" % (actual, tag), - file=sys.stderr, - ) - return 1 - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/packages/modpoll/.github/scripts/preview-release.py b/packages/modpoll/.github/scripts/preview-release.py deleted file mode 100644 index 5d3d8fa..0000000 --- a/packages/modpoll/.github/scripts/preview-release.py +++ /dev/null @@ -1,188 +0,0 @@ -"""Guard preview tags and immutable PyPI artifacts using only the standard library.""" - -import argparse -import hashlib -import json -import os -from pathlib import Path -import re -import sys - -try: - import tomllib -except ModuleNotFoundError: - import tomli as tomllib -import time -import urllib.error -import urllib.request - - -CHECKS = { - "quality-check", - "tox (3.10)", - "tox (3.14)", - "docs", - "modsim-equivalence", -} - - -def package_version(path): - metadata = tomllib.loads(Path(path).read_text(encoding="utf-8")) - try: - return metadata["project"]["version"] - except KeyError as exc: - raise ValueError("missing package version") from exc - - -def release_target(tag): - if re.fullmatch(r"v2\.[0-9]+\.[0-9]+(?:a|b|rc)[0-9]+", tag): - return "modpoll", tag[1:], Path(".") - raise ValueError("unsupported preview tag") - - -def get_json(url, token=None): - headers = {"Accept": "application/json"} - if token: - headers["Authorization"] = "Bearer " + token - with urllib.request.urlopen( - urllib.request.Request(url, headers=headers), timeout=30 - ) as response: - return json.load(response) - - -def require_checks(checks, sha): - # Select the most recent result for each name; reruns must not mask a new failure. - latest = {} - for check in checks: - name = check["name"] - if name not in latest or check["id"] > latest[name]["id"]: - latest[name] = check - for name in CHECKS: - check = latest.get(name, {}) - if check.get("head_sha") != sha or check.get("conclusion") != "success": - raise ValueError("candidate lacks a successful check: " + name) - - -def pypi_state(name, version, artifacts): - artifacts = [ - path - for path in artifacts - if path.is_file() - and (path.name.endswith(".whl") or path.name.endswith(".tar.gz")) - ] - expected = { - path.name: hashlib.sha256(path.read_bytes()).hexdigest() for path in artifacts - } - if ( - len(expected) != 2 - or not any(n.endswith(".whl") for n in expected) - or not any(n.endswith(".tar.gz") for n in expected) - ): - raise ValueError("exactly one wheel and one sdist are required") - try: - data = get_json( - f"https://pypi.org/pypi/{name}/{version}/json?cache_bust={time.time_ns()}" - ) - except urllib.error.HTTPError as exc: - if exc.code == 404: - return "absent" - raise - actual = {item["filename"]: item["digests"]["sha256"] for item in data["urls"]} - if actual != expected: - raise ValueError( - "existing PyPI release differs; use the original artifacts or a new version" - ) - return "identical" - - -def _wait_for_pypi(fetch, label, deadline): - """Wait for a newly published resource, without masking other failures.""" - attempts = 0 - while True: - attempts += 1 - try: - value = fetch() - except urllib.error.HTTPError as exc: - if exc.code != 404: - raise - value = None - if value is not None: - return value - remaining = deadline - time.monotonic() - if remaining <= 0: - raise TimeoutError( - f"PyPI {label} still unavailable after {attempts} attempts" - ) - delay = min(20, remaining) - print( - f"PyPI {label} not yet available (attempt {attempts}); retrying in {delay:.0f}s", - file=sys.stderr, - flush=True, - ) - time.sleep(delay) - - -def download_published_wheel(name, version, directory): - """Wait up to ten minutes for the published wheel and verify its digest.""" - deadline = time.monotonic() + 600 - - def find_wheel(): - # Change the query on each retry; a cache bypass is not guaranteed. - url = f"https://pypi.org/pypi/{name}/{version}/json?cache_bust={time.time_ns()}" - data = get_json(url) - wheels = [item for item in data["urls"] if item["filename"].endswith(".whl")] - if len(wheels) > 1: - raise ValueError("expected exactly one published wheel") - return wheels[0] if wheels else None - - item = _wait_for_pypi(find_wheel, "wheel metadata", deadline) - - def fetch_wheel(): - separator = "&" if "?" in item["url"] else "?" - url = f"{item['url']}{separator}cache_bust={time.time_ns()}" - with urllib.request.urlopen(url, timeout=60) as response: - return response.read() - - content = _wait_for_pypi(fetch_wheel, "wheel file", deadline) - if hashlib.sha256(content).hexdigest() != item["digests"]["sha256"]: - raise ValueError("downloaded wheel does not match PyPI's SHA-256") - destination = Path(directory) / item["filename"] - destination.parent.mkdir(parents=True, exist_ok=True) - destination.write_bytes(content) - return destination - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("operation", choices=("guard", "pypi", "download")) - parser.add_argument("tag") - parser.add_argument("--directory") - args = parser.parse_args() - name, version, path = release_target(args.tag) - if package_version(path / "pyproject.toml") != version: - raise ValueError("tag does not match package metadata") - if args.operation == "guard": - sha = os.environ["GITHUB_SHA"] - api = os.environ["GITHUB_API_URL"] - repo = os.environ["GITHUB_REPOSITORY"] - checks = get_json( - f"{api}/repos/{repo}/commits/{sha}/check-runs?per_page=100", - os.environ["GH_TOKEN"], - ) - if checks.get("total_count", 0) > 100: - raise ValueError("too many check runs; inspect the candidate explicitly") - require_checks(checks["check_runs"], sha) - print(f"Validated {name} {version} at {sha}") - elif args.operation == "pypi": - state = pypi_state(name, version, list((path / "dist").iterdir())) - with open(os.environ["GITHUB_OUTPUT"], "a") as output: - output.write(f"state={state}\n") - print("PyPI artifacts: " + state) - else: - if not args.directory: - parser.error("download requires --directory") - print(download_published_wheel(name, version, args.directory)) - - -if __name__ == "__main__": - main() diff --git a/packages/modpoll/.github/scripts/release_image_tags.py b/packages/modpoll/.github/scripts/release_image_tags.py deleted file mode 100644 index 43e598b..0000000 --- a/packages/modpoll/.github/scripts/release_image_tags.py +++ /dev/null @@ -1,85 +0,0 @@ -"""Choose Docker tags without allowing an older release to replace newer aliases.""" - -import json -import os -import re -import sys -import urllib.request - -VERSION = re.compile(r"^v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$") - - -def parse_version(tag): - match = VERSION.fullmatch(tag) - return tuple(map(int, match.groups())) if match else None - - -def select_tags(tag, releases): - version = parse_version(tag) - if version is None: - raise ValueError("release tag must be a stable semantic version") - versions = [] - for release in releases: - if release.get("draft") or release.get("prerelease"): - continue - candidate = parse_version(release.get("tag_name", "")) - if candidate is not None: - versions.append(candidate) - if version not in versions: - raise ValueError("release tag is not a published stable GitHub release") - tags = ["%d.%d.%d" % version] - if version == max(v for v in versions if v[0] == version[0]): - tags.append(str(version[0])) - if version == max(v for v in versions if v[:2] == version[:2]): - tags.append("%d.%d" % version[:2]) - is_latest = version == max(versions) - if is_latest: - tags.append("latest") - return tags, is_latest - - -def fetch_releases(): - api = os.environ["GITHUB_API_URL"].rstrip("/") - repo = os.environ["GITHUB_REPOSITORY"] - token = os.environ["GH_TOKEN"] - releases = [] - for page in range(1, 101): - req = urllib.request.Request( - "%s/repos/%s/releases?per_page=100&page=%d" % (api, repo, page), - headers={ - "Authorization": "Bearer " + token, - "Accept": "application/vnd.github+json", - }, - ) - with urllib.request.urlopen(req, timeout=30) as response: - batch = json.load(response) - if not isinstance(batch, list): - raise ValueError("GitHub releases response is not a list") - releases.extend(batch) - if len(batch) < 100: - return releases - raise ValueError("too many release pages to choose tags safely") - - -def main(): - tags, is_latest = select_tags(os.environ["TAG"], fetch_releases()) - image = "%s/%s/%s" % ( - os.environ["DOCKER_REGISTRY"], - os.environ["DOCKER_USERNAME"], - os.environ["IMAGE_NAME"], - ) - for tag in tags: - print("%s:%s" % (image, tag)) - with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output: - output.write("latest=%s\n" % str(is_latest).lower()) - output.write( - "docs=%s\n" % str(str(parse_version(os.environ["TAG"])[0]) in tags).lower() - ) - - -if __name__ == "__main__": - try: - main() - except Exception as exc: - print("Cannot select release image tags: %s" % exc, file=sys.stderr) - sys.exit(1) diff --git a/packages/modpoll/tests/test_preview_release.py b/packages/modpoll/tests/test_preview_release.py deleted file mode 100644 index da58149..0000000 --- a/packages/modpoll/tests/test_preview_release.py +++ /dev/null @@ -1,180 +0,0 @@ -"""Release gates must reject wrong routes, stale CI and differing registry bytes.""" - -import hashlib -import io -import importlib.util -from pathlib import Path -import urllib.error - -import pytest - -spec = importlib.util.spec_from_file_location( - "preview_release", - Path(__file__).resolve().parents[1] / ".github/scripts/preview-release.py", -) -release = importlib.util.module_from_spec(spec) -spec.loader.exec_module(release) - - -def test_release_routes_do_not_accept_stable_tags_or_other_packages(): - assert release.release_target("v2.0.0a2")[:2] == ("modpoll", "2.0.0a2") - for tag in ( - "v1.6.2", - "v2.0.0", - "v2.0.0a1-extra", - "other-v0.1.0a1", - "modpoll-wot-v0.2.0a1", - ): - with pytest.raises(ValueError): - release.release_target(tag) - - -def test_release_gate_requires_same_sha_and_latest_success_for_every_job(): - checks = [ - {"id": i, "name": name, "head_sha": "candidate", "conclusion": "success"} - for i, name in enumerate(release.CHECKS) - ] - release.require_checks(checks, "candidate") - for invalid in ( - checks[:-1], - checks + [dict(checks[0], id=100, conclusion="failure")], - [dict(c, head_sha="old") for c in checks], - ): - with pytest.raises(ValueError): - release.require_checks(invalid, "candidate") - - -def test_registry_retries_require_exact_original_filenames_and_hashes( - monkeypatch, tmp_path -): - wheel, sdist = tmp_path / "package.whl", tmp_path / "package.tar.gz" - wheel.write_bytes(b"wheel") - sdist.write_bytes(b"sdist") - files = [wheel, sdist] - data = { - "urls": [ - { - "filename": p.name, - "digests": {"sha256": hashlib.sha256(p.read_bytes()).hexdigest()}, - } - for p in files - ] - } - sidecar = tmp_path / ".gitignore" - sidecar.write_text("*\n") - files.append(sidecar) - requests = [] - - def get_json(url): - requests.append(url) - return data - - monkeypatch.setattr(release, "get_json", get_json) - assert release.pypi_state("package", "0.1a1", files) == "identical" - assert "cache_bust=" in requests[-1] - wheel.write_bytes(b"different build") - with pytest.raises(ValueError, match="differs"): - release.pypi_state("package", "0.1a1", files) - with pytest.raises(ValueError, match="wheel and one sdist"): - release.pypi_state("package", "0.1a1", [wheel]) - - -def test_registry_outage_is_not_treated_as_an_unused_version(monkeypatch, tmp_path): - files = [tmp_path / "package.whl", tmp_path / "package.tar.gz"] - for path in files: - path.write_bytes(b"artifact") - - def error(code): - def fetch(url): - raise urllib.error.HTTPError(url, code, "unavailable", {}, None) - - return fetch - - monkeypatch.setattr(release, "get_json", error(404)) - assert release.pypi_state("package", "0.1a1", files) == "absent" - monkeypatch.setattr(release, "get_json", error(503)) - with pytest.raises(urllib.error.HTTPError): - release.pypi_state("package", "0.1a1", files) - - -def test_downloaded_wheel_matches_pypi_metadata(monkeypatch, tmp_path): - content = b"published wheel" - data = { - "urls": [ - { - "filename": "package-0.2-py3-none-any.whl", - "url": "https://files.pythonhosted.org/package.whl", - "digests": {"sha256": hashlib.sha256(content).hexdigest()}, - } - ] - } - monkeypatch.setattr(release, "get_json", lambda url: data) - monkeypatch.setattr( - release.urllib.request, - "urlopen", - lambda url, timeout: io.BytesIO(content), - ) - wheel = release.download_published_wheel("package", "0.2", tmp_path) - assert wheel.read_bytes() == content - - data["urls"][0]["digests"]["sha256"] = "wrong" - with pytest.raises(ValueError, match="SHA-256"): - release.download_published_wheel("package", "0.2", tmp_path) - - -def test_pypi_propagation_retries_metadata_and_wheel(monkeypatch, tmp_path, capsys): - content = b"published wheel" - item = { - "filename": "package.whl", - "url": "https://files.pythonhosted.org/package.whl", - "digests": {"sha256": hashlib.sha256(content).hexdigest()}, - } - clock = [0] - urls = [] - downloads = [] - monkeypatch.setattr(release.time, "monotonic", lambda: clock[0]) - monkeypatch.setattr( - release.time, "sleep", lambda seconds: clock.__setitem__(0, clock[0] + seconds) - ) - monkeypatch.setattr(release.time, "time_ns", lambda: clock[0]) - - def metadata(url): - urls.append(url) - if len(urls) <= 8: - raise urllib.error.HTTPError(url, 404, "not yet visible", {}, None) - return {"urls": [] if len(urls) == 9 else [item]} - - def download(url, timeout): - downloads.append(url) - if len(downloads) == 1: - raise urllib.error.HTTPError(url, 404, "not yet visible", {}, None) - return io.BytesIO(content) - - monkeypatch.setattr(release, "get_json", metadata) - monkeypatch.setattr(release.urllib.request, "urlopen", download) - assert ( - release.download_published_wheel("package", "0.2", tmp_path).read_bytes() - == content - ) - assert len(urls) == 10 and len(set(urls)) == 10 - assert len(downloads) == 2 and len(set(downloads)) == 2 - assert clock[0] == 200 - assert "retrying" in capsys.readouterr().err - - -def test_pypi_retry_timeout_and_other_errors(monkeypatch): - clock = [0] - monkeypatch.setattr(release.time, "monotonic", lambda: clock[0]) - monkeypatch.setattr( - release.time, "sleep", lambda seconds: clock.__setitem__(0, clock[0] + seconds) - ) - with pytest.raises(TimeoutError, match="metadata still unavailable"): - release._wait_for_pypi(lambda: None, "metadata", 45) - assert clock[0] == 45 - - def forbidden(): - raise urllib.error.HTTPError("https://example.org", 403, "forbidden", {}, None) - - with pytest.raises(urllib.error.HTTPError, match="403"): - release._wait_for_pypi(forbidden, "metadata", 600) - assert clock[0] == 45 diff --git a/packages/modpoll/tests/test_release_image_tags.py b/packages/modpoll/tests/test_release_image_tags.py deleted file mode 100644 index 5f0a9dd..0000000 --- a/packages/modpoll/tests/test_release_image_tags.py +++ /dev/null @@ -1,122 +0,0 @@ -import importlib.util -from pathlib import Path - -import pytest - -spec = importlib.util.spec_from_file_location( - "release_image_tags", - Path(__file__).resolve().parents[1] / ".github/scripts/release_image_tags.py", -) -tags = importlib.util.module_from_spec(spec) -spec.loader.exec_module(tags) - - -def releases(*versions): - return [ - {"tag_name": "v" + version, "draft": False, "prerelease": False} - for version in versions - ] - - -def test_latest_release_updates_all_matching_aliases(): - assert tags.select_tags("v2.1.0", releases("1.8.9", "2.0.0", "2.1.0")) == ( - ["2.1.0", "2", "2.1", "latest"], - True, - ) - - -def test_maintenance_release_does_not_replace_newer_major(): - assert tags.select_tags("v1.8.1", releases("1.7.9", "1.8.1", "2.0.0")) == ( - ["1.8.1", "1", "1.8"], - False, - ) - - -def test_old_patch_does_not_replace_major_or_minor_aliases(): - assert tags.select_tags("v1.8.0", releases("1.8.0", "1.8.1", "2.0.0")) == ( - ["1.8.0"], - False, - ) - - -def test_draft_prerelease_and_unknown_tag_cannot_publish_aliases(): - data = releases("1.0.0") + [ - {"tag_name": "v3.0.0", "draft": True}, - {"tag_name": "v4.0.0", "prerelease": True}, - ] - assert tags.select_tags("v1.0.0", data)[0][-1] == "latest" - for tag in ("v1.1.0", "v1.0.0-rc1", "bad"): - with pytest.raises(ValueError): - tags.select_tags(tag, data) - - -def test_older_minor_only_updates_its_own_minor_alias(): - assert tags.select_tags("v1.8.2", releases("1.8.2", "1.9.0", "2.0.0")) == ( - ["1.8.2", "1.8"], - False, - ) - - -def test_package_version_guard_accepts_matching_tag_and_rejects_mismatch(): - import subprocess - import sys - import re - - root = Path(__file__).resolve().parents[1] - guard = root / ".github/scripts/check_release_version.py" - source = (root / "pyproject.toml").read_text() - current = re.search(r'^version = "([^" ]+)"', source, re.MULTILINE).group(1) - for tag, expected in (("v" + current, 0), ("v9.9.9", 1)): - result = subprocess.run( - [sys.executable, str(guard), tag], cwd=root, capture_output=True, text=True - ) - assert result.returncode == expected - if expected: - assert "does not match" in result.stderr - - -def test_release_listing_fetches_all_pages(monkeypatch): - import io - import json - - monkeypatch.setenv("GITHUB_API_URL", "https://api.example.test") - monkeypatch.setenv("GITHUB_REPOSITORY", "owner/repo") - monkeypatch.setenv("GH_TOKEN", "test-token") - calls = [] - first_page = releases(*["1.0.%d" % i for i in range(100)]) - second_page = releases("2.0.0") - - def fake_open(request, timeout): - calls.append((request.full_url, timeout)) - return io.BytesIO( - json.dumps(first_page if len(calls) == 1 else second_page).encode() - ) - - monkeypatch.setattr(tags.urllib.request, "urlopen", fake_open) - result = tags.fetch_releases() - assert len(result) == 101 - assert calls[0][0].endswith("page=1") - assert calls[1][0].endswith("page=2") - assert tags.select_tags("v1.0.99", result) == (["1.0.99", "1", "1.0"], False) - - -def test_release_selection_emits_image_names_and_latest_flag( - monkeypatch, tmp_path, capsys -): - monkeypatch.setattr(tags, "fetch_releases", lambda: releases("1.2.0", "2.0.0")) - output = tmp_path / "github-output" - for key, value in { - "TAG": "v1.2.0", - "DOCKER_REGISTRY": "registry.example", - "DOCKER_USERNAME": "team", - "IMAGE_NAME": "modpoll", - "GITHUB_OUTPUT": str(output), - }.items(): - monkeypatch.setenv(key, value) - tags.main() - assert capsys.readouterr().out.splitlines() == [ - "registry.example/team/modpoll:1.2.0", - "registry.example/team/modpoll:1", - "registry.example/team/modpoll:1.2", - ] - assert output.read_text() == "latest=false\ndocs=true\n" diff --git a/packages/modsim/.github/scripts/check-release-version.py b/packages/modsim/.github/scripts/check-release-version.py deleted file mode 100644 index 9ce549a..0000000 --- a/packages/modsim/.github/scripts/check-release-version.py +++ /dev/null @@ -1,43 +0,0 @@ -"""Reject releases when the CLI version differs from the release tag.""" - -import ast -import sys -from pathlib import Path - -from check_release_version import package_version - - -def main(): - tag = sys.argv[1] - expected = tag[1:] if tag.startswith("v") else tag - package = package_version() - if package != expected: - print( - "Project version %s does not match release tag %s" % (package, tag), - file=sys.stderr, - ) - return 1 - module = ast.parse(Path("modsim/__init__.py").read_text(encoding="utf-8")) - versions = [ - node.value.value - for node in module.body - if isinstance(node, ast.Assign) - and any( - isinstance(target, ast.Name) and target.id == "__version__" - for target in node.targets - ) - and isinstance(node.value, ast.Constant) - and isinstance(node.value.value, str) - ] - if versions != [expected]: - print( - "modsim CLI version does not match release tag %s (found %s)" - % (tag, versions), - file=sys.stderr, - ) - return 1 - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/packages/modsim/.github/scripts/check_release_version.py b/packages/modsim/.github/scripts/check_release_version.py deleted file mode 100644 index fc5cd31..0000000 --- a/packages/modsim/.github/scripts/check_release_version.py +++ /dev/null @@ -1,34 +0,0 @@ -"""Reject a release if its tag and checked-out package metadata differ.""" - -import sys -from pathlib import Path - -try: - import tomllib -except ModuleNotFoundError: - import tomli as tomllib - - -def package_version(): - metadata = tomllib.loads(Path("pyproject.toml").read_text(encoding="utf-8")) - try: - return metadata["project"]["version"] - except KeyError as exc: - raise ValueError("project version is missing from pyproject.toml") from exc - - -def main(): - tag = sys.argv[1] - expected = tag[1:] if tag.startswith("v") else tag - actual = package_version() - if actual != expected: - print( - "Project version %s does not match release tag %s" % (actual, tag), - file=sys.stderr, - ) - return 1 - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/packages/modsim/.github/scripts/preview-release.py b/packages/modsim/.github/scripts/preview-release.py deleted file mode 100644 index 8f5c9bc..0000000 --- a/packages/modsim/.github/scripts/preview-release.py +++ /dev/null @@ -1,189 +0,0 @@ -"""Modsim preview guards and immutable registry verification (standard library).""" - -import hashlib -import json -import os -from pathlib import Path -import re -import subprocess -import sys -import time -import urllib.error -import urllib.request - - -def metadata(version): - url = f"https://pypi.org/pypi/modsim/{version}/json?release_check={time.time_ns()}" - try: - with urllib.request.urlopen(url, timeout=30) as response: - return json.load(response) - except urllib.error.HTTPError as exc: - if exc.code == 404: - return None - raise - - -def guard(tag): - if not re.fullmatch(r"v2\.\d+\.\d+(?:a|b|rc)\d+", tag): - raise ValueError("expected a unique v2 prerelease tag") - subprocess.run( - [sys.executable, ".github/scripts/check_release_version.py", tag], check=True - ) - actual = re.search( - r'__version__ = "([^"]+)"', Path("modsim/__init__.py").read_text() - ).group(1) - if actual != tag[1:]: - raise ValueError("module version differs from release tag") - sha = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip() - subprocess.run(["git", "merge-base", "--is-ancestor", sha, "origin/v2"], check=True) - repo = os.environ["GITHUB_REPOSITORY"] - # Workflows live at the repository root since TOOL-01; job names carry the package so - # they never share a check name with modpoll's. - require_ci( - repo, - sha, - "modsim.yml", - { - "modsim quality", - "modsim docs", - "modsim tox (3.10)", - "modsim tox (3.14)", - "modpoll snapshot replay", - }, - ) - require_ci( - repo, - sha, - "modsim-acceptance.yml", - {"catalog-interop"} - | { - f"single-device ({platform})" - for platform in ("ubuntu-latest", "macos-latest", "windows-latest") - }, - ) - print(f"Accepted {sha}: main and catalog/platform CI passed") - - -def require_ci(repo, sha, workflow, expected): - listing = json.loads( - subprocess.check_output( - [ - "gh", - "api", - f"repos/{repo}/actions/workflows/{workflow}/runs?head_sha={sha}&event=push&per_page=100", - ], - text=True, - ) - ) - runs = [run for run in listing["workflow_runs"] if run["head_branch"] == "v2"] - if ( - not runs - or runs[0]["status"] != "completed" - or runs[0]["conclusion"] != "success" - ): - raise ValueError(f"exact release SHA requires successful v2 CI: {workflow}") - jobs = json.loads( - subprocess.check_output( - [ - "gh", - "api", - f"repos/{repo}/actions/runs/{runs[0]['id']}/jobs?per_page=100", - ], - text=True, - ) - )["jobs"] - if {job["name"] for job in jobs} != expected or any( - job["conclusion"] != "success" for job in jobs - ): - raise ValueError(f"release requires all expected CI jobs: {workflow}") - - -def immutable(version): - data = metadata(version) - if data is None: - result = "false" - else: - published = { - item["filename"]: item["digests"]["sha256"] for item in data["urls"] - } - local = { - p.name: hashlib.sha256(p.read_bytes()).hexdigest() - for p in Path("dist").iterdir() - if p.is_file() and (p.name.endswith(".whl") or p.name.endswith(".tar.gz")) - } - if local != published: - raise ValueError( - "immutable PyPI version already exists with different bytes; recover original artifacts" - ) - result = "true" - with open(os.environ["GITHUB_OUTPUT"], "a") as output: - output.write(f"exists={result}\n") - - -def _wait_for_pypi(fetch, label, deadline): - """Wait for a newly published resource, without masking other failures.""" - attempts = 0 - while True: - attempts += 1 - try: - value = fetch() - except urllib.error.HTTPError as exc: - if exc.code != 404: - raise - value = None - if value is not None: - return value - remaining = deadline - time.monotonic() - if remaining <= 0: - raise TimeoutError( - f"PyPI {label} still unavailable after {attempts} attempts" - ) - delay = min(20, remaining) - print( - f"PyPI {label} not yet available (attempt {attempts}); retrying in {delay:.0f}s", - file=sys.stderr, - flush=True, - ) - time.sleep(delay) - - -def download(version, directory): - # Retry delayed metadata and wheel visibility after publication. - deadline = time.monotonic() + 600 - - def find_wheel(): - data = metadata(version) - if data is None: - return None - wheels = [item for item in data["urls"] if item["filename"].endswith(".whl")] - if len(wheels) > 1: - raise ValueError("expected exactly one published wheel") - return wheels[0] if wheels else None - - item = _wait_for_pypi(find_wheel, "wheel metadata", deadline) - - def fetch_wheel(): - separator = "&" if "?" in item["url"] else "?" - url = f"{item['url']}{separator}release_check={time.time_ns()}" - with urllib.request.urlopen(url, timeout=30) as response: - return response.read() - - payload = _wait_for_pypi(fetch_wheel, "wheel file", deadline) - if hashlib.sha256(payload).hexdigest() != item["digests"]["sha256"]: - raise ValueError("published wheel SHA256 mismatch") - destination = Path(directory) - destination.mkdir(parents=True, exist_ok=True) - (destination / item["filename"]).write_bytes(payload) - print(item["filename"], item["digests"]["sha256"]) - - -if __name__ == "__main__": - command, version = sys.argv[1:3] - if command == "guard": - guard(version) - elif command == "immutable": - immutable(version) - elif command == "download": - download(version, sys.argv[3]) - else: - raise ValueError("unknown command") diff --git a/packages/modsim/.github/scripts/release_image_tags.py b/packages/modsim/.github/scripts/release_image_tags.py deleted file mode 100644 index bc847dc..0000000 --- a/packages/modsim/.github/scripts/release_image_tags.py +++ /dev/null @@ -1,82 +0,0 @@ -"""Choose Docker tags without allowing an older release to replace newer aliases.""" - -import json -import os -import re -import sys -import urllib.request - -VERSION = re.compile(r"^v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$") - - -def parse_version(tag): - match = VERSION.fullmatch(tag) - return tuple(map(int, match.groups())) if match else None - - -def select_tags(tag, releases): - version = parse_version(tag) - if version is None: - raise ValueError("release tag must be a stable semantic version") - versions = [] - for release in releases: - if release.get("draft") or release.get("prerelease"): - continue - candidate = parse_version(release.get("tag_name", "")) - if candidate is not None: - versions.append(candidate) - if version not in versions: - raise ValueError("release tag is not a published stable GitHub release") - tags = ["%d.%d.%d" % version] - if version == max(v for v in versions if v[0] == version[0]): - tags.append(str(version[0])) - if version == max(v for v in versions if v[:2] == version[:2]): - tags.append("%d.%d" % version[:2]) - is_latest = version == max(versions) - if is_latest: - tags.append("latest") - return tags, is_latest - - -def fetch_releases(): - api = os.environ["GITHUB_API_URL"].rstrip("/") - repo = os.environ["GITHUB_REPOSITORY"] - token = os.environ["GH_TOKEN"] - releases = [] - for page in range(1, 101): - req = urllib.request.Request( - "%s/repos/%s/releases?per_page=100&page=%d" % (api, repo, page), - headers={ - "Authorization": "Bearer " + token, - "Accept": "application/vnd.github+json", - }, - ) - with urllib.request.urlopen(req, timeout=30) as response: - batch = json.load(response) - if not isinstance(batch, list): - raise ValueError("GitHub releases response is not a list") - releases.extend(batch) - if len(batch) < 100: - return releases - raise ValueError("too many release pages to choose tags safely") - - -def main(): - tags, is_latest = select_tags(os.environ["TAG"], fetch_releases()) - image = "%s/%s/%s" % ( - os.environ["DOCKER_REGISTRY"], - os.environ["DOCKER_USERNAME"], - os.environ["IMAGE_NAME"], - ) - for tag in tags: - print("%s:%s" % (image, tag)) - with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output: - output.write("latest=%s\n" % str(is_latest).lower()) - - -if __name__ == "__main__": - try: - main() - except Exception as exc: - print("Cannot select release image tags: %s" % exc, file=sys.stderr) - sys.exit(1) diff --git a/packages/modsim/tests/test_modsim.py b/packages/modsim/tests/test_modsim.py index d9d9e76..c2c592c 100644 --- a/packages/modsim/tests/test_modsim.py +++ b/packages/modsim/tests/test_modsim.py @@ -209,23 +209,6 @@ def test_occupied_tcp_port_fails_promptly(): assert "Could not start Modbus TCP listener" in result.stderr -def test_release_version_guard_accepts_matching_tag_and_rejects_mismatch(): - from pathlib import Path - - project = Path(__file__).resolve().parents[1] - guard = project / ".github/scripts/check-release-version.py" - for tag, expected in (("v" + modsim.__version__, 0), ("v9.9.9", 1)): - result = subprocess.run( - [sys.executable, str(guard), tag], - cwd=project, - capture_output=True, - text=True, - ) - assert result.returncode == expected - if expected: - assert "does not match" in result.stderr - - @pytest.mark.integration def test_local_udp_server_and_shutdown(): from pymodbus.client import ModbusUdpClient diff --git a/packages/modsim/tests/test_preview_guard.py b/packages/modsim/tests/test_preview_guard.py deleted file mode 100644 index 7851cde..0000000 --- a/packages/modsim/tests/test_preview_guard.py +++ /dev/null @@ -1,156 +0,0 @@ -"""Preview release gates must enforce the current CI matrix.""" - -import importlib.util -import json -from pathlib import Path - -import pytest - -spec = importlib.util.spec_from_file_location( - "preview_guard", - Path(__file__).resolve().parents[1] / ".github/scripts/preview-release.py", -) -release = importlib.util.module_from_spec(spec) -spec.loader.exec_module(release) - - -def test_guard_requires_all_current_ci_jobs(monkeypatch): - monkeypatch.setenv("GITHUB_REPOSITORY", "example/modsim") - monkeypatch.setattr(release.subprocess, "run", lambda *a, **kw: None) - jobs = [ - {"name": name, "conclusion": "success"} - for name in ( - "modsim quality", - "modsim docs", - "modsim tox (3.10)", - "modsim tox (3.14)", - "modpoll snapshot replay", - ) - ] - - platform_jobs = [ - {"name": name, "conclusion": "success"} - for name in ( - "catalog-interop", - "single-device (ubuntu-latest)", - "single-device (macos-latest)", - "single-device (windows-latest)", - ) - ] - - def output(args, **kwargs): - if args[:3] == ["git", "rev-parse", "HEAD"]: - return "candidate\n" - if "runs?head_sha=" in " ".join(args): - return json.dumps( - { - "workflow_runs": [ - { - "head_branch": "v2", - "status": "completed", - "conclusion": "success", - "id": ( - 43 if "modsim-acceptance.yml" in " ".join(args) else 42 - ), - } - ] - } - ) - return json.dumps( - {"jobs": platform_jobs if "/runs/43/" in " ".join(args) else jobs} - ) - - monkeypatch.setattr(release.subprocess, "check_output", output) - release.guard("v" + __import__("modsim").__version__) - removed = jobs.pop() - with pytest.raises(ValueError, match="expected CI jobs"): - release.guard("v" + __import__("modsim").__version__) - jobs.append({**removed, "conclusion": "failure"}) - with pytest.raises(ValueError, match="expected CI jobs"): - release.guard("v" + __import__("modsim").__version__) - - jobs[-1]["conclusion"] = "success" - platform_jobs.pop() - with pytest.raises(ValueError, match="modsim-acceptance.yml"): - release.guard("v" + __import__("modsim").__version__) - - -def test_download_waits_for_pypi_and_checks_wheel_hash(monkeypatch, tmp_path, capsys): - import hashlib - import io - import urllib.error - - content = b"published wheel" - item = { - "filename": "package.whl", - "url": "https://files.pythonhosted.org/package.whl", - "digests": {"sha256": hashlib.sha256(content).hexdigest()}, - } - clock = [0] - metadata_calls = [] - urls = [] - monkeypatch.setattr(release.time, "monotonic", lambda: clock[0]) - monkeypatch.setattr( - release.time, "sleep", lambda seconds: clock.__setitem__(0, clock[0] + seconds) - ) - monkeypatch.setattr(release.time, "time_ns", lambda: clock[0]) - - def metadata(version): - metadata_calls.append(version) - if len(metadata_calls) <= 8: - return None - return {"urls": [] if len(metadata_calls) == 9 else [item]} - - def fetch(url, timeout): - urls.append(url) - if len(urls) == 1: - raise urllib.error.HTTPError(url, 404, "not ready", {}, None) - return io.BytesIO(content) - - monkeypatch.setattr(release, "metadata", metadata) - monkeypatch.setattr(release.urllib.request, "urlopen", fetch) - release.download("2.0.0a2", tmp_path) - assert (tmp_path / "package.whl").read_bytes() == content - assert len(metadata_calls) == 10 and len(urls) == 2 and urls[0] != urls[1] - assert clock[0] == 200 - assert "retrying" in capsys.readouterr().err - item["digests"]["sha256"] = "wrong" - with pytest.raises(ValueError, match="SHA256 mismatch"): - release.download("2.0.0a2", tmp_path) - - -def test_pypi_retry_times_out_and_does_not_hide_other_errors(monkeypatch): - import urllib.error - - clock = [0] - monkeypatch.setattr(release.time, "monotonic", lambda: clock[0]) - monkeypatch.setattr( - release.time, "sleep", lambda seconds: clock.__setitem__(0, clock[0] + seconds) - ) - with pytest.raises(TimeoutError, match="metadata still unavailable"): - release._wait_for_pypi(lambda: None, "metadata", 45) - assert clock[0] == 45 - - def forbidden(): - raise urllib.error.HTTPError("https://example.org", 403, "forbidden", {}, None) - - with pytest.raises(urllib.error.HTTPError, match="403"): - release._wait_for_pypi(forbidden, "metadata", 600) - assert clock[0] == 45 - - -def test_workflow_names_match_the_release_guard(): - import yaml - - # The workflows live at the repository root (packages/modsim/tests -> repository). - workflow = yaml.safe_load( - ( - Path(__file__).resolve().parents[3] / ".github/workflows/modsim.yml" - ).read_text() - ) - job = workflow["jobs"]["tox"] - assert job["name"] == "modsim tox (${{ matrix.python-version }})" - assert {row["python-version"] for row in job["strategy"]["matrix"]["include"]} == { - "3.10", - "3.14", - } diff --git a/packages/modsim/tests/test_release_image_tags.py b/packages/modsim/tests/test_release_image_tags.py deleted file mode 100644 index 27c7287..0000000 --- a/packages/modsim/tests/test_release_image_tags.py +++ /dev/null @@ -1,122 +0,0 @@ -import importlib.util -from pathlib import Path - -import pytest - -spec = importlib.util.spec_from_file_location( - "release_image_tags", - Path(__file__).resolve().parents[1] / ".github/scripts/release_image_tags.py", -) -tags = importlib.util.module_from_spec(spec) -spec.loader.exec_module(tags) - - -def releases(*versions): - return [ - {"tag_name": "v" + version, "draft": False, "prerelease": False} - for version in versions - ] - - -def test_latest_release_updates_all_matching_aliases(): - assert tags.select_tags("v2.1.0", releases("1.8.9", "2.0.0", "2.1.0")) == ( - ["2.1.0", "2", "2.1", "latest"], - True, - ) - - -def test_maintenance_release_does_not_replace_newer_major(): - assert tags.select_tags("v1.8.1", releases("1.7.9", "1.8.1", "2.0.0")) == ( - ["1.8.1", "1", "1.8"], - False, - ) - - -def test_old_patch_does_not_replace_major_or_minor_aliases(): - assert tags.select_tags("v1.8.0", releases("1.8.0", "1.8.1", "2.0.0")) == ( - ["1.8.0"], - False, - ) - - -def test_draft_prerelease_and_unknown_tag_cannot_publish_aliases(): - data = releases("1.0.0") + [ - {"tag_name": "v3.0.0", "draft": True}, - {"tag_name": "v4.0.0", "prerelease": True}, - ] - assert tags.select_tags("v1.0.0", data)[0][-1] == "latest" - for tag in ("v1.1.0", "v1.0.0-rc1", "bad"): - with pytest.raises(ValueError): - tags.select_tags(tag, data) - - -def test_older_minor_only_updates_its_own_minor_alias(): - assert tags.select_tags("v1.8.2", releases("1.8.2", "1.9.0", "2.0.0")) == ( - ["1.8.2", "1.8"], - False, - ) - - -def test_package_version_guard_accepts_matching_tag_and_rejects_mismatch(): - import subprocess - import sys - import re - - root = Path(__file__).resolve().parents[1] - guard = root / ".github/scripts/check_release_version.py" - source = (root / "pyproject.toml").read_text() - current = re.search(r'^version = "([^" ]+)"', source, re.MULTILINE).group(1) - for tag, expected in (("v" + current, 0), ("v9.9.9", 1)): - result = subprocess.run( - [sys.executable, str(guard), tag], cwd=root, capture_output=True, text=True - ) - assert result.returncode == expected - if expected: - assert "does not match" in result.stderr - - -def test_release_listing_fetches_all_pages(monkeypatch): - import io - import json - - monkeypatch.setenv("GITHUB_API_URL", "https://api.example.test") - monkeypatch.setenv("GITHUB_REPOSITORY", "owner/repo") - monkeypatch.setenv("GH_TOKEN", "test-token") - calls = [] - first_page = releases(*["1.0.%d" % i for i in range(100)]) - second_page = releases("2.0.0") - - def fake_open(request, timeout): - calls.append((request.full_url, timeout)) - return io.BytesIO( - json.dumps(first_page if len(calls) == 1 else second_page).encode() - ) - - monkeypatch.setattr(tags.urllib.request, "urlopen", fake_open) - result = tags.fetch_releases() - assert len(result) == 101 - assert calls[0][0].endswith("page=1") - assert calls[1][0].endswith("page=2") - assert tags.select_tags("v1.0.99", result) == (["1.0.99", "1", "1.0"], False) - - -def test_release_selection_emits_image_names_and_latest_flag( - monkeypatch, tmp_path, capsys -): - monkeypatch.setattr(tags, "fetch_releases", lambda: releases("1.2.0", "2.0.0")) - output = tmp_path / "github-output" - for key, value in { - "TAG": "v1.2.0", - "DOCKER_REGISTRY": "registry.example", - "DOCKER_USERNAME": "team", - "IMAGE_NAME": "modpoll", - "GITHUB_OUTPUT": str(output), - }.items(): - monkeypatch.setenv(key, value) - tags.main() - assert capsys.readouterr().out.splitlines() == [ - "registry.example/team/modpoll:1.2.0", - "registry.example/team/modpoll:1", - "registry.example/team/modpoll:1.2", - ] - assert output.read_text() == "latest=false\n"