From a173318d3aae402185d509db728db188fae6bff6 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Mon, 30 Nov 2026 14:08:26 +0530 Subject: [PATCH 1/2] ci(release): gate publishing on CI and dispatch bindings after crates.io (#938, #939) Release Cascade now runs on completion of a successful official tag-push Release run, checks the tag still names that commit and that CI passed on it, waits up to 60 minutes for the exact crate version, then dispatches the bindings. A Release Gate job (cargo-dist local-artifacts-jobs) blocks hosting and publishing unless the tagged commit's push CI succeeded. The hand-added crates.io publish job moves unchanged into a dist publish-jobs workflow so release.yml is generated again. Closes #938. Closes #939. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01H2a7QngaFzuCVt5umd1qoh --- .github/release/release.sh | 136 ++++++++++++++ .github/release/test_release.py | 247 ++++++++++++++++++++++++++ .github/workflows/cascade.yml | 67 +++---- .github/workflows/release-gate.yml | 31 ++++ .github/workflows/release-publish.yml | 31 ++++ .github/workflows/release.yml | 63 +++---- CONTRIBUTING.md | 14 +- dist-workspace.toml | 13 +- 8 files changed, 523 insertions(+), 79 deletions(-) create mode 100644 .github/release/release.sh create mode 100644 .github/release/test_release.py create mode 100644 .github/workflows/release-gate.yml create mode 100644 .github/workflows/release-publish.yml diff --git a/.github/release/release.sh b/.github/release/release.sh new file mode 100644 index 0000000000..f4c9c63f8a --- /dev/null +++ b/.github/release/release.sh @@ -0,0 +1,136 @@ +#!/usr/bin/env bash +set -euo pipefail + +fail() { + echo "::error::$*" >&2 + exit 1 +} + +validate_tag() { + local number='(0|[1-9][0-9]*)' + local identifier='(0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)' + [[ "$1" =~ ^v${number}\.${number}\.${number}(-${identifier}(\.${identifier})*)?$ ]] || fail "Invalid release tag: $1" +} + +resolve_tag() { + validate_tag "$1" + gh api "repos/$GITHUB_REPOSITORY/commits/refs%2Ftags%2F$1" | jq -er '.sha' +} + +release_runs() { + gh api "repos/$GITHUB_REPOSITORY/actions/workflows/release.yml/runs?head_sha=$1&event=push&per_page=100" --paginate --slurp +} + +validate_run() { + local run=$1 tag=$2 sha=$3 workflow_id + workflow_id=$(gh api "repos/$GITHUB_REPOSITORY/actions/workflows/release.yml" | jq -er '.id') + jq -e --arg repo "$GITHUB_REPOSITORY" --arg tag "$tag" --arg sha "$sha" --argjson workflow "$workflow_id" ' + .name == "Release" and .path == ".github/workflows/release.yml" and + .workflow_id == $workflow and .event == "push" and + .status == "completed" and .conclusion == "success" and + .head_branch == $tag and .head_sha == $sha and + .repository.full_name == $repo and .repository.fork == false and + .head_repository.full_name == $repo and .head_repository.fork == false + ' <<< "$run" >/dev/null || fail 'Not a successful official tag-push Release run for this commit' +} + +check_ci() { + local tag=$1 sha=$2 resolved files filename name runs latest checked=0 + resolved=$(resolve_tag "$tag") + [[ "$resolved" == "$sha" ]] || fail "Tag $tag no longer resolves to $sha" + files=$(gh api "repos/$GITHUB_REPOSITORY/contents/.github/workflows?ref=$sha") + while IFS='|' read -r filename name; do + if ! jq -e --arg file "$filename" 'any(.[]; .name == $file)' <<< "$files" >/dev/null; then + echo "Skipping $name: workflow absent from $tag ($sha)" + continue + fi + checked=$((checked + 1)) + runs=$(gh api "repos/$GITHUB_REPOSITORY/actions/workflows/$filename/runs?head_sha=$sha&event=push&per_page=100" --paginate --slurp) + latest=$(jq -c --arg repo "$GITHUB_REPOSITORY" --arg sha "$sha" --arg name "$name" --arg path ".github/workflows/$filename" ' + [.[] | .workflow_runs[] | + select(.head_sha == $sha and .event == "push" and .name == $name and .path == $path and + .repository.full_name == $repo and .repository.fork == false and + .head_repository.full_name == $repo and .head_repository.fork == false)] | + max_by(.id) + ' <<< "$runs") + jq -e '.status == "completed" and .conclusion == "success"' <<< "$latest" >/dev/null || + fail "$name has no successful latest push run for $sha; finish CI before tagging or retrying Release" + echo "$name: $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$(jq -r '.id' <<< "$latest") ($sha)" + done <<'WORKFLOWS' +rust.yml|Rust +wasm.yml|WASM +lint.yml|Lint +coverage-gates.yml|Coverage Gates +policy.yml|Policy +binary-size.yml|Binary Size +WORKFLOWS + (( checked > 0 )) || fail "No required workflows found at $sha" +} + +prepare_cascade() { + local run tag sha runs + case "$GITHUB_EVENT_NAME" in + workflow_run) + run=$(jq -c '.workflow_run' "$GITHUB_EVENT_PATH") + if [[ $(jq -r '.conclusion' <<< "$run") != success ]]; then + echo 'Release did not succeed; nothing to dispatch' + return + fi + tag=$(jq -er '.head_branch' <<< "$run") + sha=$(resolve_tag "$tag") + ;; + workflow_dispatch) + tag=$(jq -er '.inputs.tag' "$GITHUB_EVENT_PATH") + sha=$(resolve_tag "$tag") + runs=$(release_runs "$sha") + run=$(jq -c --arg tag "$tag" '[.[] | .workflow_runs[] | select(.head_branch == $tag)] | max_by(.id)' <<< "$runs") + ;; + *) fail "Unsupported cascade event: $GITHUB_EVENT_NAME" ;; + esac + validate_run "$run" "$tag" "$sha" + check_ci "$tag" "$sha" + echo "tag=$tag" >> "$GITHUB_OUTPUT" +} + +wait_for_crate() { + local tag=$1 version deadline now remaining delay=10 response + validate_tag "$tag" + version=${tag#v} + deadline=$(( $(date +%s) + 3600 )) + while true; do + if response=$(curl --fail --silent --show-error --connect-timeout 10 --max-time 30 \ + -H 'User-Agent: minigraf-cascade/1.0' "https://crates.io/api/v1/crates/minigraf/$version") && + jq -e --arg version "$version" '.version.num == $version' <<< "$response" >/dev/null; then + echo "minigraf@$version is indexed on crates.io" + return + fi + now=$(date +%s) + remaining=$((deadline - now)) + (( remaining > 0 )) || fail "minigraf@$version was not indexed within 60 minutes" + (( delay <= remaining )) || delay=$remaining + echo "Waiting ${delay}s for minigraf@$version" + sleep "$delay" + delay=$((delay * 2)) + (( delay <= 120 )) || delay=120 + done +} + +dispatch_bindings() { + local tag=$1 repo + validate_tag "$tag" + for repo in minigraf-python minigraf-node minigraf-wasm \ + minigraf-java minigraf-android minigraf-swift minigraf-c; do + echo "Dispatching core-release to project-minigraf/$repo @ $tag" + gh api "repos/project-minigraf/$repo/dispatches" \ + -f event_type=core-release -f "client_payload[version]=$tag" + done +} + +GITHUB_SERVER_URL=${GITHUB_SERVER_URL:-https://github.com} +case "${1:-}" in + prepare) prepare_cascade ;; + gate) check_ci "$2" "$3" ;; + wait) wait_for_crate "$2" ;; + dispatch) dispatch_bindings "$2" ;; + *) fail 'Usage: release.sh prepare | gate TAG SHA | wait TAG | dispatch TAG' ;; +esac diff --git a/.github/release/test_release.py b/.github/release/test_release.py new file mode 100644 index 0000000000..eee8562c5b --- /dev/null +++ b/.github/release/test_release.py @@ -0,0 +1,247 @@ +import copy +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +SCRIPT = Path(__file__).with_name('release.sh').resolve() +REPO = 'project-minigraf/minigraf' +SHA = '8ef9d46c6b3d0023cea7a9a4613f20032d484866' +OLD_SHA = 'cbd56af5bb32b8201a4c3c4bbfd636042c93b9f3' +WORKFLOWS = { + 'rust.yml': 'Rust', 'wasm.yml': 'WASM', 'lint.yml': 'Lint', + 'coverage-gates.yml': 'Coverage Gates', 'policy.yml': 'Policy', + 'binary-size.yml': 'Binary Size', +} +RUN112 = { + 'id': 44262102627, 'run_number': 112, 'workflow_id': 260892425, + 'name': 'Release', 'path': '.github/workflows/release.yml', + 'event': 'push', 'status': 'completed', 'conclusion': 'success', + 'head_branch': 'v2.0.12', 'head_sha': SHA, + 'repository': {'full_name': REPO, 'fork': False}, + 'head_repository': {'full_name': REPO, 'fork': False}, +} + +# Only external commands are replaced; jq and the release script run normally. +FAKE = '''#!/usr/bin/env python3 +import json, os, pathlib, sys +root = pathlib.Path(os.environ['FIXTURE']) +state = json.loads((root / 'state.json').read_text()) +tool = pathlib.Path(sys.argv[0]).name +args = sys.argv[1:] +if tool == 'gh': + assert args[0] == 'api', args + endpoint = args[1] + if endpoint.endswith('/dispatches'): + with (root / 'dispatches.jsonl').open('a') as f: + f.write(json.dumps(args) + '\\n') + sys.exit(0) + if endpoint not in state['api']: + sys.exit('Unexpected API request: ' + endpoint) + response = state['api'][endpoint] + if response == 'ERROR': + sys.exit(1) + if '/runs?' in endpoint: + assert args[2:] == ['--paginate', '--slurp'], args + print(json.dumps(response)) +elif tool == 'curl': + with (root / 'curl.jsonl').open('a') as f: + f.write(json.dumps(args) + '\\n') + responses = state['crates'] + response = responses.pop(0) if len(responses) > 1 else responses[0] + (root / 'state.json').write_text(json.dumps(state)) + if response == 'ERROR': + sys.exit(22) + print(json.dumps(response)) +elif tool == 'sleep': + seconds = int(args[0]) + with (root / 'sleeps').open('a') as f: + f.write(str(seconds) + '\\n') + state['clock'] += seconds + (root / 'state.json').write_text(json.dumps(state)) +elif tool == 'date': + assert args == ['+%s'], args + print(state['clock']) +''' + + +def runs_url(filename, sha=SHA): + return f'repos/{REPO}/actions/workflows/{filename}/runs?head_sha={sha}&event=push&per_page=100' + + +class ReleaseTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + for tool in ['gh', 'curl', 'sleep', 'date']: + path = self.root / tool + path.write_text(FAKE) + path.chmod(0o755) + self.env = dict(os.environ, PATH=f'{self.root}:{os.environ["PATH"]}', + FIXTURE=str(self.root), GITHUB_REPOSITORY=REPO, + GITHUB_EVENT_NAME='workflow_run', + GITHUB_EVENT_PATH=str(self.root / 'event.json'), + GITHUB_OUTPUT=str(self.root / 'output')) + self.event = {'workflow_run': copy.deepcopy(RUN112)} + api = { + f'repos/{REPO}/commits/refs%2Ftags%2Fv2.0.12': {'sha': SHA}, + f'repos/{REPO}/actions/workflows/release.yml': {'id': 260892425}, + f'repos/{REPO}/contents/.github/workflows?ref={SHA}': + [{'name': filename} for filename in WORKFLOWS], + runs_url('release.yml'): [{'workflow_runs': [RUN112]}], + } + for filename, name in WORKFLOWS.items(): + run = dict(RUN112, id=100, name=name, path=f'.github/workflows/{filename}', + head_branch='main') + api[runs_url(filename)] = [{'workflow_runs': [run]}] + self.state = {'api': api, 'clock': 0, 'crates': [{'version': {'num': '2.0.12'}}]} + + def run_script(self, *args): + (self.root / 'state.json').write_text(json.dumps(self.state)) + (self.root / 'event.json').write_text(json.dumps(self.event)) + result = subprocess.run(['bash', str(SCRIPT), *args], env=self.env, + text=True, capture_output=True, timeout=10) + self.state = json.loads((self.root / 'state.json').read_text()) + return result + + def cascade(self): + result = self.run_script('prepare') + output = self.root / 'output' + if result.returncode or not output.exists(): + return result + fields = dict(line.split('=', 1) for line in output.read_text().splitlines()) + result = self.run_script('wait', fields['tag']) + if result.returncode: + return result + return self.run_script('dispatch', fields['tag']) + + def dispatches(self): + path = self.root / 'dispatches.jsonl' + return [json.loads(line) for line in path.read_text().splitlines()] if path.exists() else [] + + def assert_successful_dispatch(self, tag='v2.0.12'): + result = self.cascade() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.dispatches(), [ + ['api', f'repos/{REPO.rsplit("/", 1)[0]}/{repo}/dispatches', + '-f', 'event_type=core-release', '-f', f'client_payload[version]={tag}'] + for repo in ['minigraf-python', 'minigraf-node', 'minigraf-wasm', + 'minigraf-java', 'minigraf-android', 'minigraf-swift', 'minigraf-c'] + ]) + + def test_cancelled_release_111_dispatches_nothing(self): + self.event['workflow_run'].update(id=44260756151, run_number=111, + head_sha=OLD_SHA, conclusion='cancelled') + result = self.cascade() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.dispatches(), []) + self.assertFalse((self.root / 'curl.jsonl').exists()) + + def test_successful_release_112_preserves_payload(self): + self.assert_successful_dispatch() + + def test_delayed_indexing_including_http_failure_and_wrong_version(self): + self.state['crates'] = ['ERROR', {}, {'version': {'num': '2.0.11'}}, + {'version': {'num': '2.0.12'}}] + self.assert_successful_dispatch() + self.assertEqual((self.root / 'sleeps').read_text(), '10\n20\n40\n') + calls = [json.loads(line) for line in (self.root / 'curl.jsonl').read_text().splitlines()] + self.assertEqual(len(calls), 4) + for args in calls: + self.assertIn('https://crates.io/api/v1/crates/minigraf/2.0.12', args) + + def test_indexing_timeout_dispatches_nothing(self): + self.state['crates'] = [{}] + result = self.cascade() + self.assertNotEqual(result.returncode, 0) + self.assertEqual(self.dispatches(), []) + self.assertEqual(self.state['clock'], 3600) + + def test_invalid_release_provenance(self): + mutations = [ + {'event': 'pull_request'}, {'event': 'workflow_dispatch'}, + {'head_branch': 'main'}, {'head_branch': 'v3.0.0-;echo bad'}, + {'head_sha': OLD_SHA}, {'workflow_id': 99}, + {'path': '.github/workflows/imposter.yml'}, + {'repository': {'full_name': 'fork/minigraf', 'fork': True}}, + {'head_repository': {'full_name': 'fork/minigraf', 'fork': True}}, + {'head_repository': {'full_name': REPO, 'fork': True}}, + ] + for mutation in mutations: + with self.subTest(mutation=mutation): + self.event['workflow_run'] = dict(RUN112, **mutation) + result = self.cascade() + self.assertNotEqual(result.returncode, 0) + self.assertEqual(self.dispatches(), []) + + def test_prerelease_tag_and_exact_crate_version(self): + self.event['workflow_run']['head_branch'] = 'v3.0.0-alpha' + self.state['api'][f'repos/{REPO}/commits/refs%2Ftags%2Fv3.0.0-alpha'] = {'sha': SHA} + self.state['crates'] = [{'version': {'num': '3.0.0-alpha'}}] + self.assert_successful_dispatch('v3.0.0-alpha') + + def test_manual_recovery_requires_successful_release(self): + self.env['GITHUB_EVENT_NAME'] = 'workflow_dispatch' + self.event = {'inputs': {'tag': 'v2.0.12'}} + self.assert_successful_dispatch() + + def test_manual_recovery_without_release_dispatches_nothing(self): + self.env['GITHUB_EVENT_NAME'] = 'workflow_dispatch' + self.event = {'inputs': {'tag': 'v2.0.12'}} + self.state['api'][runs_url('release.yml')] = [{'workflow_runs': []}] + result = self.cascade() + self.assertNotEqual(result.returncode, 0) + self.assertEqual(self.dispatches(), []) + + def test_gate_rejects_unsuccessful_or_wrong_commit_ci(self): + for mutation in [ + {'conclusion': 'failure'}, {'conclusion': 'cancelled'}, + {'conclusion': 'skipped'}, {'status': 'in_progress', 'conclusion': None}, + {'head_sha': OLD_SHA}, {'event': 'schedule'}, + {'head_repository': {'full_name': 'fork/minigraf', 'fork': True}}, + ]: + with self.subTest(mutation=mutation): + runs = self.state['api'][runs_url('policy.yml')][0]['workflow_runs'] + runs[:] = [dict(RUN112, id=100, name='Policy', + path='.github/workflows/policy.yml', **mutation)] + result = self.run_script('gate', 'v2.0.12', SHA) + self.assertNotEqual(result.returncode, 0) + + def test_gate_rejects_missing_run_and_api_failure(self): + for response in [{'workflow_runs': []}, 'ERROR']: + self.state['api'][runs_url('wasm.yml')] = [response] if isinstance(response, dict) else response + self.assertNotEqual(self.run_script('gate', 'v2.0.12', SHA).returncode, 0) + + def test_gate_uses_latest_run_across_pages(self): + old = copy.deepcopy(self.state['api'][runs_url('rust.yml')][0]['workflow_runs'][0]) + newer = dict(old, id=101, conclusion='failure') + self.state['api'][runs_url('rust.yml')] = [ + {'workflow_runs': [old]}, {'workflow_runs': [newer]}] + self.assertNotEqual(self.run_script('gate', 'v2.0.12', SHA).returncode, 0) + + def test_gate_skips_workflows_absent_from_tagged_commit(self): + self.state['api'][f'repos/{REPO}/contents/.github/workflows?ref={SHA}'] = [{'name': 'rust.yml'}] + result = self.run_script('gate', 'v2.0.12', SHA) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn('Skipping WASM', result.stdout) + + def test_failed_ci_blocks_cascade_before_crates_io(self): + self.state['api'][runs_url('lint.yml')][0]['workflow_runs'][0]['conclusion'] = 'failure' + result = self.cascade() + self.assertNotEqual(result.returncode, 0) + self.assertEqual(self.dispatches(), []) + self.assertFalse((self.root / 'curl.jsonl').exists()) + + def test_no_required_workflows_cannot_pass_vacuously(self): + self.state['api'][f'repos/{REPO}/contents/.github/workflows?ref={SHA}'] = [] + self.assertNotEqual(self.run_script('gate', 'v2.0.12', SHA).returncode, 0) + + def test_gate_checks_tag_sha(self): + self.assertNotEqual(self.run_script('gate', 'v2.0.12', OLD_SHA).returncode, 0) + + +if __name__ == '__main__': + unittest.main() diff --git a/.github/workflows/cascade.yml b/.github/workflows/cascade.yml index da44e32295..e2e2fae1ec 100644 --- a/.github/workflows/cascade.yml +++ b/.github/workflows/cascade.yml @@ -1,65 +1,48 @@ name: Release Cascade on: - push: - tags: - - 'v[0-9]*.[0-9]*.[0-9]*' + workflow_run: + workflows: [Release] + types: [completed] workflow_dispatch: inputs: - version: - description: 'Version tag to cascade (e.g. v1.2.0)' + tag: + description: 'Published version tag to cascade (e.g. v3.0.0-alpha)' required: true type: string permissions: + actions: read contents: read jobs: dispatch-bindings: name: Dispatch to binding repos + if: github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success' runs-on: ubuntu-latest + timeout-minutes: 70 steps: - - name: Resolve version + - uses: actions/checkout@v4 + with: + # workflow_run uses the default branch; never execute the triggering run's code. + ref: ${{ github.workflow_sha }} + persist-credentials: false + + - name: Validate Release run, tag and CI id: ver - run: | - if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then - TAG="${{ github.event.inputs.version }}" - else - TAG="${GITHUB_REF_NAME}" - fi - echo "tag=$TAG" >> "$GITHUB_OUTPUT" - echo "semver=${TAG#v}" >> "$GITHUB_OUTPUT" + env: + GH_TOKEN: ${{ github.token }} + run: bash .github/release/release.sh prepare - name: Wait for minigraf to be indexed on crates.io - run: | - VERSION="${{ steps.ver.outputs.semver }}" - echo "Waiting for minigraf@$VERSION on crates.io..." - FOUND=0 - for i in $(seq 1 36); do - STATUS=$(curl -s "https://crates.io/api/v1/crates/minigraf/$VERSION" \ - -H "User-Agent: minigraf-cascade/1.0" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('version',{}).get('num',''))" 2>/dev/null || echo "") - if [ "$STATUS" = "$VERSION" ]; then - echo "minigraf@$VERSION is live (attempt $i)" - FOUND=1 - break - fi - echo "Attempt $i/36: not yet available, waiting 10s..." - sleep 10 - done - if [ "$FOUND" != "1" ]; then - echo "ERROR: minigraf@$VERSION did not appear on crates.io within 6 minutes" - exit 1 - fi + if: steps.ver.outputs.tag != '' + env: + TAG: ${{ steps.ver.outputs.tag }} + run: bash .github/release/release.sh wait "$TAG" - name: Dispatch to binding repos + if: steps.ver.outputs.tag != '' env: GH_TOKEN: ${{ secrets.MINIGRAF_RELEASE_TOKEN }} - run: | - VERSION="${{ steps.ver.outputs.tag }}" - for REPO in minigraf-python minigraf-node minigraf-wasm \ - minigraf-java minigraf-android minigraf-swift minigraf-c; do - echo "Dispatching core-release to project-minigraf/$REPO @ $VERSION" - gh api repos/project-minigraf/$REPO/dispatches \ - -f event_type=core-release \ - -f "client_payload[version]=$VERSION" - done + TAG: ${{ steps.ver.outputs.tag }} + run: bash .github/release/release.sh dispatch "$TAG" diff --git a/.github/workflows/release-gate.yml b/.github/workflows/release-gate.yml new file mode 100644 index 0000000000..9d0ef213fb --- /dev/null +++ b/.github/workflows/release-gate.yml @@ -0,0 +1,31 @@ +name: Release Gate + +on: + workflow_call: + inputs: + plan: + required: true + type: string + +permissions: + actions: read + contents: read + +jobs: + check: + name: CI for the exact tagged commit + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - name: Test release validation + run: python3 -B -m unittest discover -s .github/release -v + - name: Require successful CI on the tagged commit + env: + GH_TOKEN: ${{ github.token }} + run: | + test "$GITHUB_EVENT_NAME" = push + test "$GITHUB_REF_TYPE" = tag + bash .github/release/release.sh gate "$GITHUB_REF_NAME" "$GITHUB_SHA" diff --git a/.github/workflows/release-publish.yml b/.github/workflows/release-publish.yml new file mode 100644 index 0000000000..3af9770de3 --- /dev/null +++ b/.github/workflows/release-publish.yml @@ -0,0 +1,31 @@ +name: Publish crate + +on: + workflow_call: + inputs: + plan: + required: true + type: string + +permissions: + id-token: write + contents: read + +jobs: + publish: + runs-on: ubuntu-22.04 + environment: + name: crates-io + url: https://crates.io/crates/minigraf + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@stable + - name: Authenticate with crates.io + id: auth + uses: rust-lang/crates-io-auth-action@v1 + - name: Publish to crates.io + run: cargo publish --locked -p minigraf + env: + CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3de01edfb8..fdb393b395 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -164,11 +164,24 @@ jobs: ${{ steps.cargo-dist.outputs.paths }} ${{ env.BUILD_MANIFEST_NAME }} + custom-release-gate: + needs: + - plan + if: ${{ needs.plan.outputs.publishing == 'true' || fromJson(needs.plan.outputs.val).ci.github.pr_run_mode == 'upload' }} + uses: ./.github/workflows/release-gate.yml + with: + plan: ${{ needs.plan.outputs.val }} + secrets: inherit + permissions: + "actions": "read" + "contents": "read" + # Build and package all the platform-agnostic(ish) things build-global-artifacts: needs: - plan - build-local-artifacts + - custom-release-gate runs-on: "ubuntu-22.04" env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -210,15 +223,15 @@ jobs: path: | ${{ steps.cargo-dist.outputs.paths }} ${{ env.BUILD_MANIFEST_NAME }} - # Determines if we should publish/announce host: needs: - plan - build-local-artifacts + - custom-release-gate - build-global-artifacts - # Only run if we're "publishing", and only if all build jobs didn't fail (skipped is fine) - if: ${{ always() && needs.plan.result == 'success' && needs.plan.outputs.publishing == 'true' && (needs.build-global-artifacts.result == 'skipped' || needs.build-global-artifacts.result == 'success') && (needs.build-local-artifacts.result == 'skipped' || needs.build-local-artifacts.result == 'success') }} + # Only run if we're "publishing", and only if plan, local and global didn't fail (skipped is fine) + if: ${{ always() && needs.plan.result == 'success' && needs.plan.outputs.publishing == 'true' && (needs.build-global-artifacts.result == 'skipped' || needs.build-global-artifacts.result == 'success') && (needs.build-local-artifacts.result == 'skipped' || needs.build-local-artifacts.result == 'success') && (needs.custom-release-gate.result == 'skipped' || needs.custom-release-gate.result == 'success') }} env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} runs-on: "ubuntu-22.04" @@ -278,14 +291,29 @@ jobs: gh release create "${{ needs.plan.outputs.tag }}" --target "$RELEASE_COMMIT" $PRERELEASE_FLAG --title "$ANNOUNCEMENT_TITLE" --notes-file "$RUNNER_TEMP/notes.txt" artifacts/* + custom-release-publish: + needs: + - plan + - host + if: ${{ !fromJson(needs.plan.outputs.val).announcement_is_prerelease || fromJson(needs.plan.outputs.val).publish_prereleases }} + uses: ./.github/workflows/release-publish.yml + with: + plan: ${{ needs.plan.outputs.val }} + secrets: inherit + # publish jobs get escalated permissions + permissions: + "contents": "read" + "id-token": "write" + announce: needs: - plan - host + - custom-release-publish # use "always() && ..." to allow us to wait for all publish jobs while # still allowing individual publish jobs to skip themselves (for prereleases). # "host" however must run to completion, no skipping allowed! - if: ${{ always() && needs.host.result == 'success' }} + if: ${{ always() && needs.host.result == 'success' && (needs.custom-release-publish.result == 'skipped' || needs.custom-release-publish.result == 'success') }} runs-on: "ubuntu-22.04" env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -294,30 +322,3 @@ jobs: with: persist-credentials: false submodules: recursive - - # Publish to crates.io after the GitHub release is created - publish-crates-io: - needs: - - plan - - host - if: ${{ always() && needs.host.result == 'success' && needs.plan.outputs.publishing == 'true' }} - runs-on: "ubuntu-22.04" - environment: - name: crates-io - url: https://crates.io/crates/minigraf - permissions: - id-token: write - contents: read - steps: - - uses: actions/checkout@v4 - with: - persist-credentials: false - - uses: dtolnay/rust-toolchain@stable - - name: Authenticate with crates.io - id: auth - uses: rust-lang/crates-io-auth-action@v1 - - name: Publish to crates.io - run: cargo publish --locked -p minigraf - env: - CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }} - diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9e8c081a8c..458c5ad850 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -126,10 +126,16 @@ Releases are managed by the project maintainer. The process is documented in iss 2. Version bumped consistently across all manifests (`Cargo.toml`, `package.json`, `pyproject.toml`, `build.gradle.kts`, `Package.swift`) 3. `cargo check --workspace` passes cleanly 4. All affected docs synced (see `CLAUDE.md` — "Keep documentation synchronized") -5. Tag pushed — CI publishes to crates.io, PyPI, npm, and Maven Central automatically -6. Every binding, including Tier 2, publishes every core release in lock-step, including prereleases; a binding that cannot publish blocks the release until it is fixed or successfully re-dispatched (see [support tiers](PHILOSOPHY.md#support-tiers)) -7. Known-issues issue updated, and `data-integrity`/`corruption`/`durability` issues fixed by this release closed with a link to it (see above) -8. For a minor or major release: the performance envelope re-run and the snapshot in [`docs/BENCHMARKS.md`](docs/BENCHMARKS.md) and the README refreshed (`cargo run --profile envelope --example perf_envelope`; see [Reproducing](docs/BENCHMARKS.md#reproducing)) +5. From a clean checkout of the final candidate commit, run `cargo publish --dry-run --locked` before creating the tag. Record the commit SHA and result in the release issue; a failure must be resolved before tagging. `Cargo.lock` is currently untracked, so this check does not establish that CI and publishing used the same dependency resolution. +6. Confirm successful push runs of Rust, WASM, Lint, Coverage Gates, Policy and Binary Size on that exact SHA. A successful PR run or a run on an earlier commit is insufficient. Workflows absent from the candidate branch are skipped; a present workflow with no successful latest push run blocks the cascade. +7. Push the version tag, including the prerelease suffix when applicable (for example, `v3.0.0-alpha`). After Release succeeds, Release Cascade validates the official tag-push run and its commit, checks CI, then waits up to 60 minutes for the exact crate version on crates.io before dispatching bindings. +8. Every binding, including Tier 2, publishes every core release in lock-step, including prereleases; a binding that cannot publish blocks the release until it is fixed or successfully re-dispatched (see [support tiers](PHILOSOPHY.md#support-tiers)) +9. Known-issues issue updated, and `data-integrity`/`corruption`/`durability` issues fixed by this release closed with a link to it (see above) +10. For a minor or major release: the performance envelope re-run and the snapshot in [`docs/BENCHMARKS.md`](docs/BENCHMARKS.md) and the README refreshed (`cargo run --profile envelope --example perf_envelope`; see [Reproducing](docs/BENCHMARKS.md#reproducing)) + +Release uses cargo-dist's `local-artifacts-jobs` hook to run Release Gate. Failed or cancelled CI on the tagged commit blocks GitHub hosting and crates.io publishing. The gate records the accepted run URLs in its log; after CI succeeds, retry the failed Release run. To update release automation, edit `dist-workspace.toml` and the reusable workflows, then run `dist generate --mode ci` and `dist generate --mode ci --check` with the pinned cargo-dist version. Do not edit `release.yml` by hand. + +Release Cascade must be installed on the default branch (`main`), even when the tag is created from `v3`. For recovery after a partial binding release, run `gh workflow run cascade.yml --ref main -f tag=v3.0.0-alpha` with the published tag. This re-dispatches all seven bindings; it requires a successful official Release run for the tag's current commit and passing CI. The dispatch contract remains `core-release` with `client_payload.version` set to the full tag. ## Code of Conduct diff --git a/dist-workspace.toml b/dist-workspace.toml index fc11db6446..457c06ccac 100644 --- a/dist-workspace.toml +++ b/dist-workspace.toml @@ -11,8 +11,17 @@ ci = "github" installers = [] # Target platforms to build apps for (Rust target-triple syntax) targets = ["aarch64-apple-darwin", "aarch64-unknown-linux-gnu", "x86_64-apple-darwin", "x86_64-unknown-linux-gnu", "x86_64-pc-windows-msvc"] -# Skip checking whether the specified configuration files are up to date -allow-dirty = ["ci"] +pr-run-mode = "skip" +local-artifacts-jobs = ["./release-gate"] +publish-jobs = ["./release-publish"] +publish-prereleases = true + +[dist.github-custom-job-permissions] +release-gate = { actions = "read", contents = "read" } +release-publish = { id-token = "write", contents = "read" } + +[dist.github-action-commits] +"actions/checkout" = "v4" # GitHub retired the macos-14 runner image that dist defaults to for this target [dist.github-custom-runners] From 3e78815165300ab16e7bc86be64652efcc846510 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Mon, 30 Nov 2026 14:37:09 +0530 Subject: [PATCH 2/2] ci(release): wait for the Cargo sparse index, not the crates.io API The API can list a version before Cargo can resolve it: crates.io updates the index and its CDN asynchronously. Poll index.crates.io/mi/ni/minigraf for an exact, unyanked vers row instead, within the same 60-minute bound. Review follow-up on #954/#955. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01H2a7QngaFzuCVt5umd1qoh --- .github/release/release.sh | 9 ++-- .github/release/test_release.py | 85 ++++++++++++++++++++++++++++++--- CONTRIBUTING.md | 2 +- 3 files changed, 85 insertions(+), 11 deletions(-) diff --git a/.github/release/release.sh b/.github/release/release.sh index f4c9c63f8a..f0fbbbcd08 100644 --- a/.github/release/release.sh +++ b/.github/release/release.sh @@ -99,9 +99,12 @@ wait_for_crate() { deadline=$(( $(date +%s) + 3600 )) while true; do if response=$(curl --fail --silent --show-error --connect-timeout 10 --max-time 30 \ - -H 'User-Agent: minigraf-cascade/1.0' "https://crates.io/api/v1/crates/minigraf/$version") && - jq -e --arg version "$version" '.version.num == $version' <<< "$response" >/dev/null; then - echo "minigraf@$version is indexed on crates.io" + -H 'User-Agent: minigraf-cascade/1.0' -H 'Cache-Control: no-cache' \ + --write-out $'\n%{http_code}' 'https://index.crates.io/mi/ni/minigraf') && + [[ "${response##*$'\n'}" == 200 ]] && + jq -se --arg version "$version" 'any(.[]; .vers == $version and .yanked == false)' \ + <<< "${response%$'\n'*}" >/dev/null; then + echo "minigraf@$version is available in the Cargo sparse index" return fi now=$(date +%s) diff --git a/.github/release/test_release.py b/.github/release/test_release.py index eee8562c5b..b0d7fc847b 100644 --- a/.github/release/test_release.py +++ b/.github/release/test_release.py @@ -8,6 +8,7 @@ SCRIPT = Path(__file__).with_name('release.sh').resolve() REPO = 'project-minigraf/minigraf' +INDEX_URL = 'https://index.crates.io/mi/ni/minigraf' SHA = '8ef9d46c6b3d0023cea7a9a4613f20032d484866' OLD_SHA = 'cbd56af5bb32b8201a4c3c4bbfd636042c93b9f3' WORKFLOWS = { @@ -35,6 +36,8 @@ assert args[0] == 'api', args endpoint = args[1] if endpoint.endswith('/dispatches'): + with (root / 'events.jsonl').open('a') as f: + f.write(json.dumps('dispatch') + '\\n') with (root / 'dispatches.jsonl').open('a') as f: f.write(json.dumps(args) + '\\n') sys.exit(0) @@ -49,12 +52,27 @@ elif tool == 'curl': with (root / 'curl.jsonl').open('a') as f: f.write(json.dumps(args) + '\\n') - responses = state['crates'] + url = args[-1] + with (root / 'events.jsonl').open('a') as f: + f.write(json.dumps(url) + '\\n') + if url == 'https://index.crates.io/mi/ni/minigraf': + responses = state['index'] + elif url.startswith('https://crates.io/api/v1/crates/minigraf/'): + responses = state['crates'] + else: + sys.exit('Unexpected curl request: ' + url) response = responses.pop(0) if len(responses) > 1 else responses[0] (root / 'state.json').write_text(json.dumps(state)) if response == 'ERROR': sys.exit(22) - print(json.dumps(response)) + if url == 'https://index.crates.io/mi/ni/minigraf': + sys.stdout.write(response['body']) + if '--write-out' in args: + sys.stdout.write(args[args.index('--write-out') + 1] + .replace('%{http_code}', str(response['status']))) + sys.exit(response['exit_code']) + else: + print(json.dumps(response)) elif tool == 'sleep': seconds = int(args[0]) with (root / 'sleeps').open('a') as f: @@ -71,6 +89,11 @@ def runs_url(filename, sha=SHA): return f'repos/{REPO}/actions/workflows/{filename}/runs?head_sha={sha}&event=push&per_page=100' +def index_response(*rows, status=200, exit_code=0): + return {'body': ''.join(json.dumps(row) + '\n' for row in rows), + 'status': status, 'exit_code': exit_code} + + class ReleaseTests(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() @@ -98,6 +121,7 @@ def setUp(self): head_branch='main') api[runs_url(filename)] = [{'workflow_runs': [run]}] self.state = {'api': api, 'clock': 0, 'crates': [{'version': {'num': '2.0.12'}}]} + self.state['index'] = [index_response({'vers': '2.0.12', 'yanked': False})] def run_script(self, *args): (self.root / 'state.json').write_text(json.dumps(self.state)) @@ -144,17 +168,22 @@ def test_successful_release_112_preserves_payload(self): self.assert_successful_dispatch() def test_delayed_indexing_including_http_failure_and_wrong_version(self): - self.state['crates'] = ['ERROR', {}, {'version': {'num': '2.0.11'}}, - {'version': {'num': '2.0.12'}}] + self.state['index'] = [ + index_response(status=404, exit_code=22), index_response(), + index_response({'vers': '2.0.11', 'yanked': False}), + index_response({'vers': '2.0.12', 'yanked': False}), + ] self.assert_successful_dispatch() self.assertEqual((self.root / 'sleeps').read_text(), '10\n20\n40\n') calls = [json.loads(line) for line in (self.root / 'curl.jsonl').read_text().splitlines()] self.assertEqual(len(calls), 4) for args in calls: - self.assertIn('https://crates.io/api/v1/crates/minigraf/2.0.12', args) + self.assertIn(INDEX_URL, args) + self.assertIn('User-Agent: minigraf-cascade/1.0', args) + self.assertIn('Cache-Control: no-cache', args) def test_indexing_timeout_dispatches_nothing(self): - self.state['crates'] = [{}] + self.state['index'] = [index_response()] result = self.cascade() self.assertNotEqual(result.returncode, 0) self.assertEqual(self.dispatches(), []) @@ -177,11 +206,53 @@ def test_invalid_release_provenance(self): self.assertNotEqual(result.returncode, 0) self.assertEqual(self.dispatches(), []) - def test_prerelease_tag_and_exact_crate_version(self): + def prepare_alpha(self): self.event['workflow_run']['head_branch'] = 'v3.0.0-alpha' self.state['api'][f'repos/{REPO}/commits/refs%2Ftags%2Fv3.0.0-alpha'] = {'sha': SHA} self.state['crates'] = [{'version': {'num': '3.0.0-alpha'}}] + + def test_api_ready_cascade_waits_for_sparse_index(self): + self.prepare_alpha() + self.state['index'] = [ + index_response({'vers': '2.0.12', 'yanked': False}), + index_response({'vers': '2.0.12', 'yanked': False}, + {'vers': '3.0.0-alpha', 'yanked': False}, + {'vers': '3.0.0-alpha2', 'yanked': False}), + ] self.assert_successful_dispatch('v3.0.0-alpha') + events = [json.loads(line) for line in (self.root / 'events.jsonl').read_text().splitlines()] + self.assertEqual(events, [INDEX_URL, INDEX_URL] + ['dispatch'] * 7) + self.assertEqual((self.root / 'sleeps').read_text(), '10\n') + + def test_yanked_alpha_dispatches_nothing(self): + self.prepare_alpha() + self.state['index'] = [index_response({'vers': '3.0.0-alpha', 'yanked': True})] + result = self.cascade() + self.assertNotEqual(result.returncode, 0) + self.assertEqual(self.dispatches(), []) + self.assertEqual(self.state['clock'], 3600) + + def test_near_miss_alpha_dispatches_nothing(self): + self.prepare_alpha() + self.state['index'] = [index_response({'vers': '3.0.0-alpha2', 'yanked': False})] + result = self.cascade() + self.assertNotEqual(result.returncode, 0) + self.assertEqual(self.dispatches(), []) + self.assertEqual(self.state['clock'], 3600) + + def test_http_errors_and_partial_index_responses_are_retried(self): + ready = index_response({'vers': '2.0.12', 'yanked': False}) + self.state['index'] = [ + dict(ready, status=500, exit_code=22), + dict(ready, status=206), + dict(ready, exit_code=18), + dict(ready, body=ready['body'] + '{"vers":'), + ready, + ] + self.assert_successful_dispatch() + events = [json.loads(line) for line in (self.root / 'events.jsonl').read_text().splitlines()] + self.assertEqual(events, [INDEX_URL] * 5 + ['dispatch'] * 7) + self.assertEqual((self.root / 'sleeps').read_text(), '10\n20\n40\n80\n') def test_manual_recovery_requires_successful_release(self): self.env['GITHUB_EVENT_NAME'] = 'workflow_dispatch' diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 458c5ad850..69b9173d88 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -128,7 +128,7 @@ Releases are managed by the project maintainer. The process is documented in iss 4. All affected docs synced (see `CLAUDE.md` — "Keep documentation synchronized") 5. From a clean checkout of the final candidate commit, run `cargo publish --dry-run --locked` before creating the tag. Record the commit SHA and result in the release issue; a failure must be resolved before tagging. `Cargo.lock` is currently untracked, so this check does not establish that CI and publishing used the same dependency resolution. 6. Confirm successful push runs of Rust, WASM, Lint, Coverage Gates, Policy and Binary Size on that exact SHA. A successful PR run or a run on an earlier commit is insufficient. Workflows absent from the candidate branch are skipped; a present workflow with no successful latest push run blocks the cascade. -7. Push the version tag, including the prerelease suffix when applicable (for example, `v3.0.0-alpha`). After Release succeeds, Release Cascade validates the official tag-push run and its commit, checks CI, then waits up to 60 minutes for the exact crate version on crates.io before dispatching bindings. +7. Push the version tag, including the prerelease suffix when applicable (for example, `v3.0.0-alpha`). After Release succeeds, Release Cascade validates the official tag-push run and its commit, checks CI, then waits up to 60 minutes for the exact, unyanked crate version in the Cargo sparse index before dispatching bindings. 8. Every binding, including Tier 2, publishes every core release in lock-step, including prereleases; a binding that cannot publish blocks the release until it is fixed or successfully re-dispatched (see [support tiers](PHILOSOPHY.md#support-tiers)) 9. Known-issues issue updated, and `data-integrity`/`corruption`/`durability` issues fixed by this release closed with a link to it (see above) 10. For a minor or major release: the performance envelope re-run and the snapshot in [`docs/BENCHMARKS.md`](docs/BENCHMARKS.md) and the README refreshed (`cargo run --profile envelope --example perf_envelope`; see [Reproducing](docs/BENCHMARKS.md#reproducing))