diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 100fab99..ec7ab4fe 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -51,8 +51,8 @@ permissions: env: RELEASE_PLATFORM_PROFILE: ${{ inputs.platform_profile || 'full' }} RELEASE_CHANNEL: ${{ inputs.channel || (startsWith(github.ref, 'refs/tags/rust-v') && 'beta') || 'candidate' }} - EMULEBB_BUILD_REF: 00ef942397ad7e069813f3ff5d0d6bcb9bc58acb - EMULEBB_LINUX_PREPARED_IMAGE: ghcr.io/emulebb/emulebb-build-ci/ubuntu-rust@sha256:182090666a847a8c49e4e782f172ab845e295646eb2f246e75ff3ad989519237 + EMULEBB_BUILD_REF: a322b17cdf01f1324fe238f8459066ecca0aa127 + EMULEBB_LINUX_PREPARED_IMAGE: ghcr.io/emulebb/emulebb-build-ci/ubuntu-rust@sha256:a18dfec2c58a96ed1b02fee7e63f2d0aaecbc1d68adb1b69b41c603ce9166bc7 EMULEBB_BUILD_TESTS_REF: 135930dcbf350cc37477baf528f9d29ff4a573e9 EMULEBB_TOOLING_REF: ac8609756b097d1294308abeef962fe1592e4e38 EMULEBB_RELEASE_VALIDATOR_REF: f9fd190ed6236c6ebb3a71aac8ff0e73e7a06b84 @@ -1411,6 +1411,7 @@ jobs: name: emulebb-rust-release-candidate path: ${{ runner.temp }}/emulebb-rust-out/release/rust-v${{ env.RELEASE_VERSION }} - name: Recheck source eligibility and existing draft bytes + id: draft-preflight env: RELEASE_DIR: ${{ runner.temp }}/emulebb-rust-out/release/rust-v${{ env.RELEASE_VERSION }} GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -1418,13 +1419,14 @@ jobs: set -euo pipefail python -B emulebb-rust/tools/release_publish.py release-assets \ --release-dir "$RELEASE_DIR" --build-repo emulebb-build --producer-build-repo emulebb-image-build --apk-harness-repo emulebb-apk-tests \ - --verified-candidate-sha256 "$VERIFIED_CANDIDATE_SHA" --phase before-upload + --verified-candidate-sha256 "$VERIFIED_CANDIDATE_SHA" --phase before-upload --github-output "$GITHUB_OUTPUT" - name: Attest the exact native release candidate uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 with: subject-path: ${{ runner.temp }}/emulebb-rust-out/release/rust-v${{ env.RELEASE_VERSION }}/* - name: Upload immutable assets to a draft prerelease id: draft-release + if: steps.draft-preflight.outputs.complete_draft_id == '' uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4 with: tag_name: rust-v${{ env.RELEASE_VERSION }} @@ -1439,7 +1441,7 @@ jobs: env: RELEASE_DIR: ${{ runner.temp }}/emulebb-rust-out/release/rust-v${{ env.RELEASE_VERSION }} GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - RELEASE_ID: ${{ steps.draft-release.outputs.id }} + RELEASE_ID: ${{ steps.draft-preflight.outputs.complete_draft_id || steps.draft-release.outputs.id }} run: | set -euo pipefail python -B emulebb-rust/tools/release_publish.py release-assets \ diff --git a/tools/check_rust_client_policy.py b/tools/check_rust_client_policy.py index e179c73f..200e3a78 100644 --- a/tools/check_rust_client_policy.py +++ b/tools/check_rust_client_policy.py @@ -1259,6 +1259,9 @@ def job_body(name: str) -> str | None: "VERIFIED_CANDIDATE_SHA: ${{ needs.publish-image.outputs.candidate_sha256 }}": "image-publisher candidate binding", "release_publish.py release-assets": "verified draft asset preflight", "--phase before-upload": "existing draft byte comparison before upload", + "id: draft-preflight": "verified draft recovery preflight output", + "if: steps.draft-preflight.outputs.complete_draft_id == ''": "skip upload only for a fully verified draft", + "RELEASE_ID: ${{ steps.draft-preflight.outputs.complete_draft_id || steps.draft-release.outputs.id }}": "finalize the same verified release ID", "--phase after-upload --release-id": "complete uploaded byte comparison before finalization", "id: draft-release": "draft release output", "draft: true": "draft-first release creation", diff --git a/tools/nightly_release.py b/tools/nightly_release.py index 7d7dfebd..774c6cf0 100644 --- a/tools/nightly_release.py +++ b/tools/nightly_release.py @@ -525,17 +525,67 @@ def write_release_documents(*, version: str, channel: str, source_sha: str, sour stream.write(content) +def _github_api_failure(error: subprocess.CalledProcessError) -> tuple[str, bool, float]: + """Summarize only known response metadata and classify retryable read failures.""" + stderr = error.stderr or "" + status = re.search(r"\(HTTP ([1-5][0-9]{2})\)", stderr) + headers = { + key.lower(): value for key, value in re.findall( + r"(?im)^(x-github-request-id|retry-after|x-ratelimit-remaining|x-ratelimit-reset):[ \t]*([a-z0-9:-]{1,80})[ \t]*$", + error.stdout or "", + ) + } + code = int(status[1]) if status else None + retry_after = headers.get("retry-after", "") + delay = float(retry_after) if re.fullmatch(r"[0-9]{1,10}", retry_after) else 0 + remaining = headers.get("x-ratelimit-remaining") + reset = headers.get("x-ratelimit-reset", "") + if remaining == "0" and re.fullmatch(r"[0-9]{1,10}", reset): + delay = max(delay, int(reset) - time.time()) + retryable = code in {408, 429, 500, 502, 503, 504} or ( + code == 403 and (remaining == "0" or bool(delay) + or re.search(r"(?:secondary|API) rate limit", stderr, re.IGNORECASE) is not None) + ) + label = f"HTTP {code}" if code is not None else f"gh exited {error.returncode}" + if code is None and re.search(r"i/o timeout|TLS handshake timeout|connection reset by peer|unexpected EOF", + stderr, re.IGNORECASE): + retryable = True + label = "GitHub transport interruption" + detail = ", ".join(f"{key}={value}" for key, value in sorted(headers.items())) + return label + (f" ({detail})" if detail else ""), retryable, delay + + def _action_rows(endpoint: str, field: str, *, deadline: float | None = None) -> list[dict[str, object]]: - """Read every Actions page, rejecting incomplete or malformed inventories.""" - # WHY: the qualification deadline must also bound a stalled API request. - timeout = 120 if deadline is None else min(120, deadline - time.monotonic()) - if timeout <= 0: - raise SourceChecksNotReady("Exact-source qualification timed out before an Actions request") - try: - response = run(("gh", "api", "--paginate", "--slurp", endpoint), timeout=timeout) - except subprocess.TimeoutExpired as error: - raise SourceChecksNotReady("Exact-source qualification Actions request timed out") from error - pages = json.loads(response.stdout) + """Read every Actions page with a bounded retry for transient failures.""" + request_deadline = time.monotonic() + 45 + if deadline is not None: + request_deadline = min(deadline, request_deadline) + failure = "Exact-source qualification timed out before an Actions request" + for attempt in range(1, 4): + timeout = min(15, request_deadline - time.monotonic()) + if timeout <= 0: + raise SourceChecksNotReady(f"{failure}: {endpoint}") + delay = 0.0 + try: + response = run(("gh", "api", "--paginate", "--slurp", "--include", endpoint), timeout=timeout) + except subprocess.TimeoutExpired: + failure = "Exact-source qualification Actions request timed out" + except subprocess.CalledProcessError as error: + detail, retryable, delay = _github_api_failure(error) + failure = f"Exact-source qualification Actions request failed ({detail})" + if not retryable: + raise SourceChecksNotReady(f"{failure}: {endpoint}") from None + else: + break + delay = max(delay, 2 ** (attempt - 1)) + if attempt == 3 or time.monotonic() + delay >= request_deadline: + raise SourceChecksNotReady(f"{failure}: {endpoint}") from None + print(f"{failure}: {endpoint}; retrying in {delay:.1f}s", file=sys.stderr, flush=True) + time.sleep(delay) + # gh interleaves the response headers inside the slurped JSON array. + payload = re.sub(r"(?<=[\[,])HTTP/\d+(?:\.\d+)? 2\d\d[^\r\n]*\r?\n(?:[^\r\n]+\r?\n)*\r?\n", + "", response.stdout) + pages = json.loads(payload) if not isinstance(pages, list) or not pages: raise RuntimeError("Actions eligibility requires a paginated response") rows = [] diff --git a/tools/release_publish.py b/tools/release_publish.py index a35588cd..85a4ae0d 100644 --- a/tools/release_publish.py +++ b/tools/release_publish.py @@ -650,6 +650,10 @@ def verify_release_assets(args: argparse.Namespace, data: dict, candidate: Path) source_sha=args.source_sha, complete=args.phase == "after-upload", release_id=args.release_id, ) require_publication_source(args.repository, args.source_sha) + if args.phase == "before-upload" and args.github_output is not None: + with args.github_output.open("a", encoding="utf-8", newline="\n") as stream: + if identifier is not None and len(assets) == len(expected): + stream.write(f"complete_draft_id={identifier}\n") print(json.dumps({"phase": args.phase, "releaseId": identifier, "verifiedAssets": len(assets)}, sort_keys=True)) diff --git a/tools/tests/test_nightly_release.py b/tools/tests/test_nightly_release.py index d1b112c4..a89b514d 100644 --- a/tools/tests/test_nightly_release.py +++ b/tools/tests/test_nightly_release.py @@ -1,6 +1,7 @@ from __future__ import annotations import importlib.util +import io import json import subprocess import sys @@ -618,10 +619,49 @@ def test_actions_request_uses_only_the_remaining_budget(self): self.assertEqual(NIGHTLY._action_rows("synthetic", "workflow_runs", deadline=10), []) self.assertEqual(run.call_args.kwargs["timeout"], 2) - def test_actions_timeout_is_terminal_for_this_qualification(self): - with mock.patch.object(NIGHTLY, "run", side_effect=subprocess.TimeoutExpired("gh", 120)): + def test_actions_timeout_is_terminal_after_bounded_retries(self): + with mock.patch.object(NIGHTLY, "run", side_effect=subprocess.TimeoutExpired("gh", 15)) as run, \ + mock.patch.object(NIGHTLY.time, "sleep") as sleep: with self.assertRaisesRegex(NIGHTLY.SourceChecksNotReady, "Actions request timed out"): NIGHTLY._action_rows("synthetic", "workflow_runs") + self.assertEqual(run.call_count, 3) + self.assertEqual(sleep.call_args_list, [mock.call(1), mock.call(2)]) + + def test_rate_limit_retries_and_reads_all_success_pages(self): + throttled = subprocess.CalledProcessError( + 1, "gh", output="Retry-After: 3\nX-GitHub-Request-Id: 123:ABC\n", + stderr="gh: secondary rate limit (HTTP 403)", + ) + payload = '[HTTP/2.0 200 OK\nHeader: value\n\n{"jobs":[{"id":1}]},HTTP/2.0 200 OK\n\n{"jobs":[{"id":2}]}]' + response = subprocess.CompletedProcess([], 0, stdout=payload) + with mock.patch.object(NIGHTLY, "run", side_effect=[throttled, response]), \ + mock.patch.object(NIGHTLY.time, "sleep") as sleep: + self.assertEqual(NIGHTLY._action_rows("synthetic", "jobs"), [{"id": 1}, {"id": 2}]) + sleep.assert_called_once_with(3) + + def test_forbidden_reports_safe_context_without_retry(self): + forbidden = subprocess.CalledProcessError( + 1, "gh", output="Authorization: secret\nX-GitHub-Request-Id: 123:ABC\n", + stderr="gh: Resource not accessible (HTTP 403)", + ) + with mock.patch.object(NIGHTLY, "run", side_effect=forbidden) as run, \ + mock.patch.object(NIGHTLY.time, "sleep") as sleep: + with self.assertRaisesRegex(NIGHTLY.SourceChecksNotReady, "HTTP 403 .*123:ABC.*synthetic") as error: + NIGHTLY._action_rows("synthetic", "jobs") + self.assertNotIn("secret", str(error.exception)) + run.assert_called_once() + sleep.assert_not_called() + + def test_interrupted_transport_retries_without_printing_cli_diagnostics(self): + interrupted = subprocess.CalledProcessError(1, "gh", stderr="connection reset by peer: private context") + response = subprocess.CompletedProcess([], 0, stdout='[{"jobs":[]}]') + with mock.patch.object(NIGHTLY, "run", side_effect=[interrupted, response]), \ + mock.patch.object(NIGHTLY.time, "sleep") as sleep, \ + mock.patch("sys.stderr", new_callable=io.StringIO) as log: + self.assertEqual(NIGHTLY._action_rows("synthetic", "jobs"), []) + sleep.assert_called_once_with(1) + self.assertIn("transport interruption", log.getvalue()) + self.assertNotIn("private context", log.getvalue()) def test_success_after_the_deadline_cannot_qualify_source(self): with mock.patch.object(NIGHTLY, "verify_source_checks", return_value={}), \ diff --git a/tools/tests/test_release_publish.py b/tools/tests/test_release_publish.py index ed443fc2..a65d62af 100644 --- a/tools/tests/test_release_publish.py +++ b/tools/tests/test_release_publish.py @@ -1,5 +1,6 @@ from __future__ import annotations +import argparse import hashlib import importlib.util import io @@ -305,6 +306,39 @@ def test_finalization_requires_the_same_numeric_release_id(self) -> None: with self.assertRaisesRegex(RuntimeError, "identity changed"): self.validate(complete=True, release_id=value) + def test_interrupted_publisher_recovers_only_the_same_complete_draft(self) -> None: + with tempfile.TemporaryDirectory() as temp_dir: + candidate = Path(temp_dir) / "candidate.json" + candidate.write_bytes(b"candidate") + output = Path(temp_dir) / "github-output" + candidate_asset = {"name": candidate.name, "size": candidate.stat().st_size, + "digest": "sha256:" + hashlib.sha256(b"candidate").hexdigest(), "state": "uploaded"} + assets = [*self.assets, candidate_asset] + args = argparse.Namespace(release_version=self.tag.removeprefix("rust-v"), repository="example/project", + source_sha=self.source, phase="after-upload", release_id="42", + github_output=output) + data = {"artifacts": self.expected} + with mock.patch.object(PUBLISH, "gh_rows", side_effect=[[self.release], assets] * 3) as rows, \ + mock.patch.object(PUBLISH, "require_publication_source", + side_effect=[RuntimeError("source gate interrupted"), None, None]) as gate: + with self.assertRaisesRegex(RuntimeError, "source gate interrupted"): + PUBLISH.verify_release_assets(args, data, candidate) + self.assertFalse(output.exists()) + args.phase, args.release_id = "before-upload", None + PUBLISH.verify_release_assets(args, data, candidate) + self.assertEqual(output.read_text(encoding="utf-8"), "complete_draft_id=42\n") + args.phase, args.release_id = "after-upload", "42" + PUBLISH.verify_release_assets(args, data, candidate) + self.assertEqual(gate.call_args_list, [mock.call(args.repository, self.source)] * 3) + self.assertEqual([call.args[0] for call in rows.call_args_list[1::2]], + ["repos/example/project/releases/42/assets?per_page=100"] * 3) + corrupted = {**candidate_asset, "digest": "sha256:" + "0" * 64} + with mock.patch.object(PUBLISH, "gh_rows", side_effect=[[self.release], [*self.assets, corrupted]]), \ + mock.patch.object(PUBLISH, "require_publication_source") as gate: + with self.assertRaisesRegex(RuntimeError, "Draft asset bytes differ"): + PUBLISH.verify_release_assets(args, data, candidate) + gate.assert_not_called() + class TestGitHubReleaseRows(unittest.TestCase): def test_all_pages_are_read_and_errors_are_not_interpreted_as_absence(self) -> None: