mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-03 02:08:18 +00:00
ci(release): the retention prunes image versions too
The maintainer's request, on 2026-11-29: "packages haven't beeen updated in github. do we delete them?". The two image packages were updated (2.2.0-alpha.1, three hours before); what is old is the tag latest, which release.yml gives only to a release tag without a hyphen. Asked by menu what to do with the image versions, the maintainer chose "Prune image versions (Recommended)": keep the versions of the kept release tags, keep main with its sha tags, delete the other sha-tagged and the untagged versions of openultrasast and openultrasast-runner; the first run only lists, and the deletion waits for the maintainer's word. What changed .github/workflows/release-retention.yml, 150 to 262 lines (the python of the step: 105 to 215). The rule for tags and releases is as before. For image versions, after the versions that go with a deleted release tag: a version that carries no tag of a kept release and not main is pruned when it is untagged or tagged with a sha only. Two safeguards, found while the rule was written and in its review. First, an untagged version can be the image manifest or the attestation manifest of an image that stays: the four release images read on 2026-11-29 are OCI indexes with an amd64 manifest and an attestation manifest (s10_pkg_indexes.out), and the packages hold more untagged versions than tagged ones. So the step logs in to the registry, reads the index of each image that stays once, whatever tag keeps it, with docker buildx imagetools inspect, and keeps every version whose digest is one of the manifests that index lists. The index is read one level deep: an index inside it is not followed, and build-push-action makes none. Second, that fails closed: an index none of whose manifests is a version of the package, an index entry without a digest, or output that is not an index stops the job before anything is pruned or deleted. A version with a tag the rule does not name, or untagged without a digest, stays and is listed. The limit for image versions is 100 in one run (the limit of 20 stays for tags and releases). The summary lists every version to prune with the start of its digest and its tags before anything is deleted. A failed docker call stops the job and names the call and the reason, as a failed gh call does. Checks The harness /tmp/opencode/s10_rr2_harness.py runs the python of the step on fixtures with stand-ins for git, gh and docker (/tmp/opencode/s10_rr2_bin), ten cases. Against the workflow at HEAD (d98334a) eight of the ten fail (s10_rr2_red.out): the old script prunes nothing, makes no docker call, and has no limit for image versions. Against this file ten of ten pass (s10_rr2_green.out): a dry run that lists and deletes nothing; two deleting runs that delete exactly the expected 10 image versions and 5 tag operations (keep 3), and 13 and 6 (keep 1, where the image of a pre-release goes with its release); a failing login, a failing index read, an index entry without a digest, versions named by another form of digest, the image limit, a failing read of the releases and a failing read of an image each stop the job with nothing deleted. The harness also checks that the plan is complete in the summary at the first deleting call, that each index is read once, and that the token is printed nowhere. The YAML parses, the step passes bash -n and the python compiles; the file is ASCII, its widest line 120 columns; git diff --check exits 0 (s10_rr2_diffcheck.out). The gates give ten zeros (s10_rr2_exits.txt, label rr2). No test reads the workflow. The s10 files are under /tmp/opencode, outside the repository. Not verified The run on GitHub: whether the package versions API names each version by the digest that the index lists, and what docker buildx imagetools inspect prints there. The first run is a dry run. If the API names versions by another form of digest, that run stops on the second safeguard, and nothing is deleted; its summary is read before any deletion. Review. Three read-only rounds, the harness re-run in each (last r3_new 10 of 10, r3_head 2 of 10) and copies of the fixtures under /tmp/opencode/s10_rev_rr2. Round one blocked the file on two gaps: an image that stays under another tag lost its untagged children, and a digest of another form made the safeguard match nothing. Round two found both closed, the tags and releases part identical tod98334a, and blocked the message on one sentence, since corrected. Round three found the file unchanged (same hash, same python), the new fixture right by hand, and the mutant without the empty-digest guard caught. Shown by runs: the dry run list and the deleting plan are equal; every failed or malformed read stops the job with nothing deleted; twelve mutants are caught. Open remarks: the stop needs no child to be a version; a nested index is not followed. Not seen: the API's fields, the run, the chat.
This commit is contained in:
@@ -1,9 +1,11 @@
|
||||
name: Release retention
|
||||
# Keeps the newest RELEASES_TO_KEEP version tags with their releases and their versioned images,
|
||||
# and names the older ones. The run that follows a release only lists. A manual run deletes when
|
||||
# "dry run" is off. It never touches a tag that is not a version tag (vX.Y.Z with an optional
|
||||
# pre-release), the latest stable release, or an image version that carries a tag no release made
|
||||
# (latest, main, a sha).
|
||||
# Keeps the newest RELEASES_TO_KEEP version tags with their releases, and names the older ones. The
|
||||
# run that follows a release only lists. A manual run deletes when "dry run" is off. It never touches
|
||||
# a tag that is not a version tag (vX.Y.Z with an optional pre-release) or the latest stable release.
|
||||
# Image versions: one goes with its deleted release tag. One that carries no tag of a kept release
|
||||
# and not "main" goes too when it is untagged or tagged with a sha only, unless its digest is a
|
||||
# manifest that an image which stays lists. An index whose manifests are not versions of the
|
||||
# package stops the job. The plan is in the summary before anything is deleted.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
@@ -49,12 +51,17 @@ jobs:
|
||||
import sys
|
||||
|
||||
OWNER, REPO = os.environ["GITHUB_REPOSITORY"].split("/")
|
||||
ACTOR = os.environ["GITHUB_ACTOR"]
|
||||
KEEP = int(os.environ["RELEASES_TO_KEEP"])
|
||||
APPLY = os.environ["APPLY"] == "true"
|
||||
PACKAGES = os.environ["IMAGE_PACKAGES"].split()
|
||||
VERSION = re.compile(r"^v(\d+)\.(\d+)\.(\d+)(-[0-9A-Za-z][0-9A-Za-z.-]*)?$")
|
||||
SHA_TAG = re.compile(r"^sha-[0-9a-f]{7,40}$")
|
||||
LIMIT = 20
|
||||
# More deletions than this in one run is a plan that nobody has read.
|
||||
IMAGE_LIMIT = 100
|
||||
# The same for image versions: a repository that pushed an image for every commit has many.
|
||||
REGISTRY = f"ghcr.io/{OWNER}"
|
||||
|
||||
def gh(*args):
|
||||
try:
|
||||
@@ -62,6 +69,50 @@ jobs:
|
||||
except subprocess.CalledProcessError as error:
|
||||
sys.exit(f"gh {' '.join(args)}: exit {error.returncode}\n{error.stderr}")
|
||||
|
||||
def docker(*args, stdin=None):
|
||||
"""One docker call. A failed one stops the job and names the call and the reason."""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["docker", *args], check=True, capture_output=True, text=True, input=stdin,
|
||||
)
|
||||
return result.stdout
|
||||
except FileNotFoundError:
|
||||
sys.exit("docker: not found on the runner")
|
||||
except subprocess.CalledProcessError as error:
|
||||
sys.exit(f"docker {' '.join(args)}: exit {error.returncode}\n{error.stderr}")
|
||||
|
||||
def digest_of(version):
|
||||
"""The digest a package version is stored under."""
|
||||
return version.get("digest") or version.get("name") or ""
|
||||
|
||||
read_indexes = {}
|
||||
|
||||
def index_children(package, tag, digests):
|
||||
"""The digests of the manifests an image index lists; each index is read once.
|
||||
An image that is one manifest lists none."""
|
||||
if (package, tag) in read_indexes:
|
||||
return read_indexes[(package, tag)]
|
||||
raw = docker("buildx", "imagetools", "inspect", f"{REGISTRY}/{package}:{tag}", "--raw")
|
||||
try:
|
||||
index = json.loads(raw)
|
||||
except json.JSONDecodeError as error:
|
||||
sys.exit(f"docker buildx imagetools inspect {package}:{tag}: the output is not JSON: {error}")
|
||||
if not isinstance(index, dict):
|
||||
sys.exit(f"docker buildx imagetools inspect {package}:{tag}: the output is not an image index")
|
||||
entries = index.get("manifests", [])
|
||||
if any(not isinstance(entry.get("digest"), str) for entry in entries):
|
||||
sys.exit(f"docker buildx imagetools inspect {package}:{tag}: an entry of the index has no digest")
|
||||
children = [entry["digest"] for entry in entries]
|
||||
# An index none of whose manifests is a version of this package: the parts of an image
|
||||
# cannot be told from orphans, so the job stops before it prunes or deletes anything.
|
||||
if children and not digests & set(children):
|
||||
sys.exit(
|
||||
f"image {package}:{tag} lists {len(children)} manifests, and none is a version of the "
|
||||
"package: the safeguard for untagged versions cannot work; nothing is done"
|
||||
)
|
||||
read_indexes[(package, tag)] = children
|
||||
return children
|
||||
|
||||
def say(line):
|
||||
print(line)
|
||||
with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as summary:
|
||||
@@ -118,7 +169,9 @@ jobs:
|
||||
say(f"To delete: {', '.join(kinds) if kinds else 'nothing'}")
|
||||
if len(deleted) > LIMIT:
|
||||
sys.exit(f"{len(deleted)} tags to delete, more than the limit of {LIMIT}: nothing is done")
|
||||
docker("login", "ghcr.io", "-u", ACTOR, "--password-stdin", stdin=os.environ["GH_TOKEN"])
|
||||
images = {}
|
||||
pruned = {}
|
||||
for package in PACKAGES:
|
||||
path = f"/user/packages/container/{package}/versions?per_page=100"
|
||||
pages = json.loads(gh("api", "--paginate", "--slurp", path))
|
||||
@@ -126,17 +179,76 @@ jobs:
|
||||
images[package] = image_plan(versions, deleted)
|
||||
for version_id, tags_of_version in images[package]:
|
||||
say(f"To delete: image {package}, version {version_id}, tags {', '.join(tags_of_version)}")
|
||||
chosen_ids = {version_id for version_id, _ in images[package]}
|
||||
left = [version for version in versions if version["id"] not in chosen_ids]
|
||||
with_release = {version_id for version_id, _ in images[package]}
|
||||
# Every image that stays has its index read, whatever tag keeps it: a tag of a kept
|
||||
# release, main, or one this rule does not name (latest, a hand-made one). Every
|
||||
# manifest the index lists stays with it: an untagged version can be the image
|
||||
# manifest or the attestation manifest of a release image.
|
||||
keep_tags = {tag for kept_tag in kept for tag in image_tags(kept_tag)} | {"main"}
|
||||
digests = {digest_of(version) for version in versions} - {""}
|
||||
stays = set()
|
||||
outside = []
|
||||
for version in versions:
|
||||
tags_of_version = set(version["metadata"]["container"]["tags"])
|
||||
named_tags = {tag for tag in tags_of_version if not SHA_TAG.match(tag)}
|
||||
if version["id"] in with_release or not named_tags:
|
||||
continue
|
||||
if digest_of(version):
|
||||
stays.add(digest_of(version))
|
||||
if not named_tags & keep_tags:
|
||||
outside.append(", ".join(sorted(named_tags)))
|
||||
# The tags of one version lead to one image: a kept tag names the release, and
|
||||
# else the longest tag is read.
|
||||
tag = max(named_tags & keep_tags or named_tags, key=len)
|
||||
stays.update(index_children(package, tag, digests))
|
||||
pruned[package], unnamed = [], []
|
||||
for version in versions:
|
||||
tags_of_version = set(version["metadata"]["container"]["tags"])
|
||||
if version["id"] in with_release or digest_of(version) in stays:
|
||||
continue
|
||||
sha_only = bool(tags_of_version) and all(SHA_TAG.match(tag) for tag in tags_of_version)
|
||||
if (not tags_of_version and digest_of(version)) or sha_only:
|
||||
pruned[package].append(version)
|
||||
else:
|
||||
unnamed.append(version)
|
||||
for version in pruned[package]:
|
||||
tags_of_version = version["metadata"]["container"]["tags"]
|
||||
named = ", ".join(tags_of_version) if tags_of_version else "untagged"
|
||||
say(f"To prune: image {package}, version {version['id']}, {digest_of(version)[:19]}, {named}")
|
||||
gone = with_release | {version["id"] for version in pruned[package]}
|
||||
left = [version for version in versions if version["id"] not in gone]
|
||||
names = []
|
||||
for version in left:
|
||||
tags_left = version["metadata"]["container"]["tags"]
|
||||
names.append(', '.join(tags_left) if tags_left else f"id {version['id']}, untagged")
|
||||
names.append(", ".join(tags_left) if tags_left else f"id {version['id']}, untagged")
|
||||
say(f"Image {package}: {len(left)} of {len(versions)} versions stay: {'; '.join(names)}")
|
||||
parts = [
|
||||
version["id"] for version in left
|
||||
if not version["metadata"]["container"]["tags"] and digest_of(version) in stays
|
||||
]
|
||||
parts_listed = " ".join(str(part) for part in parts) if parts else "none"
|
||||
say(
|
||||
f"Image {package}: untagged versions that stay, each part of an image that stays: {parts_listed}"
|
||||
)
|
||||
if outside:
|
||||
say(f"Image {package}: stays under a tag this rule does not name: {'; '.join(outside)}")
|
||||
if unnamed:
|
||||
unplaced = []
|
||||
for version in unnamed:
|
||||
tags_unplaced = version["metadata"]["container"]["tags"]
|
||||
unplaced.append(", ".join(tags_unplaced) if tags_unplaced else f"id {version['id']}, untagged")
|
||||
say(f"Image {package}: stays, and this rule cannot place it: {'; '.join(unplaced)}")
|
||||
count = sum(len(chosen) for chosen in images.values()) + sum(len(chosen) for chosen in pruned.values())
|
||||
if count > IMAGE_LIMIT:
|
||||
sys.exit(f"{count} image versions to delete, more than the limit of {IMAGE_LIMIT}: nothing is done")
|
||||
if not APPLY:
|
||||
say("Dry run: nothing was deleted.")
|
||||
sys.exit(0)
|
||||
for package, chosen in images.items():
|
||||
for package in PACKAGES:
|
||||
pruned_here = [
|
||||
(version["id"], version["metadata"]["container"]["tags"]) for version in pruned[package]
|
||||
]
|
||||
chosen = images[package] + pruned_here
|
||||
for version_id, _ in chosen:
|
||||
gh("api", "--method", "DELETE", f"/user/packages/container/{package}/versions/{version_id}")
|
||||
say(f"Deleted image {package}, version {version_id}")
|
||||
|
||||
Reference in New Issue
Block a user