Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 115 additions & 10 deletions .github/scripts/catalog_cleanup.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""Reconcile withdrawn versions from merged main history, never from open PRs."""
"""Select latest store versions and reconcile withdrawals from merged main."""
import argparse
import json
import os
Expand Down Expand Up @@ -28,29 +28,117 @@ def historical_manifest(path):
return json.loads(git("show", f"{commit}^:{path}"))


def plan():
if git("rev-parse", "--is-shallow-repository") != "false":
raise ValueError("full main history is required for withdrawal cleanup")
active = {}
for path in Path("pool/main").glob("*/*.deb.release.json"):
def compare_versions(left, right):
for relation, result in (("gt", 1), ("lt", -1)):
code = subprocess.run(["dpkg", "--compare-versions", left, relation, right]).returncode
if code == 0:
return result
if code != 1:
raise ValueError(f"invalid Debian versions: {left!r}, {right!r}")
return 0


def current_manifests():
result = {}
for path in sorted(Path("pool/main").glob("*/*.deb.release.json")):
match = MANIFEST.fullmatch(path.as_posix())
if not match:
raise ValueError(f"invalid manifest path: {path}")
data = json.loads(path.read_text())
if data["filename"] != match[2] or data["package"] != match[1]:
raise ValueError(f"manifest identity mismatch: {path}")
active[data["filename"]] = data
# Validate even the only version of a package before changing anything.
subprocess.run(["dpkg", "--validate-version", data["version"]], check=True)
result[data["filename"]] = data
return result


def split_latest(manifests):
"""One Debian version per package; keep both architectures at that version."""
latest = {}
for data in manifests.values():
pkg, version = data["package"], data["version"]
if pkg not in latest or compare_versions(version, latest[pkg]) > 0:
latest[pkg] = version
active, superseded = {}, {}
for name, data in manifests.items():
target = active if compare_versions(data["version"], latest[data["package"]]) == 0 else superseded
target[name] = data
return active, superseded


def supersede(package, version):
"""Stage old-manifest deletions in a publish PR, leaving listing assets alone."""
manifests = current_manifests()
if not any(m["package"] == package and compare_versions(m["version"], version) == 0
for m in manifests.values()):
raise ValueError("replacement manifest is missing")
obsolete = [m for m in manifests.values() if m["package"] == package
and compare_versions(m["version"], version) < 0]
for item in obsolete:
manifest_path(item).unlink()


def manifest_path(item):
path = f"pool/main/{item['package']}/{item['filename']}.release.json"
if not MANIFEST.fullmatch(path):
raise ValueError(f"invalid manifest path: {path}")
return Path(path)


def stage_superseded(data):
for item in data.get("superseded", []):
path = manifest_path(item)
if json.loads(path.read_text()) != item:
raise ValueError(f"manifest changed since planning: {path}")
for item in data.get("superseded", []):
manifest_path(item).unlink()


def retire_superseded(data, attempts=3):
"""Persist only still-obsolete snapshot manifests after successful publication.

Each push is a fast-forward, so a concurrent publisher cannot be overwritten.
Failed attempts re-read current main and recheck both the old identity and
the presence of a newer replacement before committing deletions.
"""
if not data.get("superseded"):
return
for _ in range(attempts):
subprocess.run(["git", "fetch", "origin", "main"], check=True)
subprocess.run(["git", "checkout", "--detach", "FETCH_HEAD"], check=True)
_, obsolete = split_latest(current_manifests())
paths = [manifest_path(m) for m in data["superseded"]
if obsolete.get(m["filename"]) == m]
if not paths:
return
for path in paths:
path.unlink()
subprocess.run(["git", "add", "--", *map(str, paths)], check=True)
subprocess.run(["git", "-c", "user.name=cardputerzero-bot", "-c",
"user.email=cardputerzero-bot@users.noreply.github.com",
"commit", "-m", "Retire superseded package versions after deployment"], check=True)
if subprocess.run(["git", "push", "origin", "HEAD:refs/heads/main"]).returncode == 0:
return
raise RuntimeError("main advanced during version retirement; retry deployment")


def plan():
if git("rev-parse", "--is-shallow-repository") != "false":
raise ValueError("full main history is required for withdrawal cleanup")
active, superseded = split_latest(current_manifests())
deleted = git("log", "--first-parent", "--format=", "--name-only", "--diff-filter=D", "HEAD", "--", "pool/main")
withdrawn = []
for path in sorted(set(deleted.splitlines())):
match = MANIFEST.fullmatch(path)
if not match or match[2] in active:
if not match or match[2] in active or match[2] in superseded:
continue
data = historical_manifest(path)
if not data or data["filename"] != match[2] or data["package"] != match[1]:
raise ValueError(f"invalid withdrawn manifest: {path}")
withdrawn.append(data)
return {"sha": git("rev-parse", "HEAD"), "active": list(active.values()), "withdrawn": withdrawn}
return {"sha": git("rev-parse", "HEAD"), "active": list(active.values()),
"superseded": list(superseded.values()), "withdrawn": withdrawn + list(superseded.values())}


def prune_tree(root):
Expand Down Expand Up @@ -108,6 +196,8 @@ def verify_registries(data, urls, attempts=20):
withdrawn = {(m["package"], m["version"]) for m in data["withdrawn"]}
active = {(m["package"], m["version"]) for m in data["active"]}
withdrawn -= active
replaced = {m["package"] for m in data["withdrawn"]}
replacements = {(pkg, ver) for pkg, ver in active if pkg in replaced}
for attempt in range(attempts):
errors = []
for url in urls:
Expand All @@ -123,10 +213,13 @@ def verify_registries(data, urls, attempts=20):
remaining = versions & withdrawn
if remaining:
errors.append(f"{url}: withdrawn versions still listed: {sorted(remaining)}")
missing = replacements - versions
if missing:
errors.append(f"{url}: replacement versions missing: {sorted(missing)}")
except (OSError, ValueError) as exc:
errors.append(f"{url}: {exc}")
if not errors:
print("Both store registries exclude withdrawn versions")
print("Both store registries exclude withdrawn versions and contain replacements")
return
print("; ".join(errors), flush=True)
if attempt + 1 < attempts:
Expand All @@ -138,6 +231,12 @@ def main():
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest="command", required=True)
commands.add_parser("plan")
replace = commands.add_parser("supersede")
replace.add_argument("package")
replace.add_argument("version")
for command in ("stage-superseded", "retire-superseded"):
action = commands.add_parser(command)
action.add_argument("plan", type=Path)
lookup = commands.add_parser("lookup")
lookup.add_argument("path")
prune = commands.add_parser("prune-tree")
Expand All @@ -151,6 +250,12 @@ def main():
args = parser.parse_args()
if args.command == "plan":
print(json.dumps(plan(), indent=2))
elif args.command == "supersede":
supersede(args.package, args.version)
elif args.command == "stage-superseded":
stage_superseded(json.loads(args.plan.read_text()))
elif args.command == "retire-superseded":
retire_superseded(json.loads(args.plan.read_text()))
elif args.command == "lookup":
if not MANIFEST.fullmatch(args.path):
raise ValueError("invalid manifest path")
Expand Down
4 changes: 4 additions & 0 deletions .github/workflows/process-web-submission.yml
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,9 @@ jobs:
--arg by "$SUBMITTER" --arg em "$UPLOADER_EMAIL" \
'{filename:$f,url:$u,sha256:$s,size:$z,package:$p,version:$v,architecture:$a,uploaded_by:$by,uploader_email:$em}' \
> "pool/main/$PKG/$ASSET_NAME.release.json"
# Match czdev: the publish PR replaces older versions of this app.
# Binaries are revoked only after the replacement is deployed.
python3 .github/scripts/catalog_cleanup.py supersede "$PKG" "$VER"
# '~' and ':' are legal in a Debian version but not in a git ref.
BRANCH="publish/${PKG}-${VER//[\~:]/_}-web-${{ github.run_id }}"
git config user.name "cardputerzero-bot"
Expand All @@ -461,6 +464,7 @@ jobs:
# sees size, installed size and binaries whichever way it arrived.
{
printf 'Submitted by @%s via the developer portal.\n\n' "$SUBMITTER"
printf 'This update replaces older versions automatically after deployment.\n\n'
python3 .github/scripts/deb_summary.py /tmp/pkg.deb "$PREV"
printf '| SHA-256 | `%s` |\n' "$WANT_SHA"
printf '| Binary | [%s](%s) |\n' "$ASSET_NAME" "$DEB_URL"
Expand Down
9 changes: 9 additions & 0 deletions .github/workflows/update-index.yml
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ jobs:
run: |
echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
python3 .github/scripts/catalog_cleanup.py plan > /tmp/withdrawals.json
# Old clients and concurrently merged PRs can leave multiple versions.
# Deploy only the highest Debian version, regardless of upload path.
python3 .github/scripts/catalog_cleanup.py stage-superseded /tmp/withdrawals.json
echo "withdrawals=$(python3 -c 'import json; print(str(bool(json.load(open("/tmp/withdrawals.json"))["withdrawn"])).lower())')" >> "$GITHUB_OUTPUT"

- uses: actions/upload-artifact@v4
Expand Down Expand Up @@ -306,6 +309,7 @@ jobs:
- uses: actions/checkout@v4
with:
ref: ${{ needs.build-and-deploy.outputs.sha }}
fetch-depth: 0

- uses: actions/download-artifact@v4
with:
Expand All @@ -321,6 +325,11 @@ jobs:
https://cardputerzero.github.io/generated/registry.json \
"${OSS_BASE%/}/${OSS_PREFIX#/}/cn/registry.json"

# Keep main unchanged if promotion, deployment or registry verification
# fails. A token-authenticated push does not recursively trigger this job.
- name: Retire superseded manifests on current main
run: python3 .github/scripts/catalog_cleanup.py retire-superseded /tmp/withdrawals.json

- name: Delete withdrawn binaries from all package releases
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
Expand Down
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,27 @@ CI then:
manifest URL into the official `apt-pool` release, rebuilds the index, deploys
Pages, and syncs OSS.

### Automatic replacement of old versions

An app keeps only its **highest Debian version** in the store, across `arm64`
and `all` builds. A version update from either `czdev publish` or the portal
includes removal of older manifests in the same PR. Metadata-only updates do
not remove versions. Ordering uses Debian rules, including epochs, `~`
prereleases and numeric revisions; it never relies on upload time or filenames.

Deployment also selects the highest version from merged main, covering older
clients, historical multi-version apps and concurrently merged submissions.
Only that version is promoted and indexed. Older binaries are revoked after
both store registries exclude the retired versions **and contain the replacement**.
Any remaining superseded manifests are then removed from current main with a
non-forced push; concurrent changes and an intentional withdrawal of the
replacement are rechecked. Failed deployment or registry verification leaves
those fallback manifest deletions uncommitted and old Release assets intact.
Retry the deployment to resume an incomplete cleanup. Contributor-owned fork
releases remain under the contributor's control.

See [publishing lifecycle and channel comparison](docs/PUBLISHING.md).

If a PR is rejected, the project stored nothing — the binary only ever lived in
the contributor's own fork release.

Expand Down
57 changes: 57 additions & 0 deletions docs/PUBLISHING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Publishing lifecycle

Each app retains its highest Debian version. Both `arm64` and `all` manifests
may remain at that same version; older versions are removed even when an app
changes architecture. Listing assets belong to the app and survive an update.

| Stage | czdev CLI | Web upload |
| --- | --- | --- |
| Upload | Contributor's fork `czdev-buffer`, or official repo for maintainers | Official `staging` Release with login-prefixed names |
| Upload limit | CLI permits up to 2 GiB per Release asset | Worker defaults to 80 MB, configurable by `MAX_SIZE_MB` |
| Submit | PR based on current upstream main, with metadata and a release manifest | Worker dispatches `web-submission`; trusted workflow creates the PR |
| Validate | Read-only fork PR checks; policies read from PR base | Trusted workflow validates downloaded `.deb` and store metadata |
| Identity | PR author must match `uploaded_by` and own the app | Authenticated Worker login; admin override is supported |
| Version | Must exceed the highest manifest version on PR base | Must exceed the highest manifest version on checked-out main |
| Replace | Publish PR removes strictly older manifests | Publish PR removes strictly older manifests using `catalog_cleanup.py supersede` |
| First release | Human review and device demo | Human review and device demo |
| Existing app update | Privileged follow-up merges after checks | Trusted workflow merges after checks and explicitly dispatches deployment |
| Store listing only | `czdev publish --meta-only` | `web-listing-update`; neither entry point adds version deletions |
| Deploy and cleanup | Shared `update-index.yml` | Shared `update-index.yml` |

The browser and CLI prechecks provide early feedback; the server-side checks
remain authoritative. In particular, index/CDN caching can make a precheck
stale. GitHub's bot token does not trigger a push workflow after merging, so
bot paths explicitly dispatch deployment.

## Shared deployment

1. Read merged main and plan historical withdrawals plus superseded versions.
Choose the highest version per app with `dpkg --compare-versions`.
2. Stage fallback deletions locally. Promote and collect only selected manifests;
verify the replacement package, rebuild APT indexes and ownership data, sync
OSS and deploy Pages. The existing withdrawal pipeline removes retired OSS
objects as part of synchronization and rebuilds the two store registries.
3. Require the global and China registries to exclude withdrawn versions and
include active replacements. An empty or stale registry cannot authorize
removal of a replacement's older Release binary.
4. Persist remaining superseded manifest deletions on current main. Recheck
manifest contents and that a newer version still exists, then push without
force. Retry concurrent pushes; never overwrite a publisher's work.
5. Delete exact withdrawn filenames from official `apt-pool`, `staging` and
`czdev-buffer` Releases. Protect active filenames in the deployed snapshot
and current main. Contributor fork Releases are not managed by this job.

This backend selection also handles an old client or a stale PR reintroducing
an obsolete manifest. Deployments are serialized and cleanup is retryable. A
failure stops subsequent steps; rerunning deployment recomputes the plan from
main and its full history. No remote deletion occurs while a publish PR is
merely open.

## Related repositories

- `CardputerZero/packages` owns the live workflows and deployment policy.
- `CardputerZero/dev-portal/packages-workflows` mirrors their source templates.
- `CardputerZero/AppBuilder/scripts/czdev/publish.py` stages the matching CLI
deletions. Existing CLI versions remain covered by backend selection.

Deploy the packages changes before relying on the portal's new lifecycle text.
Loading
Loading