From 1a80e5c3cb84cb4b68ba27cca0d563c5632b8577 Mon Sep 17 00:00:00 2001 From: Gaizka Menendez Date: Fri, 30 Oct 2026 12:16:19 +0000 Subject: [PATCH] CARRY: fix(odh): harden generic fetcher follow-ups Signed-off-by: Gaizka Menendez --- .github/workflows/odh-deploy-contract.yml | 13 +- .../konflux/e2e-odh/sync-generic-fetcher.py | 31 +++- .../e2e-odh/sync-generic-fetcher_test.py | 135 ++++++++++++++---- tasks/test-odh.toml | 3 +- 4 files changed, 149 insertions(+), 33 deletions(-) diff --git a/.github/workflows/odh-deploy-contract.yml b/.github/workflows/odh-deploy-contract.yml index 896cc9421a..12a4cde798 100644 --- a/.github/workflows/odh-deploy-contract.yml +++ b/.github/workflows/odh-deploy-contract.yml @@ -44,10 +44,21 @@ jobs: with: python-version: "3.12" + # Keep this version aligned with mise.toml. This workflow stays lean and + # installs only uv instead of bootstrapping the full mise toolchain. + - uses: astral-sh/setup-uv@ae62891fec2bb8e7d6c99fc78c9fec3a63790f8d # v10.0.0 + with: + version: "0.10.12" + - name: Run the deploy digest contract suite run: bash odh/scripts/tests/test-openshell-deploy-from-quay.sh - name: Verify generic-fetcher synchronization + env: + # Keep pytest on the Python version installed above instead of + # resolving the repository-wide development interpreter. + UV_PYTHON: ${{ env.pythonLocation }}/bin/python run: | python3 deploy/konflux/e2e-odh/sync-generic-fetcher.py --check - python3 deploy/konflux/e2e-odh/sync-generic-fetcher_test.py + # Keep this invocation in sync with test:odh-generic-fetcher in tasks/test-odh.toml. + uv run --no-project --with "pytest==9.0.3" --with "pytest-asyncio==1.3.0" pytest -o "python_files=*_test.py" deploy/konflux/e2e-odh/ diff --git a/deploy/konflux/e2e-odh/sync-generic-fetcher.py b/deploy/konflux/e2e-odh/sync-generic-fetcher.py index e63705382b..00d2f80027 100755 --- a/deploy/konflux/e2e-odh/sync-generic-fetcher.py +++ b/deploy/konflux/e2e-odh/sync-generic-fetcher.py @@ -200,6 +200,25 @@ def check(versions: dict[str, str], artifacts: list[Artifact]) -> list[str]: RETRY_ATTEMPTS = 3 +MAX_RETRY_AFTER_SECONDS = 60 + + +def retry_delay(retry_after: str | None, attempt: int) -> tuple[int, str | None]: + """Return a bounded delay and the requested value when it was capped.""" + fallback_delay = 2 ** (attempt - 1) + if not retry_after or not retry_after.isascii() or not retry_after.isdecimal(): + return fallback_delay, None + + significant_digits = retry_after.lstrip("0") + # Avoid converting an unbounded value supplied by a remote server, while + # retaining a useful exact value in the retry log for normal headers. + if len(significant_digits) > 10: + return MAX_RETRY_AFTER_SECONDS, f"more than {MAX_RETRY_AFTER_SECONDS}s" + + requested_delay = int(significant_digits or "0") + if requested_delay > MAX_RETRY_AFTER_SECONDS: + return MAX_RETRY_AFTER_SECONDS, f"{requested_delay}s" + return requested_delay, None def _with_retry(url: str, consume, what: str): @@ -228,14 +247,16 @@ def _with_retry(url: str, consume, what: str): if isinstance(last_error, urllib.error.HTTPError) else None ) - delay = ( - int(retry_after) - if retry_after and retry_after.isdigit() - else 2 ** (attempt - 1) + retry_after = retry_after.strip() if retry_after else None + delay, capped_retry_after = retry_delay(retry_after, attempt) + cap_note = ( + f"; server Retry-After was {capped_retry_after}" + if capped_retry_after is not None + else "" ) print( f"{url}: {last_error}; attempt {attempt}/{RETRY_ATTEMPTS} failed " - f"while {what}, retrying in {delay}s", + f"while {what}, retrying in {delay}s{cap_note}", file=sys.stderr, ) time.sleep(delay) diff --git a/deploy/konflux/e2e-odh/sync-generic-fetcher_test.py b/deploy/konflux/e2e-odh/sync-generic-fetcher_test.py index b4f1f77c4d..3b47e19966 100644 --- a/deploy/konflux/e2e-odh/sync-generic-fetcher_test.py +++ b/deploy/konflux/e2e-odh/sync-generic-fetcher_test.py @@ -7,11 +7,13 @@ import hashlib import importlib.util +import io import sys import unittest +from contextlib import redirect_stderr from email.message import Message from pathlib import Path -from unittest.mock import patch +from unittest.mock import call, patch from urllib.error import HTTPError @@ -58,47 +60,128 @@ def open(self, _url: str, timeout: int): return response +def _rate_limited(retry_after: str | None = None) -> HTTPError: + headers = Message() + if retry_after is not None: + headers["Retry-After"] = retry_after + return HTTPError( + "https://example.test/artifact", 429, "rate limited", headers, None + ) + + +def _sha256_with_responses(responses: list[_Response | Exception]): + opener = _Opener(responses) + with ( + patch.object( + sync_generic_fetcher.urllib.request, + "build_opener", + return_value=opener, + ), + patch.object(sync_generic_fetcher.time, "sleep") as sleep, + ): + checksum = sync_generic_fetcher.sha256_of("https://example.test/artifact") + return checksum, sleep + + class SyncGenericFetcherTests(unittest.TestCase): def test_sha256_of_retries_with_a_fresh_hash(self) -> None: complete = b"the complete retry response" - opener = _Opener( + checksum, _ = _sha256_with_responses( [ _Response([b"partial first response", OSError("interrupted")]), _Response([complete, b""]), ] ) - with ( - patch.object( - sync_generic_fetcher.urllib.request, - "build_opener", - return_value=opener, - ), - patch.object(sync_generic_fetcher.time, "sleep"), - ): - checksum = sync_generic_fetcher.sha256_of("https://example.test/artifact") self.assertEqual(checksum, f"sha256:{hashlib.sha256(complete).hexdigest()}") def test_retry_after_is_honored_for_rate_limiting(self) -> None: - headers = Message() - headers["Retry-After"] = "7" - rate_limited = HTTPError( - "https://example.test/artifact", 429, "rate limited", headers, None + for retry_after, expected_delay in ( + ("0", 0), + ("00", 0), + ("007", 7), + ("7", 7), + ("10", 10), + ("60", 60), + ("60 ", 60), + ("0" * 10_000 + "7", 7), + ): + with self.subTest(retry_after=retry_after[:8]): + complete = b"complete retry response" + checksum, sleep = _sha256_with_responses( + [_rate_limited(retry_after), _Response([complete, b""])] + ) + + self.assertEqual( + checksum, f"sha256:{hashlib.sha256(complete).hexdigest()}" + ) + sleep.assert_called_once_with(expected_delay) + + def test_retry_after_is_capped_for_rate_limiting(self) -> None: + for retry_after in ("61", "3600", "9" * 10_000): + with self.subTest(retry_after=retry_after[:4]): + complete = b"complete retry response" + checksum, sleep = _sha256_with_responses( + [_rate_limited(retry_after), _Response([complete, b""])] + ) + + self.assertEqual( + checksum, f"sha256:{hashlib.sha256(complete).hexdigest()}" + ) + sleep.assert_called_once_with(60) + + def test_retry_after_falls_back_to_exponential_backoff_when_invalid(self) -> None: + for retry_after in (None, "later", "²", "\N{ARABIC-INDIC DIGIT SEVEN}"): + with self.subTest(retry_after=retry_after): + complete = b"complete retry response" + checksum, sleep = _sha256_with_responses( + [_rate_limited(retry_after), _Response([complete, b""])] + ) + + self.assertEqual( + checksum, f"sha256:{hashlib.sha256(complete).hexdigest()}" + ) + sleep.assert_called_once_with(1) + + def test_retry_after_fallback_doubles_on_consecutive_retries(self) -> None: + complete = b"complete retry response" + checksum, sleep = _sha256_with_responses( + [_rate_limited(), _rate_limited(), _Response([complete, b""])] ) + + self.assertEqual(checksum, f"sha256:{hashlib.sha256(complete).hexdigest()}") + self.assertEqual(sleep.call_args_list, [call(1), call(2)]) + + def test_retry_after_invalid_fallback_doubles_on_consecutive_retries(self) -> None: complete = b"complete retry response" - opener = _Opener([rate_limited, _Response([complete, b""])]) - with ( - patch.object( - sync_generic_fetcher.urllib.request, - "build_opener", - return_value=opener, - ), - patch.object(sync_generic_fetcher.time, "sleep") as sleep, - ): - checksum = sync_generic_fetcher.sha256_of("https://example.test/artifact") + checksum, sleep = _sha256_with_responses( + [_rate_limited("later"), _rate_limited("later"), _Response([complete, b""])] + ) + + self.assertEqual(checksum, f"sha256:{hashlib.sha256(complete).hexdigest()}") + self.assertEqual(sleep.call_args_list, [call(1), call(2)]) + + def test_retry_after_is_honored_after_a_fallback_retry(self) -> None: + complete = b"complete retry response" + checksum, sleep = _sha256_with_responses( + [_rate_limited(), _rate_limited("7"), _Response([complete, b""])] + ) self.assertEqual(checksum, f"sha256:{hashlib.sha256(complete).hexdigest()}") - sleep.assert_called_once_with(7) + self.assertEqual(sleep.call_args_list, [call(1), call(7)]) + + def test_capped_retry_after_reports_the_requested_delay(self) -> None: + complete = b"complete retry response" + stderr = io.StringIO() + with redirect_stderr(stderr): + _, sleep = _sha256_with_responses( + [_rate_limited("3600"), _Response([complete, b""])] + ) + + sleep.assert_called_once_with(60) + self.assertIn( + "retrying in 60s; server Retry-After was 3600s", stderr.getvalue() + ) def test_published_checksum_requires_the_sidecar_asset_name(self) -> None: with ( diff --git a/tasks/test-odh.toml b/tasks/test-odh.toml index 99e2a37fc2..81a020b75d 100644 --- a/tasks/test-odh.toml +++ b/tasks/test-odh.toml @@ -52,5 +52,6 @@ hide = true ["test:odh-generic-fetcher"] description = "Test ODH generic-fetcher checksum synchronization" -run = "python3 deploy/konflux/e2e-odh/sync-generic-fetcher_test.py" +# Keep this invocation in sync with odh-deploy-contract.yml. +run = "uv run --no-project --with \"pytest==9.0.3\" --with \"pytest-asyncio==1.3.0\" pytest -o \"python_files=*_test.py\" deploy/konflux/e2e-odh/" hide = true