Skip to content

The agent that grows with you

feat(release): the stable sequencer narrates what it is doing

ethernetbfa4f5098c1a
diff --git a/scripts/bundles/release_artifacts.py b/scripts/bundles/release_artifacts.py
index 1e919f9c5f9..4ed14834cd1 100644
--- a/scripts/bundles/release_artifacts.py
+++ b/scripts/bundles/release_artifacts.py
@@ -243,7 +243,12 @@ def materialize(manifest: dict, root: Path, *, public_base: str, store_only: boo
selected = [item for item in files if item["path"].startswith("Store-") and item["path"].endswith(".msixbundle")] if store_only else files
if store_only and len(selected) != 1:
raise ValueError("Expected one Store candidate")
- for item in selected:
+ from scripts.releases.progress import log
+
+ total = sum(item.get("size", 0) for item in selected)
+ log(f"Materializing {len(selected)} candidate files ({total / 1e9:.1f} GB) into {root}")
+ for number, item in enumerate(selected, start=1):
+ log(f" [{number}/{len(selected)}] {item['path']} ({item.get('size', 0) / 1e6:.0f} MB)")
relative = Path(item["path"])
if relative.is_absolute() or ".." in relative.parts or any(c in item["path"] for c in "\\:%?#") or item["path"].startswith("/") or "//" in item["path"]:
raise ValueError("Invalid artifact path")
diff --git a/scripts/releases/channel_releases.py b/scripts/releases/channel_releases.py
index 539245b8e6e..89de95dac8a 100644
--- a/scripts/releases/channel_releases.py
+++ b/scripts/releases/channel_releases.py
@@ -16,6 +16,7 @@ from hermes_cli.release_channels import (
from scripts.bundles.channel_artifacts import assemble
from scripts.releases import handoff, optional_platforms, r2, stable
from scripts.releases.channels import ChannelPublisher, R2ChannelStore
+from scripts.releases.progress import log
from scripts.releases.versioning import parse_attempt_ref
NATIVE_LEGS = ("darwin-arm64", "darwin-x64", "win32-arm64", "win32-x64", "windows-universal")
@@ -268,6 +269,8 @@ def advance_stable(env: dict, release: dict, root: Path) -> dict:
public_base = r2.public_base_url()
key = f"releases/tag/{release['claim_tag']}/release-candidates.json"
digest = hashlib.sha256(read_archive_bytes(key)).hexdigest()
+ log(f"Candidate manifest {key}: sha256 {digest} "
+ f"(receipt {release.get('candidate_manifest_sha256')})")
if digest != release.get("candidate_manifest_sha256"):
raise ChannelError("Stable candidate manifest differs from the final release receipt")
scoped_env = {
@@ -376,6 +379,8 @@ def publish_release(policy: str, env: dict, root: Path) -> dict:
r2.public_base_url(), authorize=lambda action, record:
admit_transaction(policy, env, require_published=True))
name = select_channel(publisher, policy)
+ log(f"Channel advance: policy={policy} channel={name} archive={tag} payload={payload_tag} "
+ f"commit={commit[:10]}")
identity = product_identity(payload_tag)
current = publisher._read(name)
if current:
@@ -394,9 +399,11 @@ def publish_release(policy: str, env: dict, root: Path) -> dict:
# Native handoffs were staged under the attempt ref for stable attempts
# (identical for canary, where tag == payload_tag).
legs = native_legs(accepted)
+ log(f"Fetching native handoffs for {', '.join(legs)} from releases/tag/{tag}/")
handoff.fetch(tag, commit, list(legs), root,
["metadata-*.json", "*.zip", "*.dmg", "*.blockmap", "*.msixbundle"], public_base=publisher.public_base)
native = read_native_receipts(root, tag, commit, legs, payload_tag=payload_tag)
+ log(f"Native receipts verified: {len(native['packages'])} packages, {len(native['files'])} files")
windows = next(row for row in native["packages"] if row["platform"] == "windows")
if policy == "canary-release":
expected_windows = canary_windows_version(tag)
@@ -419,6 +426,8 @@ def publish_release(policy: str, env: dict, root: Path) -> dict:
return True
source_version = payload_tag[1:].split("+", 1)[0]
+ log(f"Allocating a protected build on {name} for {payload_tag[1:]} "
+ f"(windows {windows['version']})")
request = publisher.allocate_protected(name, commit, source_version, release_tag=payload_tag,
version=payload_tag[1:], windows_version=windows["version"],
identity=identity, policy=policy, release_gate=release_gate,
@@ -428,6 +437,7 @@ def publish_release(policy: str, env: dict, root: Path) -> dict:
if accepted is not None:
match_accepted_packages(manifest, accepted)
prefix = build_prefix(request["buildId"])
+ log(f"Build {request['buildId']}: writing {len(feeds)} immutable feeds under {prefix}")
for file in feeds:
key = prefix + file.relative_to(root).as_posix()
r2.put(tag=tag, key=key, file=str(file), key_is_full=True, immutable=True)
@@ -446,11 +456,14 @@ def publish_release(policy: str, env: dict, root: Path) -> dict:
publisher.verify_build = qualified
if accepted is not None:
+ log("Writing releases/stable/release-candidates.json and promoting the stable feeds")
publisher._write("releases/stable/release-candidates.json", accepted)
if publisher.reader.read_bytes("releases/stable/release-candidates.json") != canonical_json(accepted):
raise ChannelError("Stable candidate pointer read-back differs")
promote_stable_feeds(accepted, root, publisher.public_base)
+ log(f"Promoting build {request['buildId']} to the {name} head")
result = publisher.promote_protected(request["buildId"], policy=policy, release_gate=release_gate)
+ log(f"Channel {name} head is build {request['buildId']}")
return result
diff --git a/scripts/releases/handoff.py b/scripts/releases/handoff.py
index b5c65d22b1c..e09cf674950 100644
--- a/scripts/releases/handoff.py
+++ b/scripts/releases/handoff.py
@@ -259,7 +259,12 @@ def _fetch_receipts(receipts: list[dict], root: Path,
raise ValueError("No files selected from release handoff")
root.mkdir(parents=True, exist_ok=True)
credentials = r2.credentials() if public_base is None else None
- for row, key in selected.values():
+ from scripts.releases.progress import log
+
+ total = sum(row["size"] for row, _key in selected.values())
+ log(f"Downloading {len(selected)} receipt-bound files ({total / 1e9:.1f} GB)")
+ for number, (row, key) in enumerate(selected.values(), start=1):
+ log(f" [{number}/{len(selected)}] {key} ({row['size'] / 1e6:.0f} MB)")
if credentials is not None:
creds, base, bucket = credentials
r2.download_object(creds, base, bucket, key,
diff --git a/scripts/releases/progress.py b/scripts/releases/progress.py
new file mode 100644
index 00000000000..fe9df2c535d
--- /dev/null
+++ b/scripts/releases/progress.py
@@ -0,0 +1,74 @@
+"""Progress logging for release automation.
+
+Everything goes to stderr, flushed, so stdout stays the machine-readable
+result (the sequencer prints its steps as JSON there). On GitHub Actions the
+``::group::`` / ``::notice::`` lines render as collapsible sections and
+annotations; locally they read as plain prefixed lines.
+"""
+from __future__ import annotations
+
+import contextlib
+import sys
+import time
+from collections.abc import Callable, Iterator
+
+# Long argv values (release bodies, JSON payloads) are cut in command logs.
+_ARG_LIMIT = 160
+
+
+def log(message: str) -> None:
+ print(message, file=sys.stderr, flush=True)
+
+
+def notice(message: str, *, title: str | None = None) -> None:
+ log(f"::notice{f' title={title}' if title else ''}::{message}")
+
+
+def error(message: str, *, title: str | None = None) -> None:
+ log(f"::error{f' title={title}' if title else ''}::{message}")
+
+
+def group(title: str) -> Iterator[None]:
+ """A collapsible section that reports how long it took and whether it failed."""
+ log(f"::group::{title}")
+ started = time.monotonic()
+ try:
+ yield
+ except BaseException as exc:
+ log(f"✗ {title} failed after {time.monotonic() - started:.1f}s: {type(exc).__name__}: {exc}")
+ log("::endgroup::")
+ raise
+ log(f"✓ {title} ({time.monotonic() - started:.1f}s)")
+ log("::endgroup::")
+
+
+def describe_command(argv: list[str]) -> str:
+ shown = []
+ for arg in argv:
+ text = str(arg)
+ if len(text) > _ARG_LIMIT:
+ text = f"{text[:_ARG_LIMIT]}…(+{len(text) - _ARG_LIMIT} chars)"
+ shown.append(text.replace("\n", "\\n"))
+ return " ".join(shown)
+
+
+def logged_run(run: Callable[[list[str]], str]) -> Callable[[list[str]], str]:
+ """Wrap a ``run(argv) -> str`` so every command logs, with its time and outcome."""
+ if getattr(run, "_progress_logged", False):
+ return run
+
+ def wrapper(argv: list[str]) -> str:
+ log(f" $ {describe_command(argv)}")
+ started = time.monotonic()
+ try:
+ result = run(argv)
+ except BaseException as exc:
+ log(f" ↳ failed after {time.monotonic() - started:.1f}s: {type(exc).__name__}: {exc}")
+ raise
+ lines = result.count("\n") + 1 if result else 0
+ log(f" ↳ ok in {time.monotonic() - started:.1f}s ({lines} line{'s' if lines != 1 else ''})")
+ return result
+
+ wrapper._progress_logged = True # type: ignore[attr-defined]
+ return wrapper
diff --git a/scripts/releases/sequencer.py b/scripts/releases/sequencer.py
index 0a1948f0e3c..bc2f4e5e9d2 100644
--- a/scripts/releases/sequencer.py
+++ b/scripts/releases/sequencer.py
@@ -15,6 +15,7 @@ import time
from datetime import datetime, timedelta, timezone, UTC
from pathlib import Path
+from scripts.releases.progress import error as log_error, group, log, logged_run, notice
from scripts.releases.versioning import (
marker_ref, outstanding_attempts, parse_attempt_ref, parse_marker_ref,
tag_record, version_from_tag,
@@ -44,15 +45,19 @@ def plan(claims: list[dict], *, head: str | None,
if head_key is not None and version_key <= head_key:
if state in {"published", "burned"}:
+ log(f" plan {version}: {state}, at or below head {head} — nothing to do")
continue
raise ValueError(f"refusing to move the head backwards from {head}")
if state == "published":
+ log(f" plan {version}: published, above head {head} — advance")
steps.append({"advance": version})
continue
if state == "burned":
+ log(f" plan {version}: burned — skipped")
continue
if state == "running":
+ log(f" plan {version}: still running — stop here; nothing newer can move past it")
break
if state != "green":
raise ValueError(f"unknown claim state {state!r}")
@@ -71,7 +76,16 @@ def plan(claims: list[dict], *, head: str | None,
or flush_green_chain
)
if not eligible:
+ log(f" plan {version}: green but held — not autopublish, not requested "
+ f"(requested={requested_version!r}), and no later green claim needs it; stop")
break
+ why = [name for name, hit in (
+ ("autopublish", claim.get("autopublish", False)),
+ ("requested", version == requested_version),
+ ("a later green claim needs it", has_later_green_claim),
+ ("flushing a green chain", flush_green_chain),
+ ) if hit]
+ log(f" plan {version}: green — publish then advance ({', '.join(why)})")
steps.extend(({"flip": version}, {"advance": version}))
flush_green_chain = flush_green_chain or has_later_green_claim
@@ -213,18 +227,28 @@ def discover(repository: str, run=output) -> list[dict]:
"""Derive every stable claim state from remote refs and GitHub objects."""
from scripts.releases.stable import tagger_epoch, validate_claim, validate_final
+ log("Fetching stable receipt tags, attempt refs and abandon markers from origin")
run([
"git", "fetch", "origin", "+refs/tags/v*:refs/tags/v*",
"+refs/tags/rc.*:refs/tags/rc.*",
"+refs/tags/abandoned-rc.*:refs/tags/abandoned-rc.*",
])
refs = _remote_tags(run)
+ attempts = sorted(tag for tag in refs if parse_attempt_ref(tag))
+ log(f"Found {len(refs)} remote stable refs: {len(attempts)} attempt refs, "
+ f"{sum(1 for tag in refs if version_from_tag(tag))} receipt tags, "
+ f"{sum(1 for tag in refs if parse_marker_ref(tag))} abandon markers")
outstanding = outstanding_attempts(list(refs), lambda v: f"v{v}" in refs)
+ if outstanding:
+ log(f"Outstanding attempts (no receipt tag, not abandoned): "
+ f"{', '.join(ref for *_rest, ref in outstanding)}")
if len(outstanding) > 1:
named = ", ".join(ref for *_rest, ref in outstanding)
raise ValueError(f"more than one outstanding attempt ({named})")
releases = _release_rows(repository, run)
+ log(f"Read {len(releases)} GitHub releases")
workflow_runs = _workflow_runs(repository, run)
+ log(f"Read {len(workflow_runs)} dispatched Stable Release runs")
records = []
for claim_tag, claim_ref in refs.items():
@@ -259,6 +283,7 @@ def discover(repository: str, run=output) -> list[dict]:
# An abandoned attempt is spent whatever its version became: a later attempt
# may have won and been tagged at another commit (v0.21.6: rc.4 after rc.1-3).
state, retry = "burned", None
+ why = f"abandon marker {marker_ref(version, attempt)} exists"
elif final_ref is not None:
if set(final_ref) != {"object", "commit"}:
raise ValueError(f"{tag} must be an annotated remote tag")
@@ -272,8 +297,13 @@ def discover(repository: str, run=output) -> list[dict]:
raise ValueError(f"{tag} metadata differs from {claim_tag}") from error
if release is None or release.get("id") != final["releaseId"]:
state, needs_retarget = "burned", False
+ why = (f"{tag} exists but its release {final['releaseId']} is "
+ + ("missing" if release is None else f"not the one found ({release.get('id')})"))
else:
state, needs_retarget = classify_final_release(tag, claim_tag, release)
+ why = (f"{tag} receipt exists; release {release.get('id')} on "
+ f"{release.get('tag_name')}, draft={release.get('draft')}"
+ + ("; needs retarget onto the final tag" if needs_retarget else ""))
else:
if release is not None and (release.get("tag_name") != claim_tag
or release.get("draft") is not True
@@ -286,7 +316,19 @@ def discover(repository: str, run=output) -> list[dict]:
claimed_at=datetime.fromtimestamp(claim_epoch, tz=UTC),
has_draft=release is not None,
)
-
+ latest = max(matching_runs, key=lambda row: row.get("run_attempt", 0), default=None)
+ why = ("no Stable Release run yet" if latest is None else
+ f"run {latest.get('id')} attempt {latest.get('run_attempt')} "
+ f"{latest.get('status')}/{latest.get('conclusion') or '-'}")
+ why += f"; draft {'on ' + claim_tag if release is not None else 'missing'}"
+ if retry:
+ why += f"; failed-job retry due (attempt {retry['attempt'] + 1} of {MAX_ATTEMPTS})"
+
+ flags = [name for name, on in (("autopublish", claim["autopublish"]),
+ ("skip-bundles", claim["skipBundles"]),
+ ("skip-tests", claim["skipTests"])) if on]
+ log(f" {claim_tag} @ {commit[:10]}: {state.upper()} — {why}"
+ + (f" [{', '.join(flags)}]" if flags else ""))
records.append({
"version": version,
"attempt": attempt,
@@ -333,13 +375,19 @@ def reconcile(env: dict, *, run=output, read_head=None, advance_head=None,
from scripts.releases import channel_releases, docker, stable, store
repository = env["GITHUB_REPOSITORY"]
+ run = logged_run(run)
+ requested = env.get("REQUESTED_VERSION") or None
+ log(f"Stable sequencer: repository={repository} requested={requested or '(none)'}")
# The archive copy is the only authority for the candidate manifest digest;
# nothing records it before the publication pass hashes it.
read_archive = read_archive or channel_releases.read_archive_bytes
- records = discover(repository, run)
+ with group("Discover stable claims"):
+ records = discover(repository, run)
retries = retry_due(records)
if retries:
for retry in retries:
+ log(f"Rerunning failed jobs of {retry['version']}'s run {retry['run_id']} "
+ f"(attempt {retry['attempt']} of {MAX_ATTEMPTS}); publication waits for it")
endpoint = f"repos/{repository}/actions/runs/{retry['run_id']}"
run([
"gh", "api", "--method", "POST",
@@ -352,41 +400,62 @@ def reconcile(env: dict, *, run=output, read_head=None, advance_head=None,
and current.get("status") != "completed"):
break
if attempt < 5:
+ log(f" run {retry['run_id']} is at attempt {current.get('run_attempt')} "
+ f"({current.get('status')}); waiting 5s for attempt {retry['attempt']}")
time.sleep(5)
else:
raise ValueError(f"Stable retry {retry['run_id']} did not enter attempt {retry['attempt']}")
+ notice(", ".join(f"{r['version']} retry attempt {r['attempt']} queued" for r in retries),
+ title="Stable sequencer")
return [{"retry": retry["version"], "attempt": retry["attempt"]} for retry in retries]
for record in records:
if record["needs_retarget"]:
# Recovery for a publish that died after the receipt tag: the tag
# exists and the release is still a draft, so the retarget and the
# publication rerun. A public release can never be repaired.
- stable.edit_draft_release(repository, record["release_id"], record["tag"],
- record["commit"], run=run)
- stable.publish_release_draft(repository, record["release_id"], record["tag"],
- run=run)
+ with group(f"Repair {record['version']}: retarget release {record['release_id']} "
+ f"onto {record['tag']} and publish it"):
+ stable.edit_draft_release(repository, record["release_id"], record["tag"],
+ record["commit"], run=run)
+ stable.publish_release_draft(repository, record["release_id"], record["tag"],
+ run=run)
if any(record["needs_retarget"] for record in records):
- records = discover(repository, run)
+ with group("Rediscover after repair"):
+ records = discover(repository, run)
read_head = read_head or (lambda: channel_head(
channel_releases.stable_head_version(env), discover(repository, run),
docker.stable_alias_digest()))
- head = read_head()
- requested = env.get("REQUESTED_VERSION") or None
- steps = plan(records, head=head, requested_version=requested)
+ with group("Read the stable channel head"):
+ head = read_head()
+ log(f"Channel head: {head or '(none)'}")
+ with group("Plan"):
+ steps = plan(records, head=head, requested_version=requested)
+ log("Steps: " + (", ".join(f"{kind} {version}" for step in steps
+ for kind, version in step.items()) or "(none)"))
by_version = {record["version"]: record for record in records}
if advance_head is None:
def production_advance(record: dict) -> None:
if not record["skip_bundles"]:
+ log(f"Advancing the protected desktop channel to {record['version']} from "
+ f"releases/tag/{record['claim_tag']}/ "
+ f"(receipt manifest {record['candidate_manifest_sha256']})")
with tempfile.TemporaryDirectory() as directory:
channel_releases.advance_stable(env, record, Path(directory))
+ log(f"Desktop channel head is now {record['version']}")
+ else:
+ log(f"{record['version']} skipped bundles: no desktop channel to advance")
+ log(f"Moving Docker stable/latest aliases onto {record['claim_tag']} "
+ f"({record['docker_manifest_digest']})")
# The stable/latest aliases move onto the attempt's image here, in
# the publication pass with the feed pointer, never in the green
# build that pushed the image under the attempt ref. A release
# that skipped bundles moves only these aliases.
docker.promote_stable(record["claim_tag"], record["docker_manifest_digest"])
+ log("Docker aliases moved")
if not record["skip_bundles"]:
+ log("Checking the Microsoft Store submission")
# The Store check joins the pass here (after the feeds and aliases
# move). It never releases the held submission: the API cannot,
# so it prints the Publish now step. The Store never blocks a
@@ -398,17 +467,26 @@ def reconcile(env: dict, *, run=output, read_head=None, advance_head=None,
"upload the Store package from the release run's summary in Partner Center.")
advance_head = production_advance
- for step in steps:
+ for number, step in enumerate(steps, start=1):
if "flip" in step:
record = by_version[step["flip"]]
- # discover() ran before the receipt tag existed, so the record has no
- # receipt digests yet; the advance below must check the ones just written.
- record.update(stable.publish_attempt(
- record, repository=repository, run=run, read_archive=read_archive))
+ with group(f"[{number}/{len(steps)}] Publish {record['version']}: write {record['tag']}, "
+ f"retarget release {record['release_id']} from {record['claim_tag']}, make it public"):
+ # discover() ran before the receipt tag existed, so the record has no
+ # receipt digests yet; the advance below must check the ones just written.
+ record.update(stable.publish_attempt(
+ record, repository=repository, run=run, read_archive=read_archive))
+ log(f"Receipt {record['tag']}: manifest {record['candidate_manifest_sha256']}, "
+ f"docker {record['docker_manifest_digest']}")
+ notice(f"{record['tag']} is public", title="Stable sequencer")
else:
- advance_head(by_version[step["advance"]])
+ record = by_version[step["advance"]]
+ with group(f"[{number}/{len(steps)}] Advance channels to {record['version']}"):
+ advance_head(record)
+ notice(f"Stable channels advanced to {record['version']}", title="Stable sequencer")
- final = {record["version"]: record for record in discover(repository, run)}
+ with group("Verify"):
+ final = {record["version"]: record for record in discover(repository, run)}
for step in steps:
if "flip" in step and final[step["flip"]]["state"] != "published":
raise ValueError(f"Stable release {step['flip']} did not publish")
@@ -416,8 +494,12 @@ def reconcile(env: dict, *, run=output, read_head=None, advance_head=None,
raise ValueError(f"Requested stable release {requested} did not publish")
if any("advance" in step for step in steps):
expected = next(step["advance"] for step in reversed(steps) if "advance" in step)
- if read_head() != expected:
+ reached = read_head()
+ log(f"Channel head after the pass: {reached} (planned {expected})")
+ if reached != expected:
raise ValueError("Stable protected head did not reach the planned version")
+ log("Stable sequencer finished: " + (", ".join(
+ f"{kind} {version}" for step in steps for kind, version in step.items()) or "nothing to do"))
return steps
@@ -426,7 +508,12 @@ def main(argv: list[str] | None = None, env: dict | None = None) -> None:
argv = sys.argv[1:]
if argv:
raise ValueError("The stable sequencer takes no positional arguments")
- print(json.dumps(reconcile(dict(os.environ if env is None else env)), sort_keys=True))
+ try:
+ steps = reconcile(dict(os.environ if env is None else env))
+ except Exception as exc:
+ log_error(f"{type(exc).__name__}: {exc}", title="Stable sequencer failed")
+ raise
+ print(json.dumps(steps, sort_keys=True))
if __name__ == "__main__":
diff --git a/tests/scripts/test_release_progress.py b/tests/scripts/test_release_progress.py
new file mode 100644
index 00000000000..2cec302ece9
--- /dev/null
+++ b/tests/scripts/test_release_progress.py
@@ -0,0 +1,41 @@
+"""Release progress logging: stderr only, grouped, and commands stay readable."""
+import subprocess
+
+import pytest
+
+from scripts.releases import progress
+
+
+def test_logged_run_logs_each_command_and_its_outcome(capsys):
+ run = progress.logged_run(lambda argv: "a\nb")
+ assert run(["git", "ls-remote", "origin"]) == "a\nb"
+ err = capsys.readouterr().err
+ assert " $ git ls-remote origin" in err
+ assert "ok in" in err and "(2 lines)" in err
+ # Wrapping twice does not double the logs.
+ assert progress.logged_run(run) is run
+
+
+def test_logged_run_logs_a_failure_and_reraises(capsys):
+ def fail(argv):
+ raise subprocess.CalledProcessError(128, argv)
+
+ with pytest.raises(subprocess.CalledProcessError):
+ progress.logged_run(fail)(["git", "push", "origin", "refs/tags/v1.2.3"])
+ assert "failed after" in capsys.readouterr().err
+
+
+def test_long_arguments_are_cut_and_newlines_escaped():
+ shown = progress.describe_command(["gh", "api", "--raw-field", "body=" + "x" * 500 + "\nmore"])
+ assert "…(+" in shown and "\n" not in shown
+ assert len(shown) < 260
+
+
+def test_group_balances_and_reports_failure(capsys):
+ with pytest.raises(RuntimeError):
+ with progress.group("Advance"):
+ raise RuntimeError("nope")
+ err = capsys.readouterr().err
+ assert err.startswith("::group::Advance\n")
+ assert "✗ Advance failed after" in err and "RuntimeError: nope" in err
+ assert err.rstrip().endswith("::endgroup::")
diff --git a/tests/scripts/test_release_sequencer.py b/tests/scripts/test_release_sequencer.py
index b947b0e0e34..b57043435e5 100644
--- a/tests/scripts/test_release_sequencer.py
+++ b/tests/scripts/test_release_sequencer.py
@@ -677,3 +677,66 @@ def test_a_release_that_skipped_bundles_ships_only_its_tag_release_and_docker_al
# receipt digest, so the next pass has nothing left to advance.
assert sequencer.reconcile(env, run=run, read_archive=no_archive) == []
assert events == [("aliases", "rc.1-v0.21.5")]
+
+
+def test_the_sequencer_narrates_every_phase_on_stderr_and_keeps_stdout_json(capsys):
+ """Discovery, each claim's state and why, the plan, every step and every command."""
+ from scripts.releases.sequencer import reconcile
+
+ manifest_digest = hashlib.sha256(b"m").hexdigest()
+ _tags, _releases, run = _sequencer_fixture(
+ "0.21.5", manifest_digest=manifest_digest, final_tags=False)
+ head = ["0.21.4"]
+
+ def advance(record):
+ head[0] = record["version"]
+
+ reconcile({"GITHUB_REPOSITORY": "example/project", "REQUESTED_VERSION": "0.21.5"},
+ run=run, read_head=lambda: head[0], advance_head=advance,
+ read_archive=lambda _key: b"m")
+ captured = capsys.readouterr()
+ assert captured.out == ""
+ err = captured.err
+ for expected in (
+ "Stable sequencer: repository=example/project requested=0.21.5",
+ "::group::Discover stable claims",
+ "rc.1-v0.21.5 @ aaaaaaaaaa: GREEN — run 101 attempt 1 completed/success; draft on rc.1-v0.21.5",
+ "Channel head: 0.21.4",
+ "plan 0.21.5: green — publish then advance (requested)",
+ "Steps: flip 0.21.5, advance 0.21.5",
+ "[1/2] Publish 0.21.5",
+ f"Receipt v0.21.5: manifest {manifest_digest}",
+ "::notice title=Stable sequencer::v0.21.5 is public",
+ "[2/2] Advance channels to 0.21.5",
+ "Channel head after the pass: 0.21.5 (planned 0.21.5)",
+ "Stable sequencer finished: flip 0.21.5, advance 0.21.5",
+ " $ git push origin refs/tags/v0.21.5",
+ ):
+ assert expected in err, expected
+ assert err.count("::group::") == err.count("::endgroup::")
+
+
+def test_a_held_claim_says_why_it_was_held(capsys):
+ from scripts.releases.sequencer import plan
+
+ plan([{"version": "0.21.5", "state": "green", "autopublish": False}], head="0.21.4")
+ assert "plan 0.21.5: green but held" in capsys.readouterr().err
+
+
+def test_main_prints_only_the_steps_on_stdout_and_annotates_a_failure(monkeypatch, capsys):
+ from scripts.releases import sequencer
+
+ monkeypatch.setattr(sequencer, "reconcile", lambda env: [{"advance": "0.21.5"}])
+ sequencer.main([], {})
+ assert json.loads(capsys.readouterr().out) == [{"advance": "0.21.5"}]
+
+ def boom(env):
+ raise ValueError("Stable protected head did not reach the planned version")
+
+ monkeypatch.setattr(sequencer, "reconcile", boom)
+ with pytest.raises(ValueError):
+ sequencer.main([], {})
+ captured = capsys.readouterr()
+ assert captured.out == ""
+ assert ("::error title=Stable sequencer failed::ValueError: "
+ "Stable protected head did not reach the planned version") in captured.err