Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(release): mirror published releases to dl.avibe.bot (#2281)

Call White1264c311df10
diff --git a/.github/workflows/release-mirror.yml b/.github/workflows/release-mirror.yml
new file mode 100644
index 000000000..e6fd1f9ab
--- /dev/null
+++ b/.github/workflows/release-mirror.yml
@@ -0,0 +1,64 @@
+name: Mirror releases to dl.avibe.bot
+
+on:
+ # Release assets are uploaded with GITHUB_TOKEN, which does not emit release
+ # events to other workflows, so the mirror follows the publishing workflows.
+ workflow_run:
+ workflows:
+ - Publish to PyPI
+ - Release (AI Notes)
+ - Guard Model Hub engine release
+ - Guard Git Runtime release
+ - Build local-only Git runtime
+ types: [completed]
+ # Safety net for missed triggers and renamed workflows.
+ schedule:
+ - cron: "41 * * * *"
+ workflow_dispatch:
+ inputs:
+ dry_run:
+ description: "Plan against the live bucket without writing"
+ type: boolean
+ default: false
+
+# Deliberately no pull_request trigger: the R2 credentials can write and delete
+# every object, so they only reach code that is already on the default branch.
+permissions:
+ contents: read
+
+concurrency:
+ group: release-mirror
+ cancel-in-progress: false
+
+jobs:
+ mirror:
+ name: Reconcile the release mirror
+ if: github.repository == 'avibe-bot/avibe'
+ runs-on: ubuntu-latest
+ timeout-minutes: 90
+ steps:
+ - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
+
+ - name: Reconcile published releases with the bucket
+ env:
+ GH_TOKEN: ${{ github.token }}
+ AWS_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }}
+ AWS_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }}
+ AWS_DEFAULT_REGION: auto
+ # Recent AWS CLI releases send request checksums R2 may not implement.
+ AWS_REQUEST_CHECKSUM_CALCULATION: when_required
+ AWS_RESPONSE_CHECKSUM_VALIDATION: when_required
+ R2_ACCOUNT_ID: ${{ secrets.R2_ACCOUNT_ID }}
+ DRY_RUN: ${{ inputs.dry_run || false }}
+ shell: bash
+ run: |
+ set -euo pipefail
+ args=()
+ if [ "$DRY_RUN" = "true" ]; then
+ args+=(--dry-run)
+ fi
+ python3 scripts/release_mirror.py \
+ --repository "$GITHUB_REPOSITORY" \
+ --bucket avibe \
+ --endpoint-url "https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com" \
+ ${args[@]+"${args[@]}"}
diff --git a/docs/plans/release-download-mirror.md b/docs/plans/release-download-mirror.md
new file mode 100644
index 000000000..12dc6d121
--- /dev/null
+++ b/docs/plans/release-download-mirror.md
@@ -0,0 +1,132 @@
+# Release Download Mirror
+
+## Background
+
+Every Avibe download (desktop installers and updates, the managed runtimes, the
+Show Runtime, and wheels used by install scripts) comes from GitHub Release
+assets. Update discovery uses `api.github.com`. In mainland China, GitHub
+downloads are often slow or stall, and the 60 requests/hour unauthenticated API
+limit per IP has already surfaced as update-check 403s.
+
+`dl.avibe.bot` serves the Cloudflare R2 bucket `avibe` through a custom domain,
+with no egress fees. This plan makes it a byte-identical mirror of the
+published releases plus a static release index. Clients try the mirror first
+and fall back to GitHub.
+
+## Principles
+
+- GitHub Releases remain the source of truth. The mirror serves copies of
+ published bytes and never authenticates them. Clients keep verifying what
+ they already verify, whatever the source: updater signatures, pinned
+ manifest sha256 values, and `SHA256SUMS`.
+- A mirror miss is a fallback, not an error. Retention, lag, and outages
+ degrade to today's GitHub path.
+
+## Contract
+
+### URLs
+
+- `https://dl.avibe.bot/releases/<tag>/<asset>` is byte-identical to
+ `https://github.com/avibe-bot/avibe/releases/download/<tag>/<asset>`.
+ Clients derive the mirror URL only by substituting that prefix, which keeps
+ percent-encoding identical (for example `+` as `%2B`). The bucket key is
+ `releases/<tag>/<asset>` with the decoded asset name.
+- Release objects are immutable:
+ `Cache-Control: public, max-age=31536000, immutable`. Published assets are
+ upload-once (release workflows replace assets only on drafts), so a tag and
+ asset name never change bytes.
+- `https://dl.avibe.bot/index/releases.json` is the release index:
+ `Cache-Control: public, max-age=60`.
+- Other top-level prefixes are reserved and never touched by the release
+ mirror (for example a future `thirdparty/` for install-script dependencies).
+
+### Release index, schema 1
+
+```json
+{
+ "schema_version": 1,
+ "repository": "avibe-bot/avibe",
+ "releases": [
+ {
+ "tag": "gh-v3.1.2rc6",
+ "prerelease": true,
+ "published_at": "2026-09-29T07:35:48Z",
+ "commit": "<40-hex commit the tag points to>",
+ "assets": [{ "name": "<asset>", "size": 123, "sha256": "<64-hex>" }]
+ }
+ ]
+}
+```
+
+- Releases are ordered newest `published_at` first; assets by name.
+- The index lists exactly the releases the mirror holds. When it is written,
+ every listed asset already exists in the bucket with those bytes.
+- `sha256` is GitHub's asset digest, re-verified against the downloaded bytes
+ before upload. `commit` is the peeled tag target.
+- Producer: the release mirror workflow. Planned consumers: the desktop
+ updater, the CLI update checker, and the runtime downloaders, replacing their
+ `api.github.com` discovery calls.
+- The index is unauthenticated metadata. A hostile index can at most withhold
+ releases or name copies that then fail the consumer's existing verification.
+
+### Retention
+
+- Every full release (`prerelease: false`) is kept: stable `v*`,
+ `model-hub-engine-*`, and `git-runtime-*`. Pinned runtime manifests depend on
+ those URLs.
+- The newest 20 prereleases by `published_at` are kept. Older prereleases leave
+ the mirror and the index; their downloads fall back to GitHub.
+- Drafts are never mirrored.
+- At the time of writing that is 89 releases and about 19 GB, most of it the
+ desktop bundles in recent prereleases (about 0.7 GB each).
+
+## Reconciler
+
+`.github/workflows/release-mirror.yml` runs `scripts/release_mirror.py`:
+
+1. List published releases through the GitHub API and tag commits through
+ `git ls-remote`. Refuse to continue if GitHub reports no published releases.
+2. List the bucket and read the previous index.
+3. Upload each selected asset that is missing, has the wrong size, or is not
+ recorded with the same digest in the previous index, after verifying the
+ downloaded size and sha256 against GitHub's digest.
+4. Write the index if its bytes changed, then delete `releases/` objects that
+ left the selection. Objects appear before the index names them and
+ disappear only after it stops naming them.
+5. If GitHub's digest for an indexed asset changed, re-upload it and fail the
+ run: published bytes changed, and edge caches may hold the old copy until
+ that URL is purged.
+
+Triggers: completion of the release-publishing workflows (assets are uploaded
+with `GITHUB_TOKEN`, which does not emit release events), an hourly schedule
+as the safety net, and manual dispatch with an optional dry run. A dry run
+reports the plan without writing and still fails when published bytes changed.
+
+Credentials are the `R2_ACCOUNT_ID`, `R2_ACCESS_KEY_ID`, and
+`R2_SECRET_ACCESS_KEY` repository secrets. They can write and delete every
+object, so the workflow has no `pull_request` trigger: only code already on the
+default branch receives them.
+
+## Zone configuration
+
+Cloudflare configuration lives outside the repository. The expected state:
+
+- `dl.avibe.bot` is the bucket's custom domain; the `r2.dev` URL stays off.
+- One Cache Rule for `http.host eq "dl.avibe.bot"`: eligible for cache, edge
+ and browser TTL respect the origin. The object headers above carry the
+ policy; the rule exists because default caching skips extensions such as
+ `.whl`, `.tgz`, `.json`, and `.sig`.
+
+## Rollout
+
+1. Mirror and index (this change), then a full backfill by manual dispatch.
+2. Cache Rule, then real-file tests from the three mainland carriers at the
+ evening peak.
+3. Clients, one at a time: desktop updater, then runtime and Show Runtime
+ downloads, then `install.sh` and `install.ps1`. Each tries the mirror first,
+ then GitHub, with a connect timeout and a stall watchdog, resumes with
+ `Range` when switching source, and remembers the last source that worked.
+4. Install-script third-party dependencies (the uv installer and
+ python-build-standalone) through `UV_INSTALLER_GITHUB_BASE_URL` and
+ `UV_PYTHON_INSTALL_MIRROR`, if step 2 shows GitHub is still their
+ bottleneck. PyPI and npm keep using their existing mainland mirrors.
diff --git a/docs/release.md b/docs/release.md
index 4066b5989..a1978bfc1 100644
--- a/docs/release.md
+++ b/docs/release.md
@@ -33,3 +33,12 @@ Published managed-runtime manifests are availability contracts. Keep their
release URLs under the scheduled manifest-verified backup/recovery guard.
Publish replacement assets before changing a pinned manifest so the guard never
restores bytes from a different release.
+
+## Download mirror
+
+`Mirror releases to dl.avibe.bot` copies published release assets to
+`https://dl.avibe.bot/releases/<tag>/<asset>` and writes the release index at
+`https://dl.avibe.bot/index/releases.json`. It follows the publishing
+workflows, so a renamed publishing workflow must also be renamed in its
+trigger. The contract and retention rules are in
+`docs/plans/release-download-mirror.md`.
diff --git a/scripts/release_mirror.py b/scripts/release_mirror.py
new file mode 100644
index 000000000..3922df141
--- /dev/null
+++ b/scripts/release_mirror.py
@@ -0,0 +1,344 @@
+#!/usr/bin/env python3
+"""Mirror published GitHub Release assets into the dl.avibe.bot R2 bucket.
+
+GitHub stays the source of truth. The mirror holds byte-identical copies under
+``releases/<tag>/<asset>`` and a release index at ``index/releases.json``; see
+``docs/plans/release-download-mirror.md`` for the contract.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import re
+import subprocess
+import sys
+import tempfile
+import time
+import urllib.error
+import urllib.request
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Mapping, Sequence
+from urllib.parse import quote
+
+
+RELEASE_PREFIX = "releases/"
+INDEX_KEY = "index/releases.json"
+IMMUTABLE_CACHE_CONTROL = "public, max-age=31536000, immutable"
+INDEX_CACHE_CONTROL = "public, max-age=60"
+DEFAULT_KEEP_PRERELEASES = 20
+INDEX_SCHEMA_VERSION = 1
+
+_NAME_RE = re.compile(r"[A-Za-z0-9._+-]+")
+_SHA256_RE = re.compile(r"[0-9a-f]{64}")
+_COMMIT_RE = re.compile(r"[0-9a-f]{40}")
+
+
+class MirrorError(RuntimeError):
+ """Raised when the mirror cannot be proven to match GitHub."""
+
+
+@dataclass(frozen=True)
+class Asset:
+ name: str
+ size: int
+ sha256: str
+ url: str
+ content_type: str
+
+
+@dataclass(frozen=True)
+class Release:
+ tag: str
+ prerelease: bool
+ published_at: str
+ commit: str
+ assets: tuple[Asset, ...]
+
+ def key(self, asset: Asset) -> str:
+ return f"{RELEASE_PREFIX}{self.tag}/{asset.name}"
+
+
+@dataclass(frozen=True)
+class Plan:
+ uploads: tuple[tuple[str, Asset], ...]
+ deletions: tuple[str, ...]
+ # Keys whose published bytes changed upstream. Edge caches may still hold
+ # the old copy for up to a year, so these fail the run after repair.
+ changed: tuple[str, ...]
+ index: bytes
+
+
+def parse_releases(
+ repository: str, payload: Sequence[Mapping[str, Any]], commits: Mapping[str, str]
+) -> list[Release]:
+ """Return every published release, validated against the mirror contract."""
+ releases = []
+ for item in payload:
+ if item["draft"]:
+ continue
+ tag = item["tag_name"]
+ if not _NAME_RE.fullmatch(tag):
+ raise MirrorError(f"release tag is not mirrorable: {tag!r}")
+ commit = commits.get(tag)
+ if commit is None or not _COMMIT_RE.fullmatch(commit):
+ raise MirrorError(f"published release has no tag commit: {tag}")
+ assets = []
+ for raw in item["assets"]:
+ name = raw["name"]
+ if not _NAME_RE.fullmatch(name):
+ raise MirrorError(f"asset name is not mirrorable: {tag}/{name!r}")
+ # Clients derive a mirror URL by replacing this exact prefix.
+ expected = f"https://github.com/{repository}/releases/download/{quote(tag)}/{quote(name)}"
+ if raw["browser_download_url"] != expected:
+ raise MirrorError(f"unexpected download URL for {tag}/{name}: {raw['browser_download_url']}")
+ algorithm, _, digest = str(raw.get("digest") or "").partition(":")
+ if algorithm != "sha256" or not _SHA256_RE.fullmatch(digest):
+ raise MirrorError(f"asset has no sha256 digest: {tag}/{name}")
+ assets.append(
+ Asset(
+ name=name,
+ size=int(raw["size"]),
+ sha256=digest,
+ url=expected,
+ content_type=raw.get("content_type") or "application/octet-stream",
+ )
+ )
+ releases.append(
+ Release(
+ tag=tag,
+ prerelease=bool(item["prerelease"]),
+ published_at=item["published_at"],
+ commit=commit,
+ assets=tuple(sorted(assets, key=lambda asset: asset.name)),
+ )
+ )
+ return releases
+
+
+def select(releases: Sequence[Release], keep_prereleases: int) -> list[Release]:
+ """Keep every full release and the newest prereleases, newest first."""
+ ordered = sorted(releases, key=lambda release: (release.published_at, release.tag), reverse=True)
+ prereleases = [release for release in ordered if release.prerelease][:keep_prereleases]
+ return [release for release in ordered if not release.prerelease or release in prereleases]
+
+
+def render_index(repository: str, releases: Sequence[Release]) -> bytes:
+ document = {
+ "schema_version": INDEX_SCHEMA_VERSION,
+ "repository": repository,
+ "releases": [
+ {
+ "tag": release.tag,
+ "prerelease": release.prerelease,
+ "published_at": release.published_at,
+ "commit": release.commit,
+ "assets": [
+ {"name": asset.name, "size": asset.size, "sha256": asset.sha256}
+ for asset in release.assets
+ ],
+ }
+ for release in releases
+ ],
+ }
+ return (json.dumps(document, separators=(",", ":")) + "\n").encode()
+
+
+def _indexed_digests(index: bytes | None) -> dict[str, str]:
+ if index is None:
+ return {}
+ try:
+ document = json.loads(index)
+ return {
+ f"{RELEASE_PREFIX}{release['tag']}/{asset['name']}": asset["sha256"]
+ for release in document["releases"]
+ for asset in release["assets"]
+ }
+ except (ValueError, KeyError, TypeError) as exc:
+ # The index is this job's derived state; re-verify every object instead.
+ print(f"warning: ignoring unreadable mirror index: {exc}", file=sys.stderr)
+ return {}
+
+
+def plan(
+ repository: str,
+ releases: Sequence[Release],
+ objects: Mapping[str, int],
+ previous_index: bytes | None,
+) -> Plan:
+ """Compare the selected releases with the bucket's ``releases/`` objects."""
+ if not releases:
+ raise MirrorError("GitHub returned no published releases; refusing to reconcile")
+ indexed = _indexed_digests(previous_index)
+ uploads, changed, expected = [], [], set()
+ for release in releases:
+ for asset in release.assets:
+ key = release.key(asset)
+ expected.add(key)
+ prior = indexed.get(key)
+ if prior is not None and prior != asset.sha256:
+ changed.append(key)
+ uploads.append((key, asset))
+ elif prior is None or objects.get(key) != asset.size:
+ # Only an object this job verified and indexed is trusted.
+ uploads.append((key, asset))
+ deletions = sorted(key for key in objects if key.startswith(RELEASE_PREFIX) and key not in expected)
+ return Plan(
+ uploads=tuple(uploads),
+ deletions=tuple(deletions),
+ changed=tuple(changed),
+ index=render_index(repository, releases),
+ )
+
+
+def download(asset: Asset, destination: Path, *, attempts: int = 3) -> None:
+ """Download ``asset`` and prove its size and sha256 match GitHub's digest."""
+ request = urllib.request.Request(asset.url, headers={"User-Agent": "avibe-release-mirror/1"})
+ for attempt in range(1, attempts + 1):
+ digest, size = hashlib.sha256(), 0
+ try:
+ with urllib.request.urlopen(request, timeout=60) as response, destination.open("wb") as output:
+ while chunk := response.read(1024 * 1024):
+ size += len(chunk)
+ if size > asset.size:
+ break
+ digest.update(chunk)
+ output.write(chunk)
+ except urllib.error.HTTPError as exc:
+ if not (exc.code == 429 or 500 <= exc.code < 600) or attempt == attempts:
+ raise MirrorError(f"download failed ({exc.code}): {asset.url}") from exc
+ except (OSError, urllib.error.URLError) as exc:
+ if attempt == attempts:
+ raise MirrorError(f"download failed: {asset.url}: {exc}") from exc
+ else:
+ if size != asset.size or digest.hexdigest() != asset.sha256:
+ raise MirrorError(f"downloaded bytes do not match GitHub's digest: {asset.url}")
+ return
+ time.sleep(float(attempt))
+
+
+def _run(command: Sequence[str]) -> str:
+ completed = subprocess.run(command, capture_output=True, text=True, check=False)
+ if completed.returncode != 0:
+ detail = completed.stderr.strip() or completed.stdout.strip() or "unknown error"
+ raise MirrorError(f"{command[0]} {command[1]} failed: {detail}")
+ return completed.stdout
+
+
+def github_releases(repository: str) -> list[dict[str, Any]]:
+ pages = json.loads(_run(["gh", "api", "--paginate", "--slurp", f"repos/{repository}/releases?per_page=100"]))
+ return [release for page in pages for release in page]
+
+
+def tag_commits(repository: str) -> dict[str, str]:
+ commits: dict[str, str] = {}
+ listing = _run(["git", "ls-remote", "--tags", f"https://github.com/{repository}.git"])
+ for line in listing.splitlines():
+ sha, ref = line.split("\t")
+ tag = ref.removeprefix("refs/tags/")
+ if tag.endswith("^{}"):
+ commits[tag[:-3]] = sha
+ else:
+ commits.setdefault(tag, sha)
+ return commits
+
+
+class Bucket:
+ def __init__(self, name: str, endpoint_url: str) -> None:
+ self.name = name
+ self.endpoint_url = endpoint_url
+
+ def _s3api(self, *arguments: str) -> str:
+ return _run(["aws", "s3api", *arguments, "--bucket", self.name, "--endpoint-url", self.endpoint_url])
+
+ def objects(self) -> dict[str, int]:
+ output = self._s3api("list-objects-v2", "--output", "json")
+ listing = json.loads(output) if output.strip() else {}
+ return {item["Key"]: int(item["Size"]) for item in listing.get("Contents") or []}
+
+ def read(self, key: str) -> bytes:
+ with tempfile.TemporaryDirectory(prefix="avibe-release-mirror-") as temporary:
+ path = Path(temporary) / "object"
+ self._s3api("get-object", "--key", key, str(path))
+ return path.read_bytes()
+
+ def put(self, key: str, path: Path, *, content_type: str, cache_control: str, sha256: str) -> None:
+ self._s3api(
+ "put-object", "--key", key, "--body", str(path),
+ "--content-type", content_type, "--cache-control", cache_control,
+ "--metadata", f"sha256={sha256}",
+ )
+
+ def delete(self, key: str) -> None:
+ # DeleteObjects requires a request checksum that R2 may not implement.
+ self._s3api("delete-object", "--key", key)
+
+
+def reconcile(repository: str, bucket: Bucket, *, keep_prereleases: int, dry_run: bool) -> int:
+ releases = select(parse_releases(repository, github_releases(repository), tag_commits(repository)), keep_prereleases)
+ objects = bucket.objects()
+ previous_index = bucket.read(INDEX_KEY) if INDEX_KEY in objects else None
+ result = plan(repository, releases, objects, previous_index)
+ size = sum(asset.size for _, asset in result.uploads)
+ print(
+ f"{len(releases)} releases mirrored; {len(result.uploads)} uploads ({size / 1e9:.2f} GB), "
+ f"{len(result.deletions)} deletions, index {'unchanged' if result.index == previous_index else 'changed'}"
+ )
+ for key in result.changed:
+ print(f"error: published bytes changed upstream: {key}", file=sys.stderr)
+ if dry_run:
+ for key, _ in result.uploads:
+ print(f"would upload {key}")
+ for key in result.deletions:
+ print(f"would delete {key}")
+ else:
+ with tempfile.TemporaryDirectory(prefix="avibe-release-mirror-") as temporary:
+ path = Path(temporary) / "asset"
+ for key, asset in result.uploads:
+ download(asset, path)
+ bucket.put(
+ key, path, content_type=asset.content_type,
+ cache_control=IMMUTABLE_CACHE_CONTROL, sha256=asset.sha256,
+ )
+ print(f"uploaded {key}")
+ if result.index != previous_index:
+ path.write_bytes(result.index)
+ bucket.put(
+ INDEX_KEY, path, content_type="application/json",
+ cache_control=INDEX_CACHE_CONTROL, sha256=hashlib.sha256(result.index).hexdigest(),
+ )
+ print(f"wrote {INDEX_KEY}")
+ # Delete only after the index stops listing these objects.
+ for key in result.deletions:
+ bucket.delete(key)
+ print(f"deleted {key}")
+ if result.changed:
+ print("error: purge the changed URLs from the dl.avibe.bot cache", file=sys.stderr)
+ return 1
+ return 0
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--repository", required=True)
+ parser.add_argument("--bucket", required=True)
+ parser.add_argument("--endpoint-url", required=True)
+ parser.add_argument("--keep-prereleases", type=int, default=DEFAULT_KEEP_PRERELEASES)
+ parser.add_argument("--dry-run", action="store_true")
+ arguments = parser.parse_args(argv)
+ try:
+ return reconcile(
+ arguments.repository,
+ Bucket(arguments.bucket, arguments.endpoint_url),
+ keep_prereleases=arguments.keep_prereleases,
+ dry_run=arguments.dry_run,
+ )
+ except MirrorError as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/test_release_mirror.py b/tests/test_release_mirror.py
new file mode 100644
index 000000000..5476892ec
--- /dev/null
+++ b/tests/test_release_mirror.py
@@ -0,0 +1,186 @@
+from __future__ import annotations
+
+import hashlib
+import re
+from dataclasses import replace
+
+import pytest
+
+from scripts import release_mirror as mirror
+from tests.test_desktop_release import ROOT, workflow
+
+
+REPOSITORY = "avibe-bot/avibe"
+
+
+def github_release(tag, *, published_at, prerelease=False, draft=False, assets=("a.tgz",)):
+ return {
+ "tag_name": tag,
+ "draft": draft,
+ "prerelease": prerelease,
+ "published_at": published_at,
+ "assets": [
+ {
+ "name": name,
+ "size": len(name),
+ "digest": f"sha256:{hashlib.sha256(name.encode()).hexdigest()}",
+ "content_type": "application/x-gtar",
+ "browser_download_url": (
+ f"https://github.com/{REPOSITORY}/releases/download/{tag}/{name.replace('+', '%2B')}"
+ ),
+ }
+ for name in assets
+ ],
+ }
+
+
+def releases(*items):
+ return mirror.parse_releases(REPOSITORY, items, {item["tag_name"]: "0" * 40 for item in items})
+
+
+def test_selection_keeps_every_full_release_and_only_the_newest_prereleases():
+ parsed = releases(
+ github_release("v1.0.0", published_at="2026-01-01T00:00:00Z"),
+ github_release("gh-v1.0.1rc1", published_at="2026-01-02T00:00:00Z", prerelease=True),
+ github_release("model-hub-engine-v1-1", published_at="2026-01-03T00:00:00Z"),
+ github_release("gh-v1.0.1rc2", published_at="2026-01-04T00:00:00Z", prerelease=True),
+ github_release("gh-v1.0.1rc3", published_at="2026-01-05T00:00:00Z", prerelease=True),
+ github_release("gh-v1.0.1rc4", published_at="2026-01-06T00:00:00Z", prerelease=True, draft=True),
+ )
+
+ assert [release.tag for release in mirror.select(parsed, keep_prereleases=2)] == [
+ "gh-v1.0.1rc3", "gh-v1.0.1rc2", "model-hub-engine-v1-1", "v1.0.0",
+ ]
+
+
+def test_reconcile_plan_trusts_only_objects_the_prior_index_verified():
+ (release,) = releases(
+ github_release(
+ "v1.0.0", published_at="2026-01-01T00:00:00Z",
+ assets=("absent.tgz", "indexed.tgz", "replaced.tgz", "truncated.tgz", "unindexed.tgz"),
+ ),
+ )
+ prior = mirror.render_index(
+ REPOSITORY, [replace(release, assets=tuple(a for a in release.assets if a.name != "unindexed.tgz"))]
+ )
+ objects = {release.key(asset): asset.size for asset in release.assets if asset.name != "absent.tgz"}
+ objects["releases/v1.0.0/truncated.tgz"] -= 1
+ objects["releases/gh-v0.9.0rc1/old.tgz"] = 1
+ objects[mirror.INDEX_KEY] = len(prior)
+ objects["thirdparty/uv/uv.tar.gz"] = 1
+ current = replace(
+ release,
+ assets=tuple(
+ replace(asset, sha256="f" * 64) if asset.name == "replaced.tgz" else asset
+ for asset in release.assets
+ ),
+ )
+
+ result = mirror.plan(REPOSITORY, [current], objects, prior)
+
+ assert [key for key, _ in result.uploads] == [
+ "releases/v1.0.0/absent.tgz",
+ "releases/v1.0.0/replaced.tgz",
+ "releases/v1.0.0/truncated.tgz",
+ "releases/v1.0.0/unindexed.tgz",
+ ]
+ assert result.changed == ("releases/v1.0.0/replaced.tgz",)
+ assert result.deletions == ("releases/gh-v0.9.0rc1/old.tgz",)
+
+
+def test_a_completed_reconcile_is_a_no_op_on_the_next_run():
+ selected = releases(
+ github_release("v1.0.0", published_at="2026-01-01T00:00:00Z", assets=("a.tgz", "b+local.whl")),
+ github_release("gh-v1.0.1rc1", published_at="2026-01-02T00:00:00Z", prerelease=True),
+ )
+ first = mirror.plan(REPOSITORY, selected, {}, None)
+ objects = {key: asset.size for key, asset in first.uploads}
+
+ again = mirror.plan(REPOSITORY, selected, objects, first.index)
+
+ assert (again.uploads, again.deletions, again.changed) == ((), (), ())
+ assert again.index == first.index
+
+
+class RecordingBucket:
+ def __init__(self, objects, index):
+ self._objects, self._index, self.writes = objects, index, []
+
+ def objects(self):
+ return dict(self._objects)
+
+ def read(self, key):
+ return self._index
+
+ def put(self, key, path, **metadata):
+ self.writes.append(key)
+
+ def delete(self, key):
+ self.writes.append(key)
+
+
[email protected]("dry_run", [True, False])
+def test_published_bytes_changing_upstream_fails_the_run_even_as_a_dry_run(monkeypatch, dry_run):
+ item = github_release("v1.0.0", published_at="2026-01-01T00:00:00Z")
+ (release,) = releases(item)
+ (asset,) = release.assets
+ prior = mirror.render_index(REPOSITORY, [replace(release, assets=(replace(asset, sha256="f" * 64),))])
+ bucket = RecordingBucket({release.key(asset): asset.size, mirror.INDEX_KEY: len(prior)}, prior)
+ monkeypatch.setattr(mirror, "github_releases", lambda repository: [item])
+ monkeypatch.setattr(mirror, "tag_commits", lambda repository: {"v1.0.0": "0" * 40})
+ monkeypatch.setattr(mirror, "download", lambda asset, destination: destination.write_bytes(b""))
+
+ assert mirror.reconcile(REPOSITORY, bucket, keep_prereleases=20, dry_run=dry_run) == 1
+ assert bucket.writes == ([] if dry_run else ["releases/v1.0.0/a.tgz", mirror.INDEX_KEY])
+
+
+def test_an_empty_release_listing_never_plans_deleting_the_mirror():
+ with pytest.raises(mirror.MirrorError, match="no published releases"):
+ mirror.plan(REPOSITORY, [], {"releases/v1.0.0/a.tgz": 1}, None)
+
+
+ "mutate, message",
+ [
+ (lambda asset: asset.update(digest=None), "no sha256 digest"),
+ (lambda asset: asset.update(digest="md5:" + "0" * 32), "no sha256 digest"),
+ (
+ lambda asset: asset.update(browser_download_url="https://objects.example/a.tgz"),
+ "unexpected download URL",
+ ),
+ ],
+)
+def test_assets_outside_the_mirror_contract_fail_closed(mutate, message):
+ item = github_release("v1.0.0", published_at="2026-01-01T00:00:00Z")
+ mutate(item["assets"][0])
+
+ with pytest.raises(mirror.MirrorError, match=message):
+ releases(item)
+
+
+def test_download_refuses_bytes_that_differ_from_the_github_digest(tmp_path):
+ source = tmp_path / "a.tgz"
+ source.write_bytes(b"tampered")
+ asset = mirror.Asset(
+ name="a.tgz",
+ size=len(b"tampered"),
+ sha256=hashlib.sha256(b"original").hexdigest(),
+ url=source.as_uri(),
+ content_type="application/x-gtar",
+ )
+
+ with pytest.raises(mirror.MirrorError, match="do not match"):
+ mirror.download(asset, tmp_path / "download")
+
+ mirror.download(replace(asset, sha256=hashlib.sha256(b"tampered").hexdigest()), tmp_path / "download")
+ assert (tmp_path / "download").read_bytes() == b"tampered"
+
+
+def test_every_publishing_workflow_named_by_the_mirror_trigger_exists():
+ names = {
+ re.search(r"^name:\s*(.+)$", path.read_text(), re.MULTILINE).group(1).strip()
+ for path in (ROOT / ".github/workflows").glob("*.yml")
+ }
+ triggers = workflow("release-mirror.yml")[True]["workflow_run"]["workflows"]
+
+ assert triggers and set(triggers) <= names