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
170 changes: 160 additions & 10 deletions .github/scripts/auto_release.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@

python3 .github/scripts/auto_release.py plan --repo OWNER/NAME --mode MODE \\
[--commit SHA] [--version vX.Y.Z] [--evidence FILE] [--min-gap-hours H] \\
--notes-dir DIR [--github-output "$GITHUB_OUTPUT"]
[--due-file FILE] --notes-dir DIR [--github-output "$GITHUB_OUTPUT"]
python3 .github/scripts/auto_release.py follow-up --repo OWNER/NAME \\
[--record FILE] [--github-output "$GITHUB_OUTPUT"]

Run in a full clone of main (all tags fetched). Two update channels
(docs/self-host/updates.md, "Channels"):
Expand All @@ -24,8 +26,10 @@
(SHIPPED: the paths the release bundle is built from). With
--min-gap-hours (the beta deploy.yml starts after each deploy),
also a skip while the newest published release is younger than
that: a burst of deploys makes one beta, and the next deploy
after the gap, or the nightly, releases what waited;
that: a burst of deploys makes one beta. The skip records when
the gap ends (--due-file, a minute past it), and the follow-up
(below) starts the run that releases what waited, unless a
newer deploy or the nightly released it first;
stable the stable release for SHA, or a skip (the same reasons, counted
from the last stable release);
promote the newest beta that is ready (below), as a stable release; with
Expand Down Expand Up @@ -71,19 +75,31 @@
skips past its name instead. The tag it names never exists yet: a tag is
never re-cut or moved.

follow-up (.github/workflows/beta-follow-up.yml, every 30 minutes) reads the
newest skip record (the "beta-due" artifact of a run of auto-release.yml on
main, or --record) and says due=true once its time has come, while the
commit it skipped is in no release yet and no run of auto-release.yml is
queued or running; that workflow then starts auto-release.yml in mode
beta-after-deploy, which plans again with the gap, so a follow-up never cuts
a second beta within it and a commit released meanwhile is skipped. A record
older than FOLLOW_UP_HOURS past its time is left to the nightly.

Outputs (GITHUB_OUTPUT): releases (a JSON list of {kind, channel, tag,
commit, previous, stable_tag, beta}), count, summary. Notes for each release
commit, previous, stable_tag, beta}), count, summary, and due (when the gap
ends) on a skip for the gap; follow-up writes due (true or false) and why. Notes for each release
go to DIR/<tag>.md. Only the standard library is used; git and gh must be on
PATH.
"""

import argparse
import io
import json
import os
import re
import subprocess
import sys
from datetime import datetime, timezone
import zipfile
from datetime import datetime, timedelta, timezone

STABLE = re.compile(r"^v(\d+)\.(\d+)\.(\d+)$")
BETA = re.compile(r"^v(\d+)\.(\d+)\.(\d+)-beta\.(\d{8})$")
Expand All @@ -94,6 +110,12 @@
# stable tag (the same format as the release attestation installs read).
STABLE_BEGIN = "-----BEGIN CODERHELM STABLE ATTESTATION-----"
STABLE_END = "-----END CODERHELM STABLE ATTESTATION-----"
# The skip record a beta skipped for the gap leaves (an artifact of its run),
# the margin past the gap's end it is due at, and how long past that time the
# follow-up still acts on it (after that the nightly has had its turn).
DUE_ARTIFACT = "beta-due"
DUE_MARGIN = timedelta(minutes=1)
FOLLOW_UP_HOURS = 24

# What a self-host release is built from (.github/workflows/release.yml, build
# job): the Rust Lambdas (services/), the MCP proxy and the updater (lambda/),
Expand Down Expand Up @@ -469,7 +491,101 @@ def too_soon(published, now, hours):
if age >= hours:
return None
return ("the newest release was published %.1f hour(s) ago, under the %g-hour gap between betas: "
"the next deploy after the gap, or the nightly, releases this" % (age, hours))
"the follow-up at %s releases this, unless the next deploy or the nightly does first"
% (age, hours, _iso(due_at(published, hours))))


def _iso(t):
return t.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def due_at(published, hours):
"""When a beta skipped for the gap may be cut: the newest of `published`
plus `hours`, and a minute's margin. None when nothing was published."""
seen = [p for p in published if p]
return max(seen) + timedelta(hours=hours) + DUE_MARGIN if seen else None


def skip_record(commit, published, now, hours):
"""What a beta skipped for the gap leaves for the follow-up: {commit, skipped_at, due}."""
return {"commit": commit, "skipped_at": _iso(now), "due": _iso(due_at(published, hours))}


def follow_up(record, now, released_in, busy=False):
"""Whether the follow-up starts the beta a skip left: {due, reason}.

record the newest skip record ({commit, skipped_at, due}), or None;
released_in f(commit, skipped_at) -> the release tag that already holds
the commit (published since the skip), or None;
busy a run of auto-release.yml is queued or running: it plans
again itself, and a new run would only replace a queued one.
"""
if not record:
return {"due": False, "reason": "no beta was skipped for the gap"}
commit, due, skipped = record.get("commit"), _when(record.get("due")), _when(record.get("skipped_at"))
if not (isinstance(commit, str) and re.fullmatch(r"[0-9a-f]{40}", commit)) or not due or not skipped:
return {"due": False, "reason": "the skip record can't be read"}
if now < due:
return {"due": False, "reason": "%s waits for the gap: due at %s" % (commit[:12], _iso(due))}
if now > due + timedelta(hours=FOLLOW_UP_HOURS):
return {"due": False, "reason": "%s was due at %s, over %d hours ago: left to the nightly" % (commit[:12], _iso(due), FOLLOW_UP_HOURS)}
tag = released_in(commit, skipped)
if tag:
return {"due": False, "reason": "%s is already released in %s" % (commit[:12], tag)}
if busy:
return {"due": False, "reason": "%s is due, but a run of auto-release.yml is queued or running: the next check starts it" % commit[:12]}
return {"due": True, "reason": "%s was skipped for the gap and is due since %s" % (commit[:12], _iso(due))}


def _api_json(path):
try:
return json.loads(_run("gh", "api", path))
except (subprocess.CalledProcessError, ValueError):
return None


def _due_record(repo):
"""The newest skip record: the DUE_ARTIFACT of a run of auto-release.yml on
this repository's main, for that run's own commit. None when there is none."""
found = _api_json("repos/%s/actions/artifacts?name=%s&per_page=20" % (repo, DUE_ARTIFACT)) or {}
arts = sorted((a for a in found.get("artifacts") or [] if not a.get("expired")),
key=lambda a: a.get("created_at") or "", reverse=True)
for a in arts:
run = (a.get("workflow_run") or {}).get("id")
r = _api_json("repos/%s/actions/runs/%s" % (repo, run)) if run else None
if not r or r.get("path") != ".github/workflows/auto-release.yml" or r.get("head_branch") != "main" \
or (r.get("head_repository") or {}).get("full_name") != repo:
continue
try:
raw = subprocess.run(["gh", "api", "repos/%s/actions/artifacts/%s/zip" % (repo, a["id"])],
check=True, capture_output=True).stdout
with zipfile.ZipFile(io.BytesIO(raw)) as z:
rec = json.loads(z.read(DUE_ARTIFACT + ".json"))
except (subprocess.CalledProcessError, KeyError, ValueError, zipfile.BadZipFile):
continue
if isinstance(rec, dict) and rec.get("commit") == r.get("head_sha"):
return rec
return None


def _released_in(repo, commit, since):
"""A release (published at or after `since`) whose tag holds `commit`, or None."""
for r in _api_json("repos/%s/releases?per_page=30" % repo) or []:
t, when = r.get("tag_name"), _when(r.get("published_at"))
if r.get("draft") or not is_release(t) or not when or when < since:
continue
c = _api_json("repos/%s/compare/%s...%s" % (repo, commit, t)) or {}
if c.get("status") in ("ahead", "identical"):
return t
return None


def _busy(repo):
"""A run of auto-release.yml is queued or running (or can't be told)."""
found = _api_json("repos/%s/actions/workflows/auto-release.yml/runs?per_page=20" % repo)
if found is None:
return True
return any(r.get("status") != "completed" for r in found.get("workflow_runs") or [])


def _published(repo):
Expand Down Expand Up @@ -514,6 +630,10 @@ def git_promote(repo, version=None, evidence=None):
def main(argv):
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sub = ap.add_subparsers(dest="cmd", required=True)
f = sub.add_parser("follow-up")
f.add_argument("--repo", required=True)
f.add_argument("--record", help="the skip record (JSON); default: the newest %s artifact" % DUE_ARTIFACT)
f.add_argument("--github-output")
p = sub.add_parser("plan")
p.add_argument("--repo", required=True)
p.add_argument("--mode", choices=("stable", "beta", "promote"), default="stable")
Expand All @@ -522,20 +642,23 @@ def main(argv):
p.add_argument("--evidence", help="promote: the installs' release reports (a DynamoDB Query's JSON)")
p.add_argument("--min-gap-hours", type=float, default=0,
help="beta: skip while the newest published release is younger than this")
p.add_argument("--due-file", help="beta: where a skip for the gap writes its record, for the follow-up")
p.add_argument("--notes-dir", required=True)
p.add_argument("--github-output")
a = ap.parse_args(argv)
if not re.fullmatch(r"[A-Za-z0-9-]+/[A-Za-z0-9._-]+", a.repo):
raise SystemExit("--repo must be OWNER/NAME")
if a.cmd == "follow-up":
return main_follow_up(a)
if a.commit and not re.fullmatch(r"[0-9a-f]{40}", a.commit):
raise SystemExit("--commit must be a full commit SHA")
if a.mode in ("stable", "beta") and not a.commit:
raise SystemExit("--commit is needed for %s" % a.mode)
if not re.fullmatch(r"[A-Za-z0-9-]+/[A-Za-z0-9._-]+", a.repo):
raise SystemExit("--repo must be OWNER/NAME")
if a.version and not (parse(a.version) or parse_beta(a.version)):
raise SystemExit("--version must be vX.Y.Z or vX.Y.Z-beta.YYYYMMDD")
os.makedirs(a.notes_dir, exist_ok=True)
now = datetime.now(timezone.utc)
out, lines, failed = [], [], False
out, lines, failed, due = [], [], False, None

def keep(kind, channel, r, tag, commit):
with open(os.path.join(a.notes_dir, tag + ".md"), "w", encoding="utf-8") as f:
Expand All @@ -556,9 +679,15 @@ def keep(kind, channel, r, tag, commit):
channel = a.mode
r = git_plan(a.repo, a.commit, channel, now.strftime("%Y%m%d"))
if not r["skip"] and channel == "beta":
wait = too_soon(_published(a.repo), now, a.min_gap_hours)
published = _published(a.repo)
wait = too_soon(published, now, a.min_gap_hours)
if wait:
r = {"skip": True, "reason": "%s would be cut, but %s" % (r["tag"], wait)}
due = skip_record(a.commit, published, now, a.min_gap_hours)
if a.due_file:
os.makedirs(os.path.dirname(os.path.abspath(a.due_file)), exist_ok=True)
with open(a.due_file, "w", encoding="utf-8") as f:
json.dump(due, f)
lines.append("%s: %s" % (channel, r["reason"]))
if not r["skip"]:
assert (STABLE if channel == "stable" else BETA).match(r["tag"])
Expand All @@ -570,11 +699,32 @@ def keep(kind, channel, r, tag, commit):
f.write("releases=%s\n" % json.dumps(out, separators=(",", ":")))
f.write("count=%d\n" % len(out))
f.write("summary=%s\n" % " ".join(summary.split()))
if due:
f.write("due=%s\n" % due["due"])
if failed:
print("::error::" + summary, file=sys.stderr)
return 1
return 0


def main_follow_up(a):
now = datetime.now(timezone.utc)
if a.record:
try:
with open(a.record, encoding="utf-8") as f:
record = json.load(f)
except (OSError, ValueError):
record = None
else:
record = _due_record(a.repo)
r = follow_up(record, now, lambda c, since: _released_in(a.repo, c, since), busy=_busy(a.repo) if record else False)
print("follow-up: " + r["reason"])
if a.github_output:
with open(a.github_output, "a", encoding="utf-8") as f:
f.write("due=%s\n" % ("true" if r["due"] else "false"))
f.write("reason=%s\n" % " ".join(r["reason"].split()))
return 0


if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
108 changes: 108 additions & 0 deletions .github/scripts/test_auto_release.py
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,114 @@ def test_the_stable_block_never_reads_as_the_release_attestation(self):
self.assertIn(ar.STABLE_END, text)


class FollowUp(unittest.TestCase):
"""A beta skipped for the gap is released once the gap ends (beta-follow-up.yml)."""

now = datetime(2026, 12, 4, 15, 0, tzinfo=timezone.utc)

def record(self, due_in_minutes=-5):
return {"commit": SHA, "skipped_at": "2026-12-04T11:18:00Z",
"due": ar._iso(self.now + timedelta(minutes=due_in_minutes))}

def run_plan(self, published):
d = tempfile.mkdtemp()
out, due = os.path.join(d, "out"), os.path.join(d, "due", "beta-due.json")
real_plan, real_published = ar.git_plan, ar._published
ar.git_plan = lambda repo, commit, channel, date: {"skip": False, "reason": "1 shipped file(s) changed", "tag": "v0.9.1-beta.%s" % date,
"previous": "v0.9.0-beta.20261204", "prs": [], "stable_tag": "v0.9.1"}
ar._published = lambda repo: published
try:
rc = ar.main(["plan", "--repo", "o/r", "--mode", "beta", "--commit", SHA, "--min-gap-hours", "4", "--due-file", due,
"--notes-dir", os.path.join(d, "notes"), "--github-output", out])
finally:
ar.git_plan, ar._published = real_plan, real_published
with open(out) as f:
outputs = dict(line.split("=", 1) for line in f.read().splitlines())
record = None
if os.path.exists(due):
with open(due) as f:
record = json.load(f)
return rc, outputs, record

def test_a_skip_for_the_gap_records_when_it_is_due(self):
last = datetime.now(timezone.utc).replace(microsecond=0) - timedelta(hours=1)
rc, outputs, record = self.run_plan([last, None])
self.assertEqual((rc, outputs["count"], outputs["releases"]), (0, "0", "[]"))
# Due a minute after the gap ends, for the commit it skipped.
want = ar._iso(last + timedelta(hours=4, minutes=1))
self.assertEqual((record["commit"], record["due"], outputs["due"]), (SHA, want, want))
self.assertIn("the follow-up at %s releases this" % want, outputs["summary"])

def test_a_beta_past_the_gap_records_nothing(self):
rc, outputs, record = self.run_plan([datetime.now(timezone.utc) - timedelta(hours=5)])
self.assertEqual((rc, outputs["count"]), (0, "1"))
self.assertIsNone(record)
self.assertNotIn("due", outputs)

def test_the_record_is_due_a_minute_past_the_gap(self):
last = self.now - timedelta(hours=3, minutes=42)
rec = ar.skip_record(SHA, [last, None], self.now, 4)
self.assertEqual(rec, {"commit": SHA, "skipped_at": "2026-12-04T15:00:00Z", "due": "2026-12-04T15:19:00Z"})
self.assertIsNone(ar.due_at([None], 4))

def test_a_due_skip_releases(self):
asked = []
r = ar.follow_up(self.record(), self.now, lambda c, since: asked.append((c, since)) or None)
self.assertTrue(r["due"], r["reason"])
self.assertEqual(asked, [(SHA, datetime(2026, 12, 4, 11, 18, tzinfo=timezone.utc))])

def test_an_already_released_skip_does_nothing(self):
r = ar.follow_up(self.record(), self.now, lambda c, since: "v0.9.1-beta.20261204")
self.assertFalse(r["due"])
self.assertIn("already released in v0.9.1-beta.20261204", r["reason"])

def test_what_is_not_due_waits(self):
never = lambda c, since: self.fail("not asked before the record is due") # noqa: E731
r = ar.follow_up(self.record(due_in_minutes=10), self.now, never)
self.assertFalse(r["due"])
self.assertIn("waits for the gap", r["reason"])
self.assertFalse(ar.follow_up(None, self.now, never)["due"])
self.assertFalse(ar.follow_up({"commit": "x", "due": "soon"}, self.now, never)["due"])
# Long past its time: the nightly had its turn.
self.assertIn("left to the nightly", ar.follow_up(self.record(due_in_minutes=-25 * 60), self.now, never)["reason"])
# A run already queued or running plans again itself; a second would replace a queued one.
r = ar.follow_up(self.record(), self.now, lambda c, since: None, busy=True)
self.assertFalse(r["due"])
self.assertIn("queued or running", r["reason"])

def test_follow_up_writes_its_answer(self):
d = tempfile.mkdtemp()
rec, out = os.path.join(d, "rec.json"), os.path.join(d, "out")
with open(rec, "w") as f:
json.dump({"commit": SHA, "skipped_at": ar._iso(datetime.now(timezone.utc)),
"due": ar._iso(datetime.now(timezone.utc) + timedelta(hours=1))}, f)
self.assertEqual(ar.main(["follow-up", "--repo", "o/r", "--record", rec, "--github-output", out]), 0)
with open(out) as f:
self.assertIn("due=false", f.read().splitlines())

def test_the_workflows(self):
text, doc = Wiring.load("beta-follow-up.yml")
on = doc.get("on", doc.get(True))
self.assertEqual([s["cron"] for s in on["schedule"]], ["7,37 * * * *"])
self.assertEqual(doc["permissions"], {})
self.assertEqual(doc["concurrency"]["group"], "beta-follow-up")
due, start = doc["jobs"]["due"], doc["jobs"]["start"]
self.assertEqual(due["permissions"], {"contents": "read", "actions": "read"})
self.assertIn("auto_release.py follow-up", due["steps"][-1]["run"])
self.assertEqual(start["permissions"], {"actions": "write"})
self.assertEqual(start["if"], "success() && needs.due.outputs.due == 'true'")
# The same run a deploy starts, so the gap holds: never two betas within it.
self.assertEqual(start["steps"][-1]["run"],
'gh workflow run auto-release.yml -R "$GITHUB_REPOSITORY" --ref main -f mode=beta-after-deploy')
_, auto = Wiring.load("auto-release.yml")
steps = auto["jobs"]["plan"]["steps"]
plan = next(s for s in steps if s.get("id") == "plan")["run"]
self.assertIn('[ "$gap" != 0 ] && args+=(--due-file "$RUNNER_TEMP/beta-due/beta-due.json")', plan)
up = next(s for s in steps if (s.get("with") or {}).get("name") == ar.DUE_ARTIFACT)
self.assertEqual(up["if"], "steps.plan.outputs.due != ''")
self.assertEqual(up["with"]["path"], "${{ runner.temp }}/beta-due/beta-due.json")


class WithGit(unittest.TestCase):
"""The plan against a real repository (no GitHub: the PR lookup finds none)."""

Expand Down
Loading