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
24 changes: 24 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -957,6 +957,30 @@ jobs:
test -f install.sh
desktop/ci/release-assets.sh --unsigned dist "${VERSION}"

# main fast-forwards to the commit the merge queue already built and
# tested, then builds it again. Before anything is released from the
# candidate's build, this reports on each main release run whether that
# build is there and complete. It decides nothing and is never red.
candidate-build:
name: Could the merge candidate's build be released (observation)
needs: version
if: >-
github.ref == 'refs/heads/main' && github.event_name == 'push' &&
needs.version.outputs.dev_due != 'false'
runs-on: ubuntu-24.04
timeout-minutes: 10
permissions:
actions: read
contents: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
persist-credentials: false
- env:
GH_TOKEN: ${{ github.token }}
run: python3 desktop/ci/candidate_build.py "$GITHUB_SHA" "$RUNNER_TEMP/candidate"

merge:
name: OX merge check
if: ${{ always() && (github.event_name == 'pull_request' || github.event_name == 'merge_group') }}
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/fast.yml
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ jobs:
- run: python3 -m unittest discover -s desktop/ci -p test_pr_scope.py
- run: python3 -m unittest discover -s desktop/ci -p test_auto_queue.py
- run: bash -n desktop/ci/release-assets.sh && test -x desktop/ci/release-assets.sh && python3 -m unittest discover -s desktop/ci -p test_release_assets.py
- run: python3 -m unittest discover -s desktop/ci -p test_candidate_build.py
- run: python3 desktop/ci/contract.py --final
- run: cargo clippy --manifest-path desktop/Cargo.toml --locked --workspace --all-targets -- -D warnings
- run: cargo nextest run --manifest-path desktop/Cargo.toml --locked --workspace
Expand Down
119 changes: 119 additions & 0 deletions desktop/ci/candidate_build.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
"""Find the merge candidate that already built what main is about to release.

The merge queue builds and tests every code candidate with the full unsigned
release matrix, and main then fast-forwards to that same commit and builds it
again. This reports whether the candidate's artifacts could have been
released instead. It observes only: nothing is signed or published from them.
"""
import argparse
import json
import os
import re
import subprocess
import sys
from pathlib import Path

from delivery import git, remote_position
from pr_scope import changed_paths, delivery_channels

QUEUE_BRANCH = "gh-readonly-queue/main/"
VERSION = re.compile(r"ox-(\d+\.\d+\.\d+-dev\.\d+)-x86_64-unknown-linux-gnu")


def release_source(position, head):
"""Return the newest commit after position that changed what dev ships, or None."""
history = git("log", "--first-parent", "--format=%H %P", f"{position}..{head}")
for line in history.splitlines():
commit, parent, *_ = line.split()
if "dev" in delivery_channels(changed_paths(parent, commit)):
return commit
return None


def trusted(run, repo, sha):
"""Accept only this repository's own green queue run of ci.yml on exactly this commit."""
return (run.get("event") == "merge_group" and run.get("path") == ".github/workflows/ci.yml"
and run.get("head_sha") == sha and run.get("conclusion") == "success"
and (run.get("head_branch") or "").startswith(QUEUE_BRANCH)
and (run.get("head_repository") or {}).get("full_name") == repo)


def candidate_run(repo, sha):
runs = json.loads(subprocess.check_output([
"gh", "api", f"repos/{repo}/actions/workflows/ci.yml/runs?event=merge_group&head_sha={sha}&per_page=100",
], text=True))["workflow_runs"]
matches = [run for run in runs if trusted(run, repo, sha)]
return max(matches, key=lambda run: run["id"]) if matches else None


def built_version(directory):
"""Read the one dev version the candidate compiled into its Linux x86-64 binary's name."""
versions = {match[1] for path in (directory / "ox-x86_64-unknown-linux-gnu").glob("ox-*")
if (match := VERSION.fullmatch(path.name))}
return versions.pop() if len(versions) == 1 else None


def order(version):
"""Sort key the updater's comparison agrees with: 0.0.1-dev.2143 -> (0, 0, 1, 2143)."""
return tuple(int(part) for part in re.fullmatch(r"(\d+)\.(\d+)\.(\d+)-dev\.(\d+)", version).groups())


def published_version(repo):
"""Read the version of the rolling dev pre-release from its Linux x86-64 asset, or None."""
names = subprocess.check_output(["gh", "api", f"repos/{repo}/releases/tags/dev", "--jq", ".assets[].name"],
text=True).split()
versions = {match[1] for name in names if (match := VERSION.fullmatch(name))}
return versions.pop() if len(versions) == 1 else None


def observe(repo, head, directory):
position = remote_position("dev")
if not position:
return "no delivered/dev position to measure from"
source = release_source(position, head)
if not source:
return f"nothing after delivered/dev {position[:7]} changes what dev ships"
run = candidate_run(repo, source)
if not run:
return f"no green merge-queue run of ci.yml built {source}"
where = f"candidate run {run['id']} (#{run['run_number']}) of {source[:7]}"
# gh follows temporary signed storage URLs and names them in its errors. Keep them out of the log.
download = subprocess.run(["gh", "run", "download", str(run["id"]), "--repo", repo, "--pattern", "ox-*",
"--dir", str(directory)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if download.returncode:
return f"{where}: its artifacts did not download (gh exit {download.returncode})"
version = built_version(directory)
if not version:
return f"{where}: no single dev version among its Linux x86-64 files"
check = subprocess.run([str(Path(__file__).with_name("release-assets.sh")), "--unsigned", str(directory), version],
capture_output=True, text=True)
if check.returncode:
return f"{where}: version {version} fails the release asset list: {check.stderr.strip()[-300:]}"
files = len(check.stdout.splitlines())
# Run numbers are shared by pull request, queue and main runs, so a queue build of a newer
# commit can carry a lower number than main's build of an older one. An installed dev build
# only takes a higher version: releasing a lower one would reach nobody.
published = published_version(repo)
if not published:
return f"{where}: complete as {version}, but the published dev version could not be read"
if order(version) <= order(published):
return (f"{where}: complete, but its version {version} does not advance the published {published}; "
"main's own build is needed")
return f"REUSABLE {where}: version {version} advances {published}, {files} release files match their checksums"


if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("head")
parser.add_argument("directory", type=Path)
args = parser.parse_args()
try:
result = observe(os.environ["GITHUB_REPOSITORY"], args.head, args.directory)
except (subprocess.CalledProcessError, ValueError, KeyError, OSError) as error:
result = f"could not complete the observation ({type(error).__name__})"
line = f"Merge candidate build for {args.head[:7]}: {result}"
print(line if result.startswith("REUSABLE") else f"::warning::{line}")
if summary := os.environ.get("GITHUB_STEP_SUMMARY"):
with open(summary, "a", encoding="utf-8") as out:
out.write(f"- {line}\n")
sys.exit(0) # An observation never decides whether main releases.
78 changes: 78 additions & 0 deletions desktop/ci/test_candidate_build.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch

import candidate_build as candidate

REPO = "oxstack/ox"
SHA = "9" * 40


def run(**changes):
# Shape read from a real run: gh api repos/oxstack/ox/actions/runs/47120928906
return {"id": 1, "run_number": 2071, "event": "merge_group", "path": ".github/workflows/ci.yml",
"head_sha": SHA, "conclusion": "success", "head_repository": {"full_name": REPO},
"head_branch": f"gh-readonly-queue/main/pr-378-{'a' * 40}", **changes}


class CandidateBuild(unittest.TestCase):
def test_only_a_green_queue_run_of_ci_on_this_commit_is_trusted(self):
self.assertTrue(candidate.trusted(run(), REPO, SHA))
for change in (
{"event": "pull_request"}, {"event": "push"}, {"path": ".github/workflows/other.yml"},
{"head_sha": "8" * 40}, {"conclusion": "failure"}, {"conclusion": None},
{"head_branch": "main"}, {"head_branch": None}, {"head_branch": "feature/gh-readonly-queue/main/x"},
{"head_repository": {"full_name": "fork/ox"}}, {"head_repository": None},
):
with self.subTest(change=change):
self.assertFalse(candidate.trusted(run(**change), REPO, SHA))

def test_the_newest_run_wins_and_untrusted_runs_are_ignored(self):
runs = {"workflow_runs": [run(id=5, conclusion="failure"), run(id=3), run(id=4), run(id=9, event="push")]}
with patch("subprocess.check_output", return_value=__import__("json").dumps(runs)):
self.assertEqual(candidate.candidate_run(REPO, SHA)["id"], 4)
with patch("subprocess.check_output", return_value='{"workflow_runs": []}'):
self.assertIsNone(candidate.candidate_run(REPO, SHA))

def test_release_source_is_the_newest_commit_that_changes_what_dev_ships(self):
history = "c3 c2\nc2 c1\nc1 c0"
changes = {("c2", "c3"): ["docs/guide.md"], ("c1", "c2"): ["src/main.rs"], ("c0", "c1"): ["src/update.rs"]}
with patch.object(candidate, "git", return_value=history), \
patch.object(candidate, "changed_paths", side_effect=lambda base, head: changes[base, head]):
self.assertEqual(candidate.release_source("c0", "c3"), "c2")
with patch.object(candidate, "git", return_value="c3 c2"), \
patch.object(candidate, "changed_paths", return_value=["docs/guide.md"]):
self.assertIsNone(candidate.release_source("c2", "c3"))
with patch.object(candidate, "git", return_value=""):
self.assertIsNone(candidate.release_source("c3", "c3"))

def test_versions_order_by_number_not_by_text(self):
self.assertLess(candidate.order("0.0.1-dev.999"), candidate.order("0.0.1-dev.2143"))
# The case seen on 2026-12-03: main built 57c3fbd as dev.2145, the queue built its descendant as dev.2143.
self.assertLess(candidate.order("0.0.1-dev.2143"), candidate.order("0.0.1-dev.2145"))
self.assertLess(candidate.order("0.0.1-dev.2145"), candidate.order("0.0.2-dev.1"))

def test_the_published_version_comes_from_the_dev_release_assets(self):
# Names as gh api repos/oxstack/ox/releases/tags/dev returned them.
names = "install.sh\nox-0.0.1-dev.2060-x86_64-unknown-linux-gnu\nox-0.0.1-dev.2060-x86_64-unknown-linux-gnu.tar.gz\nox-x86_64-unknown-linux-gnu.tar.gz\n"
with patch("subprocess.check_output", return_value=names):
self.assertEqual(candidate.published_version(REPO), "0.0.1-dev.2060")
with patch("subprocess.check_output", return_value="install.sh\n"):
self.assertIsNone(candidate.published_version(REPO))

def test_the_version_is_read_only_when_the_files_agree(self):
with tempfile.TemporaryDirectory() as temporary:
files = Path(temporary) / "ox-x86_64-unknown-linux-gnu"
files.mkdir()
self.assertIsNone(candidate.built_version(Path(temporary)))
for name in ("ox-0.2.1-dev.2071-x86_64-unknown-linux-gnu", "ox-x86_64-unknown-linux-gnu.tar.gz",
"ox-0.2.1-dev.2071-x86_64-unknown-linux-gnu.tar.gz"):
(files / name).touch()
self.assertEqual(candidate.built_version(Path(temporary)), "0.2.1-dev.2071")
(files / "ox-0.2.1-dev.2072-x86_64-unknown-linux-gnu").touch()
self.assertIsNone(candidate.built_version(Path(temporary)))


if __name__ == "__main__":
unittest.main()
2 changes: 1 addition & 1 deletion docs/verification.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ For maintainers. Both publishing jobs depend on the baseline stock-client checks
patch raised by one, then `-dev.` and the workflow run number. With no
stable release it is `0.0.1-dev.N`.

Documentation-only PR and queue runs check local Markdown links, anchors and shortcut parity. Scoped code PRs build the Linux x86-64 CLI and run the additional lanes selected for the change. The optional `full-ci` label adds all release targets and unsigned package checks. To request a merge, the maintainer comments `/queue <full-head-sha>` on the PR. The existing scoped run and exact-head reviews must pass. Code merge candidates always run that matrix. Use `python3 desktop/ci/queue_timing.py RUN_ID` on a completed merge-group CI run to distinguish time waiting to start from execution and total queue residence. On main the rolling dev release and TestFlight each cover outstanding commits to their own inputs. Ordinary docs affect neither channel. A tag-protection rule or ruleset that covers
Documentation-only PR and queue runs check local Markdown links, anchors and shortcut parity. Scoped code PRs build the Linux x86-64 CLI and run the additional lanes selected for the change. The optional `full-ci` label adds all release targets and unsigned package checks. To request a merge, the maintainer comments `/queue <full-head-sha>` on the PR. The existing scoped run and exact-head reviews must pass. Code merge candidates always run that matrix. Use `python3 desktop/ci/queue_timing.py RUN_ID` on a completed merge-group CI run to distinguish time waiting to start from execution and total queue residence. On main the rolling dev release and TestFlight each cover outstanding commits to their own inputs. Each main release run also reports, in the job `Could the merge candidate's build be released (observation)`, whether the merge queue's own build of the newest commit that changes what dev ships is present and passes the release asset list. It releases nothing from that build and is never red. Ordinary docs affect neither channel. A tag-protection rule or ruleset that covers
the `dev` tag, or immutable releases, would make the dev job fail at its swap
step.

Expand Down