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
97 changes: 75 additions & 22 deletions .github/scripts/auto_release.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
[--commit SHA] [--version vX.Y.Z] [--evidence FILE] [--min-gap-hours H] \\
[--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"]
[--record FILE] [--wait-minutes M] [--github-output "$GITHUB_OUTPUT"]

Run in a full clone of main (all tags fetched). Two update channels
(docs/self-host/updates.md, "Channels"):
Expand Down Expand Up @@ -75,18 +75,30 @@
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.
follow-up (.github/workflows/beta-follow-up.yml) reads a skip 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. Two ways it runs:

the waiter the run that skipped starts beta-follow-up.yml with its own
record (--record) and --wait-minutes: it sleeps until the
record is due, checks, and while a run of auto-release.yml is
queued or running checks again every POLL_SECONDS. When the
minutes run out first it writes again=true, and the workflow
starts a new waiter with the same record. So the beta never
waits on GitHub's schedule. A newer skip's waiter replaces it;
the backstop every 30 minutes (when GitHub runs the schedule), or by
hand: one check of the newest record (the "beta-due" artifact
of a run of auto-release.yml on main).

Outputs (GITHUB_OUTPUT): releases (a JSON list of {kind, channel, tag,
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
ends) and due_record (the skip record, JSON) on a skip for the gap;
follow-up writes due (true or false), why, and again (true when a waiter ran
out of minutes before an answer). Notes for each release
go to DIR/<tag>.md. Only the standard library is used; git and gh must be on
PATH.
"""
Expand All @@ -98,6 +110,7 @@
import re
import subprocess
import sys
import time
import zipfile
from datetime import datetime, timedelta, timezone

Expand All @@ -116,6 +129,9 @@
DUE_ARTIFACT = "beta-due"
DUE_MARGIN = timedelta(minutes=1)
FOLLOW_UP_HOURS = 24
# How often a waiter checks again while a run of auto-release.yml is queued or
# running.
POLL_SECONDS = 120

# 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 @@ -512,29 +528,54 @@ def skip_record(commit, published, now, hours):


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

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.
busy a run of auto-release.yml is queued or running (a bool, or
f() -> bool, asked only when it matters): it plans again
itself, and a new run would only replace a queued one.
wait seconds after which checking again may answer otherwise
(not due yet, or busy); None when the answer is final.
"""
if not record:
return {"due": False, "reason": "no beta was skipped for the gap"}
return {"due": False, "reason": "no beta was skipped for the gap", "wait": None}
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"}
return {"due": False, "reason": "the skip record can't be read", "wait": None}
if now < due:
return {"due": False, "reason": "%s waits for the gap: due at %s" % (commit[:12], _iso(due))}
return {"due": False, "reason": "%s waits for the gap: due at %s" % (commit[:12], _iso(due)),
"wait": max(1, int((due - now).total_seconds() + 0.999))}
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)}
return {"due": False, "reason": "%s was due at %s, over %d hours ago: left to the nightly" % (commit[:12], _iso(due), FOLLOW_UP_HOURS),
"wait": None}
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))}
return {"due": False, "reason": "%s is already released in %s" % (commit[:12], tag), "wait": None}
if busy() if callable(busy) else busy:
return {"due": False, "reason": "%s is due, but a run of auto-release.yml is queued or running: checked again later" % commit[:12],
"wait": POLL_SECONDS}
return {"due": True, "reason": "%s was skipped for the gap and is due since %s" % (commit[:12], _iso(due)), "wait": None}


def wait_for_due(record, released_in, busy, clock, sleep, minutes):
"""follow_up, checked again as long as waiting may change its answer, for
at most `minutes` (a waiter). {due, reason, again}: again is True when the
minutes ran out before a final answer, so a new waiter carries on.

clock f() -> now (an aware datetime); sleep f(seconds).
"""
end = clock() + timedelta(minutes=minutes)
while True:
now = clock()
r = follow_up(record, now, released_in, busy)
if r["wait"] is None:
return {"due": r["due"], "reason": r["reason"], "again": False}
left = (end - now).total_seconds()
if left <= 0:
return {"due": False, "reason": r["reason"] + "; this waiter's time is up, a new one carries on", "again": True}
sleep(min(r["wait"], left))


def _api_json(path):
Expand Down Expand Up @@ -633,6 +674,8 @@ def main(argv):
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("--wait-minutes", type=float, default=0,
help="a waiter: check again until the record's answer is final, for at most this long")
f.add_argument("--github-output")
p = sub.add_parser("plan")
p.add_argument("--repo", required=True)
Expand Down Expand Up @@ -701,6 +744,7 @@ def keep(kind, channel, r, tag, commit):
f.write("summary=%s\n" % " ".join(summary.split()))
if due:
f.write("due=%s\n" % due["due"])
f.write("due_record=%s\n" % json.dumps(due, separators=(",", ":")))
if failed:
print("::error::" + summary, file=sys.stderr)
return 1
Expand All @@ -717,11 +761,20 @@ def main_follow_up(a):
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)
released = lambda c, since: _released_in(a.repo, c, since) # noqa: E731
busy = lambda: _busy(a.repo) # noqa: E731
if a.wait_minutes > 0:
def sleep(s):
print("follow-up: checking again in %d second(s)" % s, flush=True)
time.sleep(s)
r = wait_for_due(record, released, busy, lambda: datetime.now(timezone.utc), sleep, a.wait_minutes)
else:
r = follow_up(record, now, released, busy)
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("again=%s\n" % ("true" if r.get("again") else "false"))
f.write("reason=%s\n" % " ".join(r["reason"].split()))
return 0

Expand Down
124 changes: 120 additions & 4 deletions .github/scripts/test_auto_release.py
Original file line number Diff line number Diff line change
Expand Up @@ -505,12 +505,15 @@ def test_a_skip_for_the_gap_records_when_it_is_due(self):
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"])
# The same record, for the waiter the run starts.
self.assertEqual(json.loads(outputs["due_record"]), record)

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)
self.assertNotIn("due_record", outputs)

def test_the_record_is_due_a_minute_past_the_gap(self):
last = self.now - timedelta(hours=3, minutes=42)
Expand Down Expand Up @@ -543,6 +546,90 @@ def test_what_is_not_due_waits(self):
self.assertFalse(r["due"])
self.assertIn("queued or running", r["reason"])

def test_busy_is_asked_only_when_it_matters(self):
never = lambda: self.fail("busy asked") # noqa: E731
self.assertFalse(ar.follow_up(self.record(due_in_minutes=10), self.now, lambda c, s: None, never)["due"])
self.assertFalse(ar.follow_up(self.record(), self.now, lambda c, s: "v0.9.1-beta.20261204", never)["due"])
self.assertTrue(ar.follow_up(self.record(), self.now, lambda c, s: None, lambda: False)["due"])
r = ar.follow_up(self.record(), self.now, lambda c, s: None, lambda: True)
self.assertEqual((r["due"], r["wait"]), (False, ar.POLL_SECONDS))

def test_how_long_waiting_may_change_the_answer(self):
rel = lambda c, s: None # noqa: E731
self.assertEqual(ar.follow_up(self.record(due_in_minutes=10), self.now, rel)["wait"], 600)
# Final answers: due, released, unreadable, none, too old.
self.assertIsNone(ar.follow_up(self.record(), self.now, rel)["wait"])
self.assertIsNone(ar.follow_up(self.record(), self.now, lambda c, s: "v0.9.1-beta.20261204")["wait"])
self.assertIsNone(ar.follow_up({"commit": "x"}, self.now, rel)["wait"])
self.assertIsNone(ar.follow_up(None, self.now, rel)["wait"])
self.assertIsNone(ar.follow_up(self.record(due_in_minutes=-25 * 60), self.now, rel)["wait"])

class Clock:
"""A fake clock that sleeping moves forward."""

def __init__(self, now):
self.now, self.slept = now, []

def __call__(self):
return self.now

def sleep(self, s):
self.slept.append(s)
self.now += timedelta(seconds=s)

def test_the_waiter_sleeps_until_due_then_releases(self):
clock = self.Clock(self.now)
asked = []
r = ar.wait_for_due(self.record(due_in_minutes=230), lambda c, s: asked.append(clock()) or None,
lambda: False, clock, clock.sleep, 330)
self.assertEqual((r["due"], r["again"]), (True, False), r["reason"])
# One sleep, to the minute it is due: never a schedule's half hour.
self.assertEqual(clock.slept, [230 * 60])
self.assertEqual(asked, [self.now + timedelta(minutes=230)])

def test_the_waiter_waits_out_a_busy_release_run(self):
clock = self.Clock(self.now)
busy = iter([True, True, False])
r = ar.wait_for_due(self.record(due_in_minutes=1), lambda c, s: None, lambda: next(busy), clock, clock.sleep, 330)
self.assertTrue(r["due"], r["reason"])
self.assertEqual(clock.slept, [60, ar.POLL_SECONDS, ar.POLL_SECONDS])

def test_the_waiter_stops_once_the_commit_is_released(self):
clock = self.Clock(self.now)
answers = iter([None, "v0.9.1-beta.20261204"])
r = ar.wait_for_due(self.record(), lambda c, s: next(answers), lambda: True, clock, clock.sleep, 330)
self.assertEqual((r["due"], r["again"]), (False, False))
self.assertIn("already released", r["reason"])
self.assertEqual(clock.slept, [ar.POLL_SECONDS])

def test_a_waiter_out_of_minutes_hands_over(self):
clock = self.Clock(self.now)
r = ar.wait_for_due(self.record(), lambda c, s: None, lambda: True, clock, clock.sleep, 5)
self.assertEqual((r["due"], r["again"]), (False, True))
# Never sleeps past its minutes.
self.assertEqual(sum(clock.slept), 300)
clock = self.Clock(self.now)
r = ar.wait_for_due(self.record(due_in_minutes=400), lambda c, s: None, lambda: False, clock, clock.sleep, 330)
self.assertEqual((r["due"], r["again"], clock.slept), (False, True, [330 * 60]))

def test_the_waiter_command(self):
d = tempfile.mkdtemp()
rec, out = os.path.join(d, "rec.json"), os.path.join(d, "out")
now = datetime.now(timezone.utc)
with open(rec, "w") as f:
json.dump({"commit": SHA, "skipped_at": ar._iso(now - timedelta(hours=4)), "due": ar._iso(now - timedelta(minutes=1))}, f)
real = ar._released_in, ar._busy, ar.time.sleep
ar._released_in, ar._busy = lambda repo, c, since: None, lambda repo: False
ar.time.sleep = lambda s: self.fail("a due record never sleeps")
try:
self.assertEqual(ar.main(["follow-up", "--repo", "o/r", "--record", rec, "--wait-minutes", "330", "--github-output", out]), 0)
finally:
ar._released_in, ar._busy, ar.time.sleep = real
with open(out) as f:
lines = f.read().splitlines()
self.assertIn("due=true", lines)
self.assertIn("again=false", lines)

def test_follow_up_writes_its_answer(self):
d = tempfile.mkdtemp()
rec, out = os.path.join(d, "rec.json"), os.path.join(d, "out")
Expand All @@ -558,22 +645,51 @@ def test_the_workflows(self):
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"]
# A waiter (started with a record) and the backstop never cancel each other;
# a newer waiter replaces an older one.
self.assertEqual(doc["concurrency"]["group"],
"${{ inputs.record != '' && 'beta-follow-up-wait' || 'beta-follow-up' }}")
self.assertTrue(doc["concurrency"]["cancel-in-progress"])
self.assertEqual(on["workflow_dispatch"]["inputs"]["record"]["default"], "")
due, start, again = doc["jobs"]["due"], doc["jobs"]["start"], doc["jobs"]["again"]
self.assertEqual(due["permissions"], {"contents": "read", "actions": "read"})
self.assertIn("auto_release.py follow-up", due["steps"][-1]["run"])
step = due["steps"][-1]
self.assertIn("auto_release.py follow-up", step["run"])
self.assertIn('--record "$RUNNER_TEMP/record.json" --wait-minutes "$WAIT"', step["run"])
self.assertEqual(step["env"]["RECORD"], "${{ inputs.record }}")
# The waiter outlasts the gap and its margin, inside GitHub's 6-hour job limit.
wait = float(step["env"]["WAIT"])
_, auto = Wiring.load("auto-release.yml")
self.assertGreater(wait, float(auto["env"]["BETA_GAP_HOURS"]) * 60 + ar.DUE_MARGIN.total_seconds() / 60 + 30)
self.assertGreater(due["timeout-minutes"], wait)
self.assertLess(due["timeout-minutes"], 360)
# Out of minutes: a new waiter with the same record.
self.assertEqual(again["if"], "success() && needs.due.outputs.again == 'true'")
self.assertEqual(again["permissions"], {"actions": "write"})
self.assertEqual(again["steps"][-1]["env"]["RECORD"], "${{ inputs.record }}")
self.assertEqual(again["steps"][-1]["run"],
'gh workflow run beta-follow-up.yml -R "$GITHUB_REPOSITORY" --ref main -f record="$RECORD"')
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")
# The run that skipped starts the waiter itself, without sleeping in the "auto-release" group.
self.assertEqual(auto["jobs"]["plan"]["outputs"]["due_record"], "${{ steps.plan.outputs.due_record }}")
w = auto["jobs"]["wait"]
self.assertEqual(w["needs"], "plan")
self.assertEqual(w["if"], "${{ !cancelled() && needs.plan.result == 'success' && needs.plan.outputs.due_record != '' }}")
self.assertEqual(w["permissions"], {"actions": "write"})
self.assertLessEqual(w["timeout-minutes"], 5)
self.assertEqual(w["steps"][-1]["env"]["RECORD"], "${{ needs.plan.outputs.due_record }}")
self.assertEqual(w["steps"][-1]["run"],
'gh workflow run beta-follow-up.yml -R "$GITHUB_REPOSITORY" --ref main -f record="$RECORD"')


class WithGit(unittest.TestCase):
Expand Down
Loading